commit 27e77fff39b2189a861b96af0f3a2142369a5edc Author: lingjhf Date: Mon Oct 5 23:36:23 2026 +0800 feat: initial Cutdex application Add the Flutter video editing application with project management, media import, timeline editing, preview, AI assistance, diagnostics and settings. Include shared UI and native host packages, platform runners, application tests and release tooling. Provide usage and contribution guides, the MIT license and third-party notices. Exclude local credentials, build outputs and validation data. diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..810a0e9 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,23 @@ +--- +name: Bug report +about: 报告可复现的问题 +title: '' +labels: '' +assignees: '' +--- + +**环境** + +Cutdex 版本或提交、操作系统、设备架构;使用安装包还是源码构建。 + +**复现步骤** + +1. … + +**预期与实际结果** + +描述期望行为与实际发生的情况。 + +**补充信息** + +可附脱敏后的错误信息或使用合成素材的最小复现。不要上传 API Key、个人媒体、完整项目或未审查的诊断包。安全问题请参阅 SECURITY.md。 diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..a1f248c --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,15 @@ +--- +name: Feature request +about: 讨论功能或改进建议 +title: '' +labels: '' +assignees: '' +--- + +**要解决的问题** + +描述使用场景及目前遇到的限制。 + +**期望的行为** + +描述希望如何操作,以及应当得到的结果。 diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..74b0ef2 --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,7 @@ +## 改动 + +说明问题和修改后的行为;关联 Issue(如有)。 + +## 验证 + +列出执行的检查及结果。未执行的检查、缺少的依赖或未验证的平台请写明原因。 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bcffbc9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,103 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +**/.gradle/ +build/ +coverage/ +__pycache__/ +.pytest_cache/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/build/ +/android/app/debug +/android/app/profile +/android/app/release + +# Widget Preview related +.widget_preview/ + +# Local service credentials +.local/ + +# Local distribution artifacts +/dist/ + +# Generated from flavor-aware Windows runner templates by CMake. +/windows/runner/main.cpp +/windows/runner/Runner.rc + +# Local dependency overrides +pubspec_overrides.yaml + +# Local environment and signing credentials +.env +.env.* +!.env.example +!.env.*.example +!.env.sample +!.env.*.sample +*.local.xcconfig +*.pem +*.key +*.p8 +*.p12 +*.pfx +*.mobileprovision +*.provisionprofile +*.keystore +*.jks + +# Local test inputs, reports and editor state +/validation/ +/test-results/ +*.cutdex/ +*.sqlite +*.sqlite3 +*.sqlite-wal +*.sqlite-shm +*.sqlite3-wal +*.sqlite3-shm +*.db-wal +*.db-shm +*.dSYM/ +*.xcarchive/ +*.ipa +*.apk +*.aab +.vscode/* +!.vscode/launch.json diff --git a/.metadata b/.metadata new file mode 100644 index 0000000..615dfd4 --- /dev/null +++ b/.metadata @@ -0,0 +1,45 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "d3b14c876900e553bc736ca19295fc09e3853e8e" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + base_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + - platform: android + create_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + base_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + - platform: ios + create_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + base_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + - platform: linux + create_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + base_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + - platform: macos + create_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + base_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + - platform: web + create_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + base_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + - platform: windows + create_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + base_revision: d3b14c876900e553bc736ca19295fc09e3853e8e + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..3816c87 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,11 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "name": "Cutdex", + "request": "launch", + "type": "dart", + "program": "lib/main.dart" + } + ] +} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..352c682 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,27 @@ +# 参与贡献 + +Cutdex 仍在开发中。提交问题前请搜索已有 Issues;较大的功能或跨包修改先通过 Issue 讨论范围。 + +## 开发与验证 + +环境准备、运行应用和代码生成见 [开发指南](docs/development.md)。贡献可以围绕剪辑操作、素材管理、预览、AI 助手、设置与平台交互展开;问题报告请说明触发步骤、预期结果和实际表现。 + +```sh +# Python 3.11+,无需启动应用 +python3 tool/check_public_repository.py +python3 tool/check_package_boundaries.py +python3 -m unittest discover -s tool/tests -p 'public_repository_test.py' +python3 -m unittest discover -s tool/tests -p 'package_boundaries_test.py' +``` + +应用和内部包修改需执行 [测试指南](docs/testing.md) 中适用的检查。生成文件随源码提交;不要手改生成文件。涉及原生媒体、设备交互或处理任务时,说明真实环境验证结果以及未验证的平台。 + +## Pull request + +说明解决的问题、修改后的行为和验证结果,保持改动范围集中。测试未运行时写明原因;界面修改可附截图,剪辑行为修改应说明保存、撤销和重做是否正常。 + +请勿提交 API Key、模型服务凭据、签名材料、本地路径配置、个人媒体、项目文件、诊断包或构建产物。使用合成或可再分发的测试素材,配置示例使用占位值;本地配置放入已忽略的 `.local/` 或仓库外。 + +安全问题请遵循 [安全报告说明](SECURITY.md),不要在公开 Issue 或 PR 中附上凭据或利用细节。 + +提交贡献表示你有权提供相关代码、文档和素材,并同意以本仓库的 [MIT 许可证](LICENSE) 提供贡献。第三方内容需保留原有许可证与归属说明。 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..dbf2437 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Cutdex contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..a0d2e70 --- /dev/null +++ b/README.md @@ -0,0 +1,62 @@ +# Cutdex + +Cutdex 是一款视频剪辑应用。你可以在时间线上编辑视频、音频和字幕,也可以用自然语言让 AI 助手协助剪辑。 + +本仓库提供 Cutdex 应用源码,采用 [MIT 许可证](LICENSE)。 + +## 支持平台 + +| 平台 | 系统要求 | +| --- | --- | +| macOS | macOS 14 或更新版本,Apple Silicon | +| Windows | Windows 10 / 11,64 位 x64 | +| Android 手机与平板 | Android 12 或更新版本,64 位系统 | +| iPhone 与 iPad | iOS / iPadOS 17 或更新版本 | + +项目仍在开发中,各平台的功能持续完善。暂不提供 Linux 和浏览器版本。 + +## 下载与安装 + +本仓库目前尚未发布可下载的安装包。 + +## 可以做什么 + +- 管理项目、时间线,以及视频、音频和图片素材。 +- 移动、裁剪、分割片段,调整速度、音量和画面属性,使用关键帧与蒙版。 +- 预览剪辑结果,撤销或重做编辑,自动保存项目。 +- 生成、翻译字幕,以及为视频或图片抠像。 +- 与 AI 助手对话,让它查询素材、执行编辑并导出视频。 + +字幕、翻译和抠像需要相应的本地资源;按界面提示下载。不同平台和安装环境的可用功能以应用实际显示为准。 + +## 开始剪辑 + +1. 打开 Cutdex,选择“新建项目”,指定名称和保存位置;也可以打开已有项目。 +2. 在项目中选择“新建时间线”。 +3. 打开素材面板,点击“导入”,选择视频、音频或图片。 +4. 将素材添加到时间线。桌面可拖动素材,触控设备可使用“添加到时间线”。 +5. 选择片段,进行裁剪、分割或属性调整,使用预览检查结果。 + +项目会自动保存。关闭前确认状态显示“已保存”;如果保存失败,保留当前项目并重试。 + +本地文件导入后引用原文件,移动或删除原文件会使素材不可用,备份项目时也需要保留使用的素材。Android 系统文件选择器提供的素材会复制到项目内,导入时需要留出相应的存储空间。 + +## 使用 AI 助手 + +在“设置 → Agent”中添加你使用的模型服务,填写服务地址、模型名称和 API Key,选择默认模型并启用。 + +打开项目和时间线后,在对话区描述你的剪辑要求,例如:“把这个片段的开头剪掉两秒,再降低音量。”你可以继续对话调整结果,或点击“停止回复”停止当前任务。手动剪辑无需配置 AI 服务。 + +视频导出目前通过 AI 助手或外部工具发起,尚无独立导出按钮。可以向助手说明导出要求和保存位置。 + +## 其他设置 + +“设置 → 通用”可以切换语言、明暗主题和存储位置。桌面版还提供软件更新入口,是否可用取决于安装包的更新配置。 + +遇到编辑、保存、预览或后台任务错误时,可在“设置 → 通用 → 诊断”中导出诊断包,协助定位问题。分享前请检查内容,移除不希望公开的信息。 + +需要连接外部 AI 工具时,可查看 [MCP 连接指南](docs/mcp-connection.md)。 + +开发与贡献请参阅 [开发指南](docs/development.md) 和 [开发文档索引](docs/README.md)。 + +提交问题或代码见 [贡献指南](CONTRIBUTING.md),安全问题见 [安全报告说明](SECURITY.md),依赖和发行包许可见 [第三方说明](THIRD_PARTY_NOTICES.md)。 diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..145706f --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,9 @@ +# 安全报告 + +项目处于开发阶段,目前没有长期支持版本。安全修复优先进入主分支;正式发行版本的支持范围将在发布时说明。 + +发现凭据泄露、未授权的工具执行、项目路径访问或其他安全问题时,请使用仓库的 [私有漏洞报告入口](https://github.com/lingjhf/cutdex/security/advisories/new)。如果入口不可用,请先开一个不包含漏洞细节的 Issue,请维护者提供私密报告渠道。不要将漏洞细节、API Key、个人媒体、完整项目或诊断包发到公开讨论区。 + +报告中提供受影响的版本或提交、平台、最小复现步骤和可能的影响。复现使用测试凭据与合成素材;凭据已经泄露时应立即在所属服务撤销并替换。 + +请描述问题在 Cutdex 中的触发方式,以及是否涉及素材导入、项目读写、AI 工具调用或应用更新,便于定位影响范围。 diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md new file mode 100644 index 0000000..9fc0733 --- /dev/null +++ b/THIRD_PARTY_NOTICES.md @@ -0,0 +1,9 @@ +# 第三方依赖与素材 + +本仓库自己的应用代码和内部包采用 [MIT 许可证](LICENSE)。该许可证不覆盖第三方依赖、原生运行包和另行下载的模型;这些内容遵循各自的许可证。 + +Flutter/Dart 依赖及解析版本记录在 `pubspec.yaml`、内部包的 `pubspec.yaml` 与 `pubspec.lock` 中。应用通过 Flutter 的许可证登记机制提供依赖许可证;生成发行包时仍需核对实际捆绑内容。 + +应用发行包捆绑的媒体处理库、推理工具和模型遵循各自的许可与再分发要求。打包时保留随附的许可证和通知文件;不能用本仓库的 MIT 许可替代。 + +仓库中的测试不附带个人媒体或模型。新增第三方素材、字体或代码时,应一同记录来源和许可证,并保留要求的版权声明。 diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100644 index 0000000..67c4f6d --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1,26 @@ +include: package:flutter_lints/flutter.yaml + +analyzer: + language: + strict-casts: true + strict-inference: true + strict-raw-types: true + exclude: + - build/** + - android/** + - ios/** + - web/** + - windows/** + - macos/** + - linux/** + - packages/*/example/** + +plugins: + riverpod_lint: ^3.1.9 + +linter: + rules: + unnecessary_lambdas: true + unnecessary_parenthesis: true + unnecessary_statements: true + prefer_const_constructors: true diff --git a/android/.gitignore b/android/.gitignore new file mode 100644 index 0000000..be3943c --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,14 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java +.cxx/ + +# Remember to never publicly share your keystore. +# See https://flutter.dev/to/reference-keystore +key.properties +**/*.keystore +**/*.jks diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts new file mode 100644 index 0000000..c22ff04 --- /dev/null +++ b/android/app/build.gradle.kts @@ -0,0 +1,88 @@ +plugins { + id("com.android.application") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +// Match native libraries to Flutter's requested targets; the media runtime is 64-bit only. +val supportedAndroidAbis = mapOf( + "android-arm64" to "arm64-v8a", + "android-x64" to "x86_64", +) +val requestedAndroidPlatforms = (findProperty("target-platform") as? String) + ?.split(",") ?: supportedAndroidAbis.keys.toList() +val enabledAndroidAbis = requestedAndroidPlatforms.mapNotNull(supportedAndroidAbis::get) +check(enabledAndroidAbis.isNotEmpty()) { + "Cutdex requires Android ARM64 or x86_64. Use --target-platform android-arm64,android-x64." +} + +android { + namespace = "com.example.cutdex" + compileSdk = flutter.compileSdkVersion + ndkVersion = flutter.ndkVersion + + buildFeatures { + resValues = true + } + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "com.example.cutdex" + // You can update the following values to match your application needs. + // For more information, see: https://flutter.dev/to/review-gradle-config. + minSdk = 31 + targetSdk = flutter.targetSdkVersion + // Uses the version code from pubspec.yaml. When using split APKs, 1000 * ABI_VERSION + // is added automatically by Flutter. (https://developer.android.com/studio/build/configure-apk-splits#configure-APK-versions) + // You can force using the value of versionCode by specifying the `-P force-version-code-ignoring-abi=true` + // flag during build. + versionCode = flutter.versionCode + versionName = flutter.versionName + } + + flavorDimensions += "environment" + productFlavors { + create("development") { + dimension = "environment" + applicationIdSuffix = ".dev" + resValue("string", "app_name", "Cutdex Dev") + } + create("production") { + dimension = "environment" + resValue("string", "app_name", "Cutdex") + } + } + + buildTypes { + release { + // TODO: Add your own signing config for the release build. + // Signing with the debug keys for now, so `flutter run --release` works. + signingConfig = signingConfigs.getByName("debug") + } + } + + if (splits.abi.isEnable) { + splits.abi.reset() + splits.abi.include(*enabledAndroidAbis.toTypedArray()) + } else { + defaultConfig.ndk { + abiFilters.clear() + abiFilters += enabledAndroidAbis + } + } +} + +kotlin { + compilerOptions { + jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17 + } +} + +flutter { + source = "../.." +} diff --git a/android/app/src/debug/AndroidManifest.xml b/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/app/src/development/res/mipmap-nodpi/cutdex_launcher.png b/android/app/src/development/res/mipmap-nodpi/cutdex_launcher.png new file mode 100644 index 0000000..af990a4 Binary files /dev/null and b/android/app/src/development/res/mipmap-nodpi/cutdex_launcher.png differ diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..eddaafc --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/android/app/src/main/kotlin/com/example/cutdex/MainActivity.kt b/android/app/src/main/kotlin/com/example/cutdex/MainActivity.kt new file mode 100644 index 0000000..b1e8acb --- /dev/null +++ b/android/app/src/main/kotlin/com/example/cutdex/MainActivity.kt @@ -0,0 +1,5 @@ +package com.example.cutdex + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity : FlutterActivity() diff --git a/android/app/src/main/res/drawable-v21/launch_background.xml b/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000..f74085f --- /dev/null +++ b/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/drawable/launch_background.xml b/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000..304732f --- /dev/null +++ b/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/values-night/styles.xml b/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..06952be --- /dev/null +++ b/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/main/res/values/styles.xml b/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..cb1ef88 --- /dev/null +++ b/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/production/res/mipmap-nodpi/cutdex_launcher.png b/android/app/src/production/res/mipmap-nodpi/cutdex_launcher.png new file mode 100644 index 0000000..eea8497 Binary files /dev/null and b/android/app/src/production/res/mipmap-nodpi/cutdex_launcher.png differ diff --git a/android/app/src/profile/AndroidManifest.xml b/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/android/build.gradle.kts b/android/build.gradle.kts new file mode 100644 index 0000000..dbee657 --- /dev/null +++ b/android/build.gradle.kts @@ -0,0 +1,24 @@ +allprojects { + repositories { + google() + mavenCentral() + } +} + +val newBuildDir: Directory = + rootProject.layout.buildDirectory + .dir("../../build") + .get() +rootProject.layout.buildDirectory.value(newBuildDir) + +subprojects { + val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name) + project.layout.buildDirectory.value(newSubprojectBuildDir) +} +subprojects { + project.evaluationDependsOn(":app") +} + +tasks.register("clean") { + delete(rootProject.layout.buildDirectory) +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 0000000..e96108c --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,6 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true +# This newDsl flag was added by the Flutter template +android.newDsl=false +# This builtInKotlin flag was added by the Flutter template +android.builtInKotlin=false diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..f3ed1be --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-all.zip +distributionSha256Sum=708d2c6ecc97ca9a11838ef64a6c2301151b8dd10387e22dc1a12c30557cab5b diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts new file mode 100644 index 0000000..cd302e3 --- /dev/null +++ b/android/settings.gradle.kts @@ -0,0 +1,35 @@ +pluginManagement { + val flutterSdkPath = + run { + val properties = java.util.Properties() + file("local.properties").inputStream().use { properties.load(it) } + val flutterSdkPath = properties.getProperty("flutter.sdk") + require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" } + flutterSdkPath + } + + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +plugins { + id("dev.flutter.flutter-plugin-loader") version "1.0.0" + id("com.android.application") version "9.2.1" apply false + id("org.jetbrains.kotlin.android") version "2.3.20" apply false +} + +include(":app") + +// Native source development is opt-in; default resolution uses GitHub Packages. +providers.gradleProperty("cutdex.android.path").orNull?.let { nativePath -> + includeBuild(nativePath) { + dependencySubstitution { + substitute(module("dev.cutdex:cutdex-android")).using(project(":cutdex-android")) + } + } +} diff --git a/assets/branding/cutdex-icon-development-macos.png b/assets/branding/cutdex-icon-development-macos.png new file mode 100644 index 0000000..a3e31f1 Binary files /dev/null and b/assets/branding/cutdex-icon-development-macos.png differ diff --git a/assets/branding/cutdex-icon-development-small.png b/assets/branding/cutdex-icon-development-small.png new file mode 100644 index 0000000..096e1fd Binary files /dev/null and b/assets/branding/cutdex-icon-development-small.png differ diff --git a/assets/branding/cutdex-icon-development.png b/assets/branding/cutdex-icon-development.png new file mode 100644 index 0000000..af990a4 Binary files /dev/null and b/assets/branding/cutdex-icon-development.png differ diff --git a/assets/branding/cutdex-icon-macos.png b/assets/branding/cutdex-icon-macos.png new file mode 100644 index 0000000..5755feb Binary files /dev/null and b/assets/branding/cutdex-icon-macos.png differ diff --git a/assets/branding/cutdex-icon-small.png b/assets/branding/cutdex-icon-small.png new file mode 100644 index 0000000..f9d091e Binary files /dev/null and b/assets/branding/cutdex-icon-small.png differ diff --git a/assets/branding/cutdex-icon.png b/assets/branding/cutdex-icon.png new file mode 100644 index 0000000..ad83608 Binary files /dev/null and b/assets/branding/cutdex-icon.png differ diff --git a/build.yaml b/build.yaml new file mode 100644 index 0000000..e4a5e84 --- /dev/null +++ b/build.yaml @@ -0,0 +1,9 @@ +targets: + $default: + builders: + freezed: + options: + format: true + json_serializable: + options: + explicit_to_json: true diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..da9158b --- /dev/null +++ b/docs/README.md @@ -0,0 +1,12 @@ +# 文档 + +平台、功能和基本使用见 [项目 README](../README.md)。 + +| 需要做什么 | 入口 | +| --- | --- | +| 参与应用开发 | [开发指南](development.md) | +| 运行测试、准备真实素材 | [测试指南](testing.md) | +| 连接外部 AI 工具 | [MCP 连接指南](mcp-connection.md) | +| 使用构建、发布与诊断脚本 | [仓库工具](../tool/README.md) | + +文档记录使用步骤、开发入口和可复现的验证方法。界面尺寸、样式常量和内部状态细节以代码为准;依赖包的 API、协议与文件格式以所属包文档为准。 diff --git a/docs/development.md b/docs/development.md new file mode 100644 index 0000000..b310285 --- /dev/null +++ b/docs/development.md @@ -0,0 +1,69 @@ +# 开发指南 + +应用功能与使用步骤见 [README](../README.md),连接外部 AI 工具见 [MCP 连接指南](mcp-connection.md),验证应用行为见 [测试指南](testing.md)。 + +## 准备环境 + +使用满足 `pubspec.yaml` 约束的 Flutter 与 Dart 工具链,并安装目标平台的开发工具。仓库脚本使用 Python 3.11+。 + +应用依赖与版本以 `pubspec.yaml`、`pubspec.lock` 为准,通过 `flutter pub get` 获取。依赖的访问权限、配置和工具链要求按各依赖自身的文档准备;依赖未就绪时无法完成应用构建。 + +本地联调其他包时,可参考 `pubspec_overrides.yaml.example` 创建覆盖配置。覆盖文件只用于本机开发,不提交。 + +## 运行应用 + +在 Cutdex 根目录运行: + +```sh +flutter pub get +dart run build_runner build +flutter run -d macos --flavor development +``` + +Android、macOS、Windows 配置了 development 与 production flavor,默认是 development。按目标平台替换设备参数。iOS 使用 `Runner` scheme。构建或集成测试前,退出占用同一构建目录的应用。 + +Android 支持 ARM64 和 x86_64。按架构拆分 APK 时显式指定目标: + +```sh +flutter build apk --flavor development --split-per-abi --target-platform android-arm64,android-x64 +``` + +字幕、翻译和抠像的功能验证需要相应资源。按应用提示准备资源,并使用合成或允许再分发的素材;不要把个人媒体、模型服务凭据或项目文件提交到仓库。 + +## 修改应用功能 + +| 功能 | 代码入口 | +| --- | --- | +| 项目、时间线与自动保存 | `lib/workspace/` | +| 素材导入、字幕与后台任务 | `lib/features/media/` | +| 预览与全屏播放 | `lib/features/preview/` | +| 时间线交互与片段属性 | `lib/features/timeline/`、`lib/features/properties/` | +| AI 助手与聊天 | `lib/features/assistant/` | +| 设置、诊断与更新界面 | `lib/features/settings/` | +| 桌面、平板与手机布局 | `lib/app/shells/` | + +应用根目录是 Pub workspace。[cutdex_ui](../packages/cutdex_ui/README.md) 维护通用组件与基础主题,[cutdex_native](../packages/cutdex_native/README.md) 维护设备信息与桌面交互。应用集成入口在 `lib/integrations/`,共享布局与业务样式在 `lib/shared/`。 + +修改剪辑操作时,检查预览、保存、撤销和重做;修改素材导入时,检查文件访问及项目重新打开后的可用性;修改后台任务时,检查完成、失败和取消后的界面状态。 + +## 文案与代码生成 + +修改需要生成代码的模型后,在所属包目录运行 `dart run build_runner build`,将生成文件与源码一起提交。 + +修改文案时更新 `lib/l10n/` 中的 ARB,再运行 `flutter gen-l10n`。简体中文同时维护 `app_zh.arb` 和 `app_zh_Hans.arb`;增加界面语言时更新语言选择与 Apple bundle 声明。 + +执行 [测试指南](testing.md) 中适用的检查。界面改动还需检查桌面、平板和手机布局,以及明暗主题和不同语言下的表现。 + +## 诊断与问题复现 + +在“设置 → 通用 → 诊断”中导出诊断包,结合触发步骤检查编辑、保存、预览、AI 请求和后台任务的错误。诊断包用于辅助定位,不包含完整项目或原始媒体,也不会自动上传。 + +提交问题时附上应用版本、平台、最小操作步骤和可复现的测试素材说明。分享诊断包前检查内容,移除不希望公开的信息;不要将模型凭据、聊天正文或个人媒体放入公开问题。 + +## 构建发行包 + +构建、打包和更新验证入口见 [仓库工具](../tool/README.md)。完成集成测试后,使用 `lib/main.dart` 重建正式应用,避免分发测试入口。 + +Android release 当前使用调试签名,正式分发前需配置发布签名;production flavor 本身不提供发布证书。 + +macOS 默认 ad-hoc 签名。开发证书配置放在 `macos/Runner/Configs/Signing.local.xcconfig`;iOS 真机的 Team 设置放在 `ios/Flutter/Signing.local.xcconfig`。这些文件已忽略,凭据与私钥保留在本地或 CI 私密配置中。 diff --git a/docs/mcp-connection.md b/docs/mcp-connection.md new file mode 100644 index 0000000..7c10f0c --- /dev/null +++ b/docs/mcp-connection.md @@ -0,0 +1,15 @@ +# 连接外部 AI 工具 + +支持 MCP 的客户端可以访问 Cutdex 当前工作区的编辑工具。需要保持 Cutdex 运行,并打开希望操作的项目。 + +## 客户端配置 + +MCP 默认关闭,在设置中启用并获取端口和访问令牌。外部客户端设置 `CUTDEX_MCP_PORT`、`CUTDEX_MCP_TOKEN`,以本仓库为工作目录运行: + +```sh +dart run tool/mcp_stdio.dart +``` + +连接通过本机端口访问正在运行的 Cutdex。工具范围由当前工作区和可用功能决定,参数以客户端发现结果为准。 + +当前启动器依赖 Dart,以 Cutdex 源码目录运行。它尚未作为独立客户端程序随安装包分发。启用服务不会自动完成外部客户端配置,需将启动命令、端口与令牌填入客户端。 diff --git a/docs/testing.md b/docs/testing.md new file mode 100644 index 0000000..0d1566c --- /dev/null +++ b/docs/testing.md @@ -0,0 +1,49 @@ +# 测试指南 + +先完成 [开发环境准备](development.md#准备环境),在 cutdex 根目录运行。测试使用临时项目和非个人素材。 + +## 日常检查 + +源码检查工具检查文件卫生、文档本地链接和内部包边界;相关回归测试见 [贡献指南](../CONTRIBUTING.md)。完整 CLI 工具测试仍需解析应用依赖。源码检查不编译应用,也不代表 Flutter 或原生集成验证通过。 + +```sh +python3 tool/check_public_repository.py +``` + +该检查覆盖 Git 跟踪及未被忽略的待提交文件,可识别常见凭据格式、误纳入的本地产物和失效的本地文档链接;不代替 Git 历史审计,也不能识别任意自定义密码。 + +```sh +flutter pub get +dart analyze --fatal-infos +flutter test test packages/cutdex_ui/test packages/cutdex_native/test +# Python 3.11+ +python3 tool/check.py +``` + +| 入口 | 验证范围 | +| --- | --- | +| `test/` | 应用逻辑、Widget、会话接线与项目读回;使用模拟模型和平台通道 | +| `packages/*/test/` | 内部包组件、原生事件接线与生命周期 | +| [integration_test](../integration_test/README.md) | 对应平台上的真实预览、媒体编辑与处理任务 | +| [tool](../tool/README.md) | 脚本检查、发布包验证和平台诊断 | + +App 测试验证宿主行为,底层算法、协议及插件生命周期在所属包测试。普通测试通过不代表真实播放或模型质量已经验证。 + +## 生成文件 + +```sh +dart run build_runner build +# UI 模型修改后,在 packages/cutdex_ui 中运行相同生成命令 +flutter gen-l10n +flutter test test/generated_code_test.dart test/localization_resources_test.dart +``` + +生成文件应与源码一同提交。生成校验会重新生成应用与 UI 包并比较前后内容,同时检查应用生成文件的跟踪状态;不要暂存无关文件来掩盖失败。 + +## 真实环境 + +集成测试的设备、输入素材、配置与输出参数见其 [README](../integration_test/README.md)。先退出同一构建目录中的应用;验证程序不用于分发,结束后恢复默认应用入口构建。 + +普通测试中的可选真实模型回归使用环境变量:`CUTDEX_ACCEPTANCE_LIVE` 和 `CUTDEX_BEAT_LIVE` 指向对应测试的配置 JSON,`CUTDEX_ASR_FIXTURE` 指定语音素材。配置字段以测试读取代码为准,素材、模型及凭据放在仓库外。 + +记录实际运行的平台、输入、失败和跳过原因。缺少模型、设备或素材时明确跳过;失败先核对夹具与当前契约,不通过放宽断言或无条件跳过掩盖问题。 diff --git a/integration_test/README.md b/integration_test/README.md new file mode 100644 index 0000000..6d5f667 --- /dev/null +++ b/integration_test/README.md @@ -0,0 +1,418 @@ +# Application integration tests + +`integration_test/` contains opt-in tests for the real application and native +backends. `test_driver/integration_test.dart` is the host driver used by +`flutter drive` for Profile measurements. Both directories contain test source; +media, models, reports and credentials are supplied locally and stay outside +version control. Normal release builds use `lib/main.dart`. + +## Desktop plugin registration + +`native_desktop_plugins_test.dart` checks the real application's registration of +window chrome, dynamically configured file destinations, and the macOS fullscreen +channel. It requires no media or models and does not simulate Finder/Explorer drops. + +```sh +flutter test integration_test/native_desktop_plugins_test.dart -d macos --flavor development +``` + +Use `-d windows` on Windows. Rebuild the normal application entry point afterwards. + +## Desktop processing + +`processing_e2e_test.dart` checks Cutdex's connection to real desktop processing: +app resource configuration, applying results to the timeline, and cancellation or +closing the owning session. + +Provide an external processing package, installed models in the app's resource +directory, and a short speech fixture. A local Dart-define JSON specifies +`CUTDEX_PROCESSING_ROOT` and `CUTDEX_ASR_FIXTURE`: + +```sh +flutter test integration_test/processing_e2e_test.dart -d macos --flavor development \ + --dart-define-from-file=/absolute/path/to/processing-e2e.json +``` + +Use `-d windows` on Windows. The test skips without a configured source. It does not +download models. Check that completed results appear in the timeline and that +cancelled tasks do not apply results to a closed session. + +## Editing diagnostics and logging measurements + +`edit_diagnostics_test.dart` mounts the production timeline toolbar, speed slider +and native preview. Supply a video with audio of at least 25 seconds; generated +H.264/AAC test media is suitable. The test creates isolated projects, an in-memory +application database, per-run diagnostic storage, exports and `results.json` under +the output directory. It never opens a user project or changes the source media. + +Four controlled failures are injected at the authoritative commit boundary: +split, left/right trim and speed adjustment. Each failure must export the original +stack, operation ID, clip/timeline/project IDs and unchanged before/after versions. +Recovery then repeats the same UI path without the injected failure. These are +fault-injection checks with real media and native playback, not evidence that the +native backend itself produced these failures. + +```sh +flutter drive --profile -d macos --flavor production \ + --driver=test_driver/integration_test.dart \ + --target=integration_test/edit_diagnostics_test.dart \ + --dart-define=CUTDEX_TEST_SOURCE=/absolute/path/to/generated-720p30.mp4 \ + --dart-define=CUTDEX_TEST_REPORT=/absolute/path/to/output/profile +``` + +After a native-decoder warmup, six measured runs alternate the same-build +application diagnostic recording off/on (three pairs, alternating pair order). Each run uses +the toolbar to split and trim with undo, drags the speed slider, plays the edited +clip, and restores 1×. Reports include Flutter build/raster frame percentiles, +frames over 16.67 ms, synchronous diagnostic-call costs and durable log +appends/bytes. Bounded 16 ms pumps collect rendering samples during playback. +Flutter frame timings do not measure the independently rendered native video or +physical display refresh. No latency/FPS guarantee follows from this small sample. + +macOS 14.4+ can separately measure the mounted sample-buffer renderer's delivered +and dropped frames in an opt-in **Debug** run. Keep its window visible and +unoccluded throughout the observation; the test checks both conditions. This +native diagnostics channel is compiled only in Debug, so its frame statistics +must not be presented as Profile measurements. + +```sh +CUTDEX_PREVIEW_CADENCE_DIAGNOSTICS=1 flutter drive --debug -d macos --flavor development \ + --driver=test_driver/integration_test.dart \ + --target=integration_test/edit_diagnostics_test.dart \ + --dart-define=CUTDEX_DIAGNOSTIC_CADENCE=true \ + --dart-define=CUTDEX_TEST_SOURCE=/absolute/path/to/generated-720p30.mp4 \ + --dart-define=CUTDEX_TEST_REPORT=/absolute/path/to/output/native-debug +``` + +Retain failed reports and their logs. Rebuild `lib/main.dart` for each tested +flavor afterwards, since integration entry points are not distribution builds. + +## Windows + +Run against the original files in a separate output directory. The Windows +test mounts the real editor panels, imports through the production workspace, +and exercises the play/pause and split controls and speed slider. It also checks +independent scale/rotation/position transforms, multi-channel keyframe interpolation, +mask animation and stack ordering, audio edits, exported pixels and PCM, and exact +saved project data after close/reopen. Segmented speed changes also check the +source clock, source duration and undo. No playback backend is mocked. ISO import is accepted only +when the native backend can probe an unprotected video stream. + +```powershell +flutter test integration_test/windows_real_media_test.dart -d windows ` + --dart-define=CUTDEX_VALIDATION_SOURCE='D:\validation\media-originals' ` + --dart-define=CUTDEX_VALIDATION_ROOT='D:\validation\windows-editing' +``` + +`CUTDEX_VALIDATION_FILTER` optionally selects filenames containing any of the +comma-separated substrings. +`CUTDEX_VALIDATION_PREVIEW_SECONDS` sets each full-source playback observation +(default 2); use 30 for a longer frame-delivery audit. Reports include dropped +native frames, delivered frames per second and the maximum frame gap. These +measure native preview delivery, not physical monitor refresh or speaker sound. +`CUTDEX_VALIDATION_SOURCE_ROOTS` accepts semicolon-separated source directories +when validating multiple collections. For Flutter performance measurements use +`flutter drive --profile -d windows --flavor production +--driver=test_driver/integration_test.dart +--target=integration_test/windows_real_media_test.dart` with the same Dart +defines: `flutter test` forces Debug mode. Playback observations additionally +record process/time boundaries and Flutter build/raster timings for correlation +with actual Windows audio-session peaks. Native textures can redraw without Dart +frames, so the observation uses live frames and a continuous 16 ms viewport +refresh to collect build/raster timings. Rendering timings measure framework +work, rather than proving the physical display refreshed every source frame. +The test scans subdirectories, creates one timeline per source, records each +stage in `results.json`, and checks that source size and modification time stay +unchanged. Full-duration preview checks sample 60 seconds, quarter, middle and end; +editing checks use short clips. Exports use the selected video and audio tracks. +Frame counters verify native frame delivery, +without measuring physical display latency or judging speaker output. Keep the +output outside the media directory and rebuild the normal `lib/main.dart` +application after running an integration target. + +The harness opens another project at the editor's 50-timeline limit. For a +source with independently confirmed undecodable audio, a filtered diagnostic +can set `CUTDEX_VALIDATION_FULL_PREVIEW_AUDIO=false` to check full-source video +preview separately. The short editing clip still includes audio. Record the +failed audio interval alongside this diagnostic; do not report it as successful +full-source audio playback. + +`CUTDEX_VALIDATION_FULL_PREVIEW_MUTE=true` keeps the full-source audio layer +but sets its gain to zero and verifies the native +muted-audio path. Short-clip audio edits still run normally. Constant mute must +avoid decoding unreadable audio; keyed volume curves remain eligible to play. + +`CUTDEX_VALIDATION_MUTE_DAMAGED_ASF=true` restricts that full-source mute diagnostic +to ASF files in this corpus. Use it only alongside independent evidence of source +audio damage. The report identifies every muted source; all selected editing +clips still include audio. An accepted play command alone is insufficient: +checks wait for clock/frame progress and inspect delayed playback errors. + +`CUTDEX_VALIDATION_LONG_SPEED_ONLY=true` imports a full-length clip (the common +audio/video duration minus 100 ms), applies exact 2×, 0.5× and 1× edits, and observes +playback from the start and across the 30.72-second preview-window boundary. It +checks unchanged source timing, timeline duration and exact project data after +close/reopen. This diagnostic skips the short-clip transform/mask/export matrix; +run the normal matrix separately. It samples full-length edited clips and does +not play or export every frame of the original movies. + +## Windows seek measurements + +`windows_seek_latency_test.dart` measures real Profile preview requests and continuous +playhead dragging with any playable video at least five seconds long. It probes the +source duration and scales the seek points and drag spans to that duration. Provide +`CUTDEX_SEEK_SOURCE` and `CUTDEX_SEEK_REPORT`; run it with the shared +`test_driver/integration_test.dart` entry point using `flutter drive --profile`. + +```powershell +flutter drive --profile --flavor production -d windows ` + --driver=test_driver/integration_test.dart ` + --target=integration_test/windows_seek_latency_test.dart ` + --dart-define=CUTDEX_SEEK_SOURCE='D:/validation/media-originals/video.mp4' ` + --dart-define=CUTDEX_SEEK_REPORT='D:/validation/results/editor-seek.json' +``` + +The report records request acknowledgment, pump timing, observed native positions +and the final release position. It does not measure physical display latency or +independently verify pixels/audio. For before/after comparisons, preserve both +complete builds, use identical media and run serially without concurrent builds +or exports. This test target is for measurement, not application distribution. + +## Windows audio samples + +`windows_audio_media_test.dart` validates original audio files with the production +source preview, import service, editor widgets and Windows runtime. It creates +isolated projects and settings, checks source SHA-256 after each file, and writes +an incremental `results.json` report. The source should contain audio-only files +longer than ten seconds, with audible content in the 2–6 second edit interval. + +```powershell +flutter test integration_test/windows_audio_media_test.dart -d windows ` + --dart-define=CUTDEX_VALIDATION_SOURCE=D:/validation/audio-originals ` + --dart-define=CUTDEX_VALIDATION_ROOT=D:/validation/audio-results +``` + +Each file exercises full-source waveform decoding, preview seeks near the start, +middle and end, playback/pause, import, editor scrubbing, split/undo/redo, speed +slider, gain/mute, audio gain keyframes and saved keyframe records. Six native +H.264/AAC exports check baseline duration, 2×/0.5× duration, -6 dB RMS ratio, +silence and the keyframe fade envelope. The visual output is a black canvas for +audio-only timelines. Masks and position keyframes use the video validation test. + +`CUTDEX_VALIDATION_FILTER` selects comma-separated filename substrings. +`CUTDEX_VALIDATION_METADATA_ONLY=true` runs just the probe and full waveform +checks for faster diagnosis. Speaker sound is not measured by these assertions. +Keep downloaded external samples outside the repository and retain their source +URLs, hashes and license attribution. Rebuild `lib/main.dart` for distribution +after integration testing. + +## Android physical device + +`android_real_media_test.dart` owns the editing workflow. Helpers in `support/` +handle incremental reports (`real_media_report.dart`), full-length preview +measurements (`android_preview_measurement.dart`) and edited-export pixel/audio +checks (`real_media_export_checks.dart`). + +The suite first checks the application's real device-information and version +channels, then runs the media workflow. Its editor harness stacks the preview and +properties on narrow phone displays. It uses an isolated in-memory settings +database and creates a separate project. + +Use the debug development app's private directory to avoid scoped-storage and +device-specific restrictions on directories created by `adb push`. Install the +normal APK before copying fixtures; `-d` permits a debug version-code downgrade +after installing an ABI split, without deleting the app's data. Keep complete +originals on the host. On a POSIX shell: + +```sh +flutter build apk --debug --flavor development +adb -s DEVICE_SERIAL install -r -d build/app/outputs/flutter-apk/app-development-debug.apk +adb -s DEVICE_SERIAL shell run-as com.example.cutdex.dev mkdir -p files/real-media files/real-validation +adb -s DEVICE_SERIAL shell -T run-as com.example.cutdex.dev tee files/real-media/source.mp4 \ + < /absolute/path/to/source.mp4 > /dev/null +flutter test integration_test/android_real_media_test.dart -d DEVICE_SERIAL \ + --flavor development --no-uninstall \ + --dart-define=CUTDEX_VALIDATION_SOURCE=/data/user/0/com.example.cutdex.dev/files/real-media \ + --dart-define=CUTDEX_VALIDATION_ROOT=/data/user/0/com.example.cutdex.dev/files/real-validation +``` + +Keep `--no-uninstall`: uninstalling also removes copied fixtures and validation +reports. With `flutter drive`, use `--debug --keep-app-running` to retain them. +An optional +`CUTDEX_VALIDATION_FILTER` selects filenames containing any comma-separated +substring. `CUTDEX_VALIDATION_SAMPLE_START` selects the edit sample start in +seconds (default 60); use a visibly nonblack scene for pixel comparisons. +`CUTDEX_VALIDATION_PREVIEW_WIDTH` / `CUTDEX_VALIDATION_PREVIEW_HEIGHT` set the +native preview render size and project canvas (defaults 640 / 360). Set 1920 / +1080 for a full-HD preview run. `CUTDEX_VALIDATION_OBSERVATION_SECONDS` sets each +full-source playback window (default 2); use 30 for a longer observation. The +tail window leaves enough media for the configured observation. Reports include +seek latency, surface presentations per second and timeline progress. Maximum +frame gap is cumulative over the session. These counters do not measure unique +decoded pictures, physical display refresh or speaker synchronization. Exports +remain short 320×180 functional checks regardless of preview size. +`CUTDEX_VALIDATION_PREVIEW_ONLY=true` runs probing and the three full-source +preview windows, then checks the source file and closes the controller. This +diagnostic skips editing and exports; its report must not be counted as an +editing validation run. `CUTDEX_VALIDATION_CONCURRENT_IO` records whether fixture +transfer is running alongside playback so that such runs can be excluded from +controlled performance comparisons. +Incomplete `.xltd` downloads and torrent descriptors are excluded. + +The test verifies full-duration preview seeks at the start, middle and end, +then imports each original, selects eight seconds and exercises playback, +scrubbing, splitting, undo/redo and the 2×/0.5×/normal speed slider. It uses the +editor command service for audio gain/mute, transform keyframes and rectangular, +elliptical, feathered and inverted masks. Native exports verify duration, masked +pixels and the RMS ratio for -6 dB audio; additional audio streams are exported +and decoded separately. Each completed stage updates `results.json`. +An additional export keeps transform keyframes without masks so that native +composition is checked independently of masked rendering. Compare its one-second +frame with the baseline shifted by the authored position, as well as its gain. +Preview controllers are closed between sources to bound memory. +Full-source playback allows up to ten seconds for frame progress and records +observation time and slow playback separately. Short clips that reach their +natural end during polling are accepted only with both clock and frame progress. + +Frame counters measure delivery to the native surface writer. The short samples +do not constitute watching the entire movie, measuring physical display latency, +or independently judging audible sound through the tablet speakers. + +Restore the normal development APK with target `lib/main.dart` after testing, +using `adb install -r` to preserve fixtures and reports. + +## macOS + +Run the real macOS editor and native playback backend against a local media +directory. This opt-in test creates a separate project and one timeline per +video source, references originals without copying them, and writes an incremental +JSON report into the output directory. It does not restore or edit an existing +project. The test uses an in-memory recent-project registry and does not write +to the normal application database. Without the required Dart defines, it skips. + +```sh +flutter test integration_test/downloads_workflow_test.dart -d macos \ + --flavor development \ + --dart-define=CUTDEX_VALIDATION_SOURCE=/absolute/path/to/media \ + --dart-define=CUTDEX_VALIDATION_ROOT=/absolute/path/to/output +``` + +`CUTDEX_VALIDATION_FILTER` optionally selects filenames containing a substring +for diagnosis. Omit it for the complete directory run. Set +`--dart-define=CUTDEX_VALIDATION_DIRECT_DROP=true` to exercise external +file-drop messages directly on the timeline, including import into the media +library, instead of importing first and dragging a library tile. + +The test sends the same native file-drop messages as Finder to the actual +media panel, then uses pointer gestures to drag each tile into the timeline. +It exercises the play/pause controls, split toolbar, 2× and 0.5× speed slider, +and detach audio context menu, checks native playback after edits, and verifies +saved timeline structure. File-drop messages are injected; this test does not +drive Finder itself. Only the AppKit menu bridge is disabled inside the test, +to exercise the application's existing Flutter context-menu fallback. No +playback or import backend is mocked. Verify AppKit menu selection separately +in the normally launched application. + +Playback checks are short samples around edits. They verify the transport clock +and errors, but do not measure sustained frame cadence or physical display +latency. Use `downloads_preview_cadence_test.dart` for mounted renderer frame cadence +and pause delivery checks. It requires macOS 14.4+, the host environment variable +`CUTDEX_PREVIEW_CADENCE_DIAGNOSTICS=1`, the same source/output Dart defines, and +a visible window activated through macOS accessibility. + +## iPhone native media validation + +`ios_device_test.dart` runs seven shared regressions in one installation: real-media +playback with audio, nested/reverse/freeze/transition composition, image/canvas +composition, grouped keyframes and export, painted thumbnails, repeated canvas +drags, and the full application playback/editing lifecycle. The application test +uses the phone's Cut navigation destination when present. Desktop packaged-worker +capability fixtures, Finder drops, and macOS display-cadence diagnostics are outside +this iPhone suite; it does not validate model inference or physical display latency. + +Use an unlocked developer-enabled iPhone and a valid signing team. Select the iOS +`Runner` scheme explicitly because the default `development` flavor belongs to the +other platforms. First install the test host using the shared empty-timeline test: + +```sh +flutter test integration_test/preview_startup_test.dart -d \ + --flavor Runner --no-uninstall \ + --plain-name 'opening a timeline initializes native preview through App providers' +``` + +Copy a synthetic or nonpersonal H.264 Rec.709 + AAC fixture at least 30 seconds long +into the installed app's sandbox. Keeping the app installed preserves this fixture +through subsequent test builds: + +```sh +xcrun devicectl device copy to --device \ + --source /absolute/path/to/source.mp4 \ + --destination Documents/cutdex-validation-source.mp4 \ + --domain-type appDataContainer --domain-identifier com.example.cutdex +flutter test integration_test/ios_device_test.dart -d \ + --flavor Runner --no-uninstall --reporter expanded \ + --dart-define=CUTDEX_TEST_SOURCE_DOCUMENT=cutdex-validation-source.mp4 \ + --dart-define=CUTDEX_TEST_OUTPUT=ios-keyframes +``` + +The shared fixture helper also preserves `CUTDEX_TEST_SOURCE` for host paths and +`CUTDEX_TEST_SOURCE_BASE64` for small embedded fixtures. Large Base64 defines can +exceed Xcode's command/environment size limit; use the sandbox copy for full videos. +Temporary embedded fixtures are deleted after the owning test. The explicitly +copied sandbox fixture and optional keyframe artifacts remain available for inspection. +`KEYFRAME_ARTIFACTS`, `THUMBNAIL_TIMING`, `DRAG_TIMING`, and `ACCEPTANCE` lines record +artifact locations and completed phases in the test log. + +The app and native dependency require iOS 17. If a stale generated +`ios/Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage/Package.swift` +still declares iOS 15, align its generated platform declaration to iOS 17 before +retrying. This derived file is ignored; preserve the project's iOS 17 deployment +settings rather than lowering the native package's supported platform. + +## Arbitrary media timebases on macOS + +`media_timebase_drop_test.dart` uses the native probe and the same drop target as +Finder and project assets. It checks provisional placement, committing, exact +saved timeline ticks, playback and long-distance seeks, a three-second native +video/audio export, and undo after trimming. The source must have at least three +seconds of usable video. Supply a file outside the repository with +`CUTDEX_TEST_SOURCE`; `CUTDEX_TEST_OUTPUT` optionally preserves the export. + +```sh +flutter test integration_test/media_timebase_drop_test.dart -d macos \ + --flavor production \ + --dart-define=CUTDEX_TEST_SOURCE=/absolute/path/to/source.mp4 \ + --dart-define=CUTDEX_TEST_OUTPUT=/absolute/path/to/export.mp4 +``` + +The production scheme uses a separate build product from the default development +scheme, so a running development App does not need to be replaced for this test. + +## Android system document import + +`android_document_import_test.dart` opens the real system picker. Use a generated +H.264/AAC MP4 fixture in Downloads and select only that fixture. The test checks +streamed import into managed project storage, duplicate selection, byte identity, +native probing, thumbnails, playback, seeking and a video/audio export. + +```sh +flutter drive --debug --keep-app-running \ + --driver=test_driver/integration_test.dart \ + --target=integration_test/android_document_import_test.dart \ + -d DEVICE_SERIAL --flavor development \ + --dart-define=CUTDEX_DOCUMENT_SELECT=true \ + --dart-define=CUTDEX_DOCUMENT_ROOT=/data/user/0/com.example.cutdex.dev/files/document-validation \ + --dart-define=CUTDEX_DOCUMENT_SHA256=FIXTURE_SHA256 +``` + +After `import.json` reports `complete: true`, remove the generated original from +Downloads. Re-run the same command without `CUTDEX_DOCUMENT_SELECT=true` to start +a new app process and verify the managed original independently of provider +access. `reopen.json` records the repeated hash, playback and export checks. Keep +app data between runs; `--keep-app-running` prevents the driver from uninstalling +the app. Use `adb shell run-as com.example.cutdex.dev` to retrieve reports and +remove the test's own project and exports afterward. + +Some devices disconnect the host driver while DocumentsUI is foreground. In +that case, inspect the original application's log and private JSON reports; a +driver disconnection alone does not establish whether the import succeeded. diff --git a/integration_test/android_document_import_test.dart b/integration_test/android_document_import_test.dart new file mode 100644 index 0000000..18c8460 --- /dev/null +++ b/integration_test/android_document_import_test.dart @@ -0,0 +1,236 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:crypto/crypto.dart'; +import 'package:cutdex/integrations/platform/file_picker.dart'; +import 'package:cutdex/workspace/external_media_import.dart'; +import 'package:cutdex/workspace/media_import.dart'; +import 'package:cutdex/workspace/persistence/project_workspace.dart'; +import 'package:cutdex/workspace/persistence/timeline_creation_names.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; +import 'package:path/path.dart' as p; + +import 'support/android_preview_measurement.dart' show pumpUntil; + +// Opt-in: select only a generated video fixture in the real system picker. +// Re-run without CUTDEX_DOCUMENT_SELECT after deleting the original fixture. +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + const rootPath = String.fromEnvironment('CUTDEX_DOCUMENT_ROOT'); + const select = bool.fromEnvironment('CUTDEX_DOCUMENT_SELECT'); + const expectedHash = String.fromEnvironment('CUTDEX_DOCUMENT_SHA256'); + + testWidgets( + 'Android document import survives provider removal and app restart', + (tester) async { + expect(Platform.isAndroid, isTrue); + expect(rootPath, isNotEmpty); + final root = await Directory(rootPath).create(recursive: true); + final projectPath = p.join(root.path, 'Document.cutdex'); + final reportFile = File( + p.join(root.path, select ? 'import.json' : 'reopen.json'), + ); + final report = {'select': select, 'complete': false}; + void save() => reportFile.writeAsStringSync(jsonEncode(report)); + final runtime = CutdexRuntime(); + ProjectWorkspace createWorkspace() => ProjectWorkspace( + creationNames: const TimelineCreationNames( + timeline: 'Test', + sequence: 'Test', + storyline: 'Test', + ), + runtime: runtime, + ); + var workspace = createWorkspace(); + RuntimeSession? preview; + try { + await tester.pumpWidget( + const MaterialApp( + home: Scaffold( + body: Center(child: Text('Document import validation')), + ), + ), + ); + save(); + if (select) { + debugPrint('DOCUMENT_PICKER_READY'); + final files = await tester.runAsync( + () => const AppFilePicker().pickFiles(allowedExtensions: ['mp4']), + ); + expect(files, hasLength(1)); + expect(files!.single, isA()); + report['sourceUri'] = files.single.sourceUri.toString(); + save(); + await tester.runAsync(() async { + final providerInfo = await runtime.probe( + MediaReference( + id: 'provider-original', + uri: files.single.sourceUri, + ), + ); + expect(providerInfo.videoTrackCount, greaterThan(0)); + expect(providerInfo.audioTrackCount, greaterThan(0)); + report['providerVideoTracks'] = providerInfo.videoTrackCount; + report['providerAudioTracks'] = providerInfo.audioTrackCount; + await workspace.open(projectPath, name: 'Document'); + final projectId = workspace.project!.info.id; + final result = await workspace.importExternalMedia(projectId, [ + files.single, + files.single, + ]); + expect(result.failures, isEmpty); + expect(result.added, 1); + expect(result.duplicates, 1); + final asset = result.assets.single; + expect(asset.storage, AssetStorage.managed); + expect(asset.name, files.single.displayName); + final locations = await const MediaFileResolver().resolve( + files, + result.assets, + ); + expect( + locations[files.single], + contains(mediaSourceLocation(asset)), + ); + report['assetId'] = asset.id; + report['assetName'] = asset.name; + report['managedLocation'] = asset.location; + report['byteLength'] = asset.byteLength; + report['duplicates'] = result.duplicates; + await workspace.close(); + workspace = createWorkspace(); + }); + } + await tester.runAsync(() => workspace.open(projectPath)); + final assets = await tester.runAsync( + () => workspace.project!.listAssets(), + ); + expect(assets, hasLength(1)); + final asset = assets!.single; + expect(asset.storage, AssetStorage.managed); + final uri = (await tester.runAsync( + () => workspace.project!.resolveAsset(asset), + ))!; + expect(uri.scheme, 'file'); + final hash = await tester.runAsync( + () async => (await sha256.bind(File.fromUri(uri).openRead()).first) + .toString(), + ); + if (expectedHash.isNotEmpty) expect(hash, expectedHash); + report['sha256'] = hash; + report['resolvedUri'] = uri.toString(); + final media = MediaReference(id: asset.id, uri: uri); + final info = (await tester.runAsync(() => runtime.probe(media)))!; + expect(info.videoTrackCount, greaterThan(0)); + expect(info.audioTrackCount, greaterThan(0)); + final thumbnail = (await tester.runAsync( + () => runtime.thumbnail( + ThumbnailRequest( + media: media, + time: MediaTime(1, 1), + maximumWidth: 320, + maximumHeight: 180, + ), + ), + ))!; + expect(thumbnail.data, isNotEmpty); + final duration = MediaTime(6, 1); + final range = MediaRange(start: MediaTime(0, 1), duration: duration); + final plan = ExecutionPlan( + duration: duration, + renderSize: RenderSize(320, 180), + frameDuration: MediaTime(1, 30), + media: [media], + visualLayers: [ + VisualLayer( + id: 'video', + mediaId: media.id, + sourceRange: range, + timelineRange: range, + inputColorSpace: RenderColorSpace.rec709, + ), + ], + audioLayers: [ + AudioLayer( + id: 'audio', + mediaId: media.id, + sourceRange: range, + timelineRange: range, + ), + ], + ); + final session = (await tester.runAsync(runtime.createSession))!; + preview = session; + await tester.runAsync(() => session.load(plan)); + await tester.pumpWidget( + MaterialApp( + home: Center( + child: SizedBox( + width: 320, + height: 180, + child: RuntimePreview(session: session), + ), + ), + ), + ); + await pumpUntil( + tester, + () => (session.snapshot?.presentedVideoFrameCount ?? 0) > 0, + 'document first frame', + ); + final before = (await tester.runAsync(session.refresh))!; + await tester.runAsync(session.play); + await tester.runAsync( + () => Future.delayed(const Duration(seconds: 1)), + ); + await tester.pump(); + final playing = (await tester.runAsync(session.refresh))!; + expect(playing.message, isNull); + expect(playing.position.seconds, greaterThan(before.position.seconds)); + expect( + playing.presentedVideoFrameCount, + greaterThan(before.presentedVideoFrameCount ?? 0), + ); + await tester.runAsync(session.pause); + await tester.runAsync(() => session.seek(MediaTime(3, 1))); + final destination = File( + p.join(root.path, select ? 'import-export.mp4' : 'reopen-export.mp4'), + ); + if (await destination.exists()) await destination.delete(); + final exported = (await tester.runAsync( + () => session.export(plan, destination.uri), + ))!; + final exportInfo = (await tester.runAsync( + () => runtime.probe(MediaReference(id: 'export', uri: exported)), + ))!; + expect(exportInfo.videoTrackCount, greaterThan(0)); + expect(exportInfo.audioTrackCount, greaterThan(0)); + report.addAll({ + 'complete': true, + 'videoTracks': info.videoTrackCount, + 'audioTracks': info.audioTrackCount, + 'presentedFrames': playing.presentedVideoFrameCount, + 'exportUri': exported.toString(), + 'exportDuration': exportInfo.duration.seconds, + }); + save(); + debugPrint('DOCUMENT_IMPORT_PASSED ${jsonEncode(report)}'); + } catch (error, stack) { + report.addAll({'error': error.toString(), 'stack': stack.toString()}); + save(); + rethrow; + } finally { + await tester.pumpWidget(const SizedBox.shrink()); + await tester.runAsync(() async { + await preview?.close(); + await workspace.close(); + }); + } + }, + timeout: const Timeout(Duration(minutes: 10)), + ); +} diff --git a/integration_test/android_real_media_test.dart b/integration_test/android_real_media_test.dart new file mode 100644 index 0000000..e9b5bb2 --- /dev/null +++ b/integration_test/android_real_media_test.dart @@ -0,0 +1,804 @@ +import 'package:cutdex/app/editor_theme.dart'; + +// Opt-in validation against complete, unmodified real media on Android. +// Run with `flutter test --no-uninstall` to retain app data and source fixtures. +import 'dart:io'; +import 'dart:math' as math; + +import 'package:cutdex/features/preview/preview_panel.dart'; +import 'package:cutdex/features/properties/properties_panel.dart'; +import 'package:cutdex/features/timeline/timeline_panel.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex/persistence/app_database.dart'; +import 'package:cutdex/workspace/media_file_extensions.dart'; +import 'package:cutdex/workspace/media_import.dart'; +import 'package:cutdex/workspace/projects.dart'; +import 'package:cutdex/workspace/preview_controller_registry.dart'; +import 'package:cutdex/workspace/timeline_provider.dart'; +import 'package:cutdex_native/cutdex_native.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline/engine.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:drift/native.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; +import 'package:path/path.dart' as p; + +import 'support/android_preview_measurement.dart'; +import 'support/real_media_export_checks.dart'; +import 'support/real_media_report.dart'; + +import 'support/saved_edit_validation.dart'; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + const source = String.fromEnvironment('CUTDEX_VALIDATION_SOURCE'); + const output = String.fromEnvironment('CUTDEX_VALIDATION_ROOT'); + const filter = String.fromEnvironment('CUTDEX_VALIDATION_FILTER'); + const sampleStart = int.fromEnvironment( + 'CUTDEX_VALIDATION_SAMPLE_START', + defaultValue: 60, + ); + const previewWidth = int.fromEnvironment( + 'CUTDEX_VALIDATION_PREVIEW_WIDTH', + defaultValue: 640, + ); + const previewHeight = int.fromEnvironment( + 'CUTDEX_VALIDATION_PREVIEW_HEIGHT', + defaultValue: 360, + ); + const observationSeconds = int.fromEnvironment( + 'CUTDEX_VALIDATION_OBSERVATION_SECONDS', + defaultValue: 2, + ); + const concurrentIo = bool.fromEnvironment('CUTDEX_VALIDATION_CONCURRENT_IO'); + const previewOnly = bool.fromEnvironment('CUTDEX_VALIDATION_PREVIEW_ONLY'); + testWidgets( + 'Android host registers native device facts and application info', + (tester) async { + expect(Platform.isAndroid, isTrue); + await tester.pumpWidget(const SizedBox.shrink()); + final device = await NativeDeviceInfo.read(); + expect( + device, + isNotNull, + reason: 'The application host must register cutdex_native.', + ); + expect(device!.displayShortestSideDp, greaterThan(0)); + expect(device.interfaceIdiom, isNull); + final application = await NativeDeviceInfo.readApplicationInfo(); + expect(application['appVersion'], isNotEmpty); + expect(int.tryParse(application['appBuild'] ?? ''), greaterThan(0)); + }, + ); + testWidgets('Android real media: preview and editing through native runtime', ( + tester, + ) async { + expect(Platform.isAndroid, isTrue); + expect(source, isNotEmpty); + expect(output, isNotEmpty); + expect(previewWidth, greaterThan(0)); + expect(previewHeight, greaterThan(0)); + expect(observationSeconds, greaterThan(0)); + final paths = + Directory(source) + .listSync() + .whereType() + .where( + (file) => + mediaKindForPath(file.path) == 'video' && + (filter.isEmpty || + filter.split(',').any(p.basename(file.path).contains)), + ) + .toList() + ..sort((a, b) => a.path.compareTo(b.path)); + expect(paths, isNotEmpty); + final root = await Directory(output).create(recursive: true); + final report = RealMediaReport( + File(p.join(root.path, 'results.json')), + metadata: { + 'platform': 'android', + 'source': source, + 'previewOnly': previewOnly, + 'previewSize': [previewWidth, previewHeight], + 'playbackObservationSeconds': observationSeconds, + 'concurrentFixtureTransfer': concurrentIo, + 'frameTimingMethod': + 'Native surface presentation counters in a debug integration build; ' + 'not physical display refresh or speaker synchronization.', + 'method': previewOnly + ? 'Original files; probing, thumbnails and full-length native preview only. ' + 'Editing and exports skipped. Settings database isolated in memory.' + : 'Original files; production import service, real editor widgets, ' + 'split toolbar and speed slider; command service for keyframes/audio/masks; ' + 'native preview, thumbnails and export. Settings database isolated in memory.', + }, + ); + final savedEdits = SavedEditValidation(); + final results = report.files; + final save = report.save; + final database = AppDatabase(NativeDatabase.memory()); + final container = ProviderContainer( + overrides: [appDatabaseProvider.overrideWithValue(database)], + ); + final projects = container.read(projectsProvider.notifier); + final runtime = CutdexRuntime(); + addTearDown(database.close); + var disposed = false; + addTearDown(() { + if (!disposed) container.dispose(); + }); + + Future until( + bool Function() ready, + String label, { + int seconds = 60, + }) => pumpUntil(tester, ready, label, seconds: seconds); + + expect( + await projects.open( + p.join( + root.path, + 'Real-media-${DateTime.now().millisecondsSinceEpoch}.cutdex', + ), + name: 'Android 真实素材验证', + initialTimelineName: '01', + ), + isTrue, + ); + final projectId = container + .read(projectsProvider) + .requireValue + .activeProject! + .id; + for (var index = 0; index < paths.length; index++) { + final file = paths[index]; + final before = await file.stat(); + final checks = >[]; + final result = { + 'path': file.path, + 'checks': checks, + 'sourceStartSeconds': sampleStart, + 'passed': false, + }; + results.add(result); + save(); + var stage = 'setup'; + String? testedTimeline; + void Function()? releaseTimeline; + Future check(String name, Future Function() action) async { + stage = name; + debugPrint( + 'REAL_MEDIA ${index + 1}/${paths.length} $name ${p.basename(file.path)}', + ); + final clock = Stopwatch()..start(); + await action().timeout(const Duration(minutes: 4)); + expect( + tester.takeException(), + isNull, + reason: 'Widget error during $name', + ); + checks.add({ + 'stage': name, + 'passed': true, + 'milliseconds': clock.elapsedMilliseconds, + }); + save(); + } + + try { + if (index > 0) { + expect(await projects.createTimeline(name: '${index + 1}'), isTrue); + } + final timelineId = container + .read(projectsProvider) + .requireValue + .timeline! + .id; + testedTimeline = timelineId; + final retainedTimeline = container.listen( + editorTimelineProvider(projectId, timelineId), + (_, _) {}, + ); + releaseTimeline = retainedTimeline.close; + final session = await container.read( + editorTimelineProvider(projectId, timelineId).future, + ); + final sequence = session.activeSequenceId!; + final view = session.view(sequence); + final media = MediaReference(id: 'real-source', uri: file.uri); + late MediaInfo info; + await check('probeOriginalAndSeekThumbnails', () async { + try { + info = await runtime.probe(media); + } catch (_) { + final raw = await runtime.invoke('probe', {'media': media.toMap()}); + result['rawProbeMetadata'] = raw; + // Preserve the actual wire-contract failure in the device report. + MediaInfo.fromMap(raw! as Map); + rethrow; + } + expect(info.videoTrackCount, greaterThan(0)); + expect(info.audioTrackCount, greaterThan(0)); + expect(info.duration.seconds, greaterThan(120)); + result['durationSeconds'] = info.duration.seconds; + result['audioTracks'] = info.audioTrackCount; + result['displaySizes'] = [ + for (final size in info.videoDisplaySizes) + [size.width, size.height], + ]; + for (final seconds in [ + 60.0, + info.duration.seconds / 2, + info.duration.seconds - 5, + ]) { + final thumbnail = await runtime.thumbnail( + ThumbnailRequest( + media: media, + time: MediaTime((seconds * 1000).round(), 1000), + maximumWidth: 320, + maximumHeight: 180, + ), + ); + expect(thumbnail.data, isNotEmpty); + final image = await decodeImageFromList(thumbnail.data); + expect(image.width, greaterThan(0)); + image.dispose(); + } + }); + await check( + 'fullLengthPreviewStartMiddleAndEnd', + () => measureAndroidFullLengthPreview( + tester: tester, + runtime: runtime, + media: media, + info: info, + configuration: ( + width: previewWidth, + height: previewHeight, + observationSeconds: observationSeconds, + ), + result: result, + save: save, + ), + ); + if (previewOnly) { + final unchanged = await file.stat(); + expect(unchanged.size, before.size); + expect(unchanged.modified, before.modified); + result['passed'] = true; + result['sourceUnchanged'] = true; + releaseTimeline(); + save(); + continue; + } + await check('importOriginalAndInsertSourceRange', () async { + final imported = await projects.importExternalMedia(projectId, [ + ExternalMediaFile(path: file.path), + ]); + expect(imported!.failures, isEmpty); + final asset = imported.assets.firstWhere( + (a) => a.name == p.basename(file.path), + ); + await session.commands.executeEdit( + sequence, + SetProjectCanvas( + width: previewWidth.toDouble(), + height: previewHeight.toDouble(), + ), + ); + await session.commands.insertMedia( + sequence: sequence, + assetId: asset.id, + clipId: ElementId('real-clip'), + index: 0, + sourceStart: RationalTime.seconds(sampleStart), + duration: RationalTime.seconds(8), + ); + }); + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + theme: EditorTheme.penLight, + home: Scaffold( + body: LayoutBuilder( + builder: (context, constraints) { + final narrow = constraints.maxWidth < 600; + return Column( + children: [ + Expanded( + child: Flex( + direction: narrow ? Axis.vertical : Axis.horizontal, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Expanded( + child: EditorPreviewPanel( + projectId: projectId, + timelineId: timelineId, + ), + ), + SizedBox( + width: narrow ? null : 280, + height: narrow ? 200 : null, + child: EditorPropertiesPanel( + projectId: projectId, + timelineId: timelineId, + ), + ), + ], + ), + ), + SizedBox( + height: 210, + child: EditorTimelinePanel( + projectId: projectId, + timelineId: timelineId, + ), + ), + ], + ); + }, + ), + ), + ), + ), + ); + await check('initializeNativePreview', () async { + final initialized = await container + .read(editorPreviewProvider(projectId, timelineId).future) + .timeout(const Duration(minutes: 2)); + if (initialized == null) { + throw StateError( + 'Preview is empty; timeline duration ${session.sequenceDurationTicks(sequence)}', + ); + } + debugPrint( + 'REAL_MEDIA_INITIALIZED ready=${initialized.ready} busy=${initialized.busy} error=${initialized.error} duration=${initialized.durationTick}', + ); + await until( + () { + final state = container.read( + editorPreviewProvider(projectId, timelineId), + ); + if (state.hasError) { + throw StateError('Native preview startup: ${state.error}'); + } + final value = state.asData?.value; + if (value?.error != null) { + throw StateError('Native preview: ${value!.error}'); + } + return value?.ready == true; + }, + 'preview initialized', + seconds: 180, + ); + }); + final preview = container + .read(editorPreviewProvider(projectId, timelineId)) + .requireValue!; + // Platform-view creation spans several Flutter frames on Android. + await until( + () => (preview.session?.snapshot?.presentedVideoFrameCount ?? 0) > 0, + 'first preview frame', + seconds: 90, + ); + final clipId = ElementId('real-clip'); + ElementRecord record() { + final q = session.persistence.timeline(sequence).current.query(); + return q.element(q.elementById(clipId)!); + } + + Future settled() async { + await tester.pump(); + await until( + () => !preview.busy && preview.ready, + 'preview synchronization: ${preview.error}', + ); + expect(preview.error, isNull); + } + + Future seek(double seconds) async { + await preview.controlPreview( + sequence, + PreviewAction.seek, + at: CommandTime((seconds * 1000).round(), 1000), + ); + await settled(); + expect( + (await preview.session!.refresh()).position.seconds, + closeTo(seconds, .15), + ); + } + + Future playback() async { + await seek(0); + final beforePlay = await preview.session!.refresh(); + await tester.tap(find.byTooltip('播放').first); + var nextLog = DateTime.now(); + await until(() { + if (preview.error != null) { + throw StateError('Preview playback: ${preview.error}'); + } + final native = preview.session!.snapshot; + if (native?.message != null) { + throw StateError('Native playback: ${native!.message}'); + } + if (DateTime.now().isAfter(nextLog)) { + nextLog = DateTime.now().add(const Duration(seconds: 2)); + debugPrint( + 'REAL_MEDIA_CLOCK ui=${preview.playing}/${preview.positionTick} native=${native?.state}/${native?.position.seconds}/${native?.presentedVideoFrameCount} busy=${preview.busy}', + ); + } + final reachedEnd = + preview.durationTick > 0 && + preview.positionTick >= + preview.durationTick - TimelineClock.ticksPerSecond / 10; + return (preview.playing || reachedEnd) && + preview.positionTick > TimelineClock.ticksPerSecond / 2 && + (native?.presentedVideoFrameCount ?? 0) > + (beforePlay.presentedVideoFrameCount ?? 0); + }, 'native playback clock'); + await Future.delayed(const Duration(milliseconds: 250)); + await tester.pump(); + final playing = await preview.session!.refresh(); + expect( + playing.presentedVideoFrameCount, + greaterThan(beforePlay.presentedVideoFrameCount ?? 0), + ); + final pause = find.byTooltip('暂停播放'); + if (pause.evaluate().isNotEmpty) { + await tester.tap(pause.first); + } else { + expect( + preview.positionTick, + greaterThanOrEqualTo( + preview.durationTick - TimelineClock.ticksPerSecond / 10, + ), + ); + } + await until(() => !preview.playing && !preview.busy, 'native pause'); + final at = preview.positionTick; + await tester.pump(const Duration(milliseconds: 250)); + expect( + (preview.positionTick - at).abs(), + lessThan(TimelineClock.ticksPerSecond / 10), + ); + expect(preview.error, isNull); + (result.putIfAbsent( + 'playback', + () => >[], + ) as List).add({ + 'stage': stage, + 'positionSeconds': playing.position.seconds, + 'frames': playing.presentedVideoFrameCount, + 'dropped': playing.droppedVideoFrameCount, + 'maximumGapMs': playing.maximumVideoFrameGapMs, + 'rssBytes': ProcessInfo.currentRss, + }); + } + + await check('nativePreviewPlayPauseAndScrub', () async { + expect(find.byType(RuntimePreview), findsOneWidget); + await playback(); + for (final at in [6.5, .5, 7.5, 2.0, 0.0]) { + await seek(at); + } + }); + await check('splitToolbarUndoRedo', () async { + preview.selectVisual(clipId); + await seek(4); + await tester.tap(find.byTooltip('在播放头处分割')); + await settled(); + expect(record().duration, 4 * TimelineClock.ticksPerSecond); + expect( + session.persistence.timeline(sequence).exportDto().elements.length, + 2, + ); + await session.commands.executeEdit(sequence, const UndoEdit()); + await settled(); + expect(record().duration, 8 * TimelineClock.ticksPerSecond); + await session.commands.executeEdit(sequence, const RedoEdit()); + await settled(); + final other = session.persistence + .timeline(sequence) + .exportDto() + .elements + .firstWhere((e) => e.id != clipId); + await session.commands.executeEdit( + sequence, + DeleteClip(other.id.value), + ); + await settled(); + await playback(); + }); + await check('speedSliderHalfDoubleAndNormal', () async { + preview.selectVisual(clipId); + await seek(0); + await tester.tap(find.byKey(const ValueKey('property-tab-speed'))); + await tester.pump(); + final slider = find.descendant( + of: find.byKey(const Key('clip-speed-slider')), + matching: find.byType(Slider), + ); + expect(slider, findsOneWidget); + for (final requested in [2.0, .5, 1.0]) { + final bounds = tester.getRect(slider); + final position = (math.log(requested) / math.ln10 + 1) / 3; + final gesture = await tester.startGesture( + Offset( + bounds.left + + 12 + + (bounds.width - 24) * tester.widget(slider).value, + bounds.center.dy, + ), + ); + await gesture.moveTo( + Offset( + bounds.left + 12 + (bounds.width - 24) * position, + bounds.center.dy, + ), + ); + await tester.pump(); + await gesture.up(); + await settled(); + expect(session.clipSpeed(record()), closeTo(requested, .05)); + expect( + record().duration, + closeTo( + 4 * TimelineClock.ticksPerSecond / requested, + TimelineClock.ticksPerSecond / 4, + ), + ); + await playback(); + } + // Keep exact source timing for subsequent pixel/audio comparisons. + session.setClipSpeed(sequence, clipId, 1); + await settled(); + }); + Future export(String suffix, {int audioOrdinal = 0}) async { + final plan = const ExecutionCompiler() + .compile( + ExecutionInput( + timeline: session.persistence.timeline(sequence), + media: { + record().payloadRef!: ExecutionMediaBinding( + media: media, + videoTrackSelection: TrackSelection.index(0), + inputColorSpace: + info.videoColorSpaces[0] ?? RenderColorSpace.rec709, + audioTrackSelection: TrackSelection.index(audioOrdinal), + audioTiming: info.audioTracks[audioOrdinal], + ), + }, + renderSize: RenderSize(320, 180), + parameterTargets: { + ...ClipTransform.targets, + ...ClipAudioGain.targets, + }, + editorOnlyParameters: const {ClipAudioGain.detachedId}, + ), + ) + .plan; + return preview.session!.export( + plan, + File( + p.join( + root.path, + '${index.toString().padLeft(2, '0')}-$suffix.mp4', + ), + ).uri, + ); + } + + late Uri baseline; + await check('baselineExportAndAudio', () async { + baseline = await export('baseline'); + final exported = await runtime.probe( + MediaReference(id: 'baseline', uri: baseline), + ); + expect(exported.videoTrackCount, 1); + expect(exported.audioTrackCount, 1); + expect(exported.duration.seconds, closeTo(4, .1)); + result['baselineExport'] = baseline.toFilePath(); + }); + if (info.audioTrackCount > 1) { + await check('alternateAudioTrackExportAndDecode', () async { + final uri = await export('audio-track-1', audioOrdinal: 1); + final alternate = MediaReference(id: 'alternate-audio', uri: uri); + final wave = await runtime.waveform( + WaveformRequest( + media: alternate, + baseBucketCount: 64, + levelCount: 1, + ), + ); + expect(wave.levels.first.channels.length, 2); + expect( + wave.levels.first.channels + .expand((values) => values) + .any((value) => value.abs() > .0001), + isTrue, + ); + result['alternateAudioExport'] = uri.toFilePath(); + }); + } + await check('audioGainMuteAndRestore', () async { + await session.commands.executeEdit( + sequence, + const SetClipAudio(clipId: 'real-clip', db: -6, muted: true), + ); + await settled(); + expect(ClipAudioGain.fromRecord(record()).muted, isTrue); + await playback(); + await session.commands.executeEdit( + sequence, + const SetClipAudio(clipId: 'real-clip', db: -6, muted: false), + ); + await settled(); + expect(ClipAudioGain.fromRecord(record()).db, -6); + }); + await check('transformKeyframesAndInterpolation', () async { + for (final entry in [(0, 0.0), (2, .1)]) { + await session.commands.executeEdit( + sequence, + EditKeyframe( + clipId: 'real-clip', + parameterId: 'canvas.position.x', + at: CommandTime(entry.$1, 1), + action: KeyframeAction.set, + value: entry.$2, + interpolation: KeyInterpolation.linear, + ), + ); + } + await settled(); + await seek(1); + final animation = ClipAnimation.at( + view.version.kernelVersion.query(), + view.version.kernelVersion.query().elementById(clipId)!, + TimelineClock.ticksPerSecond, + TimelineClock.ticksPerSecond ~/ 30, + ); + expect(animation.value.x, closeTo(.05, .001)); + await playback(); + }); + await check('keyframeOnlyExport', () async { + final uri = await export('keyframes'); + final exported = await runtime.probe( + MediaReference(id: 'keyframes', uri: uri), + ); + expect(exported.duration.seconds, closeTo(4, .1)); + result['keyframeExport'] = uri.toFilePath(); + }); + await check('rectangleEllipseFeatherAndInvertedMasks', () async { + await seek(0); + await session.commands.executeEdit( + sequence, + EditMask( + clipId: 'real-clip', + at: CommandTime(0, 1), + action: MaskAction.add, + maskId: 'real-mask', + shape: MaskShape.rectangle, + x: .5, + y: .5, + width: .5, + height: .5, + ), + ); + await settled(); + for (final inverted in [false, true]) { + await session.commands.executeEdit( + sequence, + EditMask( + clipId: 'real-clip', + at: CommandTime(0, 1), + action: MaskAction.set, + maskId: 'real-mask', + shape: MaskShape.ellipse, + inverted: inverted, + feather: .1, + ), + ); + await settled(); + expect( + ClipMaskStack(record(), 0).layers.single.mask.inverted, + inverted, + ); + await playback(); + } + await session.commands.executeEdit( + sequence, + EditMask( + clipId: 'real-clip', + at: CommandTime(0, 1), + action: MaskAction.set, + maskId: 'real-mask', + shape: MaskShape.rectangle, + inverted: false, + feather: 0, + ), + ); + await settled(); + }); + await check('editedExportPixelsAudioAndPersistence', () async { + final exportedUri = await export('edited'); + result['editedExport'] = exportedUri.toFilePath(); + result['audioRmsRatio'] = await verifyEditedExport( + runtime, + edited: exportedUri, + baseline: baseline, + ); + await session.flush(); + expect(session.saveError, isNull); + final projectPath = container + .read(projectsProvider) + .requireValue + .activeProject! + .path; + final edits = await savedEdits.capture( + projectPath, + timelineId, + session, + sequence, + ); + expect( + ((edits['clips'] as List).single as Map)['parameters'], + hasLength(greaterThanOrEqualTo(3)), + ); + result['savedTimelineId'] = timelineId; + result['savedProject'] = projectPath; + }); + result['passed'] = true; + } catch (error, stack) { + checks.add({ + 'stage': stage, + 'passed': false, + 'error': '$error', + 'stack': '$stack', + }); + debugPrint('REAL_MEDIA_FAILED $stage $error\n$stack'); + } + final after = await file.stat(); + result['sourceUnchanged'] = + before.size == after.size && before.modified == after.modified; + if (result['sourceUnchanged'] != true) result['passed'] = false; + save(); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + if (testedTimeline != null) { + await container.read(previewControllerRegistryProvider).invalidate(( + projectId, + testedTimeline, + )); + } + releaseTimeline?.call(); + } + container.dispose(); + disposed = true; + await savedEdits.verify( + wait: tester.pump, + onVerified: (projectPath, timelineId, edits) { + final result = results.singleWhere( + (r) => + r['savedProject'] == projectPath && + r['savedTimelineId'] == timelineId, + ); + result['savedEditsIdenticalAfterReopen'] = true; + save(); + }, + ); + expect( + results.where((file) => file['passed'] != true).toList(), + isEmpty, + reason: 'See ${report.file.path}', + ); + }, timeout: const Timeout(Duration(minutes: 90))); +} diff --git a/integration_test/complex_preview_test.dart b/integration_test/complex_preview_test.dart new file mode 100644 index 0000000..0a60d0c --- /dev/null +++ b/integration_test/complex_preview_test.dart @@ -0,0 +1,379 @@ +import 'package:cutdex/app/editor_theme.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; + +import 'dart:io'; + +import 'package:cutdex/workspace/timeline_provider.dart'; + +import 'dart:ui' as ui; + +import 'package:cutdex/features/preview/preview_panel.dart'; +import 'package:cutdex_sdk/preview.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; + +import '../test/support/preview_fixture.dart'; +import 'support/native_media_fixture.dart'; + +RationalTime t(num value) => RationalTime((value * 1000).round(), 1000); +ParameterCurveDto scalar(String id, double value) => ParameterCurveDto( + definition: TimelineParameterDefinition( + id: id, + defaultValue: value, + minimum: -96, + maximum: 100, + ), +); +ElementDto clip( + String id, { + num source = 1, + num duration = 2, + num offset = 0, + List parameters = const [], +}) => ElementDto( + id: ElementId(id), + structure: ElementStructure.content, + payloadRef: PayloadRef('source'), + duration: t(duration), + parallelOffset: t(offset), + parameters: parameters, + sourceRange: TimeRange(start: t(source), duration: t(duration)), + mediaRange: TimeRange(start: t(0), duration: t(30)), +); +TimelineDto complexTimeline() => TimelineDto( + id: SequenceId('one'), + format: TimelineFormat.fps30, + primaryStorylineId: StorylineId('primary'), + storylines: [ + StorylineDto( + id: StorylineId('primary'), + elementIds: [ElementId('box'), ElementId('a'), ElementId('b')], + ), + StorylineDto( + id: StorylineId('inside'), + timeDomain: TimeDomain.parallel, + elementIds: [ElementId('lower'), ElementId('upper')], + ), + ], + elements: [ + ElementDto( + id: ElementId('box'), + structure: ElementStructure.container, + duration: t(2), + containerStorylineId: StorylineId('inside'), + containerViewMode: ContainerViewMode.fixedRange, + sourceRange: TimeRange(start: t(0), duration: t(1)), + parameters: [ + scalar('opacity', .9), + ParameterCurveDto( + definition: TimelineParameterDefinition( + id: 'gain', + defaultValue: -6, + minimum: -96, + maximum: 12, + semantic: ParameterSemantic.audioGainDb, + ), + ), + ], + retimeSegments: [ + RetimeSegmentDto( + projectDuration: t(1), + sourceStart: t(0), + sourceDelta: t(1), + ), + RetimeSegmentDto( + projectDuration: t(.5), + sourceStart: t(1), + sourceDelta: t(0), + ), + RetimeSegmentDto( + projectDuration: t(.5), + sourceStart: t(1), + sourceDelta: t(-.5), + ), + ], + ), + clip('lower'), + clip( + 'upper', + source: 2, + offset: .25, + parameters: [ + scalar('opacity', .5), + scalar('scale.x', .7), + scalar('scale.y', .7), + ], + ), + clip('a', source: 3), + clip('b', source: 5), + clip( + 'attached', + source: 7, + duration: 3, + parameters: [scalar('opacity', .7)], + ), + ], + connections: [ + ConnectionDto( + id: ConnectionId('link'), + anchorId: ElementId('b'), + targetId: ElementId('attached'), + anchorTime: t(1), + targetTime: t(0), + side: ConnectionSide.above, + ), + ], + transitions: [ + TransitionDto( + id: TransitionId('mix'), + storylineId: StorylineId('primary'), + leftId: ElementId('a'), + rightId: ElementId('b'), + duration: t(1), + startOffset: t(-.5), + timing: TransitionTiming.mediaHandles, + ), + ], +); + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + testWidgets( + 'native nested composition, reverse, freeze, transition and attached tail survive edits', + (tester) async { + final mediaFile = await nativeMediaFixture(); + final fixture = await createPreviewFixture( + mediaFile.uri, + hasAudio: true, + timelineOverride: complexTimeline(), + renderSize: {'width': 320, 'height': 180}, + ); + final preview = PreviewController( + timeline: fixture.timeline, + activeSequence: () => fixture.timeline.activeSequenceId, + viewForSequence: fixture.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + }); + await preview.initialize(); + expect(preview.error, isNull); + expect(preview.durationTick, TimelineClock.ticksPerSecond * 8); + final ids = (fixture.workspace.project!.info.id, 'project'); + await tester.pumpWidget( + ProviderScope( + overrides: [ + editorTimelineProvider( + ids.$1, + ids.$2, + ).overrideWith((ref) async => fixture.timeline), + editorPreviewProvider( + ids.$1, + ids.$2, + ).overrideWith((ref) async => preview), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + theme: EditorTheme.penDark, + home: Scaffold( + body: EditorPreviewPanel(projectId: ids.$1, timelineId: ids.$2), + ), + ), + ), + ); + await tester.pumpAndSettle(); + final view = fixture.timeline.view(SequenceId('one')); + final nativePreview = find.byType( + Platform.isIOS ? UiKitView : AppKitView, + ); + expect(nativePreview, findsOneWidget); + final nativeView = tester.state(nativePreview); + for (final at in [ + .1, + .8, + 1.1, + 1.4, + 1.6, + 1.9, + 2.2, + 3.6, + 4.0, + 4.4, + 5.2, + 6.5, + 7.8, + .2, + ]) { + view.seekTo((at * TimelineClock.ticksPerSecond).round()); + await Future.delayed(const Duration(milliseconds: 400)); + await tester.pump(); + var snapshot = await preview.session!.refresh(); + for ( + var attempt = 0; + attempt < 100 && (snapshot.position.seconds - at).abs() > .1; + attempt++ + ) { + await Future.delayed(const Duration(milliseconds: 50)); + await tester.pump(); + snapshot = await preview.session!.refresh(); + } + expect(preview.error, isNull, reason: 'Seek to $at'); + expect(snapshot.position.seconds, closeTo(at, .1)); + expect(tester.state(nativePreview), same(nativeView)); + } + view.seekTo((3.8 * TimelineClock.ticksPerSecond).round()); + await Future.delayed(const Duration(milliseconds: 400)); + await preview.togglePlayback(); + await Future.delayed(const Duration(milliseconds: 550)); + await preview.togglePlayback(); + expect( + (await preview.session!.refresh()).position.seconds, + greaterThan(4), + ); + view.setSelection([ + view.version.kernelVersion.query().elementById(ElementId('b'))!, + ]); + view.seekTo(TimelineClock.ticksPerSecond * 5); + await Future.delayed(const Duration(milliseconds: 300)); + for (final edit in [view.cutSelectionAtPlayhead, view.undo, view.redo]) { + edit(); + for (var i = 0; i < 600; i++) { + await Future.delayed(const Duration(milliseconds: 100)); + await tester.pump(); + if (!preview.busy) break; + } + expect(preview.busy, isFalse); + expect(preview.error, isNull); + expect(preview.durationTick, TimelineClock.ticksPerSecond * 8); + expect( + (await preview.session!.refresh()).position.seconds, + closeTo(5, .1), + ); + expect(tester.state(nativePreview), same(nativeView)); + } + final runtime = CutdexRuntime(); + final preparedMedia = await prepareEditorMedia( + session: fixture.timeline, + sequence: SequenceId('one'), + version: fixture.timeline.persistence + .timeline(SequenceId('one')) + .current, + probe: runtime.probe, + unknownVideoColorSpace: const PreviewPolicy().unknownVideoColorSpace, + ); + final execution = const ExecutionCompiler().compile( + ExecutionInput( + timeline: fixture.timeline.persistence.timeline(SequenceId('one')), + media: preparedMedia.bindings, + renderSize: RenderSize(320, 180), + toneMapping: RenderToneMapping.headroom(source: 4, target: 1), + ), + ); + final exported = await preview.session!.export( + execution.plan, + File('${fixture.directory.path}/complex.mp4').uri, + ); + final result = await runtime.probe( + MediaReference(id: 'exported', uri: exported), + ); + expect(result.duration.seconds, closeTo(8, .05)); + expect(result.videoTrackCount, 1); + expect(result.audioTrackCount, 1); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + }, + skip: !hasNativeMediaFixture, + ); + testWidgets( + 'native image and empty compositing canvas execute without video media', + (tester) async { + final directory = await Directory.systemTemp.createTemp( + 'cutdex-image-preview-', + ); + final recorder = ui.PictureRecorder(); + ui.Canvas(recorder) + .drawColor(const ui.Color(0xffff0000), ui.BlendMode.src); + final picture = recorder.endRecording(); + final image = await picture.toImage(64, 64); + final bytes = await image.toByteData(format: ui.ImageByteFormat.png); + final file = File('${directory.path}/red.png'); + await file.writeAsBytes(bytes!.buffer.asUint8List()); + picture.dispose(); + image.dispose(); + final runtime = CutdexRuntime(); + final session = await runtime.createSession(); + addTearDown(() async { + await session.close(); + await directory.delete(recursive: true); + }); + final duration = MediaTime(1, 1); + final range = MediaRange(start: MediaTime(0, 1), duration: duration); + final group = RenderCompositingGroup( + id: 'black', + backgroundOpacity: RenderAutomation( + target: 'opacity', + defaultValue: .5, + ), + ); + final plan = ExecutionPlan( + revision: 0, + duration: duration, + renderSize: RenderSize(64, 64), + frameDuration: MediaTime(1, 30), + media: [MediaReference(id: 'image', uri: file.uri, isImage: true)], + visualLayers: [ + VisualLayer( + id: 'image', + mediaId: 'image', + sourceRange: range, + timelineRange: range, + ), + VisualLayer.canvas( + id: 'canvas', + timelineRange: range, + lane: 1, + groups: [group], + ), + ], + ); + await session.load(plan); + await session.seek(MediaTime(1, 2)); + expect((await session.refresh()).position.seconds, closeTo(.5, .05)); + final exported = await session.export( + plan, + File('${directory.path}/image.mp4').uri, + ); + final cover = await runtime.thumbnail( + ThumbnailRequest( + media: MediaReference(id: 'out', uri: exported), + ), + ); + final codec = await ui.instantiateImageCodec(cover.data); + final frame = await codec.getNextFrame(); + final pixels = await frame.image.toByteData( + format: ui.ImageByteFormat.rawRgba, + ); + // A 50% opaque black group over red must darken the image, even with no children. + final center = + (frame.image.height ~/ 2 * frame.image.width + + frame.image.width ~/ 2) * + 4; + expect(pixels!.getUint8(center), inInclusiveRange(165, 200)); + expect(pixels.getUint8(center + 1), lessThan(10)); + expect(pixels.getUint8(center + 2), lessThan(10)); + frame.image.dispose(); + codec.dispose(); + }, + ); +} diff --git a/integration_test/downloads_preview_cadence_test.dart b/integration_test/downloads_preview_cadence_test.dart new file mode 100644 index 0000000..6b949ca --- /dev/null +++ b/integration_test/downloads_preview_cadence_test.dart @@ -0,0 +1,384 @@ +import 'package:cutdex/app/editor_theme.dart'; + +// Opt-in cadence measurements from the mounted macOS source-preview renderer. +// Requires macOS 14.4+, CUTDEX_PREVIEW_CADENCE_DIAGNOSTICS=1 in the host environment, +// and CUTDEX_VALIDATION_ROOT / CUTDEX_VALIDATION_SOURCE Dart defines. +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:math' as math; + +import 'package:cutdex/features/media/media_panel.dart'; +import 'package:cutdex/features/preview/preview_panel.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex/persistence/app_database.dart'; +import 'package:cutdex/workspace/media_file_extensions.dart'; +import 'package:cutdex/workspace/preview_target.dart'; +import 'package:cutdex/workspace/projects.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:drift/native.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; +import 'package:path/path.dart' as p; + +void main() { + const root = String.fromEnvironment('CUTDEX_VALIDATION_ROOT'); + const sourceDirectory = String.fromEnvironment('CUTDEX_VALIDATION_SOURCE'); + const configured = root != '' && sourceDirectory != ''; + final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + // The host activates this diagnostic window through macOS accessibility. + // Establish its OS-owned semantics handle before testWidgets records handles + // and resets node IDs; forcing a test-owned handle first conflicts with that + // late activation in Flutter's native accessibility bridge. + setUpAll(() async { + if (!configured) return; + debugPrint('APP_CADENCE_WAIT_FOR_VISIBLE_HOST_WINDOW'); + final deadline = DateTime.now().add(const Duration(seconds: 60)); + while (!binding.semanticsEnabled) { + if (DateTime.now().isAfter(deadline)) { + throw StateError( + 'Activate the cadence window through macOS accessibility', + ); + } + await Future.delayed(const Duration(milliseconds: 100)); + } + }); + testWidgets( + 'Downloads: mounted source-preview cadence', + (tester) async { + const filter = String.fromEnvironment('CUTDEX_VALIDATION_FILTER'); + const measurementSeconds = int.fromEnvironment( + 'CUTDEX_CADENCE_SECONDS', + defaultValue: 8, + ); + expect(root, isNotEmpty); + expect(sourceDirectory, isNotEmpty); + expect(measurementSeconds, greaterThan(0)); + Directory(root).createSync(recursive: true); + final paths = + Directory(sourceDirectory) + .listSync() + .whereType() + .map((file) => file.path) + .where( + (path) => + mediaKindForPath(path) == 'video' && + (filter.isEmpty || + filter + .split(',') + .any((value) => p.basename(path).contains(value))), + ) + .toList() + ..sort(); + expect(paths, isNotEmpty, reason: 'No matching video sources'); + final results = >[]; + final report = File(p.join(root, 'app-cadence.json')); + final database = AppDatabase(NativeDatabase.memory()); + final container = ProviderContainer( + overrides: [appDatabaseProvider.overrideWithValue(database)], + ); + addTearDown(() async { + container.dispose(); + await database.close(); + }); + final projects = container.read(projectsProvider.notifier); + expect( + await projects.open( + p.join( + root, + 'Cadence-${DateTime.now().millisecondsSinceEpoch}.cutdex', + ), + name: '素材预览帧率验证', + initialTimelineName: '01', + ), + isTrue, + ); + final state = container.read(projectsProvider).requireValue; + final projectId = state.activeProject!.id; + final timelineId = state.timeline!.id; + void save() => report.writeAsStringSync( + const JsonEncoder.withIndent(' ').convert({ + 'files': results, + 'scope': + 'Actual Cutdex source-preview panel, full source resolution, 30fps plan; ' + 'AVSampleBufferVideoRenderer counters on a mounted native view; adaptive warmup and up to ${measurementSeconds}s measurement per segment', + }), + ); + Future until(bool Function() predicate, String name) async { + final deadline = DateTime.now().add(const Duration(seconds: 40)); + while (!predicate()) { + if (DateTime.now().isAfter(deadline)) { + throw StateError('Timed out: $name'); + } + await tester.pump(const Duration(milliseconds: 100)); + } + await tester.pump(); + } + + Future advance(Duration duration) async { + final watch = Stopwatch()..start(); + while (watch.elapsed < duration) { + await tester.pump(const Duration(milliseconds: 100)); + } + } + + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + theme: EditorTheme.penLight, + home: Scaffold( + body: Row( + children: [ + SizedBox( + width: 300, + child: MediaPanel( + projectId: projectId, + grid: true, + onGridChanged: (_) {}, + ), + ), + Expanded( + child: EditorPreviewPanel( + projectId: projectId, + timelineId: timelineId, + ), + ), + ], + ), + ), + ), + ), + ); + await tester.pump(const Duration(milliseconds: 500)); + const channel = MethodChannel('cutdex_runtime'); + Future>> metrics() async => + (await channel.invokeListMethod('_debugPreviewCadence'))! + .map((item) => Map.from(item! as Map)) + .toList(); + Future nativeDrop(String path, int session) async { + for (final phase in ['enter', 'drop']) { + final done = Completer(); + tester.binding.defaultBinaryMessenger.handlePlatformMessage( + 'cutdex_native/file_drop/media-library', + const StandardMethodCodec().encodeMethodCall( + MethodCall('event', { + 'phase': phase, + 'session': session, + 'x': 0.0, + 'y': 0.0, + 'files': [ + {'path': path}, + ], + }), + ), + (_) => done.complete(), + ); + await done.future; + await tester.pump(); + } + } + + for (var index = 0; index < paths.length; index++) { + final path = paths[index]; + final before = File(path).statSync(); + final segments = >[]; + final result = { + 'path': path, + 'segments': segments, + 'passed': false, + }; + results.add(result); + save(); + debugPrint( + 'APP_CADENCE ${index + 1}/${paths.length} ${p.basename(path)}', + ); + final target = container.read( + previewTargetProvider(projectId, timelineId), + ); + try { + await nativeDrop(path, index + 1); + await until( + () => container + .read(projectsProvider) + .requireValue + .assets + .any((asset) => asset.name == p.basename(path)), + 'import', + ); + final asset = container + .read(projectsProvider) + .requireValue + .assets + .firstWhere((asset) => asset.name == p.basename(path)); + await target.openSource(asset); + final source = target.source!; + await until(() => source.canPlay, 'source ready'); + final duration = source.durationTick / TimelineClock.ticksPerSecond; + final warmupSeconds = duration < measurementSeconds + 3 ? 0.2 : 2.0; + final measuredSeconds = math.min( + measurementSeconds.toDouble(), + duration - warmupSeconds - 0.4, + ); + expect( + measuredSeconds, + greaterThan(1), + reason: 'Cadence needs a source longer than 1.6 seconds', + ); + final latestStart = math.max( + 0.0, + duration - warmupSeconds - measuredSeconds - 0.3, + ); + for (final positionSeconds in [ + duration > 80 ? math.min(60.0, latestStart) : 0.0, + math.min(duration / 2, latestStart), + ]) { + final position = (positionSeconds * TimelineClock.ticksPerSecond) + .round(); + await source.control( + SourcePreviewAction.seek, + at: CommandTime(position, TimelineClock.ticksPerSecond), + ); + await until( + () => !source.busy && source.canPlay, + 'source seek settled', + ); + expect(source.error, isNull); + await tester.pump(); + await tester.tap(find.byTooltip('播放')); + await until(() => source.playing, 'playing'); + await advance( + Duration(microseconds: (warmupSeconds * 1e6).round()), + ); + var first = (await metrics()).singleWhere( + (m) => m['mounted'] == true && (m['rate']! as num) > 0, + ); + final visibilityDeadline = DateTime.now().add( + const Duration(seconds: 40), + ); + while (first['windowVisible'] != true || + first['windowOccluded'] != false) { + if (DateTime.now().isAfter(visibilityDeadline)) { + throw StateError( + 'Preview window must be visible for cadence measurement', + ); + } + await tester.pump(const Duration(milliseconds: 100)); + first = (await metrics()).singleWhere( + (m) => m['id'] == first['id'], + ); + } + final watch = Stopwatch()..start(); + await advance( + Duration(microseconds: (measuredSeconds * 1e6).round()), + ); + final last = (await metrics()).singleWhere( + (m) => m['id'] == first['id'], + ); + watch.stop(); + await tester.tap(find.byTooltip('暂停播放')); + await until(() => !source.playing && !source.busy, 'paused'); + expect(source.error, isNull); + final paused = (await metrics()).singleWhere( + (m) => m['id'] == first['id'], + ); + await advance(const Duration(milliseconds: 500)); + final afterPause = (await metrics()).singleWhere( + (m) => m['id'] == first['id'], + ); + final seconds = watch.elapsedMicroseconds / 1e6; + final frames = + (last['frames']! as num).toInt() - + (first['frames']! as num).toInt(); + final dropped = + (last['dropped']! as num).toInt() - + (first['dropped']! as num).toInt(); + final segment = { + 'positionSeconds': position / TimelineClock.ticksPerSecond, + 'warmupSeconds': warmupSeconds, + 'sourceDurationSeconds': duration, + 'measurementSeconds': seconds, + 'rendererTotalFrames': frames, + 'rendererDroppedFrames': dropped, + 'rendererFPS': frames / seconds, + 'displayedFPS': (frames - dropped) / seconds, + 'clockAdvanceRatio': + ((last['clockSeconds']! as num) - + (first['clockSeconds']! as num)) / + seconds, + 'accumulatedFrameDelaySeconds': + (last['delay']! as num) - (first['delay']! as num), + 'viewWidth': first['width'], + 'viewHeight': first['height'], + 'windowVisibleAtStart': first['windowVisible'], + 'windowVisibleAtEnd': last['windowVisible'], + 'windowOccludedAtStart': first['windowOccluded'], + 'windowOccludedAtEnd': last['windowOccluded'], + 'measurementValid': + first['windowVisible'] == true && + last['windowVisible'] == true && + first['windowOccluded'] == false && + last['windowOccluded'] == false, + 'pauseClockAdvanceSeconds': + (afterPause['clockSeconds']! as num) - + (paused['clockSeconds']! as num), + 'pauseRendererFrameAdvance': + (afterPause['frames']! as num) - (paused['frames']! as num), + 'pausedRate': afterPause['rate'], + }; + segments.add(segment); + debugPrint('APP_CADENCE_SEGMENT ${index + 1} $segment'); + save(); + } + result['keepsUp'] = + segments.length == 2 && + segments.every( + (segment) => + (segment['displayedFPS']! as num) >= 28.5 && + segment['measurementValid'] == true && + (segment['rendererDroppedFrames']! as num) == 0 && + (segment['clockAdvanceRatio']! as num) >= 0.95 && + (segment['pauseClockAdvanceSeconds']! as num).abs() < + 0.001 && + (segment['pauseRendererFrameAdvance']! as num) == 0 && + (segment['pausedRate']! as num) == 0, + ); + result['passed'] = true; + } catch (error, stack) { + result['error'] = '$error'; + debugPrint('APP_CADENCE_ERROR $error\n$stack'); + } finally { + await target.closeSource(); + await tester.pump(); + } + final after = File(path).statSync(); + result['sourceUnchanged'] = + before.size == after.size && before.modified == after.modified; + save(); + } + await tester.pumpWidget(const SizedBox.shrink()); + expect( + results + .where( + (r) => + r['passed'] != true || + r['keepsUp'] != true || + r['sourceUnchanged'] != true, + ) + .toList(), + isEmpty, + reason: report.path, + ); + }, + skip: !configured, + semanticsEnabled: false, + timeout: const Timeout(Duration(minutes: 10)), + ); +} diff --git a/integration_test/downloads_workflow_test.dart b/integration_test/downloads_workflow_test.dart new file mode 100644 index 0000000..3482e59 --- /dev/null +++ b/integration_test/downloads_workflow_test.dart @@ -0,0 +1,821 @@ +import 'package:cutdex/app/editor_theme.dart'; + +// Opt-in, real desktop runtime validation. Source files are referenced, never copied. +// CUTDEX_VALIDATION_KIND=audio also checks source-preview transport and mute controls. +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:math' as math; + +import 'package:cutdex/features/media/media_asset_drag.dart'; +import 'package:cutdex/features/media/media_panel.dart'; +import 'package:cutdex/features/preview/preview_panel.dart'; +import 'package:cutdex/features/properties/properties_panel.dart'; +import 'package:cutdex/features/timeline/timeline_panel.dart'; +import 'package:cutdex/features/timeline/timeline_external_drop_target.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex/persistence/app_database.dart'; +import 'package:cutdex/workspace/media_file_extensions.dart'; +import 'package:cutdex/workspace/preview_target.dart'; +import 'package:cutdex/workspace/projects.dart'; +import 'package:cutdex/workspace/timeline_provider.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline/layout.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:drift/native.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; +import 'package:path/path.dart' as p; + +void main() { + const root = String.fromEnvironment('CUTDEX_VALIDATION_ROOT'); + const sourceDirectory = String.fromEnvironment('CUTDEX_VALIDATION_SOURCE'); + const configured = root != '' && sourceDirectory != ''; + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + testWidgets( + 'Downloads: native drop, timeline drag and editing with real playback', + (tester) async { + const filter = String.fromEnvironment('CUTDEX_VALIDATION_FILTER'); + const directDrop = bool.fromEnvironment('CUTDEX_VALIDATION_DIRECT_DROP'); + const dropOnly = bool.fromEnvironment('CUTDEX_VALIDATION_DROP_ONLY'); + const kind = String.fromEnvironment( + 'CUTDEX_VALIDATION_KIND', + defaultValue: 'video', + ); + expect(kind, anyOf('video', 'audio')); + Directory(root).createSync(recursive: true); + final paths = + Directory(sourceDirectory) + .listSync() + .whereType() + .map((file) => file.path) + .where( + (path) => + mediaKindForPath(path) == kind && + (filter.isEmpty || + filter + .split(',') + .any((value) => p.basename(path).contains(value))), + ) + .toList() + ..sort(); + expect(paths, isNotEmpty); + // AppKit menu tracking consumes physical input outside the test binding. + // Exercise the existing Flutter menu fallback; native playback stays real. + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + const MethodChannel('cutdex_native/context_menu'), + (_) async => throw MissingPluginException(), + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + const MethodChannel('cutdex_native/context_menu'), + null, + ), + ); + final results = >[]; + final report = File( + p.join( + root, + kind == 'audio' + ? 'audio-editor-results.json' + : 'downloads-editor-results.json', + ), + ); + final database = AppDatabase(NativeDatabase.memory()); + final container = ProviderContainer( + overrides: [appDatabaseProvider.overrideWithValue(database)], + ); + addTearDown(() async { + container.dispose(); + await database.close(); + }); + final projects = container.read(projectsProvider.notifier); + final projectPath = p.join( + root, + 'Downloads-${DateTime.now().millisecondsSinceEpoch}.cutdex', + ); + void save() => report.writeAsStringSync( + const JsonEncoder.withIndent(' ').convert({ + 'validatedAt': DateTime.now().toIso8601String(), + 'sourceDirectory': sourceDirectory, + 'projectPath': projectPath, + 'directDrop': directDrop, + 'dropOnly': dropOnly, + 'kind': kind, + 'method': + 'Real ${Platform.operatingSystem} application and native playback runtime; ' + '${directDrop ? 'injected native file-drop events directly on the timeline' : 'injected native file-drop events into the library, pointer drag from media tiles'}, ' + 'toolbar and property slider. AppKit menu bridge disabled only in test ' + 'to exercise production Flutter context-menu fallback.', + 'files': results, + }), + ); + Future until( + bool Function() predicate, + String stage, { + int seconds = 40, + }) async { + final deadline = DateTime.now().add(Duration(seconds: seconds)); + while (!predicate()) { + if (DateTime.now().isAfter(deadline)) { + throw StateError('Timed out: $stage'); + } + await tester.pump(const Duration(milliseconds: 100)); + } + await tester.pump(); + } + + Future nativeDrop( + String phase, + String path, + int session, { + bool timeline = false, + Offset position = Offset.zero, + }) async { + final done = Completer(); + // The same entry point receives Finder NSDraggingInfo events in production. + tester.binding.defaultBinaryMessenger.handlePlatformMessage( + timeline + ? 'cutdex_native/file_drop/timeline' + : 'cutdex_native/file_drop/media-library', + const StandardMethodCodec().encodeMethodCall( + MethodCall('event', { + 'phase': phase, + 'session': session, + 'x': position.dx, + 'y': position.dy, + 'files': [ + {'path': path}, + ], + }), + ), + (_) => done.complete(), + ); + await done.future; + await tester.pump(); + } + + expect( + await projects.open( + projectPath, + name: 'Downloads 操作验证', + initialTimelineName: '01', + ), + isTrue, + ); + final projectId = container + .read(projectsProvider) + .requireValue + .activeProject! + .id; + for (var index = 0; index < paths.length; index++) { + final path = paths[index]; + final before = File(path).statSync(); + final checks = >[]; + final result = { + 'path': path, + 'checks': checks, + 'passed': false, + }; + results.add(result); + save(); + String stage = 'setup'; + Future check(String name, Future Function() action) async { + stage = name; + debugPrint( + 'DOWNLOADS_WORKFLOW ${index + 1}/${paths.length} $name ${p.basename(path)}', + ); + await action(); + checks.add({'stage': name, 'passed': true}); + save(); + } + + try { + if (index > 0) { + expect( + await projects.createTimeline( + name: '${index + 1}'.padLeft(2, '0'), + ), + isTrue, + ); + } + final timelineId = container + .read(projectsProvider) + .requireValue + .timeline! + .id; + final ids = (projectId, timelineId); + result['timelineId'] = timelineId; + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + theme: EditorTheme.penLight, + home: Scaffold( + body: Column( + children: [ + Expanded( + child: Row( + children: [ + SizedBox( + width: 300, + child: MediaPanel( + projectId: projectId, + grid: true, + onGridChanged: (_) {}, + ), + ), + Expanded( + child: EditorPreviewPanel( + projectId: projectId, + timelineId: timelineId, + ), + ), + SizedBox( + width: 320, + child: EditorPropertiesPanel( + projectId: projectId, + timelineId: timelineId, + ), + ), + ], + ), + ), + SizedBox( + height: 330, + child: EditorTimelinePanel( + projectId: projectId, + timelineId: timelineId, + ), + ), + ], + ), + ), + ), + ), + ); + await tester.pump(const Duration(milliseconds: 400)); + final session = await container.read( + editorTimelineProvider(ids.$1, ids.$2).future, + ); + final sequence = session.activeSequenceId!; + final view = session.view(sequence); + if (directDrop) { + await check('nativeDropDirectlyIntoTimeline', () async { + final rect = tester.getRect( + find.byType(TimelineExternalDropTarget), + ); + final position = Offset( + 24, + view.camera.screenYForWorld( + view.geometry.primaryTop + + view.geometry.primaryHeight / 2 + + (kind == 'audio' ? 100 : 0), + TimelineViewportRect(width: rect.width, height: rect.height), + ), + ); + await nativeDrop( + 'enter', + path, + index + 1, + timeline: true, + position: position, + ); + await tester.pump(const Duration(milliseconds: 500)); + await nativeDrop( + 'drop', + path, + index + 1, + timeline: true, + position: position, + ); + await until( + () => session.sequenceDurationTicks(sequence) > 0, + 'direct timeline insert', + ); + expect( + container + .read(projectsProvider) + .requireValue + .assets + .any((asset) => asset.name == p.basename(path)), + isTrue, + ); + }); + } else { + await check('nativeDropIntoMediaLibrary', () async { + await nativeDrop('enter', path, index + 1); + await nativeDrop('drop', path, index + 1); + await until( + () => container + .read(projectsProvider) + .requireValue + .assets + .any((a) => a.name == p.basename(path)), + 'import', + ); + }); + final asset = container + .read(projectsProvider) + .requireValue + .assets + .firstWhere((a) => a.name == p.basename(path)); + await check('sourcePreviewSeekPlayPause', () async { + final target = container.read( + previewTargetProvider(ids.$1, ids.$2), + ); + try { + await target.openSource(asset); + final source = target.source!; + await until(() => source.canPlay, 'source ready'); + expect(source.audioOnly, kind == 'audio'); + for (final position in [0, source.durationTick ~/ 2]) { + await source.control( + SourcePreviewAction.seek, + at: CommandTime(position, TimelineClock.ticksPerSecond), + ); + await until( + () => !source.busy && source.canPlay, + 'source seek settled', + ); + expect(source.error, isNull); + await tester.pump(); + await tester.tap(find.byTooltip('播放')); + await until( + () => + source.playing && + source.positionTick > + position + TimelineClock.ticksPerSecond ~/ 5, + 'source play advances', + ); + expect(source.error, isNull); + await until( + () => find.byTooltip('暂停播放').evaluate().isNotEmpty, + 'source pause button', + ); + await tester.tap(find.byTooltip('暂停播放')); + await until( + () => !source.playing && !source.busy, + 'source pause', + ); + final paused = source.positionTick; + for (var i = 0; i < 4; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + expect( + (source.positionTick - paused).abs(), + lessThan(TimelineClock.ticksPerSecond ~/ 10), + ); + expect(source.error, isNull); + } + } finally { + await target.closeSource(); + await tester.pump(); + } + }); + await check('pointerDragIntoTimeline', () async { + final tile = find.byWidgetPredicate( + (widget) => + widget is Draggable && + widget.data?.assetId == asset.id, + ); + // Scroll the media panel as needed without opening a source preview. + final scroll = tester.state( + find + .descendant( + of: find.byType(MediaPanel), + matching: find.byType(Scrollable), + ) + .last, + ); + scroll.position.jumpTo(0); + await tester.pump(const Duration(milliseconds: 200)); + for ( + var attempt = 0; + tile.evaluate().isEmpty && attempt < 20; + attempt++ + ) { + scroll.position.jumpTo( + math.min( + scroll.position.maxScrollExtent, + scroll.position.pixels + 180, + ), + ); + await tester.pump(const Duration(milliseconds: 150)); + } + expect(tile, findsOneWidget); + await tester.ensureVisible(tile); + await tester.pump(); + final surfaceRect = tester.getRect( + find.byKey(const Key('editor-timeline-surface')), + ); + final viewport = TimelineViewportRect( + width: surfaceRect.width, + height: surfaceRect.height, + ); + final destination = + surfaceRect.topLeft + + Offset( + 24, + view.camera.screenYForWorld( + view.geometry.primaryTop + + view.geometry.primaryHeight / 2 + + (kind == 'audio' ? 100 : 0), + viewport, + ), + ); + final gesture = await tester.startGesture( + tester.getCenter(tile), + kind: PointerDeviceKind.mouse, + ); + await gesture.moveBy(const Offset(24, 0)); + await tester.pump(); + await gesture.moveTo(destination); + await tester.pump(const Duration(seconds: 1)); + final drop = tester.state( + find.byType(TimelineExternalDropTarget), + ); + debugPrint( + 'DOWNLOADS_DRAG preview=${drop.hasPreview} enabled=${drop.enabled} error=${drop.error} placement=${drop.placementError} duration=${drop.preparedMedia?.metadata.duration}', + ); + await gesture.up(); + await until( + () => session.sequenceDurationTicks(sequence) > 0, + 'timeline insert', + ); + }); + } + final query = session.persistence.timeline(sequence).current.query(); + final original = session.persistence + .timeline(sequence) + .exportDto() + .elements + .map((dto) => query.elementById(dto.id)!) + .firstWhere((h) { + final record = query.element(h); + return record.payloadRef != null && + session.payloadFor(record.payloadRef!)?.type == kind; + }); + final clipId = query.element(original).id; + final originalDuration = query.element(original).duration; + result['originalDurationTicks'] = originalDuration; + await check('sourceDurationPreserved', () async { + final source = await container + .read(runtimeConnectionProvider) + .probe( + MediaReference(id: 'duration-check', uri: File(path).uri), + ); + final numerator = BigInt.from(source.duration.numerator); + final denominator = BigInt.from(source.duration.denominator); + final expectedTicks = + numerator * + BigInt.from(TimelineClock.ticksPerSecond) ~/ + denominator; + expect(BigInt.from(originalDuration), expectedTicks); + expect(query.element(original).sourceDuration, originalDuration); + expect(query.element(original).mediaDuration, originalDuration); + result['nativeSourceDuration'] = source.duration.toMap(); + result['discardedTickFraction'] = + '${numerator * BigInt.from(TimelineClock.ticksPerSecond) % denominator}/$denominator'; + }); + final frameTicks = view.format.frameGrid.quantumTicks; + final splitTick = math.max( + frameTicks, + ((math.min(4 * TimelineClock.ticksPerSecond, originalDuration / 2) / + frameTicks) + .floor()) * + frameTicks, + ); + await until( + () => + container + .read(editorPreviewProvider(ids.$1, ids.$2)) + .asData + ?.value + ?.ready == + true, + 'preview ready', + ); + var preview = container + .read(editorPreviewProvider(ids.$1, ids.$2)) + .requireValue!; + container.read(previewTargetProvider(ids.$1, ids.$2)).showTimeline(); + Future seek(int tick) async { + var waits = 0; + debugPrint('DOWNLOADS_SEEK stage=$stage tick=$tick'); + await until(() { + // Import/autosave can replace the preview binding. Follow the + // live provider rather than waiting on a disposed controller. + final active = container + .read(editorPreviewProvider(ids.$1, ids.$2)) + .asData + ?.value; + if (active != null && active.error != null) { + throw StateError('Native preview: ${active.error}'); + } + if (active == null || !active.ready || active.busy) { + if (waits++ % 50 == 0) { + debugPrint( + 'DOWNLOADS_WAIT ready=${active?.ready} busy=${active?.busy} ' + 'playing=${active?.playing} native=${active?.session?.snapshot?.state}', + ); + } + return false; + } + preview = active; + return true; + }, 'timeline preview ready for seek'); + expect(preview.error, isNull); + await preview.controlPreview( + sequence, + PreviewAction.seek, + at: CommandTime(tick, TimelineClock.ticksPerSecond), + ); + await until(() => !preview.busy, 'seek'); + expect(preview.error, isNull); + } + + Future playPause() async { + final start = preview.positionTick; + await tester.tap(find.byTooltip('播放')); + await until( + () => + preview.playing && + preview.positionTick > + start + + math.min( + TimelineClock.ticksPerSecond ~/ 4, + math.max( + frameTicks, + (session.sequenceDurationTicks(sequence) - + start) ~/ + 3, + ), + ), + 'play advances', + ); + expect(preview.error, isNull); + await until( + () => find.byTooltip('暂停播放').evaluate().isNotEmpty, + 'pause button renders', + seconds: 5, + ); + await tester.tap(find.byTooltip('暂停播放')); + await until(() => !preview.playing && !preview.busy, 'pause'); + final paused = preview.positionTick; + await tester.pump(const Duration(milliseconds: 400)); + expect( + (preview.positionTick - paused).abs(), + lessThan(TimelineClock.ticksPerSecond ~/ 10), + ); + expect(preview.error, isNull); + final state = preview.queryPreview(sequence); + (result.putIfAbsent( + 'playbackSamples', + () => >[], + ) as List).add({ + 'startTick': start, + 'pausedTick': paused, + 'presentedVideoFrames': state.presentedVideoFrameCount, + 'droppedVideoFrames': state.droppedVideoFrameCount, + 'maximumVideoFrameGapMs': state.maximumVideoFrameGapMs, + }); + } + + await check('playAndPause', () async { + await seek(0); + await playPause(); + }); + if (dropOnly) { + await check('seekImportedClip', () async { + await seek( + math.min( + 2 * TimelineClock.ticksPerSecond, + originalDuration ~/ 2, + ), + ); + await playPause(); + }); + await check('saveImportedClip', () async { + await session.flush(); + expect(session.saveError, isNull); + final saved = session.persistence.timeline(sequence).exportDto(); + final content = saved.elements + .where((element) => element.payloadRef != null) + .single; + expect( + TimelineClock.standard.toTicks(content.duration), + originalDuration, + ); + expect(content.sourceRange.duration, content.duration); + expect(content.mediaRange!.duration, content.duration); + }); + result['passed'] = true; + final after = File(path).statSync(); + result['sourceUnchanged'] = + before.size == after.size && before.modified == after.modified; + if (result['sourceUnchanged'] != true) result['passed'] = false; + save(); + continue; + } + await check('splitFromToolbar', () async { + preview.selectVisual(clipId); + await seek(splitTick); + await tester.pump(); + await tester.tap(find.byTooltip('在播放头处分割')); + await tester.pump(const Duration(milliseconds: 500)); + final q = session.persistence.timeline(sequence).current.query(); + final clips = session.persistence + .timeline(sequence) + .exportDto() + .elements + .map((dto) => q.elementById(dto.id)!) + .where((h) { + final record = q.element(h); + return record.payloadRef != null && + session.payloadFor(record.payloadRef!)?.type == kind; + }) + .toList(); + expect(clips.length, 2); + expect(q.element(q.elementById(clipId)!).duration, splitTick); + expect( + clips.map((h) => q.element(h).duration).reduce((a, b) => a + b), + originalDuration, + ); + await seek( + math.max(0, splitTick - TimelineClock.ticksPerSecond ~/ 10), + ); + await playPause(); + }); + await check('speedFromPropertySlider', () async { + preview.selectVisual(clipId); + await tester.pump(); + await tester.tap(find.byKey(const ValueKey('property-tab-speed'))); + await tester.pump(); + final slider = find.descendant( + of: find.byKey(const Key('clip-speed-slider')), + matching: find.byType(Slider), + ); + expect(slider, findsOneWidget); + // Drag the native editor's logarithmic slider, verify the actual retime map. + for (final requestedSpeed in [2.0, 0.5]) { + final rect = tester.getRect(slider); + final oldValue = tester.widget(slider).value; + final pos = (math.log(requestedSpeed) / math.ln10 + 1) / 3; + final gesture = await tester.startGesture( + Offset( + rect.left + 12 + (rect.width - 24) * oldValue, + rect.center.dy, + ), + ); + await gesture.moveTo( + Offset( + rect.left + 12 + (rect.width - 24) * pos, + rect.center.dy, + ), + ); + await tester.pump(); + await gesture.up(); + await tester.pump(const Duration(milliseconds: 500)); + final q = session.persistence.timeline(sequence).current.query(); + final record = q.element(q.elementById(clipId)!); + final speed = session.clipSpeed(record)!; + expect(speed, closeTo(requestedSpeed, 0.05)); + expect( + record.duration, + closeTo( + splitTick / requestedSpeed, + TimelineClock.ticksPerSecond / 4, + ), + ); + (result.putIfAbsent('testedSpeeds', () => []) as List) + .add(speed); + await seek(0); + await playPause(); + } + }); + if (kind == 'audio') { + await check('muteAndUnmuteFromProperties', () async { + preview.selectVisual(clipId); + await tester.pump(); + await tester.tap( + find.byKey(const ValueKey('property-tab-audio')), + ); + await tester.pump(); + for (final muted in [true, false]) { + await tester.tap(find.byKey(const Key('audio-mute'))); + await tester.pump(const Duration(milliseconds: 500)); + final q = session.persistence + .timeline(sequence) + .current + .query(); + expect( + ClipAudioGain.fromRecord(q.element(q.elementById(clipId)!)) + .muted, + muted, + ); + await seek(0); + await playPause(); + } + }); + } else if (session.hasAudio(query.element(original))) { + await check('detachAudioFromContextMenu', () async { + await seek(0); + preview.selectVisual(clipId); + await tester.pump(); + final surface = find.byKey(const Key('editor-timeline-surface')); + final bounds = tester.getRect(surface); + final frame = view.project( + TimelineViewportRect( + width: bounds.width, + height: bounds.height, + ), + ); + // First primary video spans the first two seconds in the visible viewport. + final clipIndex = Iterable.generate(frame.length) + .firstWhere((i) { + final handle = view.elementForIdentity(frame.identityAt(i)); + return handle != null && + view.version.kernelVersion.query().element(handle).id == + clipId; + }); + final clipBounds = view.presentationBoundsAt(frame, clipIndex); + final point = + bounds.topLeft + + Offset( + math.max(clipBounds.left + 15, 20), + clipBounds.center.dy, + ); + final contextGesture = await tester.startGesture( + point, + kind: PointerDeviceKind.mouse, + buttons: kSecondaryMouseButton, + ); + await contextGesture.up(); + await until( + () => find.text('分离音频').evaluate().isNotEmpty, + 'audio menu', + ); + await tester.tap(find.text('分离音频')); + await tester.pump(const Duration(milliseconds: 500)); + final q = session.persistence.timeline(sequence).current.query(); + final video = q.element(q.elementById(clipId)!); + expect(ClipAudioGain.fromRecord(video).muted, isTrue); + expect(ClipAudioGain.isDetached(video), isTrue); + final audio = session.persistence + .timeline(sequence) + .exportDto() + .elements + .map((dto) => q.element(q.elementById(dto.id)!)) + .where( + (r) => + r.payloadRef != null && + session.payloadFor(r.payloadRef!)?.type == 'audio', + ) + .toList(); + expect(audio.length, 1); + expect(audio.single.duration, video.duration); + expect(audio.single.sourceDuration, video.sourceDuration); + expect( + session.clipSpeed(audio.single), + closeTo(session.clipSpeed(video)!, 0.001), + ); + result['detachedAudioId'] = audio.single.id.value; + await seek(0); + await playPause(); + }); + } + await check('save', () async { + await session.flush(); + expect(session.saveError, isNull); + }); + result['passed'] = true; + } catch (error, stack) { + checks.add({'stage': stage, 'passed': false, 'error': '$error'}); + debugPrint('DOWNLOADS_WORKFLOW FAILED $stage $error\n$stack'); + } + final after = File(path).statSync(); + result['sourceUnchanged'] = + before.size == after.size && before.modified == after.modified; + if (result['sourceUnchanged'] != true) result['passed'] = false; + save(); + } + await tester.pumpWidget(const SizedBox.shrink()); + expect( + results.where((r) => r['passed'] != true).toList(), + isEmpty, + reason: 'See ${report.path}', + ); + }, + skip: !configured, + timeout: const Timeout(Duration(minutes: 30)), + ); +} diff --git a/integration_test/edit_diagnostics_test.dart b/integration_test/edit_diagnostics_test.dart new file mode 100644 index 0000000..3d4656f --- /dev/null +++ b/integration_test/edit_diagnostics_test.dart @@ -0,0 +1,596 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:math' as math; +import 'dart:ui'; + +import 'package:cutdex/app/editor_theme.dart'; +import 'package:cutdex/diagnostics/app_diagnostics.dart'; +import 'package:cutdex/diagnostics/diagnostic_store.dart'; +import 'package:cutdex/features/preview/preview_panel.dart'; +import 'package:cutdex/features/properties/speed_properties.dart'; +import 'package:cutdex/features/timeline/timeline_panel.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex/persistence/app_database.dart'; +import 'package:cutdex/workspace/timeline_provider.dart'; +import 'package:cutdex/workspace/timeline_session.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/preview.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:drift/native.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; +import 'package:path/path.dart' as p; + +import 'support/native_media_fixture.dart'; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + const output = String.fromEnvironment('CUTDEX_TEST_REPORT'); + const cadence = bool.fromEnvironment('CUTDEX_DIAGNOSTIC_CADENCE'); + testWidgets( + 'real editor diagnostics and logging performance comparison', + (tester) async { + expect( + kProfileMode || cadence, + isTrue, + reason: 'Use Profile for Flutter timings, or Debug with opt-in native cadence.', + ); + final root = Directory(output)..createSync(recursive: true); + final source = await nativeMediaFixture(); + final originalSource = await source.stat(); + final store = DiagnosticStore( + Directory( + p.join(root.path, 'logs-${DateTime.now().microsecondsSinceEpoch}'), + ), + ); + final diagnostics = AppDiagnostics( + store, + metadata: { + 'validation': 'real editor', + 'platform': Platform.operatingSystem, + 'buildMode': kProfileMode ? 'profile' : 'debug', + }, + ); + await diagnostics.readApplicationInfo(); + var logging = true; + var measuring = false; + final recordCosts = []; + void sink(DiagnosticEvent event) { + if (!logging) return; + final watch = Stopwatch()..start(); + diagnostics.event(event); + if (measuring) recordCosts.add(watch.elapsedMicroseconds); + } + + final runtime = CutdexRuntime(diagnostics: sink); + final probe = await runtime.probe( + MediaReference(id: 'media', uri: source.uri), + ); + expect(probe.videoTrackCount, greaterThan(0)); + expect(probe.duration.seconds, greaterThanOrEqualTo(25)); + final sequence = SequenceId('sequence'); + final clipId = ElementId('clip'); + final duration = RationalTime( + probe.duration.numerator, + probe.duration.denominator, + ); + final project = await ProjectFile.create( + Directory( + p.join( + root.path, + 'Editing-${DateTime.now().microsecondsSinceEpoch}.cutdex', + ), + ), + name: 'Diagnostic validation', + ); + await project.saveAsset( + AssetDocument( + id: 'media', + name: 'Generated test media', + storage: AssetStorage.external, + location: source.uri.toString(), + ), + ); + await project.saveTimeline( + TimelineDocument( + id: 'timeline', + name: 'Diagnostic validation', + defaultSequenceId: sequence, + settings: { + 'renderSize': {'width': 1280, 'height': 720}, + }, + payloads: [ + PayloadDocument( + id: 'video', + type: 'video', + assetIds: ['media'], + data: { + 'videoTrackIndex': 0, + if (probe.audioTrackCount > 0) 'audioTrackIndex': 0, + }, + ), + ], + sequences: [ + TimelineDto( + id: sequence, + format: TimelineFormat.fps30, + primaryStorylineId: StorylineId('primary'), + storylines: [ + StorylineDto(id: StorylineId('primary'), elementIds: [clipId]), + ], + elements: [ + ElementDto( + id: clipId, + structure: ElementStructure.content, + duration: duration, + sourceRange: TimeRange( + start: RationalTime.zero, + duration: duration, + ), + mediaRange: TimeRange( + start: RationalTime.zero, + duration: duration, + ), + payloadRef: PayloadRef('video'), + ), + ], + ), + ], + ), + ); + final session = _FaultingSession( + document: await project.loadTimeline('timeline'), + persistence: await project.openTimelineSaveSession('timeline'), + assetUris: {'media': source.uri}, + diagnostics: (event) => withDiagnosticContext({ + 'projectId': project.info.id, + }, () => reportDiagnostic(sink, event)), + ); + final preview = PreviewController( + timeline: session, + runtime: runtime, + activeSequence: () => session.activeSequenceId, + viewForSequence: session.view, + ); + final database = AppDatabase(NativeDatabase.memory()); + final frames = _FrameMeasurements(); + addTearDown(() async { + SchedulerBinding.instance.removeTimingsCallback(frames.accept); + session.fault = null; + await preview.close(); + await session.close(); + await project.close(); + await store.flush(); + await database.close(); + }); + SchedulerBinding.instance.addTimingsCallback(frames.accept); + final faults = >[]; + final runs = >[]; + final report = File(p.join(root.path, 'results.json')); + var passed = false; + Map? savedState; + void save() => report.writeAsStringSync( + const JsonEncoder.withIndent(' ').convert({ + 'at': DateTime.now().toUtc().toIso8601String(), + 'passed': passed, + 'platform': Platform.operatingSystem, + 'dart': Platform.version, + 'mode': kProfileMode ? 'profile' : 'debug', + 'source': { + 'path': source.path, + 'durationSeconds': probe.duration.seconds, + 'bytes': originalSource.size, + }, + 'method': + 'Mounted production timeline toolbar, speed slider and native playback; ' + 'controlled failures at the authoritative commit boundary. Same-build alternating ' + 'diagnostic sink on/off; bounded 16 ms pumps during playback. ' + 'Flutter timings exclude independently rendered platform-view video. ' + 'Native cadence is available only in opt-in macOS Debug builds.', + 'faults': faults, + 'runs': runs, + 'savedState': savedState, + 'storage': { + 'flushes': store.eventFlushes, + 'bytes': store.eventBytesWritten, + 'dropped': store.dropped, + 'droppedErrors': store.droppedErrors, + 'writeFailures': store.writeFailures, + }, + }), + ); + save(); + await preview.initialize(); + expect(preview.error, isNull); + await tester.pumpWidget( + ProviderScope( + overrides: [ + appDatabaseProvider.overrideWithValue(database), + editorTimelineProvider( + project.info.id, + 'timeline', + ).overrideWith((ref) async => session), + editorPreviewProvider( + project.info.id, + 'timeline', + ).overrideWith((ref) async => preview), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + theme: EditorTheme.penDark, + home: Scaffold( + body: Column( + children: [ + Expanded( + child: Row( + children: [ + Expanded( + child: EditorPreviewPanel( + projectId: project.info.id, + timelineId: 'timeline', + ), + ), + SizedBox( + width: 280, + child: SingleChildScrollView( + child: SpeedProperties( + session: session, + sequence: sequence, + clip: clipId, + ), + ), + ), + ], + ), + ), + SizedBox( + height: 260, + child: EditorTimelinePanel( + projectId: project.info.id, + timelineId: 'timeline', + ), + ), + ], + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect(find.byType(RuntimePreview), findsOneWidget); + final view = session.view(sequence); + Future until(bool Function() predicate, String label) async { + final watch = Stopwatch()..start(); + while (!predicate()) { + if (preview.error != null) { + throw StateError('$label: ${preview.error}'); + } + if (watch.elapsed > const Duration(seconds: 30)) { + throw StateError('Timed out: $label'); + } + await tester.pump(const Duration(milliseconds: 30)); + } + await tester.pump(); + } + + Future settle() async { + await until( + () => + preview.canPlay && + !preview.busy && + preview.durationTick == session.sequenceDurationTicks(sequence), + 'native preview', + ); + await tester.pump(const Duration(milliseconds: 100)); + expect(preview.error, isNull); + } + + Future selectAt(double seconds) async { + final query = session.persistence.timeline(sequence).current.query(); + view.setSelection([query.elementById(clipId)!]); + view.seekTo((seconds * TimelineClock.ticksPerSecond).round()); + await settle(); + } + + Future slider(double speed) async { + final finder = find.descendant( + of: find.byKey(const Key('clip-speed-slider')), + matching: find.byType(Slider), + ); + expect(finder, findsOneWidget); + final rect = tester.getRect(finder); + final position = (math.log(speed) / math.ln10 + 1) / 3; + final old = tester.widget(finder).value; + final start = Offset( + rect.left + 12 + (rect.width - 24) * old, + rect.center.dy, + ); + final end = Offset( + rect.left + 12 + (rect.width - 24) * position, + rect.center.dy, + ); + final gesture = await tester.startGesture(start); + for (var i = 1; i <= 12; i++) { + await gesture.moveTo(Offset.lerp(start, end, i / 12)!); + await tester.pump(const Duration(milliseconds: 16)); + } + await gesture.up(); + await tester.pump(); + } + + Future edit(String operation) async { + switch (operation) { + case 'split': + await tester.tap(find.byTooltip('在播放头处分割')); + case 'trimLeft': + await tester.tap(find.byKey(const ValueKey('timeline-trim-left'))); + case 'trimRight': + await tester.tap(find.byKey(const ValueKey('timeline-trim-right'))); + case 'setSpeed': + await slider(2); + } + await tester.pump(); + } + + Future> exported() async => jsonDecode( + await (await diagnostics.export( + Directory(p.join(root.path, 'exports')), + )).readAsString(), + ) as Map; + for (final operation in ['split', 'trimLeft', 'trimRight', 'setSpeed']) { + await selectAt(5); + final before = session.version; + final marker = 'CONTROLLED_${operation.toUpperCase()}_STACK'; + session.fault = marker; + try { + await withDiagnosticContext({ + 'validationScenario': operation, + }, () => edit(operation)); + } finally { + session.fault = null; + } + expect(session.version, before); + final events = (await exported())['events'] as List; + final event = events.singleWhere( + (e) => + (e as Map)['level'] == 'error' && + (e['context'] as Map)['validationScenario'] == operation, + ) as Map; + expect( + event['operation'], + operation.startsWith('trim') ? 'trim' : operation, + ); + final context = event['context'] as Map; + expect(context['clipIds'], ['clip']); + expect(context['timelineId'], 'timeline'); + expect(context['projectId'], project.info.id); + expect(context['operationId'], isNotEmpty); + expect(context['versionBefore'], before); + expect(context['versionAfter'], before); + expect(event['stackTrace'], marker); + faults.add({ + 'operation': operation, + 'passed': true, + 'operationId': context['operationId'], + 'stack': event['stackTrace'], + }); + // Recovery uses the same UI path with the failure removed. + await edit(operation); + expect(session.version, isNot(before)); + await settle(); + await tester.tap(find.byTooltip('撤销')); + await tester.pump(); + await settle(); + await session.flush(); + save(); + } + Future> nativeCadence() async { + if (!cadence) return {}; + final values = (await const MethodChannel('cutdex_runtime') + .invokeListMethod('_debugPreviewCadence'))!; + return values + .map((v) => Map.from(v! as Map)) + .singleWhere( + (v) => v['mounted'] == true && (v['rate']! as num) > 0, + ); + } + + Future observe(Duration duration) async { + final watch = Stopwatch()..start(); + while (watch.elapsed < duration) { + await tester.pump(const Duration(milliseconds: 16)); + } + } + + // Warm the native decoders and editor before collecting comparisons. + await selectAt(0); + await preview.togglePlayback(); + await observe(const Duration(seconds: 2)); + await preview.togglePlayback(); + for (var round = 0; round < 6; round++) { + // Three paired comparisons; alternate pair order to reduce order bias. + logging = const [false, true, true, false, false, true][round]; + await selectAt(5); + await session.flush(); + await store.flush(); + final initialFlushes = store.eventFlushes; + final initialBytes = store.eventBytesWritten; + recordCosts.clear(); + frames.start(); + measuring = true; + final watch = Stopwatch()..start(); + for (final operation in ['split', 'trimLeft', 'trimRight']) { + await selectAt(5); + await edit(operation); + await settle(); + await tester.tap(find.byTooltip('撤销')); + await tester.pump(); + await settle(); + } + await slider(2); + await settle(); + final query = session.persistence.timeline(sequence).current.query(); + expect( + session.clipSpeed(query.element(query.elementById(clipId)!)), + closeTo(2, 0.05), + ); + await selectAt(0); + await preview.togglePlayback(); + await observe(const Duration(milliseconds: 500)); + final firstNative = await nativeCadence(); + final firstPosition = + (await preview.session!.refresh()).position.seconds; + final playbackWatch = Stopwatch()..start(); + await observe(const Duration(seconds: 3)); + final lastNative = await nativeCadence(); + final lastPosition = + (await preview.session!.refresh()).position.seconds; + playbackWatch.stop(); + await preview.togglePlayback(); + expect(lastPosition, greaterThan(firstPosition + 1)); + expect(preview.error, isNull); + await tester.tap(find.text('1×')); + await settle(); + await session.flush(); + await store.flush(); + await observe(const Duration(milliseconds: 150)); + measuring = false; + final timing = frames.stop(); + if (kProfileMode) expect(timing['count'], greaterThan(10)); + final native = {}; + if (cadence) { + for (final value in [firstNative, lastNative]) { + expect(value['windowVisible'], isTrue); + expect(value['windowOccluded'], isFalse); + } + final frames = + (lastNative['frames']! as num) - (firstNative['frames']! as num); + final dropped = + (lastNative['dropped']! as num) - + (firstNative['dropped']! as num); + native.addAll({ + 'viewWidth': firstNative['width'], + 'viewHeight': firstNative['height'], + 'windowVisible': firstNative['windowVisible'], + 'windowOccluded': firstNative['windowOccluded'], + 'frames': frames, + 'dropped': dropped, + 'rendererFps': frames / (playbackWatch.elapsedMicroseconds / 1e6), + 'displayedFps': + (frames - dropped) / (playbackWatch.elapsedMicroseconds / 1e6), + }); + expect(frames, greaterThan(0)); + } + runs.add({ + 'round': round, + 'logging': logging, + 'elapsedMs': watch.elapsedMicroseconds / 1000, + 'flutterFrames': timing, + 'nativeCadence': native, + 'playbackSeconds': playbackWatch.elapsedMicroseconds / 1e6, + 'playbackClockAdvanceSeconds': lastPosition - firstPosition, + 'logCalls': recordCosts.length, + 'recordP95Us': _percentile(recordCosts, .95), + 'flushes': store.eventFlushes - initialFlushes, + 'logBytes': store.eventBytesWritten - initialBytes, + }); + expect(store.dropped, 0); + expect(store.writeFailures, 0); + save(); + } + logging = true; + await session.flush(); + final stored = await project.loadTimeline('timeline'); + final savedClip = stored.sequences.single.elements.singleWhere( + (e) => e.id == clipId, + ); + expect(savedClip.duration, duration); + expect(savedClip.sourceRange.duration, duration); + final bundle = await exported(); + final errors = (bundle['events'] as List) + .where((e) => (e as Map)['level'] == 'error') + .toList(); + expect( + errors, + hasLength(4), + reason: 'Only the four controlled failures are expected.', + ); + savedState = { + 'passed': true, + 'durationSeconds': savedClip.duration.seconds, + 'sourceDurationSeconds': savedClip.sourceRange.duration.seconds, + 'errorEvents': errors.length, + }; + final afterSource = await source.stat(); + expect(afterSource.size, originalSource.size); + expect(afterSource.modified, originalSource.modified); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox.shrink()); + passed = true; + save(); + }, + skip: output.isEmpty || !hasNativeMediaFixture, + timeout: const Timeout(Duration(minutes: 10)), + ); +} + +class _FaultingSession extends EditorTimelineSession { + _FaultingSession({ + required super.document, + required super.persistence, + required super.assetUris, + super.diagnostics, + }); + String? fault; + @override + T commit(SequenceId? sequence, T Function() action) { + if (fault case final marker?) { + Error.throwWithStackTrace( + StateError('Controlled edit failure'), + StackTrace.fromString(marker), + ); + } + return super.commit(sequence, action); + } +} + +final class _FrameMeasurements { + final _frames = []; + var _active = false; + void accept(List frames) { + if (_active) _frames.addAll(frames); + } + + void start() { + _frames.clear(); + _active = true; + } + + Map stop() { + _active = false; + final build = _frames.map((f) => f.buildDuration.inMicroseconds).toList(); + final raster = _frames.map((f) => f.rasterDuration.inMicroseconds).toList(); + return { + 'count': _frames.length, + 'buildP95Us': _percentile(build, .95), + 'rasterP95Us': _percentile(raster, .95), + 'buildOver16ms': build.where((v) => v > 16667).length, + 'rasterOver16ms': raster.where((v) => v > 16667).length, + }; + } +} + +int? _percentile(List values, double fraction) { + if (values.isEmpty) return null; + final ordered = [...values]..sort(); + return ordered[(ordered.length * fraction).ceil() - 1]; +} diff --git a/integration_test/ios_device_test.dart b/integration_test/ios_device_test.dart new file mode 100644 index 0000000..d25785c --- /dev/null +++ b/integration_test/ios_device_test.dart @@ -0,0 +1,16 @@ +import 'complex_preview_test.dart' as composition; +import 'picture_keyframes_test.dart' as keyframes; +import 'playback_app_acceptance_test.dart' as application; +import 'preview_drag_timing_test.dart' as dragging; +import 'preview_test.dart' as playback; +import 'timeline_thumbnail_timing_test.dart' as thumbnails; + +/// Runs the shared native media regressions in one installation on an iPhone. +void main() { + playback.main(); + composition.main(); + keyframes.main(); + thumbnails.main(); + dragging.main(); + application.main(); +} diff --git a/integration_test/media_timebase_drop_test.dart b/integration_test/media_timebase_drop_test.dart new file mode 100644 index 0000000..08d7b59 --- /dev/null +++ b/integration_test/media_timebase_drop_test.dart @@ -0,0 +1,230 @@ +import 'dart:io'; + +import 'package:cutdex/features/timeline/timeline_drop_preparation.dart'; +import 'package:cutdex/features/timeline/timeline_external_drop_target.dart'; +import 'package:cutdex/workspace/persistence/project_workspace.dart'; +import 'package:cutdex/workspace/project_state.dart'; +import 'package:cutdex/workspace/projects.dart'; +import 'package:cutdex/workspace/timeline_session.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/preview.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; + +import '../test/support/preview_fixture.dart'; +import 'support/native_media_fixture.dart'; + +class _DropProjects extends Projects { + _DropProjects(this.workspace, this.session, this.asset); + final ProjectWorkspace workspace; + final EditorTimelineSession session; + final AssetDocument asset; + String get _projectId => workspace.project!.info.id; + + @override + Future build() async => ProjectState( + activeProject: RecentProject( + id: _projectId, + name: 'Media timebase test', + path: workspace.project!.directory.path, + ), + timeline: session.document, + assets: [asset], + ); + + @override + Future withAssetMedia( + String? projectId, + AssetDocument asset, + Future Function(MediaReference) action, + ) => workspace.withAssetMedia(_projectId, asset, action); +} + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + testWidgets('real media timebase supports Finder and project asset drops', ( + tester, + ) async { + final source = await nativeMediaFixture(); + expect(await source.exists(), isTrue); + final info = await CutdexRuntime().probe( + MediaReference(id: 'source', uri: source.uri), + ); + debugPrint( + 'DROP_PROBE ${info.duration.numerator}/${info.duration.denominator}', + ); + final fixture = await createPreviewFixture(source.uri); + final session = fixture.timeline; + final workspace = fixture.workspace; + session.selectSequence(SequenceId('empty')); + final asset = (await workspace.project!.listAssets()).single; + final projects = _DropProjects(workspace, session, asset); + final container = ProviderContainer( + overrides: [projectsProvider.overrideWith(() => projects)], + ); + final target = GlobalKey(); + final incoming = ValueNotifier(null); + addTearDown(() async { + incoming.dispose(); + container.dispose(); + await workspace.close(); + await fixture.directory.delete(recursive: true); + }); + await container.read(projectsProvider.future); + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: MaterialApp( + home: Scaffold( + body: TimelineExternalDropTarget( + key: target, + projectId: projects._projectId, + session: session, + sequenceId: SequenceId('empty'), + incoming: incoming, + child: const SizedBox.expand(), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + final ticks = + (BigInt.from(info.duration.numerator) * + BigInt.from(TimelineClock.ticksPerSecond) ~/ + BigInt.from(info.duration.denominator)) + .toInt(); + final runtime = CutdexRuntime(); + final native = await runtime.createSession(); + addTearDown(native.close); + Future plan() async { + final kernel = session.persistence.timeline(SequenceId('empty')); + final media = await prepareEditorMedia( + session: session, + sequence: SequenceId('empty'), + version: kernel.current, + probe: runtime.probe, + unknownVideoColorSpace: const PreviewPolicy().unknownVideoColorSpace, + ); + return const ExecutionCompiler() + .compile( + ExecutionInput( + timeline: kernel, + media: media.bindings, + renderSize: RenderSize(320, 180), + ), + ) + .plan; + } + + for (final finder in [true, false]) { + if (finder) { + target.currentState!.enterExternal( + 1, + source.path, + const Offset(125, 65), + ); + } else { + incoming.value = ( + asset: asset, + globalPosition: + tester.getTopLeft(find.byType(TimelineExternalDropTarget)) + + const Offset(125, 65), + ); + } + final preparer = container.read( + timelineDropPreparationProvider( + projects._projectId, + session, + SequenceId('empty'), + ).notifier, + ); + await preparer.waitForPreparation(); + await tester.pumpAndSettle(); + expect(target.currentState!.placementError, isNull); + expect(target.currentState!.incomingClip?.layout, isNotNull); + await target.currentState!.drop(); + incoming.value = null; + await tester.pumpAndSettle(); + final query = session.persistence + .timeline(SequenceId('empty')) + .current + .query(); + final clip = query.element( + query.storylineElements(query.primaryStoryline).single, + ); + expect(clip.duration, ticks); + await session.flush(); + final saved = await workspace.project!.loadTimeline('project'); + expect( + saved.sequences + .singleWhere((s) => s.id == SequenceId('empty')) + .elements + .single + .duration, + RationalTime.timelineTicks(ticks), + ); + debugPrint('DROP_VALIDATED finder=$finder ticks=$ticks'); + if (finder) { + await native.load(await plan()); + for (final fraction in [.5, .9, 0.0]) { + final tick = (ticks * fraction).floor(); + await native.seek(MediaTime(tick, TimelineClock.ticksPerSecond)); + expect( + (await native.refresh()).position.seconds, + closeTo(tick / TimelineClock.ticksPerSecond, .05), + ); + } + await native.play(); + await Future.delayed(const Duration(milliseconds: 500)); + await native.pause(); + expect((await native.refresh()).position.seconds, greaterThan(.1)); + debugPrint('DROP_NATIVE_PLAYBACK_VALIDATED'); + } else { + session.commands.applyEdit( + SequenceId('empty'), + TrimClip(clip.id.value, CommandTime(3, 1)), + ); + const output = String.fromEnvironment('CUTDEX_TEST_OUTPUT'); + final destination = File( + output.isEmpty + ? '${fixture.directory.path}/timebase-export.mp4' + : output, + ); + final exported = await native.export(await plan(), destination.uri); + final result = await runtime.probe( + MediaReference(id: 'export', uri: exported), + ); + expect(result.duration.seconds, closeTo(3, .05)); + expect(result.videoTrackCount, 1); + expect(result.audioTrackCount, info.audioTrackCount > 0 ? 1 : 0); + final thumbnail = await runtime.thumbnail( + ThumbnailRequest( + media: MediaReference(id: 'export', uri: exported), + time: MediaTime(1, 1), + ), + ); + expect(thumbnail.data, isNotEmpty); + debugPrint('DROP_EXPORT_VALIDATED $exported'); + session.view(SequenceId('empty')).undo(); + expect( + session.persistence + .timeline(SequenceId('empty')) + .current + .query() + .storylineSpan(query.primaryStoryline), + ticks, + ); + } + session.view(SequenceId('empty')).undo(); + await tester.pumpAndSettle(); + } + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + }, skip: !hasNativeMediaFixture); +} diff --git a/integration_test/native_desktop_plugins_test.dart b/integration_test/native_desktop_plugins_test.dart new file mode 100644 index 0000000..81db2f2 --- /dev/null +++ b/integration_test/native_desktop_plugins_test.dart @@ -0,0 +1,67 @@ +import 'dart:io'; + +import 'package:cutdex_native/cutdex_native.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + + testWidgets( + 'desktop host registers native window and dynamic file destinations', + (tester) async { + // This harness has no project state to save when the native host quits. + const lifecycle = MethodChannel('cutdex/lifecycle'); + lifecycle.setMethodCallHandler( + (call) async => call.method == 'prepareToQuit', + ); + await lifecycle.invokeMethod('ready'); + await tester.pumpWidget( + const MaterialApp(home: Scaffold(body: SizedBox.expand())), + ); + + final chrome = WindowChromeSession(headerHeight: 40); + chrome.attach(); + addTearDown(chrome.dispose); + for (var attempt = 0; attempt < 20 && !chrome.integrated; attempt++) { + await tester.pump(const Duration(milliseconds: 50)); + } + expect( + chrome.integrated, + isTrue, + reason: 'The real native host must register window chrome.', + ); + + final drop = NativeFileDropConnection( + regionId: 'integration-host', + onEvent: (_) async {}, + ); + drop.bind(); + addTearDown(drop.dispose); + await drop.setRegion( + const Rect.fromLTWH(0, 80, 100, 100), + NativeDropConfiguration( + allowedExtensions: ['wav'], + maximumFileCount: 1, + ), + ); + // No mock handler: this must reach a destination created by the real plugin. + await drop.release(0); + await drop.setRegion(null, NativeDropConfiguration.unrestricted); + + if (Platform.isMacOS) { + var exits = 0; + final fullscreen = NativeFullscreenSession(onExit: () => exits++); + fullscreen.attach(); + await fullscreen.setFullscreen(true); + await fullscreen.setFullscreen(false); + await tester.pump(); + expect(exits, 1); + fullscreen.dispose(); + } + }, + skip: !(Platform.isMacOS || Platform.isWindows), + ); +} diff --git a/integration_test/picture_keyframes_test.dart b/integration_test/picture_keyframes_test.dart new file mode 100644 index 0000000..2cd87ef --- /dev/null +++ b/integration_test/picture_keyframes_test.dart @@ -0,0 +1,225 @@ +import 'package:cutdex/app/editor_theme.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; + +import 'dart:io'; +import 'dart:ui' as ui; + +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex/features/preview/preview_panel.dart'; +import 'package:cutdex/features/properties/picture_properties.dart'; +import 'package:cutdex_sdk/preview.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; + +import '../test/support/preview_fixture.dart'; +import 'support/native_media_fixture.dart'; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + const outputName = String.fromEnvironment('CUTDEX_TEST_OUTPUT'); + testWidgets('native grouped keyframes preview, scrub, play and export', ( + tester, + ) async { + final output = outputName.isEmpty + ? '' + : '${(await Directory.systemTemp.createTemp('cutdex-keyframes-')).path}/$outputName'; + final mediaFile = await nativeMediaFixture(); + final f = await createPreviewFixture( + mediaFile.uri, + clipDuration: RationalTime.seconds(4), + renderSize: {'width': 640, 'height': 360}, + ); + final runtime = CutdexRuntime(); + final preview = PreviewController( + timeline: f.timeline, + activeSequence: () => f.timeline.activeSequenceId, + viewForSequence: f.timeline.view, + runtime: runtime, + ); + addTearDown(() async { + await preview.close(); + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + await preview.initialize(); + expect(preview.error, isNull); + final sequence = SequenceId('one'); + final clip = ElementId('clip'); + final view = f.timeline.view(sequence); + ClipAnimation at(int seconds) { + final q = view.version.kernelVersion.query(); + return ClipAnimation.at( + q, + q.elementById(clip)!, + seconds * TimelineClock.ticksPerSecond, + TimelineClock.ticksPerSecond ~/ 30, + ); + } + + Future ready() async { + for (var i = 0; i < 200 && preview.busy; i++) { + await Future.delayed(const Duration(milliseconds: 25)); + await tester.pump(); + } + expect(preview.busy, isFalse); + expect(preview.error, isNull); + } + + Future commit(List curves) async { + f.timeline.commitParameters( + sequence, + f.timeline.previewParameters(sequence, clip, curves), + parameterTargets: ClipTransform.targets, + ); + await ready(); + } + + await commit(at(0).edit(const ClipTransform(scale: .5))); + await commit([ + for (final channel in TransformChannel.values) ...at(0).toggle(channel), + ]); + await commit( + at(2).edit( + const ClipTransform(x: .2, y: .1, scale: .7, scaleY: .9, rotation: 45), + ), + ); + final ids = (f.workspace.project!.info.id, 'project'); + final boundary = GlobalKey(); + Future mount(ThemeData theme, double width) => tester.pumpWidget( + ProviderScope( + overrides: [ + editorPreviewProvider( + ids.$1, + ids.$2, + ).overrideWith((ref) async => preview), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + theme: theme, + home: Scaffold( + body: Row( + children: [ + Expanded( + child: EditorPreviewPanel( + projectId: ids.$1, + timelineId: ids.$2, + ), + ), + SizedBox( + width: width, + child: RepaintBoundary( + key: boundary, + child: ColoredBox( + color: theme.scaffoldBackgroundColor, + child: SingleChildScrollView( + padding: const EdgeInsets.all(12), + child: PictureProperties( + projectId: ids.$1, + timelineId: ids.$2, + session: f.timeline, + sequence: sequence, + clip: at(0).record, + animationView: true, + ), + ), + ), + ), + ), + ], + ), + ), + ), + ), + ); + await mount(EditorTheme.penDark, 280); + preview.selectVisual(clip); + await tester.pumpAndSettle(); + expect( + find.descendant( + of: find.byType(PreviewInteractionOverlay), + matching: find.byType(CustomPaint), + ), + findsOneWidget, + ); + view.seekTo(TimelineClock.ticksPerSecond); + await Future.delayed(const Duration(milliseconds: 500)); + await tester.pump(); + final visual = preview.visualForProperties(clip)!; + expect(visual.transform.scaleY, closeTo(.7, 1e-8)); + expect(visual.transform.rotation, closeTo(22.5, 1e-8)); + final drag = preview.transforms.begin(visual)!; + expect(await drag.prepared, isTrue); + drag.update(drag.value.copyWith(scaleY: .8)); + await Future.delayed(const Duration(milliseconds: 100)); + await drag.end(); + preview.cancelTransform(); + await ready(); + expect(at(1).value.scaleY, closeTo(.8, 1e-8)); + expect(at(0).value.scaleY, .5); + expect(at(2).value.scaleY, .9); + await preview.togglePlayback(); + await Future.delayed(const Duration(milliseconds: 400)); + await tester.pump(); + expect(preview.playing, isTrue); + expect(preview.selectedVisualIds, {clip}); + expect( + find.descendant( + of: find.byType(PreviewInteractionOverlay), + matching: find.byType(CustomPaint), + ), + findsOneWidget, + ); + await preview.pauseForCanvasInteraction(); + final snapshot = await preview.session!.refresh(); + expect(snapshot.position.seconds, greaterThan(1)); + expect(preview.error, isNull); + for (final (theme, width, name) in [ + (EditorTheme.penDark, 280.0, 'dark'), + (EditorTheme.penLight, 225.0, 'light'), + ]) { + await mount(theme, width); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + if (output.isNotEmpty) { + final image = + await (boundary.currentContext!.findRenderObject()! + as RenderRepaintBoundary) + .toImage(pixelRatio: 2); + final bytes = await image.toByteData(format: ui.ImageByteFormat.png); + await File('$output-$name.png') + .writeAsBytes(bytes!.buffer.asUint8List()); + image.dispose(); + } + } + if (output.isNotEmpty) { + final preparedMedia = await prepareEditorMedia( + session: f.timeline, + sequence: sequence, + version: f.timeline.persistence.timeline(sequence).current, + probe: runtime.probe, + unknownVideoColorSpace: const PreviewPolicy().unknownVideoColorSpace, + ); + final compiled = const ExecutionCompiler().compile( + ExecutionInput( + timeline: f.timeline.persistence.timeline(sequence), + renderSize: RenderSize(640, 360), + parameterTargets: ClipTransform.targets, + media: preparedMedia.bindings, + ), + ); + await preview.session!.export(compiled.plan, File('$output.mp4').uri); + expect(await File('$output.mp4').length(), greaterThan(1000)); + debugPrint('KEYFRAME_ARTIFACTS $output'); + } + await f.timeline.flush(); + await tester.pumpWidget(const SizedBox()); + }); +} diff --git a/integration_test/playback_app_acceptance_test.dart b/integration_test/playback_app_acceptance_test.dart new file mode 100644 index 0000000..d137522 --- /dev/null +++ b/integration_test/playback_app_acceptance_test.dart @@ -0,0 +1,306 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:cutdex/app/app.dart'; +import 'package:cutdex/features/preview/preview_panel.dart'; +import 'package:cutdex/persistence/app_database.dart'; +import 'package:cutdex/workspace/projects.dart'; +import 'package:cutdex/workspace/timeline_provider.dart'; +import 'package:cutdex_sdk/preview.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:cutdex_sdk/timeline_ui.dart'; +import 'package:drift/native.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; + +import '../test/support/preview_fixture.dart'; +import 'support/native_media_fixture.dart'; + +void main() { + final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + const report = String.fromEnvironment('CUTDEX_TEST_REPORT'); + + testWidgets('full Cutdex app playback lifecycle and sustained editing', ( + tester, + ) async { + final mediaFile = await nativeMediaFixture(); + final fixture = await createPreviewFixture( + mediaFile.uri, + clipDuration: RationalTime.seconds(12), + hasAudio: true, + renderSize: {'width': 640, 'height': 360}, + ); + await fixture.workspace.close(); + final database = AppDatabase(NativeDatabase.memory()); + final container = ProviderContainer( + overrides: [appDatabaseProvider.overrideWithValue(database)], + ); + // macOS can hide the test window while another app is foreground. Keep + // tester.pump progressing without changing the application's lifecycle state. + final hiddenWindowFrames = Timer.periodic( + const Duration(milliseconds: 16), + (_) { + if (!binding.framesEnabled) binding.scheduleForcedFrame(); + }, + ); + final samples = >[]; + final steps = []; + void mark(String step) { + steps.add(step); + debugPrint('ACCEPTANCE: $step'); + } + + final watch = Stopwatch()..start(); + var quit = false; + final projects = container.read(projectsProvider.notifier); + Future until( + bool Function() condition, { + String label = 'UI settled', + }) async { + for (var attempt = 0; attempt < 500; attempt++) { + await tester.pump(const Duration(milliseconds: 20)); + await Future.delayed(const Duration(milliseconds: 5)); + if (condition()) { + expect(tester.takeException(), isNull, reason: label); + return; + } + } + fail('Timed out: $label'); + } + + Future settled(PreviewController preview) async { + await tester.pump(); + await until( + () => !preview.busy && preview.ready, + label: 'preview ready: ${preview.error}', + ); + expect(preview.error, isNull); + } + + void sample(String phase, int edits) { + samples.add({ + 'phase': phase, + 'edits': edits, + 'elapsedMs': watch.elapsedMilliseconds, + 'rssBytes': ProcessInfo.currentRss, + }); + debugPrint('ACCEPTANCE MEMORY: ${samples.last}'); + if (report.isNotEmpty) { + File(report).writeAsStringSync( + jsonEncode({ + 'steps': steps, + 'memory': samples, + 'durationMs': watch.elapsedMilliseconds, + 'complete': false, + }), + ); + } + } + + try { + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: const CutdexApp(), + ), + ); + await until(() => container.read(projectsProvider).hasValue); + final phoneCut = find.byKey(const Key('workspace-cut-destination')); + final desktopMode = find.byKey(const Key('sidebar-mode-trigger')); + await until( + () => + phoneCut.evaluate().isNotEmpty || desktopMode.evaluate().isNotEmpty, + ); + if (phoneCut.evaluate().isNotEmpty) { + expect(find.byKey(const Key('phone-workspace-shell')), findsOneWidget); + await tester.tap(phoneCut); + } else { + await tester.tap(desktopMode); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const ValueKey('sidebar-mode-cut'))); + } + await tester.pumpAndSettle(); + mark('selected Cut mode through the application navigation'); + expect( + await projects.open('${fixture.directory.path}/Preview.cutdex'), + isTrue, + ); + final state = await container.read(projectsProvider.future); + final ids = (state.activeProject!.id, 'project'); + expect(await projects.openTimeline(ids.$1, ids.$2), isTrue); + await until( + () => + container + .read(editorPreviewProvider(ids.$1, ids.$2)) + .asData + ?.value + ?.ready == + true, + label: 'full application preview initialized', + ); + final preview = container + .read(editorPreviewProvider(ids.$1, ids.$2)) + .requireValue!; + final timeline = await container.read( + editorTimelineProvider(ids.$1, ids.$2).future, + ); + final sequence = SequenceId('one'); + final view = timeline.view(sequence); + expect(find.byType(CutdexApp), findsOneWidget); + await until( + () => find.byType(RuntimePreview).evaluate().isNotEmpty, + label: 'native preview widget mounted', + ); + expect(find.byType(RuntimePreview), findsOneWidget); + expect(find.byType(TimelineView), findsOneWidget); + mark('full application and native preview mounted'); + + final panel = find.byType(EditorPreviewPanel); + await tester.tap( + find + .descendant(of: panel, matching: find.byIcon(Icons.play_arrow)) + .first, + ); + await until(() => preview.playing, label: 'UI play'); + await Future.delayed(const Duration(milliseconds: 700)); + await tester.pump(); + expect( + (await preview.session!.refresh()).position.seconds, + greaterThan(0), + ); + await tester.tap( + find.descendant(of: panel, matching: find.byIcon(Icons.pause)).first, + ); + await until(() => !preview.playing, label: 'UI pause'); + mark('real play and pause buttons advanced native media clock'); + + final timelineRect = tester.getRect(find.byType(TimelineView)); + await tester.dragFrom( + Offset(timelineRect.left + 80, timelineRect.top + 10), + const Offset(160, 0), + ); + await tester.pump(const Duration(milliseconds: 150)); + expect(preview.error, isNull); + for (final second in [3, 8, 1, 10, 0]) { + view.seekTo(second * TimelineClock.ticksPerSecond); + await tester.pump(const Duration(milliseconds: 120)); + await Future.delayed(const Duration(milliseconds: 80)); + expect(preview.error, isNull); + } + mark('timeline pointer drag and repeated forward/backward seeking'); + + expect( + await projects.createTimeline(name: 'Acceptance empty timeline'), + isTrue, + ); + await tester.pump(const Duration(milliseconds: 300)); + expect(await projects.openTimeline(ids.$1, ids.$2), isTrue); + await settled(preview); + mark('switch to empty timeline and return'); + + for (final events in [ + [ + PlaybackSystemEvent.systemWillSleep, + PlaybackSystemEvent.systemDidWake, + ], + [ + PlaybackSystemEvent.interruptionBegan, + PlaybackSystemEvent.interruptionEnded, + ], + ]) { + await preview.session!.handleSystemEvent(events.first); + final before = preview.session!.snapshot!.revision; + for (var i = 0; i < 8; i++) { + timeline.commands.setTransform( + sequence: sequence, + clip: ElementId('clip'), + tick: 0, + change: (value) => value.copyWith(x: i / 100), + ); + } + await tester.pump(const Duration(milliseconds: 100)); + expect(preview.session!.snapshot!.revision, before); + await preview.session!.handleSystemEvent(events.last); + await settled(preview); + } + await preview.session!.handleSystemEvent( + PlaybackSystemEvent.audioRouteChanged, + ); + timeline.commands.setTransform( + sequence: sequence, + clip: ElementId('clip'), + tick: 0, + change: (value) => value.copyWith(x: .12), + ); + await settled(preview); + expect(preview.session!.availability, PlaybackAvailability.available); + mark( + 'native sleep/wake, interruption and audio route events during real edits', + ); + + sample('before warmup', 0); + for (var index = 0; index < 180; index++) { + timeline.commands.setTransform( + sequence: sequence, + clip: ElementId('clip'), + tick: 0, + change: (value) => value.copyWith(x: (index % 10) / 100), + ); + await settled(preview); + if (index % 10 == 0) { + view.seekTo((index % 11) * TimelineClock.ticksPerSecond); + } + await tester.pump(const Duration(milliseconds: 40)); + await Future.delayed(const Duration(milliseconds: 700)); + if ((index + 1) % 20 == 0) sample('editing', index + 1); + expect(preview.error, isNull); + expect(tester.takeException(), isNull); + } + await timeline.saveTimeline(); + mark('180 native-backed edits with periodic seeks, saved successfully'); + + await preview.session!.handleSystemEvent( + PlaybackSystemEvent.systemWillSleep, + ); + timeline.commands.setTransform( + sequence: sequence, + clip: ElementId('clip'), + tick: 0, + change: (value) => value.copyWith(x: .2), + ); + await tester.pump(const Duration(milliseconds: 50)); + expect( + await projects.prepareToQuit().timeout(const Duration(seconds: 15)), + isTrue, + ); + quit = true; + mark('close workspace while preview waits for recovery'); + if (report.isNotEmpty) { + await File(report).writeAsString( + const JsonEncoder.withIndent(' ').convert({ + 'steps': steps, + 'memory': samples, + 'durationMs': watch.elapsedMilliseconds, + 'systemEvents': 'injected into the actual app native facade; no physical machine sleep', + }), + ); + } + } finally { + if (!quit) { + try { + await projects.prepareToQuit(); + } catch (_) {} + } + await tester.pumpWidget(const SizedBox.shrink()); + hiddenWindowFrames.cancel(); + container.dispose(); + await Future.delayed(const Duration(milliseconds: 200)); + await database.close(); + await fixture.directory.delete(recursive: true); + } + }, timeout: const Timeout(Duration(minutes: 10))); +} diff --git a/integration_test/preview_drag_timing_test.dart b/integration_test/preview_drag_timing_test.dart new file mode 100644 index 0000000..183604b --- /dev/null +++ b/integration_test/preview_drag_timing_test.dart @@ -0,0 +1,193 @@ +import 'package:cutdex/app/editor_theme.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; + +import 'dart:convert'; +import 'dart:io'; + +import 'package:cutdex/workspace/timeline_provider.dart'; + +import 'dart:math' as math; + +import 'package:cutdex_sdk/preview.dart'; +import 'package:cutdex/features/preview/preview_panel.dart'; +import 'package:cutdex/features/properties/properties_panel.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; + +import '../test/support/preview_fixture.dart'; +import 'support/native_media_fixture.dart'; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + testWidgets('measure repeated real-media canvas drags', (tester) async { + final channel = _TimingChannel(); + final mediaFile = await nativeMediaFixture(); + final fixture = await createPreviewFixture( + mediaFile.uri, + renderSize: {'width': 1920, 'height': 1440}, + ); + final preview = PreviewController( + timeline: fixture.timeline, + activeSequence: () => fixture.timeline.activeSequenceId, + viewForSequence: fixture.timeline.view, + runtime: CutdexRuntime(channel: channel), + ); + addTearDown(() async { + await preview.close(); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + }); + await preview.initialize(); + expect(preview.error, isNull); + final ids = (fixture.workspace.project!.info.id, 'project'); + await tester.pumpWidget( + ProviderScope( + overrides: [ + editorTimelineProvider( + ids.$1, + ids.$2, + ).overrideWith((ref) async => fixture.timeline), + editorPreviewProvider( + ids.$1, + ids.$2, + ).overrideWith((ref) async => preview), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + theme: EditorTheme.penDark, + home: Scaffold( + body: Row( + children: [ + Expanded( + child: EditorPreviewPanel( + projectId: ids.$1, + timelineId: ids.$2, + ), + ), + SizedBox( + width: 280, + child: EditorPropertiesPanel( + projectId: ids.$1, + timelineId: ids.$2, + ), + ), + ], + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + await Future.delayed(const Duration(seconds: 1)); + await tester.pump(); + final canvas = tester.getRect(find.byKey(const Key('preview-canvas'))); + final screenScale = canvas.width / preview.canvas.width; + preview.selectVisual(ElementId('clip')); + await tester.pump(); + await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); + final samples = []; + final records = >[]; + final clock = Stopwatch()..start(); + // Identical inputs before/after. Option excludes snap acquisition/release. + for (var run = 0; run < 3; run++) { + final visual = preview.visuals.single; + final origin = canvas.topLeft + visual.geometry.center * screenScale; + final gesture = await tester.startGesture(origin); + for (var i = 1; i <= 120; i++) { + final dx = 100 * math.sin(i * 2 * math.pi / 120); + final dy = 30 * math.sin(i * 4 * math.pi / 120); + await gesture.moveTo(origin + Offset(dx, dy)); + await tester.pump(); + final paint = tester.widget( + find.descendant( + of: find.byType(PreviewInteractionOverlay), + matching: find.byType(CustomPaint), + ), + ); + final geometry = + (paint.painter as dynamic).geometry as PreviewGeometry?; + if (geometry != null) { + final shownX = geometry.center.dx / preview.canvas.width - .5; + final error = (shownX - channel.completedX).abs() * canvas.width; + samples.add(error); + records.add({ + 'ms': clock.elapsedMicroseconds / 1000, + 'boxX': shownX, + 'nativeX': channel.completedX, + 'gapPx': error, + }); + } + await Future.delayed(const Duration(milliseconds: 8)); + } + await gesture.up(); + await preview.transforms.settled; + await Future.delayed(const Duration(milliseconds: 150)); + await tester.pump(); + expect(preview.error, isNull); + } + await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); + samples.sort(); + channel.latency.sort(); + double percentile(List values, double p) => + values[((values.length - 1) * p).round()]; + final result = { + 'samples': samples.length, + 'updates': channel.latency.length, + 'gapMeasurement': 'callbackGeometry', + 'gapP50Px': percentile(samples, .5), + 'gapP95Px': percentile(samples, .95), + 'gapMaxPx': samples.last, + 'nativeP50Ms': percentile(channel.latency, .5), + 'nativeP95Ms': percentile(channel.latency, .95), + 'nativeMaxMs': channel.latency.last, + 'canvasWidth': canvas.width, + 'records': records, + }; + debugPrint('DRAG_TIMING ${jsonEncode({...result}..remove('records'))}'); + const report = String.fromEnvironment('CUTDEX_TEST_REPORT'); + if (report.isNotEmpty) await File(report).writeAsString(jsonEncode(result)); + expect(samples.length, 360); + expect(channel.latency.length, greaterThan(0)); + expect( + samples.last, + lessThan(1), + reason: 'Selection must follow the acknowledged native snapshot', + ); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + }, skip: !hasNativeMediaFixture); +} + +class _TimingChannel extends MethodChannel { + _TimingChannel() : super('cutdex_runtime'); + double completedX = 0; + final latency = []; + + @override + Future invokeMethod(String method, [dynamic arguments]) async { + final request = method == 'request' + ? jsonDecode(arguments['request'] as String) as Map + : arguments as Map; + final update = + method == 'updateInteractiveTransform' || + request['method'] == 'updateInteractiveTransform'; + final watch = Stopwatch()..start(); + final response = await super.invokeMethod(method, arguments); + if (update) { + latency.add(watch.elapsedMicroseconds / 1000); + final transforms = request['transforms'] as List; + if (transforms.isNotEmpty) { + completedX = (transforms.first['x'] as num).toDouble(); + } + } + return response; + } +} diff --git a/integration_test/preview_startup_test.dart b/integration_test/preview_startup_test.dart new file mode 100644 index 0000000..a74ffed --- /dev/null +++ b/integration_test/preview_startup_test.dart @@ -0,0 +1,156 @@ +import '../test/support/creation_names.dart'; + +import 'dart:io'; + +import 'package:cutdex/workspace/persistence/project_workspace.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:cutdex_sdk/editor.dart'; + +import '../test/support/processing_fixture.dart'; + +import 'package:cutdex/features/preview/preview_panel.dart'; +import 'package:cutdex/integrations/editor_tools.dart'; +import 'package:cutdex/persistence/app_database.dart'; +import 'package:cutdex/workspace/projects.dart'; +import 'package:cutdex/workspace/timeline_provider.dart'; +import 'package:drift/native.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + + for (final mask in [0, 1, 2, 4, 3, 5, 6, 7, -1]) { + testWidgets('timeline native preview with optional capability mask $mask', ( + tester, + ) async { + final root = await Directory.systemTemp.createTemp( + 'preview-capabilities-', + ); + final config = await processingFixture( + root, + mask < 0 ? 7 : mask, + stale: mask < 0, + ); + final workspace = ProjectWorkspace( + creationNames: testCreationNames, + processing: config, + ); + try { + await workspace.open('${root.path}/Test.cutdex', name: 'Preview'); + final document = TimelineDocument( + id: 'timeline', + name: 'Preview', + defaultSequenceId: SequenceId('main'), + sequences: [ + TimelineDto( + id: SequenceId('main'), + format: TimelineFormat.fps30, + primaryStorylineId: StorylineId('primary'), + storylines: [ + StorylineDto(id: StorylineId('primary'), elementIds: []), + ], + elements: [], + ), + ], + ); + await workspace.project!.saveTimeline(document); + final timeline = await workspace.openTimelineSession( + workspace.project!.info.id, + await workspace.project!.loadTimeline(document.id), + ); + final ids = (workspace.project!.info.id, document.id); + final scoped = ProviderContainer( + overrides: [ + editorTimelineProvider( + ids.$1, + ids.$2, + ).overrideWith((ref) async => timeline), + ], + ); + try { + final subscription = scoped.listen( + editorPreviewProvider(ids.$1, ids.$2), + (_, _) {}, + ); + final preview = await scoped.read( + editorPreviewProvider(ids.$1, ids.$2).future, + ); + expect(preview, isNotNull); + expect(preview!.ready, isTrue); + expect(preview.error, isNull); + final enabled = mask < 0 ? 0 : mask; + expect( + timeline.supportedCommandOperations.contains( + EditorOperation.startTranscription, + ), + enabled & 1 != 0, + ); + expect( + timeline.supportedCommandOperations.contains( + EditorOperation.startSubtitleTranslation, + ), + enabled & 2 != 0, + ); + expect( + timeline.supportedCommandOperations.contains( + EditorOperation.startVocalSeparation, + ), + enabled & 4 != 0, + ); + await preview.close(); + subscription.close(); + } finally { + scoped.dispose(); + } + } finally { + await workspace.close(); + await root.delete(recursive: true); + } + }); + } + testWidgets( + 'opening a timeline initializes native preview through App providers', + (tester) async { + final directory = await Directory.systemTemp.createTemp( + 'cutdex preview startup ', + ); + final database = AppDatabase(NativeDatabase.memory()); + final container = ProviderContainer( + overrides: [appDatabaseProvider.overrideWithValue(database)], + ); + try { + container.read(applicationToolAccessProvider); + final projects = container.read(projectsProvider.notifier); + expect( + await projects.open('${directory.path}/Test.cutdex', name: 'Preview'), + isTrue, + ); + expect(await projects.createTimeline(name: 'Timeline'), isTrue); + final state = await container.read(projectsProvider.future); + final ids = (state.activeProject!.id, state.timeline!.id); + final subscription = container.listen( + editorPreviewProvider(ids.$1, ids.$2), + (_, _) {}, + ); + final preview = await container.read( + editorPreviewProvider(ids.$1, ids.$2).future, + ); + expect(preview, isNull); + final timeline = await container.read( + editorTimelineProvider(ids.$1, ids.$2).future, + ); + expect(timeline.preview, isNull); + subscription.close(); + await timeline.close(); + } finally { + container.dispose(); + await Future.delayed(const Duration(milliseconds: 200)); + await database.close(); + await directory.delete(recursive: true); + } + }, + ); +} diff --git a/integration_test/preview_test.dart b/integration_test/preview_test.dart new file mode 100644 index 0000000..652c2fa --- /dev/null +++ b/integration_test/preview_test.dart @@ -0,0 +1,332 @@ +import 'package:cutdex/app/editor_theme.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex/features/properties/canvas_presets.dart'; + +import 'package:cutdex/workspace/timeline_provider.dart'; + +import 'dart:convert'; +import 'dart:ui' as ui; + +import 'package:cutdex/features/preview/preview_panel.dart'; +import 'package:cutdex/features/timeline/timeline_panel.dart'; +import 'package:cutdex_sdk/preview.dart'; +import 'package:cutdex/integrations/runtime/timeline_thumbnails.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:cutdex_sdk/timeline_ui.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; + +import '../test/support/preview_fixture.dart'; +import 'support/native_media_fixture.dart'; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + testWidgets( + 'native preview follows the full real-media timeline with audio', + (tester) async { + final mediaFile = await nativeMediaFixture(); + expect(await mediaFile.exists(), isTrue); + final channel = _ObservedRuntimeChannel(); + final runtime = CutdexRuntime(channel: channel); + final info = await runtime.probe( + MediaReference(id: 'media', uri: mediaFile.uri), + ); + final ticks = + (BigInt.from(info.duration.numerator) * + BigInt.from(TimelineClock.ticksPerSecond) ~/ + BigInt.from(info.duration.denominator)) + .toInt(); + final fixture = await createPreviewFixture( + mediaFile.uri, + clipDuration: RationalTime.timelineTicks(ticks), + hasAudio: info.audioTrackCount > 0, + ); + final preview = PreviewController( + timeline: fixture.timeline, + activeSequence: () => fixture.timeline.activeSequenceId, + viewForSequence: fixture.timeline.view, + runtime: runtime, + ); + addTearDown(() async { + await preview.close(); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + }); + await preview.initialize(); + expect(preview.error, isNull); + final ids = (fixture.workspace.project!.info.id, 'project'); + await tester.pumpWidget( + ProviderScope( + overrides: [ + editorTimelineProvider( + ids.$1, + ids.$2, + ).overrideWith((ref) async => fixture.timeline), + editorPreviewProvider( + ids.$1, + ids.$2, + ).overrideWith((ref) async => preview), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + theme: EditorTheme.penDark, + home: Scaffold( + body: Column( + children: [ + Expanded( + child: EditorPreviewPanel( + projectId: ids.$1, + timelineId: ids.$2, + ), + ), + Expanded( + child: EditorTimelinePanel( + projectId: ids.$1, + timelineId: ids.$2, + ), + ), + ], + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect(find.byType(RuntimePreview), findsOneWidget); + final view = fixture.timeline.view(SequenceId('one')); + final thumbnails = tester + .widget(find.byType(TimelineView)) + .thumbnails!; + final query = view.version.kernelVersion.query(); + final clip = query.element(query.elementById(ElementId('clip'))!); + const logicalThumbnailSize = Size(82, 46); + final devicePixelRatio = tester.view.devicePixelRatio; + ui.Image? cover; + for (var attempt = 0; attempt < 100 && cover == null; attempt++) { + thumbnails.beginFrame(); + cover = thumbnails.imageFor( + clip, + 0, + sourceSpanTicks: TimelineClock.ticksPerSecond, + logicalSize: logicalThumbnailSize, + devicePixelRatio: devicePixelRatio, + ); + thumbnails.endFrame(); + await tester.pump(const Duration(milliseconds: 100)); + } + expect( + cover, + isNotNull, + reason: 'Timeline must decode an actual runtime thumbnail', + ); + final maximumEdge = RuntimeTimelineThumbnails.maximumEdgeFor( + logicalSize: logicalThumbnailSize, + devicePixelRatio: devicePixelRatio, + ); + expect(cover!.width, lessThanOrEqualTo(maximumEdge)); + expect(cover.height, lessThanOrEqualTo(maximumEdge)); + view.seekTo(TimelineClock.ticksPerSecond ~/ 2); + await channel.settle(tester); + var snapshot = await preview.session!.refresh(); + expect(snapshot.position.seconds, closeTo(0.5, 0.1)); + await preview.togglePlayback(); + await Future.delayed(const Duration(milliseconds: 350)); + await preview.session!.pause(); + snapshot = await preview.session!.refresh(); + expect(snapshot.position.seconds, greaterThan(0.5)); + expect( + snapshot.position.seconds, + lessThanOrEqualTo(info.duration.seconds), + ); + final previewView = tester.element(find.byType(RuntimePreview)); + // Scrub repeatedly in both directions, then locate the exact end. + for (final fraction in [0.7, 0.1, 0.8, 0.2, 0.6, 0.0, 1.0]) { + view.seekTo((ticks * fraction).floor()); + await channel.settle(tester); + snapshot = await preview.session!.refresh(); + expect(preview.error, isNull); + expect( + snapshot.position.seconds, + closeTo(info.duration.seconds * fraction, 0.1), + ); + expect(tester.element(find.byType(RuntimePreview)), same(previewView)); + } + view.seekTo(TimelineClock.ticksPerSecond ~/ 2); + await channel.settle(tester); + snapshot = await preview.session!.refresh(); + for (var i = 0; i < 3; i++) { + final pausedAt = snapshot.position.seconds; + await Future.delayed(const Duration(milliseconds: 20)); + channel.calls.clear(); + await preview.togglePlayback(); + expect(channel.calls, [ + 'play', + ], reason: 'Resume must retain the current native image'); + await Future.delayed(const Duration(milliseconds: 150)); + await tester.pump(); + expect(tester.element(find.byType(RuntimePreview)), same(previewView)); + expect(preview.playing, isTrue); + await preview.togglePlayback(); + snapshot = await preview.session!.refresh(); + expect(snapshot.state, PlaybackState.paused); + expect(snapshot.position.seconds, greaterThan(pausedAt)); + } + if (info.duration.seconds > 10) { + // Exercise actual nanosecond clock observations across the int64 + // multiplication boundary; a short initial playback cannot catch this. + view.seekTo(TimelineClock.ticksPerSecond * 5); + await channel.settle(tester); + await preview.togglePlayback(); + final observed = []; + for (var i = 0; i < 40; i++) { + await Future.delayed(const Duration(milliseconds: 100)); + await tester.pump(); + observed.add(view.playheadTick); + } + await preview.session!.pause(); + expect( + observed.first, + greaterThanOrEqualTo(TimelineClock.ticksPerSecond * 5), + ); + expect(observed.last, greaterThan(TimelineClock.ticksPerSecond * 8)); + for (var i = 1; i < observed.length; i++) { + expect( + observed[i], + greaterThanOrEqualTo(observed[i - 1]), + reason: + 'Playback observations must not send the playhead back to zero', + ); + } + expect(preview.error, isNull); + } + // The tail must remain seekable even when the source audio ends sooner. + final tail = ticks - TimelineClock.ticksPerSecond ~/ 20; + view.seekTo(tail); + await channel.settle(tester); + snapshot = await preview.session!.refresh(); + expect( + snapshot.position.seconds, + closeTo(tail / TimelineClock.ticksPerSecond, 0.1), + ); + expect(preview.error, isNull); + // The real App keeps one frozen-frame context across repeated releases. + preview.setCanvas(ProjectCanvasPresets.values['4:3']!); + await tester.pumpAndSettle(); + await channel.settle(tester); + await tester.pump(const Duration(milliseconds: 200)); + channel.calls.clear(); + for (var i = 0; i < 8; i++) { + final rect = tester.getRect(find.byKey(const Key('preview-canvas'))); + final center = preview.visuals.first.geometry.center; + final start = + rect.topLeft + center * (rect.width / preview.canvas.width); + await tester.dragFrom(start, Offset(i.isEven ? 30 : -30, 0)); + await preview.transforms.settled; + await tester.pump(const Duration(milliseconds: 60)); + expect(preview.error, isNull); + } + expect( + channel.calls.where((c) => c == 'beginInteractiveTransform'), + hasLength(1), + ); + expect( + channel.calls.where((c) => c == 'updateInteractiveTransform').length, + greaterThanOrEqualTo(8), + ); + expect(channel.calls, isNot(contains('applyPatch'))); + view.setSelection([ + view.version.kernelVersion.query().elementById(ElementId('clip'))!, + ]); + view.seekTo(TimelineClock.ticksPerSecond); + await channel.settle(tester); + for (final edit in [view.cutSelectionAtPlayhead, view.undo, view.redo]) { + channel.calls.clear(); + edit(); + await tester.pumpAndSettle(); + await channel.settle(tester); + expect(preview.busy, isFalse); + expect(preview.error, isNull); + expect(channel.calls, contains('applyPatch')); + expect(channel.calls, isNot(contains('seek'))); + snapshot = await preview.session!.refresh(); + expect(snapshot.position.seconds, closeTo(1, 0.1)); + expect(tester.element(find.byType(RuntimePreview)), same(previewView)); + } + fixture.timeline.selectSequence(SequenceId('empty')); + await tester.pumpAndSettle(); + await Future.delayed(const Duration(milliseconds: 200)); + expect(preview.error, isNull); + expect(preview.durationTick, 0); + expect(preview.canPlay, isFalse); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + }, + skip: !hasNativeMediaFixture, + ); +} + +class _ObservedRuntimeChannel extends MethodChannel { + _ObservedRuntimeChannel() : super('cutdex_runtime'); + final calls = []; + var _pendingControls = 0; + final _quiet = Stopwatch()..start(); + + Future settle(WidgetTester tester) async { + final deadline = Stopwatch()..start(); + // Includes the controller's trailing exact-seek debounce. Pumping is + // required for frame-bound transform handoffs; wall-clock sleep is not enough. + _quiet.reset(); + while (_pendingControls != 0 || _quiet.elapsedMilliseconds < 200) { + if (deadline.elapsed > const Duration(seconds: 30)) { + fail('Preview controls did not settle within 30 seconds'); + } + await tester.pump(const Duration(milliseconds: 16)); + await Future.delayed(const Duration(milliseconds: 20)); + } + } + + @override + Future invokeMethod(String method, [dynamic arguments]) async { + final operation = method == 'request' + ? (jsonDecode(arguments['request'] as String) as Map)['method'] + as String + : method; + calls.add(operation); + final control = const { + 'load', + 'seek', + 'play', + 'pause', + 'applyPatch', + 'applySnapshot', + 'beginInteractiveTransform', + 'updateInteractiveTransform', + 'endInteractiveTransform', + 'recover', + }.contains(operation); + if (control) { + _pendingControls++; + _quiet.reset(); + } + const timings = bool.fromEnvironment('CUTDEX_TEST_TIMINGS'); + final watch = Stopwatch()..start(); + try { + return await super.invokeMethod(method, arguments); + } finally { + if (control) { + _pendingControls--; + _quiet.reset(); + } + if (timings && operation != 'snapshot') { + debugPrint('RUNTIME_TIMING $operation ${watch.elapsedMilliseconds}ms'); + } + } + } +} diff --git a/integration_test/processing_e2e_test.dart b/integration_test/processing_e2e_test.dart new file mode 100644 index 0000000..d55b142 --- /dev/null +++ b/integration_test/processing_e2e_test.dart @@ -0,0 +1,392 @@ +import '../test/support/creation_names.dart'; + +import 'dart:io'; +import 'dart:convert'; + +import 'package:cutdex/integrations/runtime/processing_configuration.dart'; +import 'package:cutdex/workspace/persistence/project_workspace.dart'; +import 'package:cutdex/workspace/timeline_session.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/preview.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; + +const source = String.fromEnvironment('CUTDEX_ASR_FIXTURE'); +const packageRoot = String.fromEnvironment('CUTDEX_PROCESSING_ROOT'); +Future until( + bool Function() done, { + Duration timeout = const Duration(minutes: 4), +}) async { + final watch = Stopwatch()..start(); + while (!done()) { + if (watch.elapsed > timeout) { + throw StateError('Timed out waiting for processing'); + } + await Future.delayed(const Duration(milliseconds: 30)); + } +} + +Future> workers() async { + final List processes; + if (Platform.isWindows) { + final result = await Process.run('powershell.exe', [ + '-NoProfile', + '-Command', + r"Get-CimInstance Win32_Process | Where-Object { $_.Name -match '^(cutdex-(processing|asr|audio|m2m100)-worker|ffmpeg)\.exe$' } | Select-Object -ExpandProperty ExecutablePath | ConvertTo-Json -Compress", + ]); + if (result.exitCode != 0) throw StateError('${result.stderr}'); + final output = (result.stdout as String).trim(); + final decoded = output.isEmpty ? null : jsonDecode(output); + processes = switch (decoded) { + null => [], + String path => [path], + List paths => paths.cast(), + _ => throw StateError('Unexpected Windows process inventory'), + }; + } else { + final result = await Process.run('/bin/ps', ['-axo', 'pid=,command=']); + if (result.exitCode != 0) throw StateError('${result.stderr}'); + processes = (result.stdout as String).split('\n'); + } + final normalizedRoot = packageRoot.replaceAll(r'\', '/').toLowerCase(); + return processes.where((line) { + final normalized = line.replaceAll(r'\', '/').toLowerCase(); + return normalized.contains('$normalizedRoot/') && + RegExp(r'(cutdex-(processing|asr|audio|m2m100)-worker|/ffmpeg)') + .hasMatch(normalized); + }).toList(); +} + +Future workerStarted(bool Function() terminal, String worker) async { + final watch = Stopwatch()..start(); + while (!(await workers()).any((line) => line.contains(worker))) { + if (terminal() || watch.elapsed > const Duration(seconds: 30)) { + throw StateError('No live worker observed'); + } + await Future.delayed(const Duration(milliseconds: 20)); + } +} + +Future< + ({ + ProjectWorkspace workspace, + EditorTimelineSession session, + Directory root, + String projectId, + String assetId, + }) +> +fixture() async { + final config = ProcessingConfiguration.configured()!; + expect(config.transcriptionModel, isNotNull); + expect(config.translationModel, isNotNull); + expect(config.vocalSeparationModel, isNotNull); + final root = await Directory.systemTemp.createTemp('cutdex-real-processing-'); + final workspace = ProjectWorkspace( + creationNames: testCreationNames, + processing: config, + ); + await workspace.open('${root.path}/Test.cutdex', name: 'Real processing'); + final timelines = await workspace.createTimeline('Speech'); + final project = workspace.project!; + final imported = await project.importFile(File(source), name: 'Speech'); + final document = await workspace.loadTimeline( + project.info.id, + timelines.single.id, + ); + final session = await workspace.openTimelineSession( + project.info.id, + document, + ); + final media = await workspace.prepareMedia(project.info.id, imported.id); + session.insertAsset( + sequenceId: session.activeSequenceId!, + assetId: imported.id, + assetName: 'Speech', + uri: media.uri, + duration: media.duration, + position: 0, + kind: 'audio', + hasAudio: true, + clipId: ElementId('speech'), + ); + return ( + workspace: workspace, + session: session, + root: root, + projectId: project.info.id, + assetId: imported.id, + ); +} + +Future play(EditorTimelineSession session) async { + session.view(session.activeSequenceId!).seekTo(0); + final preview = PreviewController( + timeline: session, + activeSequence: () => session.activeSequenceId, + viewForSequence: session.view, + runtime: CutdexRuntime(), + ); + try { + await preview.initialize(); + expect(preview.error, isNull); + expect(preview.ready, isTrue); + await preview.controlPreview(session.activeSequenceId!, PreviewAction.play); + await until( + () => + preview.positionTick > TimelineClock.ticksPerSecond ~/ 5 || + preview.error != null, + timeout: const Duration(seconds: 15), + ); + expect(preview.error, isNull); + expect(preview.positionTick, greaterThan(0)); + await preview.controlPreview( + session.activeSequenceId!, + PreviewAction.pause, + ); + } finally { + await preview.close(); + } +} + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + testWidgets( + 'real recognition, independent translation, stems and native playback', + (tester) async { + final f = await fixture(); + try { + final session = f.session; + final sequence = session.activeSequenceId!; + final service = session.transcriptions!; + final recognition = await service.start( + StartTranscription(mediaId: f.assetId, language: 'en', threads: 2), + ); + await until(() => recognition.terminal); + expect( + recognition.status, + TranscriptionStatus.succeeded, + reason: recognition.error, + ); + expect(recognition.result!.cues, isNotEmpty); + final recognized = await session.applyTranscription( + sequence, + ApplyTranscription(taskId: recognition.id, clipId: 'speech'), + ); + final recognizedIds = (recognized['captionIds'] as List).cast(); + expect(recognizedIds, hasLength(recognition.result!.cues.length)); + expect( + session.caption(sequence, recognizedIds.first).text, + recognition.result!.cues.first.text, + ); + service.configure( + backend: null, + modelDirectory: null, + translationBackend: service.translationBackend, + translationModel: service.translationModel, + ); + expect(service.recognitionAvailable, isFalse); + final translation = await service.startTranslation( + StartSubtitleTranslation( + source: recognition.result!.subtitles.toFilePath(), + sourceLanguage: 'en', + targetLanguage: 'zh', + threads: 2, + ), + ); + await until(() => translation.terminal); + expect( + translation.status, + TranscriptionStatus.succeeded, + reason: translation.error, + ); + expect(translation.result!.document.cues, isNotEmpty); + final translated = await session.applySubtitleTranslation( + sequence, + ApplySubtitleTranslation( + taskId: translation.id, + clipId: 'speech', + source: recognition.source!.toFilePath(), + sourceStartMs: recognition.sourceStartMs, + ), + ); + final translatedIds = (translated['captionIds'] as List).cast(); + expect( + translatedIds, + hasLength(translation.result!.document.cues.length), + ); + expect( + session.caption(sequence, translatedIds.first).text, + translation.result!.document.cues.first.text, + ); + await play(session); + final separated = await session.vocalSeparations!.start( + StartVocalSeparation(mediaId: f.assetId, threads: 2), + ); + await until(() => separated.terminal); + expect( + separated.status, + VocalSeparationStatus.succeeded, + reason: separated.error, + ); + for (final uri in [ + separated.result!.vocals, + separated.result!.instrumental, + ]) { + expect(await File.fromUri(uri).length(), greaterThan(44)); + final info = await CutdexRuntime().probe( + MediaReference(id: 'stem', uri: uri), + ); + expect(info.audioTrackCount, greaterThan(0)); + expect( + info.duration.seconds, + closeTo(recognition.result!.durationMs / 1000, 0.1), + ); + } + await session.applyVocalSeparation( + sequence, + ApplyVocalSeparation( + taskId: separated.id, + clipId: 'speech', + stems: VocalStem.values, + insertIntoTimeline: true, + ), + ); + expect(await f.workspace.listAssets(f.projectId), hasLength(3)); + await play(session); + await session.flush(); + expect(await workers(), isEmpty); + } finally { + await f.workspace.close(); + await f.root.delete(recursive: true); + } + }, + skip: !(Platform.isMacOS || Platform.isWindows) || source.isEmpty, + timeout: const Timeout(Duration(minutes: 12)), + ); + for (final capability in ['asr', 'translation', 'audio']) { + for (final action in [ + 'cancel', + 'closeTimeline', + 'switchProjectThenClose', + ]) { + testWidgets( + 'real $capability $action reaps processes and avoids partial publication', + (tester) async { + final f = await fixture(); + try { + final destination = '${f.root.path}/cancel-output'; + late bool Function() terminal; + late void Function() cancel; + late String Function() status; + late String worker; + switch (capability) { + case 'asr': + final task = await f.session.transcriptions!.start( + StartTranscription( + mediaId: f.assetId, + language: 'en', + threads: 2, + destination: destination, + ), + ); + terminal = () => task.terminal; + cancel = () => f.session.transcriptions!.cancel(task.id); + status = () => task.status.name; + worker = 'cutdex-asr-worker'; + case 'translation': + final input = File('${f.root.path}/input.json'); + await input.writeAsString( + jsonEncode({ + 'schemaVersion': 1, + 'language': 'en', + 'cues': [ + { + 'startMs': 0, + 'endMs': 1000, + 'text': 'This is a short translation test.', + }, + ], + }), + ); + final task = await f.session.transcriptions!.startTranslation( + StartSubtitleTranslation( + source: input.path, + sourceLanguage: 'en', + targetLanguage: 'zh', + threads: 2, + destination: destination, + ), + ); + terminal = () => task.terminal; + cancel = () => + f.session.transcriptions!.cancelTranslation(task.id); + status = () => task.status.name; + worker = 'cutdex-m2m100-worker'; + case 'audio': + final task = await f.session.vocalSeparations!.start( + StartVocalSeparation( + mediaId: f.assetId, + threads: 2, + destination: destination, + ), + ); + terminal = () => task.terminal; + cancel = () => f.session.vocalSeparations!.cancel(task.id); + status = () => task.status.name; + worker = 'cutdex-audio-worker'; + } + await workerStarted(terminal, worker); + switch (action) { + case 'cancel': + cancel(); + await until(terminal); + case 'closeTimeline': + await f.session.close(); + case 'switchProjectThenClose': + await f.workspace.open( + '${f.root.path}/Other.cutdex', + name: 'Other', + ); + expect(f.session.acceptsEdits, isTrue); + await f.session.close(); + } + expect(status(), action == 'cancel' ? 'cancelled' : 'interrupted'); + expect(await workers(), isEmpty); + expect(await Directory(destination).exists(), isFalse); + final staging = await f.root + .list() + .where( + (entry) => entry.uri.pathSegments + .where((segment) => segment.isNotEmpty) + .last + .startsWith('.cutdex-'), + ) + .toList(); + if (action == 'cancel' || capability == 'translation') { + expect( + staging, + isEmpty, + reason: 'Disposable staging must be removed', + ); + } else { + // Host interruption preserves a resumable ASR/audio checkpoint, not a published result. + expect(staging, hasLength(1)); + expect( + await File('${staging.single.path}/checkpoint.json').exists(), + isTrue, + ); + } + } finally { + await f.workspace.close(); + await f.root.delete(recursive: true); + } + }, + skip: !(Platform.isMacOS || Platform.isWindows) || source.isEmpty, + timeout: const Timeout(Duration(minutes: 2)), + ); + } + } +} diff --git a/integration_test/support/android_preview_measurement.dart b/integration_test/support/android_preview_measurement.dart new file mode 100644 index 0000000..63f6150 --- /dev/null +++ b/integration_test/support/android_preview_measurement.dart @@ -0,0 +1,156 @@ +import 'dart:async'; +import 'dart:math' as math; + +import 'package:cutdex_sdk/runtime.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +Future pumpUntil( + WidgetTester tester, + bool Function() ready, + String label, { + int seconds = 60, +}) async { + final deadline = DateTime.now().add(Duration(seconds: seconds)); + while (!ready()) { + if (DateTime.now().isAfter(deadline)) throw TimeoutException(label); + await tester.pump(const Duration(milliseconds: 50)); + await Future.delayed(const Duration(milliseconds: 10)); + } + await tester.pump(); +} + +Future measureAndroidFullLengthPreview({ + required WidgetTester tester, + required CutdexRuntime runtime, + required MediaReference media, + required MediaInfo info, + required ({int width, int height, int observationSeconds}) configuration, + required Map result, + required void Function() save, +}) async { + final full = await runtime.createSession(); + try { + final duration = MediaTime( + (math.min( + info.duration.seconds, + info.audioTracks.first.duration.seconds, + ) * + 1000) + .floor() - + 100, + 1000, + ); + final range = MediaRange(start: MediaTime(0, 1), duration: duration); + await full.load( + ExecutionPlan( + duration: duration, + renderSize: RenderSize( + configuration.width.toDouble(), + configuration.height.toDouble(), + ), + frameDuration: MediaTime(1, 30), + media: [media], + visualLayers: [ + VisualLayer( + id: 'full-video', + mediaId: media.id, + sourceRange: range, + timelineRange: range, + inputColorSpace: + info.videoColorSpaces[0] ?? RenderColorSpace.rec709, + ), + ], + audioLayers: [ + AudioLayer( + id: 'full-audio', + mediaId: media.id, + sourceRange: range, + timelineRange: range, + ), + ], + ), + ); + await tester.pumpWidget( + MaterialApp( + home: Center( + child: SizedBox( + width: configuration.width.toDouble(), + height: configuration.height.toDouble(), + child: RuntimePreview(session: full), + ), + ), + ), + ); + await pumpUntil( + tester, + () => (full.snapshot?.presentedVideoFrameCount ?? 0) > 0, + 'full-length first frame', + seconds: 90, + ); + final observations = >[]; + result['fullLengthPlayback'] = observations; + for (final seconds in [ + 60.0, + duration.seconds / 2, + duration.seconds - math.max(5, configuration.observationSeconds + 2), + ]) { + final seekWatch = Stopwatch()..start(); + await full.seek(MediaTime((seconds * 1000).round(), 1000)); + final before = await full.refresh(); + final seekLatency = seekWatch.elapsedMilliseconds; + final startWatch = Stopwatch()..start(); + await full.play(); + final startLatency = startWatch.elapsedMilliseconds; + await Future.delayed( + Duration(seconds: configuration.observationSeconds), + ); + await tester.pump(); + var after = await full.refresh(); + while (after.message == null && + (after.position.seconds <= seconds + .5 || + (after.presentedVideoFrameCount ?? 0) <= + (before.presentedVideoFrameCount ?? 0)) && + startWatch.elapsedMilliseconds < + startLatency + + math.max(10000, configuration.observationSeconds * 1000)) { + await Future.delayed(const Duration(milliseconds: 250)); + await tester.pump(); + after = await full.refresh(); + } + expect(after.message, isNull); + expect(after.position.seconds, greaterThan(seconds + .5)); + expect( + after.presentedVideoFrameCount, + greaterThan(before.presentedVideoFrameCount ?? 0), + ); + observations.add({ + 'at': seconds, + 'position': after.position.seconds, + 'seekMilliseconds': seekLatency, + 'playStartupMilliseconds': startLatency, + 'observationMilliseconds': startWatch.elapsedMilliseconds, + 'slowPlayback': + startWatch.elapsedMilliseconds - startLatency > + configuration.observationSeconds * 1000 + 1000, + 'presentedFramesPerSecond': + ((after.presentedVideoFrameCount ?? 0) - + (before.presentedVideoFrameCount ?? 0)) * + 1000 / + (startWatch.elapsedMilliseconds - startLatency), + 'timelineAdvanceSeconds': + after.position.seconds - before.position.seconds, + 'frames': + (after.presentedVideoFrameCount ?? 0) - + (before.presentedVideoFrameCount ?? 0), + 'maximumFrameGapMs': after.maximumVideoFrameGapMs, + 'maximumFrameGapScope': 'session cumulative', + }); + await full.pause(); + save(); + } + } finally { + await tester.pumpWidget(const SizedBox.shrink()); + await full.close(); + } +} diff --git a/integration_test/support/native_media_fixture.dart b/integration_test/support/native_media_fixture.dart new file mode 100644 index 0000000..a7dce83 --- /dev/null +++ b/integration_test/support/native_media_fixture.dart @@ -0,0 +1,25 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:path_provider/path_provider.dart'; + +const _source = String.fromEnvironment('CUTDEX_TEST_SOURCE'); +const _encodedSource = String.fromEnvironment('CUTDEX_TEST_SOURCE_BASE64'); +const _document = String.fromEnvironment('CUTDEX_TEST_SOURCE_DOCUMENT'); + +const hasNativeMediaFixture = + _source != '' || _encodedSource != '' || _document != ''; + +/// Uses a host file, a sandbox document, or embedded media written to a temporary file. +Future nativeMediaFixture() async { + if (_encodedSource.isEmpty) { + if (_document.isEmpty) return File(_source).absolute; + final directory = await getApplicationDocumentsDirectory(); + return File('${directory.path}/$_document'); + } + final directory = await Directory.systemTemp.createTemp('cutdex-media-'); + addTearDown(() => directory.delete(recursive: true)); + return File('${directory.path}/source.mp4') + .writeAsBytes(base64Decode(_encodedSource)); +} diff --git a/integration_test/support/real_media_export_checks.dart b/integration_test/support/real_media_export_checks.dart new file mode 100644 index 0000000..b48a6c0 --- /dev/null +++ b/integration_test/support/real_media_export_checks.dart @@ -0,0 +1,70 @@ +import 'dart:math' as math; +import 'dart:ui' as ui; + +import 'package:cutdex_sdk/runtime.dart'; +import 'package:flutter/painting.dart'; +import 'package:flutter_test/flutter_test.dart'; + +Future verifyEditedExport( + CutdexRuntime runtime, { + required Uri edited, + required Uri baseline, +}) async { + final editedMedia = MediaReference(id: 'edited', uri: edited); + final editedInfo = await runtime.probe(editedMedia); + expect(editedInfo.duration.seconds, closeTo(4, .1)); + expect(editedInfo.audioTrackCount, 1); + final thumbnail = await runtime.thumbnail( + ThumbnailRequest( + media: editedMedia, + time: MediaTime(1, 1), + maximumWidth: 320, + maximumHeight: 180, + ), + ); + final image = await decodeImageFromList(thumbnail.data); + try { + final pixels = (await image.toByteData( + format: ui.ImageByteFormat.rawRgba, + ))!; + // The authored half-size mask must leave the canvas corners black. + for (final at in [ + 0, + (image.width - 1) * 4, + (image.height - 1) * image.width * 4, + ]) { + expect( + pixels.getUint8(at) + pixels.getUint8(at + 1) + pixels.getUint8(at + 2), + lessThan(35), + ); + } + } finally { + image.dispose(); + } + final originalWave = await runtime.waveform( + WaveformRequest( + media: MediaReference(id: 'baseline', uri: baseline), + baseBucketCount: 64, + levelCount: 1, + ), + ); + final editedWave = await runtime.waveform( + WaveformRequest(media: editedMedia, baseBucketCount: 64, levelCount: 1), + ); + double rms(MediaWaveform wave) { + final values = [ + for (final channel in wave.levels.first.channels) + for (var i = 2; i < channel.length; i += 3) channel[i], + ]; + return math.sqrt( + values.fold(0, (sum, value) => sum + value * value) / + values.length, + ); + } + + final baseRms = rms(originalWave); + expect(baseRms, greaterThan(0)); + final ratio = rms(editedWave) / baseRms; + expect(ratio, closeTo(math.pow(10, -6 / 20).toDouble(), .08)); + return ratio; +} diff --git a/integration_test/support/real_media_report.dart b/integration_test/support/real_media_report.dart new file mode 100644 index 0000000..0b7f527 --- /dev/null +++ b/integration_test/support/real_media_report.dart @@ -0,0 +1,19 @@ +import 'dart:convert'; +import 'dart:io'; + +final class RealMediaReport { + RealMediaReport(this.file, {required Map metadata}) + : metadata = Map.unmodifiable(metadata); + + final File file; + final Map metadata; + final files = >[]; + + void save() { + final temporary = File('${file.path}.part'); + temporary.writeAsStringSync( + const JsonEncoder.withIndent(' ').convert({...metadata, 'files': files}), + ); + temporary.renameSync(file.path); + } +} diff --git a/integration_test/support/saved_edit_validation.dart b/integration_test/support/saved_edit_validation.dart new file mode 100644 index 0000000..00db4e6 --- /dev/null +++ b/integration_test/support/saved_edit_validation.dart @@ -0,0 +1,87 @@ +import 'dart:io'; + +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter_test/flutter_test.dart'; + +class SavedEditValidation { + final _edits = >>{}; + + Future> capture( + String projectPath, + String timelineId, + EditorSession session, + SequenceId sequence, + ) async { + final edits = await _editingState(session, sequence); + _edits.putIfAbsent(projectPath, () => {})[timelineId] = edits; + return edits; + } + + Future verify({ + required Future Function(Duration) wait, + required void Function( + String projectPath, + String timelineId, + Map edits, + ) + onVerified, + }) async { + for (final project in _edits.entries) { + ProjectFile? reopened; + final deadline = DateTime.now().add(const Duration(seconds: 40)); + while (reopened == null) { + try { + reopened = await ProjectFile.open(Directory(project.key)); + } on ProjectFileException catch (error) { + if (error.code != ProjectFileError.conflict || + DateTime.now().isAfter(deadline)) { + rethrow; + } + await wait(const Duration(milliseconds: 100)); + } + } + try { + for (final entry in project.value.entries) { + final session = EditorSession( + document: await reopened.loadTimeline(entry.key), + persistence: await reopened.openTimelineSaveSession(entry.key), + ); + late Map actual; + try { + actual = await _editingState( + session, + SequenceId(entry.value['sequenceId'] as String), + ); + } finally { + await session.close(); + } + expect( + actual, + entry.value, + reason: 'Edited timeline changed after close/reopen', + ); + onVerified(project.key, entry.key, actual); + } + } finally { + await reopened.close(); + } + } + } + + Future> _editingState( + EditorSession session, + SequenceId sequence, + ) async { + final result = await session.executeCommand( + sequence, + const QueryTimeline(), + ); + // History availability and save status describe the current session. + return Map.of(result.data) + ..remove('canUndo') + ..remove('canRedo') + ..remove('saveState'); + } +} diff --git a/integration_test/timeline_thumbnail_timing_test.dart b/integration_test/timeline_thumbnail_timing_test.dart new file mode 100644 index 0000000..e49f08a --- /dev/null +++ b/integration_test/timeline_thumbnail_timing_test.dart @@ -0,0 +1,188 @@ +import 'package:cutdex/l10n/app_localizations.dart'; + +import 'dart:convert'; +import 'dart:io'; + +import 'package:cutdex/integrations/runtime/timeline_thumbnails.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline/engine.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; + +import 'support/native_media_fixture.dart'; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + const concurrency = int.fromEnvironment( + 'CUTDEX_THUMBNAIL_CONCURRENCY', + defaultValue: 2, + ); + const batchSize = int.fromEnvironment( + 'CUTDEX_THUMBNAIL_BATCH_SIZE', + defaultValue: 4, + ); + + testWidgets('measure native request through painted timeline thumbnails', ( + tester, + ) async { + final directory = await Directory.systemTemp.createTemp( + 'cutdex-thumbnail-', + ); + final original = await nativeMediaFixture(); + final alias = File( + '${directory.path}/source${original.uri.pathSegments.last.contains('.mp4') ? '.mp4' : '.mkv'}', + ); + if (Platform.isIOS) { + // AVFoundation denies this symlink on iOS; copy before starting the clock. + await original.copy(alias.path); + } else { + await Link(alias.path).create(original.path); + } + addTearDown(() => directory.delete(recursive: true)); + + final clock = Stopwatch()..start(); + final channel = _ThumbnailTimingChannel(clock); + final frames = RuntimeTimelineThumbnails( + runtime: CutdexRuntime(channel: channel), + resolveMedia: (_) => MediaReference(id: 'source', uri: alias.uri), + resolveTrackSelection: (_) => TrackSelection.index(0), + maximumConcurrent: concurrency, + maximumBatchSize: batchSize, + ); + addTearDown(frames.dispose); + final element = ElementRecord( + id: ElementId('clip'), + structure: ElementStructure.content, + sourceStart: 0, + sourceDuration: TimelineClock.ticksPerSecond * 30, + duration: TimelineClock.ticksPerSecond * 30, + enabled: true, + payloadRef: PayloadRef('source'), + ); + final paintTimes = {}; + final notifications = >[]; + frames.addListener(() { + final loaded = List.generate(9, (index) => index) + .where( + (index) => + frames.imageFor( + element, + TimelineClock.ticksPerSecond * (15 + index), + sourceSpanTicks: 1, + logicalSize: const Size(96, 54), + devicePixelRatio: 2, + ) != + null, + ) + .length; + notifications.add({ + 'count': loaded, + 'ms': clock.elapsedMicroseconds / 1000, + }); + }); + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + home: Center( + child: SizedBox( + width: 864, + height: 54, + child: CustomPaint( + painter: _ThumbnailTimingPainter(frames, element, (count) { + for (final target in [1, 5, 9]) { + if (count >= target) { + paintTimes.putIfAbsent( + target, + () => clock.elapsedMicroseconds / 1000, + ); + } + } + }), + ), + ), + ), + ), + ); + + for ( + var attempt = 0; + attempt < 600 && !paintTimes.containsKey(9); + attempt++ + ) { + await tester.pump(const Duration(milliseconds: 16)); + await Future.delayed(const Duration(milliseconds: 4)); + } + expect(paintTimes[9], isNotNull); + debugPrint( + 'THUMBNAIL_TIMING ${jsonEncode({'source': original.uri.pathSegments.last, 'concurrency': concurrency, 'batchSize': batchSize, 'paintMs': paintTimes.map((key, value) => MapEntry('$key', value)), 'nativeBatches': channel.batches, 'notifications': notifications})}', + ); + await tester.pumpWidget(const SizedBox()); + }, skip: !hasNativeMediaFixture); +} + +final class _ThumbnailTimingChannel extends MethodChannel { + _ThumbnailTimingChannel(this.clock) : super('cutdex_runtime'); + final Stopwatch clock; + final batches = >[]; + + @override + Future invokeMethod(String method, [dynamic arguments]) async { + if (method != 'thumbnails') return super.invokeMethod(method, arguments); + final started = clock.elapsedMicroseconds / 1000; + try { + final result = await super.invokeMethod(method, arguments); + batches.add({ + 'count': ((arguments as Map)['times'] as List).length, + 'startedMs': started, + 'returnedMs': clock.elapsedMicroseconds / 1000, + }); + return result; + } catch (error) { + debugPrint('THUMBNAIL_REQUEST_FAILED $error'); + rethrow; + } + } +} + +final class _ThumbnailTimingPainter extends CustomPainter { + _ThumbnailTimingPainter(this.frames, this.element, this.onPaint) + : super(repaint: frames); + + final RuntimeTimelineThumbnails frames; + final ElementRecord element; + final void Function(int count) onPaint; + + @override + void paint(Canvas canvas, Size size) { + var painted = 0; + frames.beginFrame(); + for (var index = 0; index < 9; index++) { + final image = frames.imageFor( + element, + TimelineClock.ticksPerSecond * (15 + index), + sourceSpanTicks: 1, + logicalSize: const Size(96, 54), + devicePixelRatio: 2, + ); + if (image == null) continue; + painted++; + canvas.drawImageRect( + image, + Rect.fromLTWH(0, 0, image.width.toDouble(), image.height.toDouble()), + Rect.fromLTWH(index * 96, 0, 96, 54), + Paint(), + ); + } + frames.endFrame(); + onPaint(painted); + } + + @override + bool shouldRepaint(_ThumbnailTimingPainter oldDelegate) => false; +} diff --git a/integration_test/windows_audio_media_test.dart b/integration_test/windows_audio_media_test.dart new file mode 100644 index 0000000..f083a95 --- /dev/null +++ b/integration_test/windows_audio_media_test.dart @@ -0,0 +1,733 @@ +import 'package:cutdex/app/editor_theme.dart'; + +// Opt-in validation of original audio through the real Windows editor/runtime. +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:math' as math; + +import 'package:crypto/crypto.dart'; +import 'package:cutdex/features/preview/preview_panel.dart'; +import 'package:cutdex/features/properties/properties_panel.dart'; +import 'package:cutdex/features/timeline/timeline_panel.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex/persistence/app_database.dart'; +import 'package:cutdex/workspace/media_file_extensions.dart'; +import 'package:cutdex/workspace/media_import.dart'; +import 'package:cutdex/workspace/preview_controller_registry.dart'; +import 'package:cutdex/workspace/projects.dart'; +import 'package:cutdex/workspace/timeline_provider.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/preview.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline/engine.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:drift/native.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; +import 'package:path/path.dart' as p; + +import 'support/saved_edit_validation.dart'; + +double _rms(MediaWaveform wave) { + final values = [ + for (final channel in wave.levels.first.channels) + for (var i = 2; i < channel.length; i += 3) channel[i], + ]; + return math.sqrt( + values.fold(0, (sum, value) => sum + value * value) / values.length, + ); +} + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + const source = String.fromEnvironment('CUTDEX_VALIDATION_SOURCE'); + const output = String.fromEnvironment('CUTDEX_VALIDATION_ROOT'); + const filter = String.fromEnvironment('CUTDEX_VALIDATION_FILTER'); + const metadataOnly = bool.fromEnvironment('CUTDEX_VALIDATION_METADATA_ONLY'); + testWidgets('Windows original audio: import, preview and editing', ( + tester, + ) async { + expect(Platform.isWindows, isTrue); + expect(source, isNotEmpty); + expect(output, isNotEmpty); + final paths = + Directory(source) + .listSync(recursive: true, followLinks: false) + .whereType() + .where( + (file) => + mediaKindForPath(file.path) != null && + (filter.isEmpty || + filter.split(',').any(p.basename(file.path).contains)), + ) + .toList() + ..sort((a, b) => a.path.compareTo(b.path)); + expect(paths, isNotEmpty); + final root = await Directory(output).create(recursive: true); + final report = File(p.join(root.path, 'results.json')); + final savedEdits = SavedEditValidation(); + final results = >[]; + final database = AppDatabase(NativeDatabase.memory()); + final container = ProviderContainer( + overrides: [appDatabaseProvider.overrideWithValue(database)], + ); + final projects = container.read(projectsProvider.notifier); + final runtime = CutdexRuntime(); + addTearDown(database.close); + var disposed = false; + addTearDown(() { + if (!disposed) container.dispose(); + }); + void save() => report.writeAsStringSync( + const JsonEncoder.withIndent(' ').convert({ + 'platform': 'windows', + 'source': source, + 'metadataOnly': metadataOnly, + 'method': 'Original files; production source-preview controller, import service and editor widgets; native waveform, preview and H.264/AAC exports. Isolated settings/projects. Source SHA-256 checked.', + 'files': results, + }), + ); + Future until( + bool Function() ready, + String label, { + int seconds = 60, + }) async { + final deadline = DateTime.now().add(Duration(seconds: seconds)); + while (!ready()) { + if (DateTime.now().isAfter(deadline)) throw TimeoutException(label); + await tester.pump(const Duration(milliseconds: 50)); + await Future.delayed(const Duration(milliseconds: 10)); + } + await tester.pump(); + } + + expect( + await projects.open( + p.join( + root.path, + 'Audio-${DateTime.now().millisecondsSinceEpoch}.cutdex', + ), + name: 'Windows 音频素材验证', + initialTimelineName: '01', + ), + isTrue, + ); + var projectId = container + .read(projectsProvider) + .requireValue + .activeProject! + .id; + for (var index = 0; index < paths.length; index++) { + final file = paths[index]; + final before = await file.stat(); + final beforeHash = (await sha256.bind(file.openRead()).first).toString(); + final checks = >[]; + final result = { + 'path': file.path, + 'sourceSha256': beforeHash, + 'checks': checks, + 'passed': false, + }; + results.add(result); + save(); + var stage = 'setup'; + String? testedTimeline; + void Function()? releaseTimeline; + Future check(String name, Future Function() action) async { + stage = name; + debugPrint( + 'AUDIO_MEDIA ${index + 1}/${paths.length} $name ${p.basename(file.path)}', + ); + final clock = Stopwatch()..start(); + await action().timeout(const Duration(minutes: 4)); + expect( + tester.takeException(), + isNull, + reason: 'Widget error during $name', + ); + checks.add({ + 'stage': name, + 'passed': true, + 'milliseconds': clock.elapsedMilliseconds, + }); + save(); + } + + try { + if (index > 0) { + if (container.read(projectsProvider).requireValue.timelines.length >= + Projects.maxTimelineCount) { + expect( + await projects.open( + p.join( + root.path, + 'Audio-batch-${index + 1}-${DateTime.now().millisecondsSinceEpoch}.cutdex', + ), + name: 'Windows 音频素材验证 ${index + 1}', + initialTimelineName: '${index + 1}', + ), + isTrue, + ); + projectId = container + .read(projectsProvider) + .requireValue + .activeProject! + .id; + } else { + expect(await projects.createTimeline(name: '${index + 1}'), isTrue); + } + } + final timelineId = container + .read(projectsProvider) + .requireValue + .timeline! + .id; + testedTimeline = timelineId; + final retained = container.listen( + editorTimelineProvider(projectId, timelineId), + (_, _) {}, + ); + releaseTimeline = retained.close; + final session = await container.read( + editorTimelineProvider(projectId, timelineId).future, + ); + final sequence = session.activeSequenceId!; + final media = MediaReference(id: 'audio-source', uri: file.uri); + late MediaInfo info; + await check('probeOriginal', () async { + info = await runtime.probe(media); + expect(info.audioTrackCount, 1); + expect(info.videoTrackCount, 0); + expect(info.duration.seconds, greaterThan(10)); + expect(info.isProtected, isFalse); + result['durationSeconds'] = info.duration.seconds; + result['audioTracks'] = info.audioTracks + .map( + (track) => { + 'start': track.start.toMap(), + 'duration': track.duration.toMap(), + }, + ) + .toList(); + }); + await check('fullSourceWaveform', () async { + final wave = await runtime.waveform( + WaveformRequest( + media: media, + trackSelection: const TrackSelection.defaultTrack(), + baseBucketCount: 512, + levelCount: 3, + ), + ); + expect(wave.frameCount, greaterThan(0)); + expect(_rms(wave), greaterThan(.0001)); + result['waveform'] = { + 'sampleRate': wave.sampleRate, + 'channels': wave.levels.first.channels.length, + 'frames': wave.frameCount, + 'rms': _rms(wave), + }; + expect( + wave.frameCount / wave.sampleRate, + closeTo(info.duration.seconds, .5), + ); + }); + if (!metadataOnly) { + await check('sourcePreviewPlayPauseAndSeek', () async { + final controller = SourcePreviewController( + loadMedia: (action) => action(media), + frameDuration: RationalTime(1, 30), + rememberPosition: (_) {}, + runtime: runtime, + ); + try { + await controller.initialize(Future.value()); + expect(controller.error, isNull); + expect(controller.audioOnly, isTrue); + expect(controller.canPlay, isTrue); + final observations = >[]; + for (final at in [ + 0.0, + info.duration.seconds / 2, + info.duration.seconds - 2, + ]) { + await controller.session!.seek( + MediaTime((at * 1000).round(), 1000), + ); + await controller.togglePlayback(); + await until(() { + if (controller.error != null) { + throw StateError('${controller.error}'); + } + return controller.playing && + controller.positionTick > + (at + .4) * TimelineClock.ticksPerSecond; + }, 'source playback at $at'); + final played = await controller.session!.refresh(); + expect(played.message, isNull); + await controller.togglePlayback(); + final paused = await controller.session!.refresh(); + await Future.delayed(const Duration(milliseconds: 200)); + final still = await controller.session!.refresh(); + expect(still.state, PlaybackState.paused); + expect( + still.position.seconds, + closeTo(paused.position.seconds, .05), + ); + observations.add({ + 'at': at, + 'playedTo': played.position.seconds, + 'pausedAt': paused.position.seconds, + }); + } + result['sourcePlayback'] = observations; + } finally { + await controller.close(); + controller.dispose(); + } + }); + final clipId = ElementId('audio-clip'); + await check('importOriginalAndInsertAudio', () async { + final imported = await projects.importExternalMedia(projectId, [ + ExternalMediaFile(path: file.path), + ]); + expect(imported!.failures, isEmpty); + final asset = imported.assets.firstWhere( + (a) => a.name == p.basename(file.path), + ); + await session.commands.executeEdit( + sequence, + const SetProjectCanvas(width: 320, height: 180), + ); + await session.commands.insertMedia( + sequence: sequence, + assetId: asset.id, + clipId: clipId, + index: 0, + sourceStart: RationalTime.seconds(2), + duration: RationalTime.seconds(8), + ); + final binding = session.mediaBinding( + session.persistence + .timeline(sequence) + .exportDto() + .elements + .single + .payloadRef!, + ); + expect(binding!.videoTrackIndex, isNull); + expect(binding.audioTrackIndex, 0); + }); + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + theme: EditorTheme.penLight, + home: Scaffold( + body: Column( + children: [ + Expanded( + child: Row( + children: [ + Expanded( + child: EditorPreviewPanel( + projectId: projectId, + timelineId: timelineId, + ), + ), + SizedBox( + width: 280, + child: EditorPropertiesPanel( + projectId: projectId, + timelineId: timelineId, + ), + ), + ], + ), + ), + SizedBox( + height: 210, + child: EditorTimelinePanel( + projectId: projectId, + timelineId: timelineId, + ), + ), + ], + ), + ), + ), + ), + ); + await check('initializeEditorPreview', () async { + await container.read( + editorPreviewProvider(projectId, timelineId).future, + ); + await until(() { + final state = container.read( + editorPreviewProvider(projectId, timelineId), + ); + if (state.hasError) throw StateError('${state.error}'); + if (state.asData?.value?.error != null) { + throw StateError('${state.asData!.value!.error}'); + } + return state.asData?.value?.ready == true; + }, 'editor preview initialization'); + }); + final preview = container + .read(editorPreviewProvider(projectId, timelineId)) + .requireValue!; + ElementRecord record() { + final q = session.persistence.timeline(sequence).current.query(); + return q.element(q.elementById(clipId)!); + } + + Future settled() async { + await tester.pump(); + await until( + () => !preview.busy && preview.ready, + 'preview synchronization', + ); + expect(preview.error, isNull); + } + + Future seek(double seconds) async { + await preview.controlPreview( + sequence, + PreviewAction.seek, + at: CommandTime((seconds * 1000).round(), 1000), + ); + await settled(); + expect( + (await preview.session!.refresh()).position.seconds, + closeTo(seconds, .1), + ); + } + + Future playback() async { + await seek(0); + await tester.tap(find.byTooltip('播放').first); + await until(() { + if (preview.error != null) throw StateError('${preview.error}'); + final snapshot = preview.session!.snapshot; + if (snapshot?.message != null) { + throw StateError('${snapshot!.message}'); + } + return preview.playing && + preview.positionTick > TimelineClock.ticksPerSecond / 2; + }, 'timeline playback'); + final playing = await preview.session!.refresh(); + await tester.tap(find.byTooltip('暂停播放').first); + await until( + () => !preview.playing && !preview.busy, + 'timeline pause', + ); + final paused = await preview.session!.refresh(); + await Future.delayed(const Duration(milliseconds: 200)); + expect( + (await preview.session!.refresh()).position.seconds, + closeTo(paused.position.seconds, .05), + ); + (result.putIfAbsent( + 'timelinePlayback', + () => >[], + ) as List).add({ + 'stage': stage, + 'playedTo': playing.position.seconds, + }); + } + + ExecutionPlan plan() => const ExecutionCompiler() + .compile( + ExecutionInput( + timeline: session.persistence.timeline(sequence), + media: { + record().payloadRef!: ExecutionMediaBinding( + media: media, + videoTrackSelection: null, + audioTrackSelection: TrackSelection.id( + info.audioTrackIds.first!, + ), + audioTiming: info.audioTracks.first, + ), + }, + renderSize: RenderSize(320, 180), + parameterTargets: { + ...ClipTransform.targets, + ...ClipAudioGain.targets, + }, + editorOnlyParameters: const {ClipAudioGain.detachedId}, + ), + ) + .plan; + Future export(String suffix, double duration) async { + final compiled = plan(); + expect(compiled.visualLayers, isEmpty); + expect(compiled.audioLayers, hasLength(1)); + final destination = File( + p.join( + root.path, + '${index.toString().padLeft(2, '0')}-$suffix.mp4', + ), + ).uri; + final uri = await preview.session!.export(compiled, destination); + final exported = MediaReference(id: suffix, uri: uri); + final metadata = await runtime.probe(exported); + expect(metadata.audioTrackCount, 1); + expect(metadata.duration.seconds, closeTo(duration, .12)); + final wave = await runtime.waveform( + WaveformRequest( + media: exported, + baseBucketCount: 64, + levelCount: 1, + ), + ); + expect(wave.frameCount / wave.sampleRate, closeTo(duration, .12)); + (result.putIfAbsent( + 'exports', + () => >[], + ) as List).add({ + 'kind': suffix, + 'path': uri.toFilePath(), + 'duration': metadata.duration.seconds, + 'rms': _rms(wave), + }); + return wave; + } + + await check('editorPlayPauseAndScrub', () async { + await playback(); + for (final at in [6.5, .5, 7.5, 2.0, 0.0]) { + await seek(at); + } + }); + await check('splitToolbarUndoRedo', () async { + preview.selectVisual(clipId); + await seek(4); + await tester.tap(find.byTooltip('在播放头处分割')); + await settled(); + expect(record().duration, 4 * TimelineClock.ticksPerSecond); + expect( + session.persistence.timeline(sequence).exportDto().elements, + hasLength(2), + ); + await session.commands.executeEdit(sequence, const UndoEdit()); + await settled(); + expect(record().duration, 8 * TimelineClock.ticksPerSecond); + await session.commands.executeEdit(sequence, const RedoEdit()); + await settled(); + final other = session.persistence + .timeline(sequence) + .exportDto() + .elements + .firstWhere((e) => e.id != clipId); + await session.commands.executeEdit( + sequence, + DeleteClip(other.id.value), + ); + await settled(); + await playback(); + }); + late MediaWaveform baseline; + await check('baselineExport', () async { + baseline = await export('baseline', 4); + expect(_rms(baseline), greaterThan(.0001)); + }); + await check('speedSliderAndRenderedHalfDouble', () async { + preview.selectVisual(clipId); + await seek(0); + await tester.tap(find.byKey(const ValueKey('property-tab-speed'))); + await tester.pump(); + final slider = find.descendant( + of: find.byKey(const Key('clip-speed-slider')), + matching: find.byType(Slider), + ); + expect(slider, findsOneWidget); + for (final speed in [2.0, .5, 1.0]) { + final bounds = tester.getRect(slider); + final position = (math.log(speed) / math.ln10 + 1) / 3; + final gesture = await tester.startGesture( + Offset( + bounds.left + + 12 + + (bounds.width - 24) * tester.widget(slider).value, + bounds.center.dy, + ), + ); + await gesture.moveTo( + Offset( + bounds.left + 12 + (bounds.width - 24) * position, + bounds.center.dy, + ), + ); + await tester.pump(); + await gesture.up(); + await settled(); + expect(session.clipSpeed(record()), closeTo(speed, .05)); + expect( + record().duration, + closeTo( + 4 * TimelineClock.ticksPerSecond / speed, + TimelineClock.ticksPerSecond / 4, + ), + ); + await playback(); + if (speed != 1) { + final wave = await export( + 'speed-$speed', + record().duration / TimelineClock.ticksPerSecond, + ); + expect(_rms(wave), greaterThan(.0001)); + } + } + session.setClipSpeed(sequence, clipId, 1); + await settled(); + }); + await check('gainMuteAndRenderedAudio', () async { + await session.commands.executeEdit( + sequence, + const SetClipAudio(clipId: 'audio-clip', db: -6, muted: false), + ); + await settled(); + await playback(); + final gained = await export('gain-minus6', 4); + final ratio = _rms(gained) / _rms(baseline); + expect(ratio, closeTo(math.pow(10, -6 / 20).toDouble(), .06)); + result['gainRmsRatio'] = ratio; + await session.commands.executeEdit( + sequence, + const SetClipAudio(clipId: 'audio-clip', db: -6, muted: true), + ); + await settled(); + await playback(); + expect( + _rms(await export('muted', 4)), + lessThanOrEqualTo(1 / 32768), + ); + await session.commands.executeEdit( + sequence, + const SetClipAudio(clipId: 'audio-clip', db: 0, muted: false), + ); + await settled(); + }); + await check('audioKeyframesInterpolationAndRenderedFade', () async { + for (final entry in [(0, 0.0), (3500, -10.5)]) { + await session.commands.executeEdit( + sequence, + EditKeyframe( + clipId: 'audio-clip', + parameterId: ClipAudioGain.gainId, + at: CommandTime(entry.$1, 1000), + action: KeyframeAction.set, + value: entry.$2, + interpolation: KeyInterpolation.linear, + ), + ); + } + await settled(); + final curve = record().parameters![ClipAudioGain.gainId]!; + expect(curve.toDto().keyframes, hasLength(2)); + expect( + curve.valueAt( + record().sourceStart + TimelineClock.ticksPerSecond, + ), + closeTo(-3, .01), + ); + await playback(); + final faded = await export('keyframe-fade', 4); + final reference = baseline.levels.first.channels.first; + final rendered = faded.levels.first.channels.first; + double ratioAt(int start, int end) { + final ratios = []; + for (var bucket = start; bucket < end; bucket++) { + final at = bucket * 3 + 2; + if (reference[at] > .001) { + ratios.add(rendered[at] / reference[at]); + } + } + expect(ratios, isNotEmpty); + return ratios.reduce((a, b) => a + b) / ratios.length; + } + + final early = ratioAt(4, 12); + final late = ratioAt(48, 56); + expect(early, closeTo(.84, .15)); + expect(late, closeTo(.33, .15)); + expect(late, lessThan(early * .65)); + result['keyframeRatios'] = {'early': early, 'late': late}; + }); + await check('saveAndReadPersistedAudioEdits', () async { + await session.flush(); + expect(session.saveError, isNull); + final projectPath = container + .read(projectsProvider) + .requireValue + .activeProject! + .path; + final edits = await savedEdits.capture( + projectPath, + timelineId, + session, + sequence, + ); + expect( + ((edits['clips'] as List).single as Map)['parameters'], + hasLength(greaterThanOrEqualTo(2)), + ); + result['savedTimelineId'] = timelineId; + result['savedProject'] = projectPath; + }); + } + result['passed'] = true; + } catch (error, stack) { + checks.add({ + 'stage': stage, + 'passed': false, + 'error': '$error', + 'stack': '$stack', + }); + debugPrint('AUDIO_MEDIA_FAILED $stage $error\n$stack'); + } + final after = await file.stat(); + result['sourceUnchanged'] = + before.size == after.size && + before.modified == after.modified && + beforeHash == (await sha256.bind(file.openRead()).first).toString(); + if (result['sourceUnchanged'] != true) result['passed'] = false; + save(); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + if (testedTimeline != null) { + await container.read(previewControllerRegistryProvider).invalidate(( + projectId, + testedTimeline, + )); + } + releaseTimeline?.call(); + } + container.dispose(); + disposed = true; + await savedEdits.verify( + wait: tester.pump, + onVerified: (projectPath, timelineId, edits) { + final result = results.singleWhere( + (r) => + r['savedProject'] == projectPath && + r['savedTimelineId'] == timelineId, + ); + result['savedEditsIdenticalAfterReopen'] = true; + save(); + }, + ); + expect( + results.where((file) => file['passed'] != true).toList(), + isEmpty, + reason: 'See ${report.path}', + ); + }, timeout: const Timeout(Duration(minutes: 120))); +} diff --git a/integration_test/windows_real_media_test.dart b/integration_test/windows_real_media_test.dart new file mode 100644 index 0000000..4d62b3e --- /dev/null +++ b/integration_test/windows_real_media_test.dart @@ -0,0 +1,1267 @@ +import 'package:cutdex/app/editor_theme.dart'; + +// Opt-in Windows validation against original media; sources are read-only. +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:math' as math; +import 'dart:ui' as ui; + +import 'package:cutdex/features/preview/preview_panel.dart'; +import 'package:cutdex/features/properties/properties_panel.dart'; +import 'package:cutdex/features/timeline/timeline_panel.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex/persistence/app_database.dart'; +import 'package:cutdex/workspace/media_file_extensions.dart'; +import 'package:cutdex/workspace/media_import.dart'; +import 'package:cutdex/workspace/projects.dart'; +import 'package:cutdex/workspace/preview_controller_registry.dart'; +import 'package:cutdex/workspace/timeline_provider.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline/engine.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:drift/native.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; +import 'package:path/path.dart' as p; + +import 'support/saved_edit_validation.dart'; + +void main() { + final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + const source = String.fromEnvironment('CUTDEX_VALIDATION_SOURCE'); + const output = String.fromEnvironment('CUTDEX_VALIDATION_ROOT'); + const filter = String.fromEnvironment('CUTDEX_VALIDATION_FILTER'); + const previewObservationSeconds = int.fromEnvironment( + 'CUTDEX_VALIDATION_PREVIEW_SECONDS', + defaultValue: 2, + ); + const longSpeedOnly = bool.fromEnvironment( + 'CUTDEX_VALIDATION_LONG_SPEED_ONLY', + ); + const fullPreviewAudio = bool.fromEnvironment( + 'CUTDEX_VALIDATION_FULL_PREVIEW_AUDIO', + defaultValue: true, + ); + const fullPreviewMuted = bool.fromEnvironment( + 'CUTDEX_VALIDATION_FULL_PREVIEW_MUTE', + ); + const muteDamagedAsf = bool.fromEnvironment( + 'CUTDEX_VALIDATION_MUTE_DAMAGED_ASF', + ); + const sourceRoots = String.fromEnvironment('CUTDEX_VALIDATION_SOURCE_ROOTS'); + testWidgets('Windows real media: preview, transport and editing through native runtime', ( + tester, + ) async { + expect(Platform.isWindows, isTrue); + expect(sourceRoots.isEmpty ? source : sourceRoots, isNotEmpty); + expect(output, isNotEmpty); + final paths = + (sourceRoots.isEmpty ? [source] : sourceRoots.split(';')) + .expand( + (root) => + Directory(root).listSync(recursive: true, followLinks: false), + ) + .whereType() + .where( + (file) => + mediaKindForPath(file.path) == 'video' && + (filter.isEmpty || + filter.split(',').any(p.basename(file.path).contains)), + ) + .toList() + ..sort((a, b) => a.path.compareTo(b.path)); + expect(paths, isNotEmpty); + final root = await Directory(output).create(recursive: true); + final report = File(p.join(root.path, 'results.json')); + final results = >[]; + final savedEdits = SavedEditValidation(); + final database = AppDatabase(NativeDatabase.memory()); + final container = ProviderContainer( + overrides: [appDatabaseProvider.overrideWithValue(database)], + ); + final projects = container.read(projectsProvider.notifier); + final runtime = CutdexRuntime(); + addTearDown(database.close); + var disposed = false; + addTearDown(() { + if (!disposed) container.dispose(); + }); + void save() => report.writeAsStringSync( + const JsonEncoder.withIndent(' ').convert({ + 'platform': 'windows', + 'fullPreviewAudio': fullPreviewAudio, + 'fullPreviewMuted': fullPreviewMuted, + 'longSpeedOnly': longSpeedOnly, + 'source': source, + 'method': + 'Original files; production import service, real editor widgets, ' + 'split toolbar and speed slider; command service for keyframes/audio/masks; ' + 'native preview, thumbnails and export. Settings database isolated in memory.', + 'files': results, + }), + ); + Future until( + bool Function() ready, + String label, { + int seconds = 60, + }) async { + final deadline = DateTime.now().add(Duration(seconds: seconds)); + while (!ready()) { + if (DateTime.now().isAfter(deadline)) throw TimeoutException(label); + await tester.pump(const Duration(milliseconds: 50)); + await Future.delayed(const Duration(milliseconds: 10)); + } + await tester.pump(); + } + + expect( + await projects.open( + p.join( + root.path, + 'Real-media-${DateTime.now().millisecondsSinceEpoch}.cutdex', + ), + name: 'Windows 真实素材剪辑验证', + initialTimelineName: '01', + ), + isTrue, + ); + var projectId = container + .read(projectsProvider) + .requireValue + .activeProject! + .id; + for (var index = 0; index < paths.length; index++) { + final file = paths[index]; + final muteFullSource = + fullPreviewMuted || + (muteDamagedAsf && p.extension(file.path).toLowerCase() == '.asf'); + final before = await file.stat(); + final checks = >[]; + final result = { + 'path': file.path, + 'checks': checks, + 'passed': false, + 'fullSourceMuted': muteFullSource, + }; + results.add(result); + save(); + var stage = 'setup'; + String? testedTimeline; + void Function()? releaseTimeline; + Future check(String name, Future Function() action) async { + stage = name; + debugPrint( + 'REAL_MEDIA ${index + 1}/${paths.length} $name ${p.basename(file.path)}', + ); + final clock = Stopwatch()..start(); + await action().timeout(const Duration(minutes: 4)); + expect( + tester.takeException(), + isNull, + reason: 'Widget error during $name', + ); + checks.add({ + 'stage': name, + 'passed': true, + 'milliseconds': clock.elapsedMilliseconds, + }); + save(); + } + + try { + if (index > 0) { + if (container.read(projectsProvider).requireValue.timelines.length >= + Projects.maxTimelineCount) { + expect( + await projects.open( + p.join( + root.path, + 'Real-media-batch-${index + 1}-${DateTime.now().millisecondsSinceEpoch}.cutdex', + ), + name: 'Windows 真实素材剪辑验证 ${index + 1}', + initialTimelineName: '${index + 1}', + ), + isTrue, + ); + projectId = container + .read(projectsProvider) + .requireValue + .activeProject! + .id; + } else { + expect(await projects.createTimeline(name: '${index + 1}'), isTrue); + } + } + final timelineId = container + .read(projectsProvider) + .requireValue + .timeline! + .id; + testedTimeline = timelineId; + final retainedTimeline = container.listen( + editorTimelineProvider(projectId, timelineId), + (_, _) {}, + ); + releaseTimeline = retainedTimeline.close; + final session = await container.read( + editorTimelineProvider(projectId, timelineId).future, + ); + final sequence = session.activeSequenceId!; + final view = session.view(sequence); + final media = MediaReference(id: 'real-source', uri: file.uri); + late MediaInfo info; + await check('probeOriginalAndSeekThumbnails', () async { + info = await runtime.probe(media); + expect(info.videoTrackCount, greaterThan(0)); + expect(info.audioTrackCount, greaterThan(0)); + expect(info.duration.seconds, greaterThan(120)); + result['durationSeconds'] = info.duration.seconds; + result['audioTracks'] = info.audioTrackCount; + result['displaySizes'] = [ + for (final size in info.videoDisplaySizes) + [size.width, size.height], + ]; + for (final seconds in [ + 60.0, + info.duration.seconds / 2, + info.duration.seconds - 5, + ]) { + final thumbnail = await runtime.thumbnail( + ThumbnailRequest( + media: media, + time: MediaTime((seconds * 1000).round(), 1000), + maximumWidth: 320, + maximumHeight: 180, + ), + ); + expect(thumbnail.data, isNotEmpty); + final image = await decodeImageFromList(thumbnail.data); + expect(image.width, greaterThan(0)); + image.dispose(); + } + }); + if (!longSpeedOnly) { + await check('fullLengthPreviewStartMiddleAndEnd', () async { + final full = await runtime.createSession(); + try { + final duration = MediaTime( + (math.min( + info.duration.seconds, + info.audioTracks.first.duration.seconds, + ) * + 1000) + .floor() - + 100, + 1000, + ); + final range = MediaRange( + start: MediaTime(0, 1), + duration: duration, + ); + await full.load( + ExecutionPlan( + duration: duration, + renderSize: RenderSize(640, 360), + frameDuration: MediaTime(1, 30), + media: [media], + visualLayers: [ + VisualLayer( + id: 'full-video', + mediaId: media.id, + sourceRange: range, + timelineRange: range, + inputColorSpace: + info.videoColorSpaces[0] ?? RenderColorSpace.rec709, + ), + ], + audioLayers: [ + if (fullPreviewAudio) + AudioLayer( + id: 'full-audio', + volume: muteFullSource ? 0 : 1, + mediaId: media.id, + sourceRange: range, + timelineRange: range, + ), + ], + ), + ); + for (var i = 0; i < 3; i++) { + await full.pause(); + await Future.delayed(const Duration(milliseconds: 100)); + expect((await full.refresh()).message, isNull); + } + await tester.pumpWidget( + MaterialApp( + home: Center( + child: SizedBox( + width: 640, + height: 360, + child: RuntimePreview(session: full), + ), + ), + ), + ); + await full.play(); + await until( + () => (full.snapshot?.presentedVideoFrameCount ?? 0) > 0, + 'full-length first playback frames', + seconds: 90, + ); + await full.pause(); + final observations = >[]; + for (final seconds in [ + 60.0, + duration.seconds / 2, + duration.seconds - math.max(5, previewObservationSeconds + 3), + duration.seconds / 4, + ]) { + await full.seek(MediaTime((seconds * 1000).round(), 1000)); + await full.play(); + final before = await full.refresh(); + final uiTimings = []; + void collectTimings(List timings) { + uiTimings.addAll(timings); + } + + WidgetsBinding.instance.addTimingsCallback(collectTimings); + // Native textures can redraw without a Dart frame. Refresh the + // viewport continuously so Profile runs also measure Flutter's + // raster cost instead of treating missing timings as zero cost. + final previousPolicy = binding.framePolicy; + binding.framePolicy = + LiveTestWidgetsFlutterBindingFramePolicy.fullyLive; + final viewportRefresh = Timer.periodic( + const Duration(milliseconds: 16), + (_) => binding.scheduleFrame(), + ); + final startUnixMs = DateTime.now().millisecondsSinceEpoch; + final observed = Stopwatch()..start(); + try { + await Future.delayed( + const Duration(seconds: previewObservationSeconds), + ); + await tester.pump(); + } finally { + viewportRefresh.cancel(); + binding.framePolicy = previousPolicy; + WidgetsBinding.instance.removeTimingsCallback(collectTimings); + } + final after = await full.refresh(); + final observation = { + 'pid': pid, + 'startUnixMs': startUnixMs, + 'endUnixMs': DateTime.now().millisecondsSinceEpoch, + 'at': seconds, + 'position': after.position.seconds, + 'beforeFrames': before.presentedVideoFrameCount, + 'frames': + (after.presentedVideoFrameCount ?? 0) - + (before.presentedVideoFrameCount ?? 0), + 'maximumFrameGapMs': after.maximumVideoFrameGapMs, + 'droppedFrames': after.droppedVideoFrameCount, + 'observationSeconds': observed.elapsedMicroseconds / 1000000, + 'deliveredFramesPerSecond': + ((after.presentedVideoFrameCount ?? 0) - + (before.presentedVideoFrameCount ?? 0)) / + (observed.elapsedMicroseconds / 1000000), + 'message': after.message, + 'flutterFrameTimingCount': uiTimings.length, + 'flutterTimingMode': 'continuous viewport refresh', + 'flutterBuildOver16ms': uiTimings + .where( + (timing) => timing.buildDuration.inMicroseconds > 16667, + ) + .length, + 'flutterRasterOver16ms': uiTimings + .where( + (timing) => + timing.rasterDuration.inMicroseconds > 16667, + ) + .length, + 'flutterMaximumBuildMs': uiTimings.fold( + 0, + (maximum, timing) => math.max( + maximum, + timing.buildDuration.inMicroseconds / 1000, + ), + ), + 'flutterMaximumRasterMs': uiTimings.fold( + 0, + (maximum, timing) => math.max( + maximum, + timing.rasterDuration.inMicroseconds / 1000, + ), + ), + }; + observations.add(observation); + result['fullLengthPlayback'] = observations; + debugPrint('REAL_MEDIA_FULL_PLAYBACK $observation'); + expect(after.message, isNull); + expect(after.position.seconds, greaterThan(seconds + .5)); + expect( + after.presentedVideoFrameCount, + greaterThan(before.presentedVideoFrameCount ?? 0), + ); + await full.pause(); + } + result['fullLengthPlayback'] = observations; + } finally { + await tester.pumpWidget(const SizedBox.shrink()); + await full.close(); + } + }); + } + await check('importOriginalAndInsertSourceRange', () async { + final imported = await projects.importExternalMedia(projectId, [ + ExternalMediaFile(path: file.path), + ]); + expect(imported!.failures, isEmpty); + final asset = imported.assets.firstWhere( + (a) => a.name == p.basename(file.path), + ); + await session.commands.executeEdit( + sequence, + const SetProjectCanvas(width: 640, height: 360), + ); + await session.commands.insertMedia( + sequence: sequence, + assetId: asset.id, + clipId: ElementId('real-clip'), + index: 0, + sourceStart: RationalTime.seconds(longSpeedOnly ? 0 : 60), + duration: longSpeedOnly + ? RationalTime( + (math.min( + info.duration.seconds, + info.audioTracks.first.duration.seconds, + ) * + 1000) + .floor() - + 100, + 1000, + ) + : RationalTime.seconds(8), + ); + }); + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + theme: EditorTheme.penLight, + home: Scaffold( + body: Column( + children: [ + Expanded( + child: Row( + children: [ + Expanded( + child: EditorPreviewPanel( + projectId: projectId, + timelineId: timelineId, + ), + ), + SizedBox( + width: 280, + child: EditorPropertiesPanel( + projectId: projectId, + timelineId: timelineId, + ), + ), + ], + ), + ), + SizedBox( + height: 210, + child: EditorTimelinePanel( + projectId: projectId, + timelineId: timelineId, + ), + ), + ], + ), + ), + ), + ), + ); + await check('initializeNativePreview', () async { + final initialized = await container + .read(editorPreviewProvider(projectId, timelineId).future) + .timeout(const Duration(minutes: 2)); + if (initialized == null) { + throw StateError( + 'Preview is empty; timeline duration ${session.sequenceDurationTicks(sequence)}', + ); + } + debugPrint( + 'REAL_MEDIA_INITIALIZED ready=${initialized.ready} busy=${initialized.busy} error=${initialized.error} duration=${initialized.durationTick}', + ); + await until( + () { + final state = container.read( + editorPreviewProvider(projectId, timelineId), + ); + if (state.hasError) { + throw StateError('Native preview startup: ${state.error}'); + } + final value = state.asData?.value; + if (value?.error != null) { + throw StateError('Native preview: ${value!.error}'); + } + return value?.ready == true; + }, + 'preview initialized', + seconds: 180, + ); + }); + final preview = container + .read(editorPreviewProvider(projectId, timelineId)) + .requireValue!; + // Windows counts presented frames while the playback clock runs. + await preview.controlPreview(sequence, PreviewAction.play); + await until( + () => (preview.session?.snapshot?.presentedVideoFrameCount ?? 0) > 0, + 'first preview frame', + seconds: 90, + ); + await preview.controlPreview(sequence, PreviewAction.pause); + final clipId = ElementId('real-clip'); + ElementRecord record() { + final q = session.persistence.timeline(sequence).current.query(); + return q.element(q.elementById(clipId)!); + } + + Future settled() async { + await tester.pump(); + await until( + () => !preview.busy && preview.ready, + 'preview synchronization: ${preview.error}', + ); + expect(preview.error, isNull); + } + + Future seek(double seconds) async { + await preview.controlPreview( + sequence, + PreviewAction.seek, + at: CommandTime((seconds * 1000).round(), 1000), + ); + await settled(); + expect( + (await preview.session!.refresh()).position.seconds, + closeTo(seconds, .15), + ); + } + + Future playback({double start = 0}) async { + await seek(start); + await tester.tap(find.byTooltip('播放').first); + await until(() => preview.playing, 'play control accepted'); + final beforePlay = await preview.session!.refresh(); + var nextLog = DateTime.now(); + await until(() { + if (preview.error != null) { + throw StateError('Preview playback: ${preview.error}'); + } + final native = preview.session!.snapshot; + if (native?.message != null) { + throw StateError('Native playback: ${native!.message}'); + } + if (DateTime.now().isAfter(nextLog)) { + nextLog = DateTime.now().add(const Duration(seconds: 2)); + debugPrint( + 'REAL_MEDIA_CLOCK ui=${preview.playing}/${preview.positionTick} native=${native?.state}/${native?.position.seconds}/${native?.presentedVideoFrameCount} busy=${preview.busy}', + ); + } + return preview.playing && + preview.positionTick > + (start + .5) * TimelineClock.ticksPerSecond && + (native?.presentedVideoFrameCount ?? 0) > + (beforePlay.presentedVideoFrameCount ?? 0); + }, 'native playback clock'); + await Future.delayed( + const Duration(milliseconds: longSpeedOnly ? 1800 : 250), + ); + await tester.pump(); + final playing = await preview.session!.refresh(); + expect( + playing.presentedVideoFrameCount, + greaterThan(beforePlay.presentedVideoFrameCount ?? 0), + ); + await tester.tap(find.byTooltip('暂停播放').first); + await until(() => !preview.playing && !preview.busy, 'native pause'); + final at = preview.positionTick; + await tester.pump(const Duration(milliseconds: 250)); + expect( + (preview.positionTick - at).abs(), + lessThan(TimelineClock.ticksPerSecond / 10), + ); + expect(preview.error, isNull); + (result.putIfAbsent( + 'playback', + () => >[], + ) as List).add({ + 'stage': stage, + 'positionSeconds': playing.position.seconds, + 'frames': playing.presentedVideoFrameCount, + 'dropped': playing.droppedVideoFrameCount, + 'maximumGapMs': playing.maximumVideoFrameGapMs, + 'rssBytes': ProcessInfo.currentRss, + }); + } + + if (longSpeedOnly) { + await check( + 'fullLengthPitchPreservingSpeedAndWindowCrossing', + () async { + final sourceStart = record().sourceStart; + final sourceDuration = record().sourceDuration; + final speeds = >[]; + for (final speed in [2.0, .5, 1.0]) { + session.setClipSpeed(sequence, clipId, speed); + await settled(); + expect(session.clipSpeed(record()), speed); + expect(record().sourceStart, sourceStart); + expect(record().sourceDuration, sourceDuration); + expect(record().duration, closeTo(sourceDuration / speed, 1)); + final clock = Stopwatch()..start(); + await playback(); + await playback(start: 29.5); + speeds.add({ + 'speed': speed, + 'sourceTicks': sourceDuration, + 'timelineTicks': record().duration, + 'playbackMs': clock.elapsedMilliseconds, + }); + } + result['fullLengthSpeeds'] = speeds; + }, + ); + } else { + await check('nativePreviewPlayPauseAndScrub', () async { + expect(find.byType(RuntimePreview), findsOneWidget); + await playback(); + for (final at in [6.5, .5, 7.5, 2.0, 0.0]) { + await seek(at); + } + }); + await check('splitToolbarUndoRedo', () async { + preview.selectVisual(clipId); + await seek(4); + await tester.tap(find.byTooltip('在播放头处分割')); + await settled(); + expect(record().duration, 4 * TimelineClock.ticksPerSecond); + expect( + session.persistence + .timeline(sequence) + .exportDto() + .elements + .length, + 2, + ); + await session.commands.executeEdit(sequence, const UndoEdit()); + await settled(); + expect(record().duration, 8 * TimelineClock.ticksPerSecond); + await session.commands.executeEdit(sequence, const RedoEdit()); + await settled(); + final other = session.persistence + .timeline(sequence) + .exportDto() + .elements + .firstWhere((e) => e.id != clipId); + await session.commands.executeEdit( + sequence, + DeleteClip(other.id.value), + ); + await settled(); + await playback(); + }); + await check('speedSliderHalfDoubleAndNormal', () async { + preview.selectVisual(clipId); + await seek(0); + await tester.tap(find.byKey(const ValueKey('property-tab-speed'))); + await tester.pump(); + final slider = find.descendant( + of: find.byKey(const Key('clip-speed-slider')), + matching: find.byType(Slider), + ); + expect(slider, findsOneWidget); + for (final requested in [2.0, .5, 1.0]) { + final bounds = tester.getRect(slider); + final position = (math.log(requested) / math.ln10 + 1) / 3; + final gesture = await tester.startGesture( + Offset( + bounds.left + + 12 + + (bounds.width - 24) * tester.widget(slider).value, + bounds.center.dy, + ), + ); + await gesture.moveTo( + Offset( + bounds.left + 12 + (bounds.width - 24) * position, + bounds.center.dy, + ), + ); + await tester.pump(); + await gesture.up(); + await settled(); + expect(session.clipSpeed(record()), closeTo(requested, .05)); + expect( + record().duration, + closeTo( + 4 * TimelineClock.ticksPerSecond / requested, + TimelineClock.ticksPerSecond / 4, + ), + ); + await playback(); + } + // Keep exact source timing for subsequent pixel/audio comparisons. + session.setClipSpeed(sequence, clipId, 1); + await settled(); + }); + await check('segmentedSpeedSourceClockAndRestore', () async { + await seek(0); + final originalSource = record().sourceStart; + final originalDuration = record().sourceDuration; + session.splitClipSpeedAt( + sequence, + clipId, + 2 * TimelineClock.ticksPerSecond, + ); + await settled(); + expect(session.clipSpeedSegments(record()), hasLength(2)); + session.setClipSpeedSegmentDuration( + sequence, + clipId, + 1, + TimelineClock.ticksPerSecond, + ); + await settled(); + expect(record().duration, 3 * TimelineClock.ticksPerSecond); + expect(record().sourceDuration, originalDuration); + expect( + TimelineSourceClock(record()) + .nearestSourceTick(TimelineClock.ticksPerSecond * 5 ~/ 2), + originalSource + 3 * TimelineClock.ticksPerSecond, + ); + await seek(2.5); + await playback(); + await session.commands.executeEdit(sequence, const UndoEdit()); + await settled(); + expect(record().duration, 4 * TimelineClock.ticksPerSecond); + session.setClipSpeed(sequence, clipId, 1); + await settled(); + expect(session.clipSpeedSegments(record()), hasLength(1)); + expect(record().sourceDuration, originalDuration); + }); + Future export(String suffix, {int audioOrdinal = 0}) async { + final plan = const ExecutionCompiler() + .compile( + ExecutionInput( + timeline: session.persistence.timeline(sequence), + media: { + record().payloadRef!: ExecutionMediaBinding( + media: media, + videoTrackSelection: TrackSelection.id( + info.videoTrackIds.first!, + ), + inputColorSpace: + info.videoColorSpaces[0] ?? RenderColorSpace.rec709, + audioTrackSelection: TrackSelection.id( + info.audioTrackIds[audioOrdinal]!, + ), + audioTiming: info.audioTracks[audioOrdinal], + ), + }, + renderSize: RenderSize(320, 180), + parameterTargets: { + ...ClipTransform.targets, + ...ClipAudioGain.targets, + }, + editorOnlyParameters: const {ClipAudioGain.detachedId}, + ), + ) + .plan; + return preview.session!.export( + plan, + File( + p.join( + root.path, + '${index.toString().padLeft(2, '0')}-$suffix.mp4', + ), + ).uri, + ); + } + + late Uri baseline; + await check('baselineExportAndAudio', () async { + baseline = await export('baseline'); + final exported = await runtime.probe( + MediaReference(id: 'baseline', uri: baseline), + ); + expect(exported.videoTrackCount, 1); + expect(exported.audioTrackCount, 1); + expect(exported.duration.seconds, closeTo(4, .1)); + result['baselineExport'] = baseline.toFilePath(); + }); + if (info.audioTrackCount > 1) { + await check('alternateAudioTrackExportAndDecode', () async { + final uri = await export('audio-track-1', audioOrdinal: 1); + final alternate = MediaReference(id: 'alternate-audio', uri: uri); + final wave = await runtime.waveform( + WaveformRequest( + media: alternate, + baseBucketCount: 64, + levelCount: 1, + ), + ); + expect(wave.levels.first.channels.length, 2); + expect( + wave.levels.first.channels + .expand((values) => values) + .any((value) => value.abs() > .0001), + isTrue, + ); + result['alternateAudioExport'] = uri.toFilePath(); + }); + } + await check('staticTransformExportAndReset', () async { + await session.commands.executeEdit( + sequence, + SetClipTransform( + clipId: 'real-clip', + at: CommandTime(0, 1), + x: 32, + y: -18, + scaleX: .5, + scaleY: .75, + rotation: 30, + ), + ); + await settled(); + final value = ClipTransform.fromRecord(record()); + expect(value.x, closeTo(.05, .000001)); + expect(value.y, closeTo(-.05, .000001)); + expect(value.scale, .5); + expect(value.scaleY, .75); + expect(value.rotation, 30); + await playback(); + final uri = await export('transform'); + result['transformExport'] = uri.toFilePath(); + await session.commands.executeEdit( + sequence, + SetClipTransform( + clipId: 'real-clip', + at: CommandTime(0, 1), + x: 0, + y: 0, + scaleX: 1, + scaleY: 1, + rotation: 0, + ), + ); + await settled(); + }); + await check('multiChannelKeyframesInterpolationAndClear', () async { + final channels = { + 'canvas.position.y': (0, .1), + 'canvas.scale.x': (1, .5), + 'canvas.scale.y': (1, .75), + 'canvas.rotation': (0, 30), + }; + for (final channel in channels.entries) { + for (final key in [ + (0, channel.value.$1), + (2, channel.value.$2), + ]) { + await session.commands.executeEdit( + sequence, + EditKeyframe( + clipId: 'real-clip', + parameterId: channel.key, + at: CommandTime(key.$1, 1), + action: KeyframeAction.set, + value: key.$2, + interpolation: KeyInterpolation.linear, + ), + ); + } + } + await settled(); + await seek(1); + final q = session.persistence.timeline(sequence).current.query(); + final value = ClipAnimation.at( + q, + q.elementById(clipId)!, + TimelineClock.ticksPerSecond, + TimelineClock.ticksPerSecond ~/ 30, + ).value; + expect(value.y, closeTo(-.05, .001)); + expect(value.scale, closeTo(.75, .001)); + expect(value.scaleY, closeTo(.875, .001)); + expect(value.rotation, closeTo(15, .001)); + await playback(); + for (final channel in channels.keys) { + await session.commands.executeEdit( + sequence, + EditKeyframe( + clipId: 'real-clip', + parameterId: channel, + at: CommandTime(0, 1), + action: KeyframeAction.clear, + ), + ); + } + await session.commands.executeEdit( + sequence, + SetClipTransform( + clipId: 'real-clip', + at: CommandTime(0, 1), + x: 0, + y: 0, + scaleX: 1, + scaleY: 1, + rotation: 0, + ), + ); + await settled(); + }); + await check('audioGainMuteAndRestore', () async { + await session.commands.executeEdit( + sequence, + const SetClipAudio(clipId: 'real-clip', db: -6, muted: true), + ); + await settled(); + expect(ClipAudioGain.fromRecord(record()).muted, isTrue); + await playback(); + await session.commands.executeEdit( + sequence, + const SetClipAudio(clipId: 'real-clip', db: -6, muted: false), + ); + await settled(); + expect(ClipAudioGain.fromRecord(record()).db, -6); + }); + await check('transformKeyframesAndInterpolation', () async { + for (final entry in [(0, 0.0), (2, .1)]) { + await session.commands.executeEdit( + sequence, + EditKeyframe( + clipId: 'real-clip', + parameterId: 'canvas.position.x', + at: CommandTime(entry.$1, 1), + action: KeyframeAction.set, + value: entry.$2, + interpolation: KeyInterpolation.linear, + ), + ); + } + await settled(); + await seek(1); + final animation = ClipAnimation.at( + view.version.kernelVersion.query(), + view.version.kernelVersion.query().elementById(clipId)!, + TimelineClock.ticksPerSecond, + TimelineClock.ticksPerSecond ~/ 30, + ); + expect(animation.value.x, closeTo(.05, .001)); + await playback(); + }); + await check('rectangleEllipseFeatherAndInvertedMasks', () async { + await seek(0); + await session.commands.executeEdit( + sequence, + EditMask( + clipId: 'real-clip', + at: CommandTime(0, 1), + action: MaskAction.add, + maskId: 'real-mask', + shape: MaskShape.rectangle, + x: .5, + y: .5, + width: .5, + height: .5, + ), + ); + await settled(); + for (final inverted in [false, true]) { + await session.commands.executeEdit( + sequence, + EditMask( + clipId: 'real-clip', + at: CommandTime(0, 1), + action: MaskAction.set, + maskId: 'real-mask', + shape: MaskShape.ellipse, + inverted: inverted, + feather: .1, + ), + ); + await settled(); + expect( + ClipMaskStack(record(), 0).layers.single.mask.inverted, + inverted, + ); + await playback(); + } + await session.commands.executeEdit( + sequence, + EditMask( + clipId: 'real-clip', + at: CommandTime(0, 1), + action: MaskAction.set, + maskId: 'real-mask', + shape: MaskShape.rectangle, + inverted: false, + feather: 0, + ), + ); + await settled(); + }); + await check('maskAnimationStackAndRestore', () async { + final layer = ClipMaskStack(record(), 0).layers.single; + for (final key in [(0, .5), (2, .7)]) { + await session.commands.executeEdit( + sequence, + EditKeyframe( + clipId: 'real-clip', + parameterId: layer.target('center.x'), + at: CommandTime(key.$1, 1), + action: KeyframeAction.set, + value: key.$2, + interpolation: KeyInterpolation.linear, + ), + ); + } + await settled(); + await seek(1); + expect( + ClipMaskStack( + record(), + TimelineClock.ticksPerSecond, + ).layers.single.mask.x, + closeTo(.6, .001), + ); + await playback(); + await session.commands.executeEdit( + sequence, + EditMask( + clipId: 'real-clip', + at: CommandTime(0, 1), + action: MaskAction.add, + maskId: 'second-mask', + shape: MaskShape.ellipse, + mode: MaskMode.intersect, + width: .8, + height: .8, + ), + ); + await session.commands.executeEdit( + sequence, + EditMask( + clipId: 'real-clip', + at: CommandTime(0, 1), + action: MaskAction.reorder, + maskIds: ['second-mask', 'real-mask'], + ), + ); + await settled(); + expect(ClipMaskStack(record(), 0).layers.map((l) => l.id), [ + 'second-mask', + 'real-mask', + ]); + await playback(); + await session.commands.executeEdit( + sequence, + EditMask( + clipId: 'real-clip', + at: CommandTime(0, 1), + action: MaskAction.setEnabled, + maskId: 'second-mask', + enabled: false, + ), + ); + await settled(); + expect(ClipMaskStack(record(), 0).layers.first.enabled, isFalse); + await session.commands.executeEdit( + sequence, + EditMask( + clipId: 'real-clip', + at: CommandTime(0, 1), + action: MaskAction.remove, + maskId: 'second-mask', + ), + ); + await session.commands.executeEdit( + sequence, + EditKeyframe( + clipId: 'real-clip', + parameterId: layer.target('center.x'), + at: CommandTime(0, 1), + action: KeyframeAction.clear, + ), + ); + await session.commands.executeEdit( + sequence, + EditMask( + clipId: 'real-clip', + at: CommandTime(0, 1), + action: MaskAction.set, + maskId: 'real-mask', + x: .5, + ), + ); + await settled(); + expect(ClipMaskStack(record(), 0).layers, hasLength(1)); + }); + await check('editedExportPixelsAudioAndPersistence', () async { + final exportedUri = await export('edited'); + result['editedExport'] = exportedUri.toFilePath(); + final editedMedia = MediaReference(id: 'edited', uri: exportedUri); + final editedInfo = await runtime.probe(editedMedia); + expect(editedInfo.duration.seconds, closeTo(4, .1)); + expect(editedInfo.audioTrackCount, 1); + final thumbnail = await runtime.thumbnail( + ThumbnailRequest( + media: editedMedia, + time: MediaTime(1, 1), + maximumWidth: 320, + maximumHeight: 180, + ), + ); + final image = await decodeImageFromList(thumbnail.data); + final pixels = (await image.toByteData( + format: ui.ImageByteFormat.rawRgba, + ))!; + // The authored half-size mask must leave the canvas corners black. + for (final at in [ + 0, + (image.width - 1) * 4, + (image.height - 1) * image.width * 4, + ]) { + expect( + pixels.getUint8(at) + + pixels.getUint8(at + 1) + + pixels.getUint8(at + 2), + lessThan(35), + ); + } + image.dispose(); + final originalWave = await runtime.waveform( + WaveformRequest( + media: MediaReference(id: 'baseline', uri: baseline), + baseBucketCount: 64, + levelCount: 1, + ), + ); + final editedWave = await runtime.waveform( + WaveformRequest( + media: editedMedia, + baseBucketCount: 64, + levelCount: 1, + ), + ); + double rms(MediaWaveform wave) { + final values = [ + for (final channel in wave.levels.first.channels) + for (var i = 2; i < channel.length; i += 3) channel[i], + ]; + return math.sqrt( + values.fold(0, (sum, value) => sum + value * value) / + values.length, + ); + } + + final baseRms = rms(originalWave); + final editedRms = rms(editedWave); + if (baseRms <= 1 / 32768) { + // Silent source intervals have no measurable gain ratio. + expect(editedRms, lessThanOrEqualTo(1 / 32768)); + result['audioObservation'] = + 'baseline interval is silent; edited interval remains silent'; + } else { + final ratio = editedRms / baseRms; + expect(ratio, closeTo(math.pow(10, -6 / 20).toDouble(), .08)); + result['audioRmsRatio'] = ratio; + } + }); + } + await check('saveEditedTimeline', () async { + await session.flush(); + expect(session.saveError, isNull); + final projectPath = container + .read(projectsProvider) + .requireValue + .activeProject! + .path; + final edits = await savedEdits.capture( + projectPath, + timelineId, + session, + sequence, + ); + if (!longSpeedOnly) { + expect( + ((edits['clips'] as List).single as Map)['parameters'], + hasLength(greaterThan(2)), + ); + } + result['savedTimelineId'] = timelineId; + result['savedProject'] = projectPath; + }); + result['passed'] = true; + } catch (error, stack) { + checks.add({ + 'stage': stage, + 'passed': false, + 'error': '$error', + 'stack': '$stack', + }); + debugPrint('REAL_MEDIA_FAILED $stage $error\n$stack'); + } + final after = await file.stat(); + result['sourceUnchanged'] = + before.size == after.size && before.modified == after.modified; + if (result['sourceUnchanged'] != true) result['passed'] = false; + save(); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + if (testedTimeline != null) { + await container.read(previewControllerRegistryProvider).invalidate(( + projectId, + testedTimeline, + )); + } + releaseTimeline?.call(); + } + container.dispose(); + disposed = true; + await savedEdits.verify( + wait: tester.pump, + onVerified: (projectPath, timelineId, edits) { + final result = results.singleWhere( + (r) => + r['savedProject'] == projectPath && + r['savedTimelineId'] == timelineId, + ); + result['savedEditsIdenticalAfterReopen'] = true; + File( + p.join(root.path, 'reopened-edits-$timelineId.json'), + ).writeAsStringSync(const JsonEncoder.withIndent(' ').convert(edits)); + save(); + }, + ); + expect( + results.where((file) => file['passed'] != true).toList(), + isEmpty, + reason: 'See ${report.path}', + ); + }, timeout: const Timeout(Duration(minutes: 240))); +} diff --git a/integration_test/windows_seek_latency_test.dart b/integration_test/windows_seek_latency_test.dart new file mode 100644 index 0000000..c525fe9 --- /dev/null +++ b/integration_test/windows_seek_latency_test.dart @@ -0,0 +1,203 @@ +import 'package:cutdex/app/editor_theme.dart'; + +import 'dart:convert'; +import 'dart:io'; +import 'dart:math' as math; + +import 'package:cutdex/features/preview/preview_panel.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex/workspace/timeline_provider.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/preview.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; + +import '../test/support/preview_fixture.dart'; + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + const source = String.fromEnvironment('CUTDEX_SEEK_SOURCE'); + const report = String.fromEnvironment('CUTDEX_SEEK_REPORT'); + testWidgets('original source seek and live playhead timing', (tester) async { + expect( + report, + isNotEmpty, + reason: 'Set CUTDEX_SEEK_REPORT to an output file.', + ); + final media = File(source); + expect(await media.exists(), isTrue); + final channel = _SeekChannel(); + final runtime = CutdexRuntime(channel: channel); + final info = await runtime.probe( + MediaReference(id: 'source', uri: media.uri), + ); + expect(info.videoTrackCount, greaterThan(0)); + final duration = info.duration.seconds; + expect(duration, greaterThanOrEqualTo(5)); + final start = duration * .01; + final middle = duration * .5; + final nearbyStep = math.min(1.0, duration * .01); + final fixture = await createPreviewFixture( + media.uri, + hasAudio: info.audioTrackCount > 0, + clipDuration: RationalTime( + info.duration.numerator, + info.duration.denominator, + ), + renderSize: {'width': 1280, 'height': 720}, + ); + final preview = PreviewController( + timeline: fixture.timeline, + activeSequence: () => fixture.timeline.activeSequenceId, + viewForSequence: fixture.timeline.view, + runtime: runtime, + ); + addTearDown(() async { + await preview.close(); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + }); + await preview.initialize(); + expect(preview.error, isNull); + final project = fixture.workspace.project!.info.id; + final view = fixture.timeline.view(fixture.timeline.activeSequenceId!); + await tester.pumpWidget( + ProviderScope( + overrides: [ + editorTimelineProvider( + project, + 'project', + ).overrideWith((ref) async => fixture.timeline), + editorPreviewProvider( + project, + 'project', + ).overrideWith((ref) async => preview), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + theme: EditorTheme.penDark, + home: Scaffold( + body: EditorPreviewPanel(projectId: project, timelineId: 'project'), + ), + ), + ), + ); + await tester.pumpAndSettle(); + final samples = >[]; + Future seek(double at) => preview.controlPreview( + fixture.timeline.activeSequenceId!, + PreviewAction.seek, + at: CommandTime((at * 1000).round(), 1000), + ); + for (final at in [ + start, + start + nearbyStep * .2, + start + nearbyStep, + start + nearbyStep * .9, + start + nearbyStep * .8, + middle, + middle + nearbyStep * .2, + middle + nearbyStep, + middle + nearbyStep * .9, + duration * .25, + duration * .99, + start, + ]) { + final started = Stopwatch()..start(); + await seek(at); + final acknowledged = started.elapsedMicroseconds / 1000; + await tester.pump(); + samples.add({ + 'at': at, + 'acknowledgedMs': acknowledged, + 'pumpedMs': started.elapsedMicroseconds / 1000, + }); + expect(preview.error, isNull); + } + final drags = >[]; + for (final pattern in [ + (start, math.min(.05, duration * .01 / 59)), + (middle, duration * .4 / 59), + ]) { + await seek(pattern.$1); + final started = Stopwatch()..start(); + final observations = >[]; + var previous = preview.session!.snapshot!.position.seconds; + view.beginScrubbing(); + var target = pattern.$1; + for (var index = 0; index < 120; index++) { + target = pattern.$1 + (index < 60 ? index : 119 - index) * pattern.$2; + view.seekTo((target * TimelineClock.ticksPerSecond).round()); + await tester.pump(); + await Future.delayed(const Duration(milliseconds: 16)); + final shown = preview.session!.snapshot!.position.seconds; + if (shown != previous) { + observations.add({ + 'ms': started.elapsedMicroseconds / 1000, + 'requested': target, + 'nativeObserved': shown, + }); + previous = shown; + } + } + final release = Stopwatch()..start(); + view.endScrubbing(); + await seek(target); + await preview.session!.refresh(); + expect(preview.session!.snapshot!.position.seconds, closeTo(target, .01)); + expect(preview.error, isNull); + drags.add({ + 'start': pattern.$1, + 'step': pattern.$2, + 'requests': 120, + 'durationMs': started.elapsedMicroseconds / 1000, + 'releaseMs': release.elapsedMicroseconds / 1000, + 'observations': observations, + }); + } + final output = File(report); + await output.parent.create(recursive: true); + await output.writeAsString( + jsonEncode({ + 'source': source, + 'durationSeconds': duration, + 'samples': samples, + 'drags': drags, + 'channelCalls': channel.samples, + 'error': preview.error?.toString(), + 'measurement': 'Real Profile preview panel and playhead controller; acknowledgment plus pumped frame, not physical display timestamp', + }), + ); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + }, skip: !Platform.isWindows || source.isEmpty); +} + +class _SeekChannel extends MethodChannel { + _SeekChannel() : super('cutdex_runtime'); + final samples = >[]; + @override + Future invokeMethod(String method, [dynamic arguments]) async { + final request = method == 'request' + ? jsonDecode(arguments['request'] as String) as Map + : arguments as Map; + final name = request['method'] ?? method; + final started = Stopwatch()..start(); + final response = await super.invokeMethod(method, arguments); + if (['seek', 'skim', 'beginSkimming', 'endSkimming'].contains(name)) { + samples.add({ + 'method': name, + 'ms': started.elapsedMicroseconds / 1000, + 'time': request['time'], + }); + } + return response; + } +} diff --git a/ios/.gitignore b/ios/.gitignore new file mode 100644 index 0000000..7a7f987 --- /dev/null +++ b/ios/.gitignore @@ -0,0 +1,34 @@ +**/dgph +*.mode1v3 +*.mode2v3 +*.moved-aside +*.pbxuser +*.perspectivev3 +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Generated.xcconfig +Flutter/ephemeral/ +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!default.mode1v3 +!default.mode2v3 +!default.pbxuser +!default.perspectivev3 diff --git a/ios/Flutter/AppFrameworkInfo.plist b/ios/Flutter/AppFrameworkInfo.plist new file mode 100644 index 0000000..391a902 --- /dev/null +++ b/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + + diff --git a/ios/Flutter/Debug.xcconfig b/ios/Flutter/Debug.xcconfig new file mode 100644 index 0000000..e8e1eba --- /dev/null +++ b/ios/Flutter/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "Generated.xcconfig" +#include? "Signing.local.xcconfig" diff --git a/ios/Flutter/Release.xcconfig b/ios/Flutter/Release.xcconfig new file mode 100644 index 0000000..e8e1eba --- /dev/null +++ b/ios/Flutter/Release.xcconfig @@ -0,0 +1,2 @@ +#include "Generated.xcconfig" +#include? "Signing.local.xcconfig" diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..0709b4a --- /dev/null +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,665 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 60; + objects = { + +/* Begin PBXBuildFile section */ + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C807B294A618700263BE5 /* RunnerTests.swift */; }; + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */; }; + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C8085294A63A400263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 97C146E61CF9000F007C117D /* Project object */; + proxyType = 1; + remoteGlobalIDString = 97C146ED1CF9000F007C117D; + remoteInfo = Runner; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 9705A1C41CF9048500538489 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 331C807B294A618700263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 331C8081294A63A400263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; + 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; + 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 4E254DA83D36F76F3DC6EC40 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C8082294A63A400263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C807B294A618700263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 9740EEB31CF90195004384FC /* Generated.xcconfig */, + ); + name = Flutter; + sourceTree = ""; + }; + 97C146E51CF9000F007C117D = { + isa = PBXGroup; + children = ( + 9740EEB11CF90186004384FC /* Flutter */, + 97C146F01CF9000F007C117D /* Runner */, + 97C146EF1CF9000F007C117D /* Products */, + 331C8082294A63A400263BE5 /* RunnerTests */, + ); + sourceTree = ""; + }; + 97C146EF1CF9000F007C117D /* Products */ = { + isa = PBXGroup; + children = ( + 97C146EE1CF9000F007C117D /* Runner.app */, + 331C8081294A63A400263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 97C146F01CF9000F007C117D /* Runner */ = { + isa = PBXGroup; + children = ( + 97C146FA1CF9000F007C117D /* Main.storyboard */, + 97C146FD1CF9000F007C117D /* Assets.xcassets */, + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, + 97C147021CF9000F007C117D /* Info.plist */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 7884E8672EC3CC0400C636F2 /* SceneDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, + ); + path = Runner; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C8080294A63A400263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C807D294A63A400263BE5 /* Sources */, + 331C807F294A63A400263BE5 /* Resources */, + 4E254DA83D36F76F3DC6EC40 /* Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + 331C8086294A63A400263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C8081294A63A400263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 97C146ED1CF9000F007C117D /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 9740EEB61CF901F6004384FC /* Run Script */, + 97C146EA1CF9000F007C117D /* Sources */, + 97C146EB1CF9000F007C117D /* Frameworks */, + 97C146EC1CF9000F007C117D /* Resources */, + 9705A1C41CF9048500538489 /* Embed Frameworks */, + 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Runner; + packageProductDependencies = ( + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */, + ); + productName = Runner; + productReference = 97C146EE1CF9000F007C117D /* Runner.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 97C146E61CF9000F007C117D /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C8080294A63A400263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 97C146ED1CF9000F007C117D; + }; + 97C146ED1CF9000F007C117D = { + CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 1100; + }; + }; + }; + buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + "zh-Hans", + "zh-Hant", + ja, + ko, + fr, + de, + es, + pt, + it, + ru, + Base, + ); + mainGroup = 97C146E51CF9000F007C117D; + packageReferences = ( + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "FlutterGeneratedPluginSwiftPackage" */, + ); + productRefGroup = 97C146EF1CF9000F007C117D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 97C146ED1CF9000F007C117D /* Runner */, + 331C8080294A63A400263BE5 /* RunnerTests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C807F294A63A400263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EC1CF9000F007C117D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${TARGET_BUILD_DIR}/${INFOPLIST_PATH}", + ); + name = "Thin Binary"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; + }; + 9740EEB61CF901F6004384FC /* Run Script */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Run Script"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C807D294A63A400263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 97C146EA1CF9000F007C117D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + 7884E8682EC3CC0700C636F2 /* SceneDelegate.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C8086294A63A400263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 97C146ED1CF9000F007C117D /* Runner */; + targetProxy = 331C8085294A63A400263BE5 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 97C146FA1CF9000F007C117D /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C146FB1CF9000F007C117D /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C147001CF9000F007C117D /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 249021D3217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SUPPORTED_PLATFORMS = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.example.cutdex; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 331C8088294A63A400263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.cutdex.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Debug; + }; + 331C8089294A63A400263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.cutdex.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Release; + }; + 331C808A294A63A400263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.cutdex.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Runner.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/Runner"; + }; + name = Profile; + }; + 97C147031CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 97C147041CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 17.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SUPPORTED_PLATFORMS = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 97C147061CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.example.cutdex; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Debug; + }; + 97C147071CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.example.cutdex; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C8087294A63A400263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C8088294A63A400263BE5 /* Debug */, + 331C8089294A63A400263BE5 /* Release */, + 331C808A294A63A400263BE5 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147031CF9000F007C117D /* Debug */, + 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147061CF9000F007C117D /* Debug */, + 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCLocalSwiftPackageReference section */ + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "FlutterGeneratedPluginSwiftPackage" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = { + isa = XCSwiftPackageProductDependency; + productName = FlutterGeneratedPluginSwiftPackage; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..c3fedb2 --- /dev/null +++ b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,119 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100644 index 0000000..f9b0d7c --- /dev/null +++ b/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift new file mode 100644 index 0000000..c30b367 --- /dev/null +++ b/ios/Runner/AppDelegate.swift @@ -0,0 +1,16 @@ +import Flutter +import UIKit + +@main +@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } + + func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) { + GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry) + } +} diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..d36b1fa --- /dev/null +++ b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,122 @@ +{ + "images" : [ + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@3x.png", + "scale" : "3x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@3x.png", + "scale" : "3x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@3x.png", + "scale" : "3x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@2x.png", + "scale" : "2x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@3x.png", + "scale" : "3x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@1x.png", + "scale" : "1x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@1x.png", + "scale" : "1x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@1x.png", + "scale" : "1x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@2x.png", + "scale" : "2x" + }, + { + "size" : "83.5x83.5", + "idiom" : "ipad", + "filename" : "Icon-App-83.5x83.5@2x.png", + "scale" : "2x" + }, + { + "size" : "1024x1024", + "idiom" : "ios-marketing", + "filename" : "Icon-App-1024x1024@1x.png", + "scale" : "1x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100644 index 0000000..61e7a60 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png new file mode 100644 index 0000000..00040d4 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100644 index 0000000..e2422d8 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100644 index 0000000..a8de60b Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100644 index 0000000..818a14b Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100644 index 0000000..4378d11 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png new file mode 100644 index 0000000..56afaca Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png new file mode 100644 index 0000000..e2422d8 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100644 index 0000000..c58893d Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png new file mode 100644 index 0000000..b1fa7d4 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100644 index 0000000..b1fa7d4 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100644 index 0000000..41262db Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png new file mode 100644 index 0000000..1d5139f Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png new file mode 100644 index 0000000..f3101f2 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100644 index 0000000..ea1549c Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100644 index 0000000..0bedcf2 --- /dev/null +++ b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100644 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/ios/Runner/Base.lproj/LaunchScreen.storyboard b/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 0000000..f2e259c --- /dev/null +++ b/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Base.lproj/Main.storyboard b/ios/Runner/Base.lproj/Main.storyboard new file mode 100644 index 0000000..f3c2851 --- /dev/null +++ b/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist new file mode 100644 index 0000000..3f72bff --- /dev/null +++ b/ios/Runner/Info.plist @@ -0,0 +1,84 @@ + + + + + CFBundleLocalizations + + en + zh-Hans + zh-Hant + ja + ko + fr + de + es + pt + it + ru + + CADisableMinimumFrameDurationOnPhone + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Cutdex + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + cutdex + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + UISceneConfigurations + + UIWindowSceneSessionRoleApplication + + + UISceneClassName + UIWindowScene + UISceneConfigurationName + flutter + UISceneDelegateClassName + $(PRODUCT_MODULE_NAME).SceneDelegate + UISceneStoryboardFile + Main + + + + + UIApplicationSupportsIndirectInputEvents + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/ios/Runner/Runner-Bridging-Header.h b/ios/Runner/Runner-Bridging-Header.h new file mode 100644 index 0000000..308a2a5 --- /dev/null +++ b/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/ios/Runner/SceneDelegate.swift b/ios/Runner/SceneDelegate.swift new file mode 100644 index 0000000..b9ce8ea --- /dev/null +++ b/ios/Runner/SceneDelegate.swift @@ -0,0 +1,6 @@ +import Flutter +import UIKit + +class SceneDelegate: FlutterSceneDelegate { + +} diff --git a/ios/RunnerTests/RunnerTests.swift b/ios/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..86a7c3b --- /dev/null +++ b/ios/RunnerTests/RunnerTests.swift @@ -0,0 +1,12 @@ +import Flutter +import UIKit +import XCTest + +class RunnerTests: XCTestCase { + + func testExample() { + // If you add code to the Runner application, consider adding tests here. + // See https://developer.apple.com/documentation/xctest for more information about using XCTest. + } + +} diff --git a/l10n.yaml b/l10n.yaml new file mode 100644 index 0000000..e0db7d8 --- /dev/null +++ b/l10n.yaml @@ -0,0 +1,5 @@ +arb-dir: lib/l10n +template-arb-file: app_en.arb +output-localization-file: app_localizations.dart +preferred-supported-locales: + - en diff --git a/lib/app/adaptive/desktop_workspace_controller.dart b/lib/app/adaptive/desktop_workspace_controller.dart new file mode 100644 index 0000000..1aafb34 --- /dev/null +++ b/lib/app/adaptive/desktop_workspace_controller.dart @@ -0,0 +1,16 @@ +import 'package:flutter/foundation.dart'; + +/// Desktop split preferences outlive the desktop shell when a window narrows. +class DesktopWorkspaceController extends ChangeNotifier { + double? _agentWidth; + bool _editorCollapsedByAgent = false; + + double? get agentWidth => _agentWidth; + bool get editorCollapsedByAgent => _editorCollapsedByAgent; + + void setSplit(double? width, {required bool editorCollapsed}) { + _agentWidth = width; + _editorCollapsedByAgent = editorCollapsed; + notifyListeners(); + } +} diff --git a/lib/app/adaptive/workspace_layout_policy.dart b/lib/app/adaptive/workspace_layout_policy.dart new file mode 100644 index 0000000..f26f6bc --- /dev/null +++ b/lib/app/adaptive/workspace_layout_policy.dart @@ -0,0 +1,78 @@ +import 'dart:math' as math; + +import '../../workspace/workspace_mode.dart'; +import '../../shared/layout/workspace_layout_metrics.dart'; + +/// Spatial rules used within a device experience; never selects a device shell. +abstract final class WorkspaceLayoutPolicy { + static bool desktopNavigationFits(double width) => + width >= + WorkspaceLayoutMetrics.sidebarMinimumWidth + + WorkspaceLayoutMetrics.contentMinimumWidth + + 1; + + static bool showAgentBesideEditor(double width) => + width >= WorkspaceLayoutMetrics.dualPaneMinimumWidth; +} + +/// Desktop geometry is resolved without mutating preferences during build. +final class DesktopWorkspaceGeometry { + const DesktopWorkspaceGeometry({ + required this.sidebarWidth, + required this.agentWidth, + required this.editorHidden, + }); + + static const editorCollapseWidth = 480.0; + static const editorCollapseDragBuffer = editorCollapseWidth / 3; + static const editorRestoreWidth = 560.0; + + final double sidebarWidth; + final double agentWidth; + final bool editorHidden; + + static double sidebarMaximum(double width, WorkspaceMode mode) => + WorkspaceLayoutMetrics.sidebarMaximumWidth( + width - (mode == WorkspaceMode.agent ? 221 : 0), + ); + + factory DesktopWorkspaceGeometry.resolve({ + required double width, + required WorkspaceMode mode, + required bool sidebarCollapsed, + double? sidebarWidth, + double? agentWidth, + bool editorCollapsedByAgent = false, + }) { + final navigationWidth = + (sidebarWidth ?? WorkspaceLayoutMetrics.sidebarDefaultWidth) + .clamp( + WorkspaceLayoutMetrics.sidebarMinimumWidth, + sidebarMaximum(width, mode), + ) + .toDouble(); + final navigationSpace = sidebarCollapsed ? 0.0 : navigationWidth; + final requestedAgentWidth = mode == WorkspaceMode.agent + ? (agentWidth ?? (width * .25).clamp(260.0, 320.0)) + .clamp(220.0, math.max(220.0, width - navigationSpace - 1)) + .toDouble() + : 0.0; + final remaining = width - navigationSpace - requestedAgentWidth - 1; + final hidden = + mode == WorkspaceMode.agent && + (width - navigationSpace - 1 < 220 + editorCollapseWidth || + (editorCollapsedByAgent && remaining < editorRestoreWidth) || + remaining <= editorCollapseWidth - editorCollapseDragBuffer); + return DesktopWorkspaceGeometry( + sidebarWidth: navigationWidth, + agentWidth: hidden + ? width - navigationSpace + : mode == WorkspaceMode.agent + ? requestedAgentWidth + .clamp(220.0, width - navigationSpace - editorCollapseWidth - 1) + .toDouble() + : 0, + editorHidden: hidden, + ); + } +} diff --git a/lib/app/app.dart b/lib/app/app.dart new file mode 100644 index 0000000..2225827 --- /dev/null +++ b/lib/app/app.dart @@ -0,0 +1,37 @@ +import 'package:cutdex/app/editor_theme.dart'; + +import '../l10n/app_localizations.dart'; +import '../features/settings/language_settings.dart'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import 'router/app_router.dart'; +import '../integrations/app_updates.dart'; +import '../integrations/editor_tools.dart'; +import '../features/settings/appearance_settings.dart'; + +class CutdexApp extends ConsumerWidget { + const CutdexApp({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + ref.watch(applicationMcpConnectionProvider); + ref.watch(appUpdateLifecycleProvider); + final appearance = + ref.watch(appearanceSettingsProvider).asData?.value ?? + AppAppearance.system; + return MaterialApp.router( + title: 'Cutdex', + locale: ref.watch(languageSettingsProvider).asData?.value.locale, + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + localeListResolutionCallback: resolveAppLocale, + debugShowCheckedModeBanner: false, + theme: EditorTheme.penLight, + darkTheme: EditorTheme.penDark, + themeMode: appearance.themeMode, + routerConfig: ref.watch(appRouterProvider), + ); + } +} diff --git a/lib/app/editor_theme.dart b/lib/app/editor_theme.dart new file mode 100644 index 0000000..d5c7f3e --- /dev/null +++ b/lib/app/editor_theme.dart @@ -0,0 +1,72 @@ +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex_sdk/timeline_ui.dart'; +import 'package:flutter/material.dart'; + +/// Connects the application palette to the SDK timeline presentation. +abstract final class EditorTheme { + static ThemeData get penLight => adapt(AppTheme.penLight); + static ThemeData get penDark => adapt(AppTheme.penDark); + + static ThemeData adapt(ThemeData theme) { + final palette = theme.brightness == Brightness.dark + ? AppColors.penDark + : AppColors.penLight; + final dark = theme.brightness == Brightness.dark; + final text = theme.textTheme; + final timelineBorder = palette.divider; + final timelineSecondary = dark + ? palette.foreground.withValues(alpha: .71) + : palette.mutedForeground; + final timelineTertiary = dark + ? palette.foreground.withValues(alpha: .498) + : palette.mutedForeground.withValues(alpha: .8); + return theme.copyWith( + extensions: [ + ...theme.extensions.values, + const TimelineThemeData.dark().copyWith( + backgroundColor: palette.background, + primaryLaneBackgroundColor: palette.sidebar, + visualClipColor: palette.visualClip, + audioClipColor: palette.popover, + audioAccentColor: timelineSecondary, + gapColor: timelineBorder, + gapBorderColor: timelineBorder, + containerAccentColor: timelineSecondary, + transitionColor: timelineTertiary, + connectionLineColor: timelineBorder, + connectionLineWidth: 3, + clipBorderColor: timelineBorder, + clipBorderWidth: 1, + selectionOutlineColor: palette.foreground, + selectionOutlineWidth: 2, + keyframeColor: timelineSecondary, + keyframeBorderColor: palette.background, + keyframeInvalidColor: palette.destructive, + disabledOverlayColor: palette.background.withValues(alpha: 0.5), + outsideSourceRangeOverlayColor: palette.background.withValues( + alpha: 0.65, + ), + clipCornerRadius: AppRadius.small, + clipHeaderHeight: 16, + clipHeaderPadding: 2, + clipNameTextStyle: text.bodySmall!.copyWith( + color: palette.foreground, + fontSize: 10, + height: 1.4, + ), + rulerHeight: 20, + rulerBackgroundColor: palette.background, + rulerTickColor: timelineTertiary, + rulerTextStyle: text.bodySmall!.copyWith( + height: 16 / 12, + color: timelineSecondary, + ), + playheadColor: palette.foreground, + scrollbarThickness: AppSpacing.compact, + scrollbarTrackColor: Colors.transparent, + scrollbarThumbColor: palette.foreground.withValues(alpha: .084), + ), + ], + ); + } +} diff --git a/lib/app/router/app_router.dart b/lib/app/router/app_router.dart new file mode 100644 index 0000000..cc3b93c --- /dev/null +++ b/lib/app/router/app_router.dart @@ -0,0 +1,28 @@ +import 'package:cutdex/l10n/l10n.dart'; +import 'package:flutter/material.dart'; +import 'package:go_router/go_router.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import '../../features/projects/projects_page.dart'; + +part 'app_router.g.dart'; + +// The router is an application resource, independent of editor state changes. +@Riverpod(keepAlive: true) +GoRouter appRouter(Ref ref) { + final router = GoRouter( + routes: [ + GoRoute(path: '/', builder: (context, state) => const EditingPage()), + ], + errorBuilder: (context, state) => Scaffold( + body: Center( + child: FilledButton( + onPressed: () => context.go('/'), + child: Text(context.l10n.backToProjects), + ), + ), + ), + ); + ref.onDispose(router.dispose); + return router; +} diff --git a/lib/app/router/app_router.g.dart b/lib/app/router/app_router.g.dart new file mode 100644 index 0000000..4918d69 --- /dev/null +++ b/lib/app/router/app_router.g.dart @@ -0,0 +1,51 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'app_router.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(appRouter) +final appRouterProvider = AppRouterProvider._(); + +final class AppRouterProvider + extends $FunctionalProvider + with $Provider { + AppRouterProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'appRouterProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$appRouterHash(); + + @$internal + @override + $ProviderElement $createElement($ProviderPointer pointer) => + $ProviderElement(pointer); + + @override + GoRouter create(Ref ref) { + return appRouter(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(GoRouter value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$appRouterHash() => r'ebb3f9239a43568767def98552081806bd614bb4'; diff --git a/lib/app/shells/desktop_workspace_shell.dart b/lib/app/shells/desktop_workspace_shell.dart new file mode 100644 index 0000000..50734b6 --- /dev/null +++ b/lib/app/shells/desktop_workspace_shell.dart @@ -0,0 +1,276 @@ +import '../adaptive/desktop_workspace_controller.dart'; + +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; + +import '../../workspace/workspace_mode.dart'; +import '../../shared/layout/workspace_layout_metrics.dart'; + +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex_native/cutdex_native.dart'; + +import '../adaptive/workspace_layout_policy.dart'; + +typedef WorkspaceSidebarBuilder = Widget Function( + DesktopWorkspaceGeometry geometry, + VoidCallback expandEditor, +); + +/// Arranges slots and handles splitters; it does not own editing sessions. +class DesktopWorkspaceShell extends StatefulWidget { + const DesktopWorkspaceShell({ + super.key, + required this.mode, + required this.controller, + required this.sidebarCollapsed, + required this.sidebarWidth, + required this.onSidebarCollapsedChanged, + required this.onSidebarWidthChanged, + required this.sidebarBuilder, + required this.editor, + required this.scaffoldKey, + required this.navigationDrawer, + }); + + final WorkspaceMode mode; + final DesktopWorkspaceController controller; + final bool sidebarCollapsed; + final double? sidebarWidth; + final ValueChanged onSidebarCollapsedChanged; + final ValueChanged onSidebarWidthChanged; + final WorkspaceSidebarBuilder sidebarBuilder; + final Widget editor; + final GlobalKey scaffoldKey; + final Widget navigationDrawer; + + @override + State createState() => _DesktopWorkspaceShellState(); +} + +class _DesktopWorkspaceShellState extends State { + double? get _agentWidth => widget.controller.agentWidth; + bool get _editorCollapsedByAgent => widget.controller.editorCollapsedByAgent; + + @override + void initState() { + super.initState(); + widget.controller.addListener(_changed); + } + + void _changed() => setState(() {}); + + @override + void didUpdateWidget(covariant DesktopWorkspaceShell oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.controller != widget.controller) { + oldWidget.controller.removeListener(_changed); + widget.controller.addListener(_changed); + } + } + + @override + void dispose() { + widget.controller.removeListener(_changed); + super.dispose(); + } + + double? _sidebarDragStart; + double _sidebarDragWidth = 0; + double? _agentDragStart; + double _agentDragWidth = 0; + + @override + Widget build(BuildContext context) => LayoutBuilder( + builder: (context, constraints) { + final width = constraints.maxWidth; + final geometry = DesktopWorkspaceGeometry.resolve( + width: width, + mode: widget.mode, + sidebarCollapsed: widget.sidebarCollapsed, + sidebarWidth: widget.sidebarWidth, + agentWidth: _agentWidth, + editorCollapsedByAgent: _editorCollapsedByAgent, + ); + final navigationSpace = widget.sidebarCollapsed + ? 0.0 + : geometry.sidebarWidth; + void expandEditor() { + final collapseNavigation = width - navigationSpace - 1 < 780; + if (collapseNavigation) widget.onSidebarCollapsedChanged(true); + widget.controller.setSplit( + width - + (collapseNavigation ? 0 : navigationSpace) - + DesktopWorkspaceGeometry.editorRestoreWidth - + 1, + editorCollapsed: false, + ); + } + + return Scaffold( + key: widget.scaffoldKey, + drawer: Drawer( + width: 320, + child: SafeArea(child: widget.navigationDrawer), + ), + body: Stack( + key: const Key('desktop-workspace-shell'), + fit: StackFit.expand, + children: [ + Row( + children: [ + if (!widget.sidebarCollapsed || + widget.mode == WorkspaceMode.agent) + SizedBox( + width: navigationSpace + geometry.agentWidth, + child: widget.sidebarBuilder(geometry, expandEditor), + ), + if (!widget.sidebarCollapsed && !geometry.editorHidden) + SizedBox( + width: 1, + height: double.infinity, + child: ColoredBox( + key: const Key('project-sidebar-separator'), + color: AppTheme.sidebarDividerColor(context), + ), + ), + Expanded( + child: Offstage( + key: const Key('editor-auto-collapse'), + offstage: geometry.editorHidden, + child: TickerMode( + enabled: !geometry.editorHidden, + child: OverflowBox( + alignment: Alignment.topLeft, + minWidth: geometry.editorHidden + ? DesktopWorkspaceGeometry.editorRestoreWidth + : null, + maxWidth: geometry.editorHidden + ? DesktopWorkspaceGeometry.editorRestoreWidth + : null, + child: WindowHeaderPane( + offset: Offset( + navigationSpace + + geometry.agentWidth + + (!widget.sidebarCollapsed && + !geometry.editorHidden + ? 1 + : 0), + 0, + ), + child: widget.editor, + ), + ), + ), + ), + ), + ], + ), + if (!widget.sidebarCollapsed) + Positioned( + key: const Key('project-sidebar-divider'), + top: AppControlSize.panelHeader, + bottom: 0, + left: geometry.sidebarWidth - 4, + width: 8, + child: MouseRegion( + cursor: SystemMouseCursors.resizeColumn, + child: GestureDetector( + key: const Key('project-sidebar-resize'), + behavior: HitTestBehavior.opaque, + dragStartBehavior: DragStartBehavior.down, + onHorizontalDragStart: (details) { + _sidebarDragStart = details.globalPosition.dx; + _sidebarDragWidth = geometry.sidebarWidth; + }, + onHorizontalDragUpdate: (details) { + final start = _sidebarDragStart; + if (start == null) return; + widget.onSidebarWidthChanged( + (_sidebarDragWidth + details.globalPosition.dx - start) + .clamp( + WorkspaceLayoutMetrics.sidebarMinimumWidth, + DesktopWorkspaceGeometry.sidebarMaximum( + width, + widget.mode, + ), + ) + .toDouble(), + ); + }, + onHorizontalDragEnd: (_) => _sidebarDragStart = null, + onHorizontalDragCancel: () => _sidebarDragStart = null, + child: const SizedBox.expand(), + ), + ), + ), + if (widget.mode == WorkspaceMode.agent && + width - navigationSpace - 1 >= 220) + Positioned( + top: 0, + bottom: 0, + left: + navigationSpace + + geometry.agentWidth - + (geometry.editorHidden ? 8 : 4), + width: 8, + child: MouseRegion( + cursor: SystemMouseCursors.resizeColumn, + child: GestureDetector( + key: const Key('agent-panel-resize'), + behavior: HitTestBehavior.opaque, + dragStartBehavior: DragStartBehavior.down, + onHorizontalDragStart: (details) { + _agentDragStart = details.globalPosition.dx; + _agentDragWidth = geometry.agentWidth; + }, + onHorizontalDragUpdate: (details) { + final start = _agentDragStart; + if (start == null) return; + final agentWidth = + (_agentDragWidth + details.globalPosition.dx - start) + .clamp(220.0, width - navigationSpace - 1); + final remaining = + width - navigationSpace - agentWidth - 1; + widget.controller.setSplit( + agentWidth, + editorCollapsed: geometry.editorHidden + ? remaining < + DesktopWorkspaceGeometry.editorRestoreWidth + : remaining <= + DesktopWorkspaceGeometry.editorCollapseWidth - + DesktopWorkspaceGeometry + .editorCollapseDragBuffer, + ); + }, + onHorizontalDragEnd: (_) { + _agentDragStart = null; + if (!_editorCollapsedByAgent && + _agentWidth != null && + width - + navigationSpace - + DesktopWorkspaceGeometry.editorCollapseWidth - + 1 >= + 220) { + widget.controller.setSplit( + _agentWidth!.clamp( + 220.0, + width - + navigationSpace - + DesktopWorkspaceGeometry.editorCollapseWidth - + 1, + ), + editorCollapsed: false, + ); + } + }, + onHorizontalDragCancel: () => _agentDragStart = null, + child: const SizedBox.expand(), + ), + ), + ), + ], + ), + ); + }, + ); +} diff --git a/lib/app/shells/phone_workspace_shell.dart b/lib/app/shells/phone_workspace_shell.dart new file mode 100644 index 0000000..bc0b5e9 --- /dev/null +++ b/lib/app/shells/phone_workspace_shell.dart @@ -0,0 +1,58 @@ +import 'package:flutter/material.dart'; + +import '../../l10n/l10n.dart'; + +import '../../workspace/workspace_mode.dart'; +import 'workspace_frame.dart'; + +/// A focused surface; hidden features keep their state in workspace controllers. +class PhoneWorkspaceShell extends StatelessWidget { + const PhoneWorkspaceShell({ + super.key, + required this.mode, + required this.onModeChanged, + required this.navigation, + required this.headerActions, + required this.title, + required this.integratedTitlebar, + required this.agent, + required this.editor, + }); + + final WorkspaceMode mode; + final ValueChanged onModeChanged; + final Widget navigation; + final Widget headerActions; + final String title; + final bool integratedTitlebar; + final Widget agent; + final Widget editor; + + @override + Widget build(BuildContext context) => WorkspaceFrame( + key: const Key('phone-workspace-shell'), + navigation: navigation, + headerActions: headerActions, + title: title, + integratedTitlebar: integratedTitlebar, + bottomNavigationBar: NavigationBar( + height: 64, + selectedIndex: mode == WorkspaceMode.agent ? 0 : 1, + onDestinationSelected: (index) => + onModeChanged(index == 0 ? WorkspaceMode.agent : WorkspaceMode.cut), + destinations: [ + NavigationDestination( + key: const Key('workspace-agent-destination'), + icon: const Icon(Icons.chat_bubble_outline), + label: context.l10n.workspaceAgent, + ), + NavigationDestination( + key: const Key('workspace-cut-destination'), + icon: const Icon(Icons.movie_outlined), + label: context.l10n.workspaceCut, + ), + ], + ), + child: mode == WorkspaceMode.agent ? agent : editor, + ); +} diff --git a/lib/app/shells/tablet_workspace_shell.dart b/lib/app/shells/tablet_workspace_shell.dart new file mode 100644 index 0000000..9623dfd --- /dev/null +++ b/lib/app/shells/tablet_workspace_shell.dart @@ -0,0 +1,99 @@ +import 'dart:math' as math; + +import 'package:flutter/material.dart'; + +import '../../l10n/l10n.dart'; + +import '../../workspace/workspace_mode.dart'; +import '../adaptive/workspace_layout_policy.dart'; +import 'workspace_frame.dart'; + +/// Two working surfaces when space permits, with project navigation on demand. +class TabletWorkspaceShell extends StatelessWidget { + const TabletWorkspaceShell({ + super.key, + required this.mode, + required this.onModeChanged, + required this.navigation, + required this.headerActions, + required this.title, + required this.integratedTitlebar, + required this.agent, + required this.editor, + }); + + final WorkspaceMode mode; + final ValueChanged onModeChanged; + final Widget navigation; + final Widget headerActions; + final String title; + final bool integratedTitlebar; + final Widget agent; + final Widget editor; + + @override + Widget build(BuildContext context) => WorkspaceFrame( + key: const Key('tablet-workspace-shell'), + navigation: navigation, + headerActions: headerActions, + title: title, + integratedTitlebar: integratedTitlebar, + child: Row( + children: [ + SizedBox( + width: 72, + child: LayoutBuilder( + builder: (context, constraints) => SingleChildScrollView( + child: SizedBox( + height: math.max(240, constraints.maxHeight), + child: NavigationRail( + selectedIndex: mode == WorkspaceMode.agent ? 0 : 1, + labelType: NavigationRailLabelType.all, + onDestinationSelected: (index) => onModeChanged( + index == 0 ? WorkspaceMode.agent : WorkspaceMode.cut, + ), + destinations: [ + NavigationRailDestination( + icon: const Icon( + Icons.chat_bubble_outline, + key: Key('workspace-agent-destination'), + ), + label: Text(context.l10n.workspaceAgent), + ), + NavigationRailDestination( + icon: const Icon( + Icons.movie_outlined, + key: Key('workspace-cut-destination'), + ), + label: Text(context.l10n.workspaceCut), + ), + ], + ), + ), + ), + ), + ), + const VerticalDivider(width: 1), + Expanded( + child: LayoutBuilder( + builder: (context, constraints) => + mode == WorkspaceMode.agent && + WorkspaceLayoutPolicy.showAgentBesideEditor( + constraints.maxWidth, + ) + ? Row( + children: [ + SizedBox(width: constraints.maxWidth * .38, child: agent), + const VerticalDivider(width: 1), + Expanded(child: editor), + ], + ) + : mode == WorkspaceMode.agent + ? agent + : editor, + ), + ), + ], + ), + ); +} diff --git a/lib/app/shells/workspace_frame.dart b/lib/app/shells/workspace_frame.dart new file mode 100644 index 0000000..4be4b01 --- /dev/null +++ b/lib/app/shells/workspace_frame.dart @@ -0,0 +1,70 @@ +import 'package:flutter/material.dart'; + +import '../../integrations/platform/editor_window_chrome.dart'; + +import 'package:cutdex_native/cutdex_native.dart'; + +import '../../l10n/l10n.dart'; + +/// Navigation and mode controls for bounded workspaces. Drawer visibility is +/// local presentation state and never overwrites the desktop sidebar preference. +class WorkspaceFrame extends StatelessWidget { + const WorkspaceFrame({ + super.key, + required this.navigation, + required this.headerActions, + required this.title, + required this.integratedTitlebar, + required this.child, + this.bottomNavigationBar, + }); + + final Widget navigation; + final Widget headerActions; + final String title; + final bool integratedTitlebar; + final Widget child; + final Widget? bottomNavigationBar; + + @override + Widget build(BuildContext context) => Scaffold( + drawer: Drawer(width: 320, child: SafeArea(child: navigation)), + body: Column( + children: [ + SizedBox( + key: const Key('workspace-window-header'), + height: 48, + child: WindowHeaderPadding( + child: Row( + children: [ + if (integratedTitlebar) + SizedBox(width: EditorWindowChrome.leadingWidth), + HeaderControlRegion( + child: Builder( + builder: (context) => IconButton( + key: const Key('workspace-navigation-button'), + tooltip: context.l10n.expandSidebar, + onPressed: () => Scaffold.of(context).openDrawer(), + icon: const Icon(Icons.menu), + ), + ), + ), + Expanded( + child: Text( + title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + headerActions, + ], + ), + ), + ), + const Divider(height: 1), + Expanded(child: child), + ], + ), + bottomNavigationBar: bottomNavigationBar, + ); +} diff --git a/lib/diagnostics/agent_request_diagnostics.dart b/lib/diagnostics/agent_request_diagnostics.dart new file mode 100644 index 0000000..9f52f4d --- /dev/null +++ b/lib/diagnostics/agent_request_diagnostics.dart @@ -0,0 +1,139 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:math'; + +import 'package:flutter/scheduler.dart'; +import 'package:uuid/uuid.dart'; +import 'package:path/path.dart' as p; + +import 'request_report.dart'; +import 'app_diagnostics.dart'; +import 'diagnostic_redactor.dart'; + +/// Per-send measurements; never retains prompts, results, or credentials. +class AgentRequestDiagnostics { + AgentRequestDiagnostics({String? requestId}) + : requestId = requestId ?? const Uuid().v4() { + SchedulerBinding.instance.addTimingsCallback(_frames); + _timer = Timer.periodic(const Duration(milliseconds: 200), (_) { + final now = _clock.elapsedMicroseconds; + maxTimerDelayUs = max(maxTimerDelayUs, now - _lastTickUs - 200000); + _lastTickUs = now; + }); + } + + final _clock = Stopwatch()..start(); + final String requestId; + late final Timer _timer; + int _lastTickUs = 0; + int frameCount = 0; + int slowFrames = 0; + int maxBuildUs = 0; + int maxRasterUs = 0; + int maxTimerDelayUs = 0; + int? preparationUs; + String outcome = 'error'; + final List> runs = []; + + void prepared() => preparationUs = _clock.elapsedMicroseconds; + + void _frames(List frames) { + for (final frame in frames) { + frameCount++; + final build = frame.buildDuration.inMicroseconds; + final raster = frame.rasterDuration.inMicroseconds; + maxBuildUs = max(maxBuildUs, build); + maxRasterUs = max(maxRasterUs, raster); + if (build > 16667 || raster > 16667) slowFrames++; + } + } + + RequestReport stop() { + maxTimerDelayUs = max( + maxTimerDelayUs, + _clock.elapsedMicroseconds - _lastTickUs - 200000, + ); + _timer.cancel(); + SchedulerBinding.instance.removeTimingsCallback(_frames); + _clock.stop(); + return RequestReport( + requestId: requestId, + sessionId: AppDiagnostics.instance?.sessionId, + outcome: outcome, + elapsedUs: _clock.elapsedMicroseconds, + preparationUs: preparationUs, + frames: RequestFrameReport( + count: frameCount, + slowFrames: slowFrames, + maxBuildUs: maxBuildUs, + maxRasterUs: maxRasterUs, + maxTimerDelayUs: maxTimerDelayUs, + ), + runs: List.of(runs), + ); + } + + /// Keeps the latest 20 reports, serializing publication and pruning. + /// Best effort: storage failures never prevent the next edit. + static Future _writes = Future.value(); + static Future persist(Directory root, RequestReport report) { + final write = _writes.then((_) async { + try { + final directory = Directory(p.join(root.path, 'diagnostics')); + await directory.create(recursive: true); + final now = DateTime.now().toUtc(); + final suppliedId = report.requestId; + final requestId = + suppliedId != null && + RegExp(r'^[a-fA-F0-9-]{36}$').hasMatch(suppliedId) + ? suppliedId + : const Uuid().v4(); + final file = File( + p.join( + directory.path, + 'request-${now.microsecondsSinceEpoch}-$requestId.json', + ), + ); + final temporary = File('${file.path}.tmp'); + final encoded = jsonEncode( + DiagnosticRedactor().value(report.copyWith(at: now).toJson()), + ); + if (utf8.encode(encoded).length > 256 * 1024) return; + await temporary.writeAsString(encoded, flush: true); + await temporary.rename(file.path); + final files = await directory + .list() + .where( + (e) => + e is File && + p.basename(e.path).startsWith('request-') && + e.path.endsWith('.json'), + ) + .cast() + .toList(); + final dated = <(File, DateTime)>[]; + for (final file in files) { + dated.add((file, (await file.stat()).modified)); + } + dated.sort((a, b) => a.$2.compareTo(b.$2)); + if (dated.length > 20) { + for (final entry in dated.take(dated.length - 20)) { + await entry.$1.delete(); + } + } + } catch (error, stack) { + AppDiagnostics.failure( + 'agent', + 'persistRequestReport', + error, + stack, + context: {'requestId': report.requestId}, + ); + // Disk and encoding failures must not affect the conversation. + } + }); + _writes = write; + return write; + } +} diff --git a/lib/diagnostics/app_diagnostics.dart b/lib/diagnostics/app_diagnostics.dart new file mode 100644 index 0000000..3fa2d72 --- /dev/null +++ b/lib/diagnostics/app_diagnostics.dart @@ -0,0 +1,215 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_native/cutdex_native.dart'; +import 'package:flutter/foundation.dart'; +import 'package:path/path.dart' as p; +import 'package:path_provider/path_provider.dart'; +import 'package:uuid/uuid.dart'; + +import 'diagnostic_store.dart'; +import 'request_report.dart'; + +/// Application-owned storage and SDK adapter. Inactive unless explicitly installed. +final class AppDiagnostics { + AppDiagnostics( + this.store, { + String? sessionId, + Map metadata = const {}, + }) : sessionId = sessionId ?? const Uuid().v4(), + metadata = Map.of(metadata); + static AppDiagnostics? instance; + final DiagnosticStore store; + final String sessionId; + final Map metadata; + + static Future initialize() async { + Directory directory; + Object? initializationFailure; + StackTrace? initializationStack; + try { + directory = Directory( + p.join( + (await getApplicationSupportDirectory()).path, + 'Cutdex', + 'Diagnostics', + ), + ); + } catch (error, stack) { + initializationFailure = error; + initializationStack = stack; + // Use temporary storage when support-directory discovery is unavailable. + directory = Directory( + p.join(Directory.systemTemp.path, 'Cutdex', 'Diagnostics'), + ); + } + final diagnostics = AppDiagnostics( + DiagnosticStore(directory), + metadata: { + 'platform': Platform.operatingSystem, + 'osVersion': Platform.operatingSystemVersion, + 'dartVersion': Platform.version, + 'buildMode': kReleaseMode + ? 'release' + : kProfileMode + ? 'profile' + : 'debug', + 'appVersion': const String.fromEnvironment( + 'CUTDEX_APP_VERSION', + defaultValue: 'unknown', + ), + 'appBuild': const String.fromEnvironment( + 'CUTDEX_APP_BUILD', + defaultValue: 'unknown', + ), + }, + ); + instance = diagnostics; + diagnostics.event( + const DiagnosticEvent( + component: 'app', + operation: 'start', + level: DiagnosticSeverity.info, + ), + ); + if (initializationFailure != null) { + diagnostics.event( + DiagnosticEvent( + component: 'diagnostics', + operation: 'initialize', + error: initializationFailure, + stackTrace: initializationStack, + ), + ); + } + return diagnostics; + } + + static void report(DiagnosticEvent event) => instance?.event(event); + + static void failure( + String component, + String operation, + Object error, + StackTrace stack, { + Map context = const {}, + }) => reportDiagnostic( + report, + DiagnosticEvent( + component: component, + operation: operation, + error: error, + stackTrace: stack, + context: context, + ), + ); + + void event(DiagnosticEvent event, {bool immediate = false}) { + try { + final error = event.error; + store.record({ + 'version': 1, + 'at': DateTime.now().toUtc().toIso8601String(), + 'sessionId': sessionId, + 'environment': metadata, + 'level': event.level.name, + 'component': event.component, + 'operation': event.operation, + if (error != null) + 'error': { + 'type': error.runtimeType.toString(), + 'message': switch (error) { + FormatException() => 'FormatException: ${error.message}', + ArgumentError() => + 'ArgumentError(${error.name}): ${error.message}', + ProcessException() => + 'ProcessException: ${error.message} (${error.errorCode})', + _ => error.toString(), + }, + if (error is RuntimeException) ...{ + 'code': error.code, + 'domain': error.domain, + 'retryable': error.retryable, + 'nativeDetails': error.details, + }, + if (error is ProcessingException) ...{ + 'code': error.code, + 'backend': error.backend, + }, + }, + if (event.stackTrace != null) 'stackTrace': event.stackTrace.toString(), + 'context': event.context, + }, immediate: immediate); + } catch (_) { + // Diagnostics cannot change the application failure path. + } + } + + Future request(RequestReport report, String requestId) => + store.saveRequest({ + ...report.copyWith(at: report.at ?? DateTime.now().toUtc()).toJson(), + 'requestId': requestId, + 'sessionId': sessionId, + }, requestId); + + Future export(Directory destination) => + store.export(destination, {...metadata, 'sessionId': sessionId}); + + Future readApplicationInfo() async { + try { + metadata.addAll( + await NativeDeviceInfo.readApplicationInfo().timeout( + const Duration(seconds: 2), + ), + ); + event( + const DiagnosticEvent( + component: 'app', + operation: 'applicationInfo', + level: DiagnosticSeverity.info, + ), + ); + } catch (error, stack) { + event( + DiagnosticEvent( + component: 'diagnostics', + operation: 'applicationInfo', + error: error, + stackTrace: stack, + level: DiagnosticSeverity.warning, + ), + ); + } + } + + /// Preserves framework/engine behavior while observing both error routes. + void installErrorHandlers() { + final previousFlutter = FlutterError.onError; + FlutterError.onError = (details) { + event( + DiagnosticEvent( + component: 'flutter', + operation: 'frameworkError', + error: details.exception, + stackTrace: details.stack, + context: {'library': details.library}, + ), + ); + if (previousFlutter != null) previousFlutter(details); + }; + final previousPlatform = PlatformDispatcher.instance.onError; + PlatformDispatcher.instance.onError = (error, stack) { + event( + DiagnosticEvent( + component: 'dart', + operation: 'uncaughtAsyncError', + error: error, + stackTrace: stack, + ), + immediate: true, + ); + return previousPlatform?.call(error, stack) ?? false; + }; + } +} diff --git a/lib/diagnostics/diagnostic_redactor.dart b/lib/diagnostics/diagnostic_redactor.dart new file mode 100644 index 0000000..e6dbfc0 --- /dev/null +++ b/lib/diagnostics/diagnostic_redactor.dart @@ -0,0 +1,76 @@ +/// Sanitizes diagnostic values before they reach memory, disk or an export. +final class DiagnosticRedactor { + static final _privateKey = RegExp( + r'^(authorization|cookies?|password|secret|(?:access|refresh|auth)?[_-]?token|credential(?:Id)?|api.?key|prompt|messages|responseBody|requestBody)$', + caseSensitive: false, + ); + static final _bearer = RegExp( + r'\bBearer\s+[^\s,;"\x27]+', + caseSensitive: false, + ); + static final _apiKey = RegExp(r'\bsk-[a-zA-Z0-9_-]+'); + static final _assignment = RegExp( + r'\b(api[_-]?key|access[_-]?token|password|secret|authorization)\s*[:=]\s*[^\r\n,;]+', + caseSensitive: false, + ); + static final _url = RegExp(r'https?://[^\s<>"\x27]+'); + static final _path = RegExp( + r'(?:file://)?/(?:Users|home|private|tmp|var|Volumes|storage|data|mnt|media|sdcard|Documents)/[^\r\n"\x27,;]*|[A-Za-z]:[\\/][^\r\n"\x27,;]*|\\\\[^\r\n"\x27,;]+', + ); + static final _email = RegExp(r'\b[^\s@]+@[^\s@]+\.[a-zA-Z]{2,}\b'); + + String text(String value, {int limit = 8192}) { + var result = value; + // Most metadata consists of identifiers. Avoid expensive pattern scans when + // their required marker is absent; matching and redaction stay unchanged. + if (result.toLowerCase().contains('bearer')) { + result = result.replaceAll(_bearer, 'Bearer [redacted]'); + } + if (result.contains('sk-')) { + result = result.replaceAll(_apiKey, '[redacted]'); + } + if (result.contains(':') || result.contains('=')) { + result = result.replaceAllMapped( + _assignment, + (m) => '${m[1]}=[redacted]', + ); + } + if (result.contains('http://') || result.contains('https://')) { + result = result.replaceAllMapped(_url, (m) { + final uri = Uri.tryParse(m[0]!); + return uri == null ? '[url]' : '${uri.scheme}://${uri.host}/[redacted]'; + }); + } + if (result.contains('/') || result.contains(r'\')) { + result = result.replaceAll(_path, '[local-path]'); + } + if (result.contains('@')) { + result = result.replaceAll(_email, '[email]'); + } + if (result.length > limit) { + result = '${result.substring(0, limit)}…[truncated]'; + } + return result; + } + + Object? value(Object? input, {int depth = 0}) { + if (depth > 8) return '[truncated]'; + if (input == null || input is bool || input is num) return input; + if (input is String) return text(input); + if (input is Map) { + return { + for (final entry in input.entries.take(64)) + text( + entry.key.toString(), + limit: 128, + ): _privateKey.hasMatch(entry.key.toString()) + ? '[redacted]' + : value(entry.value, depth: depth + 1), + }; + } + if (input is Iterable) { + return input.take(2048).map((v) => value(v, depth: depth + 1)).toList(); + } + return text(input.toString()); + } +} diff --git a/lib/diagnostics/diagnostic_store.dart b/lib/diagnostics/diagnostic_store.dart new file mode 100644 index 0000000..d00d759 --- /dev/null +++ b/lib/diagnostics/diagnostic_store.dart @@ -0,0 +1,353 @@ +import 'dart:async'; +import 'dart:collection'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:path/path.dart' as p; + +import 'diagnostic_redactor.dart'; + +/// Serializes bounded log writes, rotation and exports; failures remain observable +/// in memory without interrupting editing or recursively logging themselves. +final class DiagnosticStore { + DiagnosticStore( + this.directory, { + this.maxFileBytes = 512 * 1024, + this.fileCount = 5, + this.maxPending = 256, + this.flushInterval = const Duration(milliseconds: 250), + this.batchSize = 32, + this.maxBatchBytes = 64 * 1024, + this.maxPendingBytes = 1024 * 1024, + int? errorReserveRecords, + int? errorReserveBytes, + }) : errorReserveRecords = errorReserveRecords ?? maxPending ~/ 8, + errorReserveBytes = errorReserveBytes ?? maxPendingBytes ~/ 4, + assert( + errorReserveRecords == null || + (errorReserveRecords >= 0 && errorReserveRecords < maxPending), + ), + assert( + errorReserveBytes == null || + (errorReserveBytes >= 0 && errorReserveBytes < maxPendingBytes), + ), + assert(maxFileBytes >= 1024), + assert(fileCount > 0), + assert(maxPending > 0), + assert(flushInterval > Duration.zero), + assert(batchSize > 0), + assert(maxBatchBytes > 0), + assert(maxPendingBytes > 0); + + final Directory directory; + final int maxFileBytes, fileCount, maxPending; + final Duration flushInterval; + final int batchSize, maxBatchBytes, maxPendingBytes; + final int errorReserveRecords, errorReserveBytes; + final _buffer = Queue<_DiagnosticRecord>(); + Timer? _timer; + int _bufferBytes = 0; + int _pendingBytes = 0; + int eventWriteBatches = 0; + int eventFlushes = 0; + int eventBytesWritten = 0; + int get pendingRecords => _pending; + int get pendingEventBytes => _pendingBytes; + final _redactor = DiagnosticRedactor(); + Future _tail = Future.value(); + int _pending = 0; + int dropped = 0; + int droppedErrors = 0; + int writeFailures = 0; + String? lastWriteFailure; + final List> _fallback = []; + File _log(int index) => File(p.join(directory.path, 'events-$index.jsonl')); + + void record(Map record, {bool immediate = false}) { + final isError = record['level'] == 'error'; + final recordLimit = isError ? maxPending : maxPending - errorReserveRecords; + final byteLimit = isError + ? maxPendingBytes + : maxPendingBytes - errorReserveBytes; + // Non-error events and reports cannot consume reserved error capacity. + // Saturated queues skip formatting; fatal errors bypass both limits. + if (!immediate && (_pending >= recordLimit || _pendingBytes >= byteLimit)) { + _drop(isError); + return; + } + try { + final safe = (_redactor.value(record)! as Map).cast(); + final encoded = utf8.encode('${jsonEncode(safe)}\n'); + if (encoded.length > maxFileBytes) { + _drop(isError); + return; + } + if (immediate) { + try { + directory.createSync(recursive: true); + final fatal = File(p.join(directory.path, 'fatal.jsonl')); + if (fatal.existsSync() && + fatal.lengthSync() + encoded.length > maxFileBytes) { + fatal.deleteSync(); + } + fatal.writeAsBytesSync(encoded, mode: FileMode.append, flush: true); + } catch (error) { + _failed([_DiagnosticRecord(safe, encoded)], error); + } + return; + } + if (_pendingBytes + encoded.length > byteLimit) { + _drop(isError); + return; + } + _pending++; + _pendingBytes += encoded.length; + _bufferBytes += encoded.length; + _buffer.add(_DiagnosticRecord(safe, encoded)); + if (_buffer.length >= batchSize || _bufferBytes >= maxBatchBytes) { + _enqueueBuffered(); + } else { + _timer ??= Timer(flushInterval, _enqueueBuffered); + } + } catch (_) { + _drop(isError); + } + } + + void _drop(bool isError) { + dropped++; + if (isError) droppedErrors++; + } + + void _enqueueBuffered() { + _timer?.cancel(); + _timer = null; + if (_buffer.isEmpty) return; + final records = _buffer.toList(growable: false); + _buffer.clear(); + _bufferBytes = 0; + _tail = _tail.then((_) => _writeBatch(records)); + } + + Future _writeBatch(List<_DiagnosticRecord> records) async { + eventWriteBatches++; + var written = 0; + try { + await directory.create(recursive: true); + while (written < records.length) { + final current = _log(0); + var length = 0; + var interrupted = false; + if (await current.exists()) { + final reader = await current.open(); + try { + length = await reader.length(); + if (length > 0) { + await reader.setPosition(length - 1); + interrupted = await reader.readByte() != 10; + } + } finally { + await reader.close(); + } + } + if (length + (interrupted ? 1 : 0) + records[written].encoded.length > + maxFileBytes) { + await _rotate(); + length = 0; + interrupted = false; + } + final bytes = BytesBuilder(copy: false); + // Isolate an interrupted append from the next complete JSONL record. + if (interrupted) bytes.addByte(10); + var end = written; + while (end < records.length) { + final encoded = records[end].encoded; + if (length + bytes.length + encoded.length > maxFileBytes || + (end > written && + bytes.length + encoded.length > maxBatchBytes)) { + break; + } + bytes.add(encoded); + end++; + } + final chunk = bytes.takeBytes(); + await current.writeAsBytes(chunk, mode: FileMode.append, flush: true); + eventFlushes++; + eventBytesWritten += chunk.length; + written = end; + } + } catch (error) { + // A failed batch retains every unconfirmed record, with bounded fallback. + _failed(records.skip(written), error); + } finally { + _pending -= records.length; + _pendingBytes -= records.fold( + 0, + (size, record) => size + record.encoded.length, + ); + } + } + + Future _rotate() async { + final oldest = _log(fileCount - 1); + if (await oldest.exists()) await oldest.delete(); + for (var i = fileCount - 2; i >= 0; i--) { + final file = _log(i); + if (await file.exists()) await file.rename(_log(i + 1).path); + } + } + + void _failed(Iterable<_DiagnosticRecord> records, Object error) { + lastWriteFailure = _redactor.text(error.toString()); + for (final record in records) { + writeFailures++; + _fallback.add(record.safe); + if (_fallback.length > 100) _fallback.removeAt(0); + } + } + + /// Drains buffered records and waits for writes already accepted by the store. + Future flush() { + _enqueueBuffered(); + return _tail; + } + + Future saveRequest(Map report, String requestId) { + // UUID-only names prevent user text or paths from choosing a destination. + if (!RegExp(r'^[a-fA-F0-9-]{36}$').hasMatch(requestId)) { + return Future.value(); + } + if (_pending >= maxPending - errorReserveRecords) { + dropped++; + return Future.value(); + } + _enqueueBuffered(); + _pending++; + final operation = _tail.then((_) async { + final requests = Directory(p.join(directory.path, 'requests')); + try { + await requests.create(recursive: true); + final safe = _redactor.value(report); + final encoded = jsonEncode(safe); + if (utf8.encode(encoded).length > 256 * 1024) { + dropped++; + return; + } + final file = File( + p.join( + requests.path, + '${DateTime.now().toUtc().microsecondsSinceEpoch}-$requestId.json', + ), + ); + final temporary = File('${file.path}.tmp'); + await temporary.writeAsString(encoded, flush: true); + await temporary.rename(file.path); + final files = await requests + .list() + .where((e) => e is File && e.path.endsWith('.json')) + .cast() + .toList(); + files.sort((a, b) => a.path.compareTo(b.path)); + if (files.length > 20) { + for (final old in files.take(files.length - 20)) { + await old.delete(); + } + } + } catch (error) { + writeFailures++; + lastWriteFailure = _redactor.text(error.toString()); + } finally { + _pending--; + } + }); + _tail = operation; + return operation; + } + + /// Exports only managed diagnostics, never project files or conversations. + Future export(Directory destination, Map metadata) { + _enqueueBuffered(); + final completion = Completer(); + _tail = _tail.then((_) async { + try { + final records = []; + final logs = [ + for (var i = fileCount - 1; i >= 0; i--) _log(i), + File(p.join(directory.path, 'fatal.jsonl')), + ]; + for (final file in logs) { + if (!await file.exists() || await file.length() > maxFileBytes) { + continue; + } + for (final line in await file.readAsLines()) { + try { + records.add(_redactor.value(jsonDecode(line))); + } catch (_) { + // An interrupted append must not prevent exporting other records. + } + } + } + final reports = []; + final requests = Directory(p.join(directory.path, 'requests')); + if (await requests.exists()) { + final files = await requests + .list() + .where((e) => e is File && e.path.endsWith('.json')) + .cast() + .toList(); + files.sort((a, b) => b.path.compareTo(a.path)); + for (final file in files.take(20)) { + if (await file.length() > 256 * 1024) continue; + try { + reports.add( + _redactor.value(jsonDecode(await file.readAsString())), + ); + } catch (_) {} + } + } + await destination.create(recursive: true); + final file = File( + p.join( + destination.path, + 'cutdex-diagnostics-${DateTime.now().toUtc().microsecondsSinceEpoch}.json', + ), + ); + final temporary = File('${file.path}.tmp'); + await temporary.writeAsString( + jsonEncode({ + 'version': 1, + 'exportedAt': DateTime.now().toUtc().toIso8601String(), + 'metadata': _redactor.value(metadata), + 'storage': { + 'dropped': dropped, + 'droppedErrors': droppedErrors, + 'errorReserveRecords': errorReserveRecords, + 'errorReserveBytes': errorReserveBytes, + 'writeFailures': writeFailures, + 'eventWriteBatches': eventWriteBatches, + 'eventFlushes': eventFlushes, + 'eventBytesWritten': eventBytesWritten, + 'lastWriteFailure': lastWriteFailure, + }, + 'events': records, + 'requests': reports, + 'fallbackEvents': _fallback, + }), + flush: true, + ); + await temporary.rename(file.path); + completion.complete(file); + } catch (error, stack) { + completion.completeError(error, stack); + } + }); + return completion.future; + } +} + +final class _DiagnosticRecord { + const _DiagnosticRecord(this.safe, this.encoded); + final Map safe; + final List encoded; +} diff --git a/lib/diagnostics/frame_timings.dart b/lib/diagnostics/frame_timings.dart new file mode 100644 index 0000000..5a760b1 --- /dev/null +++ b/lib/diagnostics/frame_timings.dart @@ -0,0 +1,53 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:ui'; + +import 'package:flutter/scheduler.dart'; + +/// Opt-in real-engine timings. No callbacks or I/O in ordinary app launches. +/// Set CUTDEX_FRAME_TIMINGS to a JSONL output path before launching the app. +void recordFrameTimingsFromEnvironment() { + final path = Platform.environment['CUTDEX_FRAME_TIMINGS']; + if (path == null || path.isEmpty) return; + final pending = >[]; + var writing = false; + var dropped = 0; + SchedulerBinding.instance.addTimingsCallback((frames) { + for (final frame in frames) { + if (pending.length >= 2048) { + dropped++; + continue; + } + pending.add([ + frame.timestampInMicroseconds(FramePhase.vsyncStart), + frame.buildDuration.inMicroseconds, + frame.rasterDuration.inMicroseconds, + frame.totalSpan.inMicroseconds, + ]); + } + }); + Timer.periodic(const Duration(seconds: 2), (_) async { + if (writing || pending.isEmpty) return; + writing = true; + final batch = List>.of(pending); + pending.clear(); + final lost = dropped; + dropped = 0; + try { + await File(path).writeAsString( + '${jsonEncode({ + 'at': DateTime.now().toUtc().toIso8601String(), + 'columns': ['vsyncUs', 'buildUs', 'rasterUs', 'totalUs'], + 'dropped': lost, + 'frames': batch, + })}\n', + mode: FileMode.append, + ); + } on FileSystemException { + // Diagnostics must never interrupt editing (e.g. an unavailable drive). + } finally { + writing = false; + } + }); +} diff --git a/lib/diagnostics/request_report.dart b/lib/diagnostics/request_report.dart new file mode 100644 index 0000000..bb32d5c --- /dev/null +++ b/lib/diagnostics/request_report.dart @@ -0,0 +1,34 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'request_report.freezed.dart'; +part 'request_report.g.dart'; + +@freezed +abstract class RequestFrameReport with _$RequestFrameReport { + const factory RequestFrameReport({ + required int count, + @JsonKey(name: 'over16ms') required int slowFrames, + required int maxBuildUs, + required int maxRasterUs, + required int maxTimerDelayUs, + }) = _RequestFrameReport; + factory RequestFrameReport.fromJson(Map json) => + _$RequestFrameReportFromJson(json); +} + +@freezed +abstract class RequestReport with _$RequestReport { + const factory RequestReport({ + @Default(1) int version, + required String outcome, + required int elapsedUs, + int? preparationUs, + required RequestFrameReport frames, + required List> runs, + @JsonKey(includeIfNull: false) DateTime? at, + @JsonKey(includeIfNull: false) String? requestId, + @JsonKey(includeIfNull: false) String? sessionId, + }) = _RequestReport; + factory RequestReport.fromJson(Map json) => + _$RequestReportFromJson(json); +} diff --git a/lib/diagnostics/request_report.freezed.dart b/lib/diagnostics/request_report.freezed.dart new file mode 100644 index 0000000..2c06dfd --- /dev/null +++ b/lib/diagnostics/request_report.freezed.dart @@ -0,0 +1,1067 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'request_report.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +T _$identity(T value) => value; + +/// @nodoc +mixin _$RequestFrameReport { + int get count; + @JsonKey(name: 'over16ms') + int get slowFrames; + int get maxBuildUs; + int get maxRasterUs; + int get maxTimerDelayUs; + + /// Create a copy of RequestFrameReport + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $RequestFrameReportCopyWith get copyWith => + _$RequestFrameReportCopyWithImpl( + this as RequestFrameReport, + _$identity, + ); + + /// Serializes this RequestFrameReport to a JSON map. + Map toJson(); + + @override + bool operator ==(Object other) { + final _this = this as RequestFrameReport; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is RequestFrameReport && + (identical(other.count, _this.count) || + other.count == _this.count) && + (identical(other.slowFrames, _this.slowFrames) || + other.slowFrames == _this.slowFrames) && + (identical(other.maxBuildUs, _this.maxBuildUs) || + other.maxBuildUs == _this.maxBuildUs) && + (identical(other.maxRasterUs, _this.maxRasterUs) || + other.maxRasterUs == _this.maxRasterUs) && + (identical(other.maxTimerDelayUs, _this.maxTimerDelayUs) || + other.maxTimerDelayUs == _this.maxTimerDelayUs)); + } + + @JsonKey(includeFromJson: false, includeToJson: false) + @override + int get hashCode { + final _this = this as RequestFrameReport; + return Object.hash( + runtimeType, + _this.count, + _this.slowFrames, + _this.maxBuildUs, + _this.maxRasterUs, + _this.maxTimerDelayUs, + ); + } + + @override + String toString() { + final _this = this as RequestFrameReport; + return 'RequestFrameReport(count: ${_this.count}, slowFrames: ${_this.slowFrames}, maxBuildUs: ${_this.maxBuildUs}, maxRasterUs: ${_this.maxRasterUs}, maxTimerDelayUs: ${_this.maxTimerDelayUs})'; + } +} + +/// @nodoc +abstract mixin class $RequestFrameReportCopyWith<$Res> { + factory $RequestFrameReportCopyWith( + RequestFrameReport value, + $Res Function(RequestFrameReport) _then, + ) = _$RequestFrameReportCopyWithImpl; + @useResult + $Res call({ + int count, + @JsonKey(name: 'over16ms') int slowFrames, + int maxBuildUs, + int maxRasterUs, + int maxTimerDelayUs, + }); +} + +/// @nodoc +class _$RequestFrameReportCopyWithImpl<$Res> + implements $RequestFrameReportCopyWith<$Res> { + _$RequestFrameReportCopyWithImpl(this._self, this._then); + + final RequestFrameReport _self; + final $Res Function(RequestFrameReport) _then; + + /// Create a copy of RequestFrameReport + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? count = null, + Object? slowFrames = null, + Object? maxBuildUs = null, + Object? maxRasterUs = null, + Object? maxTimerDelayUs = null, + }) { + return _then( + RequestFrameReport( + count: null == count + ? _self.count + : count // ignore: cast_nullable_to_non_nullable + as int, + slowFrames: null == slowFrames + ? _self.slowFrames + : slowFrames // ignore: cast_nullable_to_non_nullable + as int, + maxBuildUs: null == maxBuildUs + ? _self.maxBuildUs + : maxBuildUs // ignore: cast_nullable_to_non_nullable + as int, + maxRasterUs: null == maxRasterUs + ? _self.maxRasterUs + : maxRasterUs // ignore: cast_nullable_to_non_nullable + as int, + maxTimerDelayUs: null == maxTimerDelayUs + ? _self.maxTimerDelayUs + : maxTimerDelayUs // ignore: cast_nullable_to_non_nullable + as int, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [RequestFrameReport]. +extension RequestFrameReportPatterns on RequestFrameReport { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_RequestFrameReport value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _RequestFrameReport() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_RequestFrameReport value) $default, + ) { + final _that = this; + switch (_that) { + case _RequestFrameReport(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_RequestFrameReport value)? $default, + ) { + final _that = this; + switch (_that) { + case _RequestFrameReport() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + int count, + @JsonKey(name: 'over16ms') int slowFrames, + int maxBuildUs, + int maxRasterUs, + int maxTimerDelayUs, + )? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _RequestFrameReport() when $default != null: + return $default( + _that.count, + _that.slowFrames, + _that.maxBuildUs, + _that.maxRasterUs, + _that.maxTimerDelayUs, + ); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function( + int count, + @JsonKey(name: 'over16ms') int slowFrames, + int maxBuildUs, + int maxRasterUs, + int maxTimerDelayUs, + ) + $default, + ) { + final _that = this; + switch (_that) { + case _RequestFrameReport(): + return $default( + _that.count, + _that.slowFrames, + _that.maxBuildUs, + _that.maxRasterUs, + _that.maxTimerDelayUs, + ); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + int count, + @JsonKey(name: 'over16ms') int slowFrames, + int maxBuildUs, + int maxRasterUs, + int maxTimerDelayUs, + )? + $default, + ) { + final _that = this; + switch (_that) { + case _RequestFrameReport() when $default != null: + return $default( + _that.count, + _that.slowFrames, + _that.maxBuildUs, + _that.maxRasterUs, + _that.maxTimerDelayUs, + ); + case _: + return null; + } + } +} + +/// @nodoc +@JsonSerializable() +class _RequestFrameReport implements RequestFrameReport { + const _RequestFrameReport({ + required this.count, + @JsonKey(name: 'over16ms') required this.slowFrames, + required this.maxBuildUs, + required this.maxRasterUs, + required this.maxTimerDelayUs, + }); + factory _RequestFrameReport.fromJson(Map json) => + _$RequestFrameReportFromJson(json); + + @override + final int count; + @override + @JsonKey(name: 'over16ms') + final int slowFrames; + @override + final int maxBuildUs; + @override + final int maxRasterUs; + @override + final int maxTimerDelayUs; + + /// Create a copy of RequestFrameReport + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$RequestFrameReportCopyWith<_RequestFrameReport> get copyWith => + __$RequestFrameReportCopyWithImpl<_RequestFrameReport>(this, _$identity); + + @override + Map toJson() { + return _$RequestFrameReportToJson(this); + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _RequestFrameReport && + (identical(other.count, count) || other.count == count) && + (identical(other.slowFrames, slowFrames) || + other.slowFrames == slowFrames) && + (identical(other.maxBuildUs, maxBuildUs) || + other.maxBuildUs == maxBuildUs) && + (identical(other.maxRasterUs, maxRasterUs) || + other.maxRasterUs == maxRasterUs) && + (identical(other.maxTimerDelayUs, maxTimerDelayUs) || + other.maxTimerDelayUs == maxTimerDelayUs)); + } + + @JsonKey(includeFromJson: false, includeToJson: false) + @override + int get hashCode { + return Object.hash( + runtimeType, + count, + slowFrames, + maxBuildUs, + maxRasterUs, + maxTimerDelayUs, + ); + } + + @override + String toString() { + return 'RequestFrameReport(count: $count, slowFrames: $slowFrames, maxBuildUs: $maxBuildUs, maxRasterUs: $maxRasterUs, maxTimerDelayUs: $maxTimerDelayUs)'; + } +} + +/// @nodoc +abstract mixin class _$RequestFrameReportCopyWith<$Res> + implements $RequestFrameReportCopyWith<$Res> { + factory _$RequestFrameReportCopyWith( + _RequestFrameReport value, + $Res Function(_RequestFrameReport) _then, + ) = __$RequestFrameReportCopyWithImpl; + @override + @useResult + $Res call({ + int count, + @JsonKey(name: 'over16ms') int slowFrames, + int maxBuildUs, + int maxRasterUs, + int maxTimerDelayUs, + }); +} + +/// @nodoc +class __$RequestFrameReportCopyWithImpl<$Res> + implements _$RequestFrameReportCopyWith<$Res> { + __$RequestFrameReportCopyWithImpl(this._self, this._then); + + final _RequestFrameReport _self; + final $Res Function(_RequestFrameReport) _then; + + /// Create a copy of RequestFrameReport + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? count = null, + Object? slowFrames = null, + Object? maxBuildUs = null, + Object? maxRasterUs = null, + Object? maxTimerDelayUs = null, + }) { + return _then( + _RequestFrameReport( + count: null == count + ? _self.count + : count // ignore: cast_nullable_to_non_nullable + as int, + slowFrames: null == slowFrames + ? _self.slowFrames + : slowFrames // ignore: cast_nullable_to_non_nullable + as int, + maxBuildUs: null == maxBuildUs + ? _self.maxBuildUs + : maxBuildUs // ignore: cast_nullable_to_non_nullable + as int, + maxRasterUs: null == maxRasterUs + ? _self.maxRasterUs + : maxRasterUs // ignore: cast_nullable_to_non_nullable + as int, + maxTimerDelayUs: null == maxTimerDelayUs + ? _self.maxTimerDelayUs + : maxTimerDelayUs // ignore: cast_nullable_to_non_nullable + as int, + ), + ); + } +} + +/// @nodoc +mixin _$RequestReport { + int get version; + String get outcome; + int get elapsedUs; + int? get preparationUs; + RequestFrameReport get frames; + List> get runs; + @JsonKey(includeIfNull: false) + DateTime? get at; + @JsonKey(includeIfNull: false) + String? get requestId; + @JsonKey(includeIfNull: false) + String? get sessionId; + + /// Create a copy of RequestReport + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $RequestReportCopyWith get copyWith => + _$RequestReportCopyWithImpl( + this as RequestReport, + _$identity, + ); + + /// Serializes this RequestReport to a JSON map. + Map toJson(); + + @override + bool operator ==(Object other) { + final _this = this as RequestReport; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is RequestReport && + (identical(other.version, _this.version) || + other.version == _this.version) && + (identical(other.outcome, _this.outcome) || + other.outcome == _this.outcome) && + (identical(other.elapsedUs, _this.elapsedUs) || + other.elapsedUs == _this.elapsedUs) && + (identical(other.preparationUs, _this.preparationUs) || + other.preparationUs == _this.preparationUs) && + (identical(other.frames, _this.frames) || + other.frames == _this.frames) && + const DeepCollectionEquality().equals(other.runs, _this.runs) && + (identical(other.at, _this.at) || other.at == _this.at) && + (identical(other.requestId, _this.requestId) || + other.requestId == _this.requestId) && + (identical(other.sessionId, _this.sessionId) || + other.sessionId == _this.sessionId)); + } + + @JsonKey(includeFromJson: false, includeToJson: false) + @override + int get hashCode { + final _this = this as RequestReport; + return Object.hash( + runtimeType, + _this.version, + _this.outcome, + _this.elapsedUs, + _this.preparationUs, + _this.frames, + const DeepCollectionEquality().hash(_this.runs), + _this.at, + _this.requestId, + _this.sessionId, + ); + } + + @override + String toString() { + final _this = this as RequestReport; + return 'RequestReport(version: ${_this.version}, outcome: ${_this.outcome}, elapsedUs: ${_this.elapsedUs}, preparationUs: ${_this.preparationUs}, frames: ${_this.frames}, runs: ${_this.runs}, at: ${_this.at}, requestId: ${_this.requestId}, sessionId: ${_this.sessionId})'; + } +} + +/// @nodoc +abstract mixin class $RequestReportCopyWith<$Res> { + factory $RequestReportCopyWith( + RequestReport value, + $Res Function(RequestReport) _then, + ) = _$RequestReportCopyWithImpl; + @useResult + $Res call({ + int version, + String outcome, + int elapsedUs, + int? preparationUs, + RequestFrameReport frames, + List> runs, + @JsonKey(includeIfNull: false) DateTime? at, + @JsonKey(includeIfNull: false) String? requestId, + @JsonKey(includeIfNull: false) String? sessionId, + }); + + $RequestFrameReportCopyWith<$Res> get frames; +} + +/// @nodoc +class _$RequestReportCopyWithImpl<$Res> + implements $RequestReportCopyWith<$Res> { + _$RequestReportCopyWithImpl(this._self, this._then); + + final RequestReport _self; + final $Res Function(RequestReport) _then; + + /// Create a copy of RequestReport + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? version = null, + Object? outcome = null, + Object? elapsedUs = null, + Object? preparationUs = freezed, + Object? frames = null, + Object? runs = null, + Object? at = freezed, + Object? requestId = freezed, + Object? sessionId = freezed, + }) { + return _then( + RequestReport( + version: null == version + ? _self.version + : version // ignore: cast_nullable_to_non_nullable + as int, + outcome: null == outcome + ? _self.outcome + : outcome // ignore: cast_nullable_to_non_nullable + as String, + elapsedUs: null == elapsedUs + ? _self.elapsedUs + : elapsedUs // ignore: cast_nullable_to_non_nullable + as int, + preparationUs: freezed == preparationUs + ? _self.preparationUs + : preparationUs // ignore: cast_nullable_to_non_nullable + as int?, + frames: null == frames + ? _self.frames + : frames // ignore: cast_nullable_to_non_nullable + as RequestFrameReport, + runs: null == runs + ? _self.runs + : runs // ignore: cast_nullable_to_non_nullable + as List>, + at: freezed == at + ? _self.at + : at // ignore: cast_nullable_to_non_nullable + as DateTime?, + requestId: freezed == requestId + ? _self.requestId + : requestId // ignore: cast_nullable_to_non_nullable + as String?, + sessionId: freezed == sessionId + ? _self.sessionId + : sessionId // ignore: cast_nullable_to_non_nullable + as String?, + ), + ); + } + + /// Create a copy of RequestReport + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $RequestFrameReportCopyWith<$Res> get frames { + return $RequestFrameReportCopyWith<$Res>(_self.frames, (value) { + return _then(_self.copyWith(frames: value)); + }); + } +} + +/// Adds pattern-matching-related methods to [RequestReport]. +extension RequestReportPatterns on RequestReport { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_RequestReport value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _RequestReport() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_RequestReport value) $default, + ) { + final _that = this; + switch (_that) { + case _RequestReport(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_RequestReport value)? $default, + ) { + final _that = this; + switch (_that) { + case _RequestReport() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + int version, + String outcome, + int elapsedUs, + int? preparationUs, + RequestFrameReport frames, + List> runs, + @JsonKey(includeIfNull: false) DateTime? at, + @JsonKey(includeIfNull: false) String? requestId, + @JsonKey(includeIfNull: false) String? sessionId, + )? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _RequestReport() when $default != null: + return $default( + _that.version, + _that.outcome, + _that.elapsedUs, + _that.preparationUs, + _that.frames, + _that.runs, + _that.at, + _that.requestId, + _that.sessionId, + ); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function( + int version, + String outcome, + int elapsedUs, + int? preparationUs, + RequestFrameReport frames, + List> runs, + @JsonKey(includeIfNull: false) DateTime? at, + @JsonKey(includeIfNull: false) String? requestId, + @JsonKey(includeIfNull: false) String? sessionId, + ) + $default, + ) { + final _that = this; + switch (_that) { + case _RequestReport(): + return $default( + _that.version, + _that.outcome, + _that.elapsedUs, + _that.preparationUs, + _that.frames, + _that.runs, + _that.at, + _that.requestId, + _that.sessionId, + ); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + int version, + String outcome, + int elapsedUs, + int? preparationUs, + RequestFrameReport frames, + List> runs, + @JsonKey(includeIfNull: false) DateTime? at, + @JsonKey(includeIfNull: false) String? requestId, + @JsonKey(includeIfNull: false) String? sessionId, + )? + $default, + ) { + final _that = this; + switch (_that) { + case _RequestReport() when $default != null: + return $default( + _that.version, + _that.outcome, + _that.elapsedUs, + _that.preparationUs, + _that.frames, + _that.runs, + _that.at, + _that.requestId, + _that.sessionId, + ); + case _: + return null; + } + } +} + +/// @nodoc +@JsonSerializable() +class _RequestReport implements RequestReport { + const _RequestReport({ + this.version = 1, + required this.outcome, + required this.elapsedUs, + this.preparationUs, + required this.frames, + required List> runs, + @JsonKey(includeIfNull: false) this.at, + @JsonKey(includeIfNull: false) this.requestId, + @JsonKey(includeIfNull: false) this.sessionId, + }) : _runs = runs; + factory _RequestReport.fromJson(Map json) => + _$RequestReportFromJson(json); + + @override + @JsonKey() + final int version; + @override + final String outcome; + @override + final int elapsedUs; + @override + final int? preparationUs; + @override + final RequestFrameReport frames; + final List> _runs; + @override + List> get runs { + if (_runs is EqualUnmodifiableListView) return _runs; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_runs); + } + + @override + @JsonKey(includeIfNull: false) + final DateTime? at; + @override + @JsonKey(includeIfNull: false) + final String? requestId; + @override + @JsonKey(includeIfNull: false) + final String? sessionId; + + /// Create a copy of RequestReport + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$RequestReportCopyWith<_RequestReport> get copyWith => + __$RequestReportCopyWithImpl<_RequestReport>(this, _$identity); + + @override + Map toJson() { + return _$RequestReportToJson(this); + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _RequestReport && + (identical(other.version, version) || other.version == version) && + (identical(other.outcome, outcome) || other.outcome == outcome) && + (identical(other.elapsedUs, elapsedUs) || + other.elapsedUs == elapsedUs) && + (identical(other.preparationUs, preparationUs) || + other.preparationUs == preparationUs) && + (identical(other.frames, frames) || other.frames == frames) && + const DeepCollectionEquality().equals(other.runs, _runs) && + (identical(other.at, at) || other.at == at) && + (identical(other.requestId, requestId) || + other.requestId == requestId) && + (identical(other.sessionId, sessionId) || + other.sessionId == sessionId)); + } + + @JsonKey(includeFromJson: false, includeToJson: false) + @override + int get hashCode { + return Object.hash( + runtimeType, + version, + outcome, + elapsedUs, + preparationUs, + frames, + const DeepCollectionEquality().hash(_runs), + at, + requestId, + sessionId, + ); + } + + @override + String toString() { + return 'RequestReport(version: $version, outcome: $outcome, elapsedUs: $elapsedUs, preparationUs: $preparationUs, frames: $frames, runs: $runs, at: $at, requestId: $requestId, sessionId: $sessionId)'; + } +} + +/// @nodoc +abstract mixin class _$RequestReportCopyWith<$Res> + implements $RequestReportCopyWith<$Res> { + factory _$RequestReportCopyWith( + _RequestReport value, + $Res Function(_RequestReport) _then, + ) = __$RequestReportCopyWithImpl; + @override + @useResult + $Res call({ + int version, + String outcome, + int elapsedUs, + int? preparationUs, + RequestFrameReport frames, + List> runs, + @JsonKey(includeIfNull: false) DateTime? at, + @JsonKey(includeIfNull: false) String? requestId, + @JsonKey(includeIfNull: false) String? sessionId, + }); + + @override + $RequestFrameReportCopyWith<$Res> get frames; +} + +/// @nodoc +class __$RequestReportCopyWithImpl<$Res> + implements _$RequestReportCopyWith<$Res> { + __$RequestReportCopyWithImpl(this._self, this._then); + + final _RequestReport _self; + final $Res Function(_RequestReport) _then; + + /// Create a copy of RequestReport + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? version = null, + Object? outcome = null, + Object? elapsedUs = null, + Object? preparationUs = freezed, + Object? frames = null, + Object? runs = null, + Object? at = freezed, + Object? requestId = freezed, + Object? sessionId = freezed, + }) { + return _then( + _RequestReport( + version: null == version + ? _self.version + : version // ignore: cast_nullable_to_non_nullable + as int, + outcome: null == outcome + ? _self.outcome + : outcome // ignore: cast_nullable_to_non_nullable + as String, + elapsedUs: null == elapsedUs + ? _self.elapsedUs + : elapsedUs // ignore: cast_nullable_to_non_nullable + as int, + preparationUs: freezed == preparationUs + ? _self.preparationUs + : preparationUs // ignore: cast_nullable_to_non_nullable + as int?, + frames: null == frames + ? _self.frames + : frames // ignore: cast_nullable_to_non_nullable + as RequestFrameReport, + runs: null == runs + ? _self._runs + : runs // ignore: cast_nullable_to_non_nullable + as List>, + at: freezed == at + ? _self.at + : at // ignore: cast_nullable_to_non_nullable + as DateTime?, + requestId: freezed == requestId + ? _self.requestId + : requestId // ignore: cast_nullable_to_non_nullable + as String?, + sessionId: freezed == sessionId + ? _self.sessionId + : sessionId // ignore: cast_nullable_to_non_nullable + as String?, + ), + ); + } + + /// Create a copy of RequestReport + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $RequestFrameReportCopyWith<$Res> get frames { + return $RequestFrameReportCopyWith<$Res>(_self.frames, (value) { + return _then(_self.copyWith(frames: value)); + }); + } +} diff --git a/lib/diagnostics/request_report.g.dart b/lib/diagnostics/request_report.g.dart new file mode 100644 index 0000000..bd0fd68 --- /dev/null +++ b/lib/diagnostics/request_report.g.dart @@ -0,0 +1,55 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'request_report.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_RequestFrameReport _$RequestFrameReportFromJson(Map json) => + _RequestFrameReport( + count: (json['count'] as num).toInt(), + slowFrames: (json['over16ms'] as num).toInt(), + maxBuildUs: (json['maxBuildUs'] as num).toInt(), + maxRasterUs: (json['maxRasterUs'] as num).toInt(), + maxTimerDelayUs: (json['maxTimerDelayUs'] as num).toInt(), + ); + +Map _$RequestFrameReportToJson(_RequestFrameReport instance) => + { + 'count': instance.count, + 'over16ms': instance.slowFrames, + 'maxBuildUs': instance.maxBuildUs, + 'maxRasterUs': instance.maxRasterUs, + 'maxTimerDelayUs': instance.maxTimerDelayUs, + }; + +_RequestReport _$RequestReportFromJson(Map json) => + _RequestReport( + version: (json['version'] as num?)?.toInt() ?? 1, + outcome: json['outcome'] as String, + elapsedUs: (json['elapsedUs'] as num).toInt(), + preparationUs: (json['preparationUs'] as num?)?.toInt(), + frames: RequestFrameReport.fromJson( + json['frames'] as Map, + ), + runs: (json['runs'] as List) + .map((e) => e as Map) + .toList(), + at: json['at'] == null ? null : DateTime.parse(json['at'] as String), + requestId: json['requestId'] as String?, + sessionId: json['sessionId'] as String?, + ); + +Map _$RequestReportToJson(_RequestReport instance) => + { + 'version': instance.version, + 'outcome': instance.outcome, + 'elapsedUs': instance.elapsedUs, + 'preparationUs': instance.preparationUs, + 'frames': instance.frames.toJson(), + 'runs': instance.runs, + 'at': ?instance.at?.toIso8601String(), + 'requestId': ?instance.requestId, + 'sessionId': ?instance.sessionId, + }; diff --git a/lib/errors/app_failure.dart b/lib/errors/app_failure.dart new file mode 100644 index 0000000..5ca7c0a --- /dev/null +++ b/lib/errors/app_failure.dart @@ -0,0 +1,103 @@ +/// Stable application error identities; independent of interface language. +enum AppErrorCode { + operationFailed, + agentRestartHint, + loadRecentProjectsFailed, + loadProjectsFailed, + projectAccessFailed, + projectLocationNotWritable, + projectLocationUnavailable, + projectLocationCreateFailed, + projectMissingDirectory, + recentProjectSaveFailed, + lastProjectSaveFailed, + enterProjectName, + projectSwitched, + notLocalMedia, + revealMediaFailed, + openMatchingProject, + openTimelineFailed, + projectMismatch, + openProjectFirst, + localFilesOnly, + foldersUnsupported, + mediaImportCancelled, + fileAccessFailed, + registerMediaFailed, + mediaNoLongerExists, + mediaNoTracks, + invalidMediaDuration, + mediaInfoUnsupported, + mediaInfoFailed, + saveTimelineFailed, + projectNameInvalid, + projectLocationDefaultUnavailable, + chooseProjectLocation, + timelineMissing, + timelineInUse, + timelineHasBackgroundTasks, + timelineRequired, + projectSessionClosed, + timelineSessionClosed, + mediaReadFailed, + mediaImportFailed, + unsupportedMediaType, + mediaNoVideoTracks, + mediaDurationOutOfRange, + resourceChecksumFailed, + enterName, + agentLocationUnavailable, + agentLocationBusy, + startBackgroundRemovalFailed, + subtitleEngineUnavailable, + timelineChanged, + resourceDownloadHttpFailed, + diagnostic, +} + +/// An error remains structured until the presentation layer chooses its wording. +final class AppFailure { + const AppFailure(this.code, {this.diagnostic, this.httpStatusCode}); + + final AppErrorCode code; + final String? diagnostic; + final int? httpStatusCode; + + bool get requiresProjectLocation => switch (code) { + AppErrorCode.projectLocationNotWritable || + AppErrorCode.projectLocationUnavailable || + AppErrorCode.projectLocationCreateFailed || + AppErrorCode.projectLocationDefaultUnavailable || + AppErrorCode.chooseProjectLocation => true, + _ => false, + }; + + @override + bool operator ==(Object other) => + other is AppFailure && + code == other.code && + diagnostic == other.diagnostic && + httpStatusCode == other.httpStatusCode; + + @override + int get hashCode => Object.hash(code, diagnostic, httpStatusCode); + + @override + String toString() => diagnostic ?? code.name; +} + +/// Keeps existing StateError catch boundaries while carrying a stable identity. +final class AppException extends StateError { + AppException(AppErrorCode code, {String? diagnostic, int? httpStatusCode}) + : this.fromFailure( + AppFailure( + code, + diagnostic: diagnostic, + httpStatusCode: httpStatusCode, + ), + ); + + AppException.fromFailure(this.failure) : super(failure.toString()); + + final AppFailure failure; +} diff --git a/lib/features/assistant/agent_attachment_card.dart b/lib/features/assistant/agent_attachment_card.dart new file mode 100644 index 0000000..dcdb802 --- /dev/null +++ b/lib/features/assistant/agent_attachment_card.dart @@ -0,0 +1,103 @@ +import 'package:cutdex_sdk/project.dart'; +import 'package:flutter/material.dart'; + +import '../media/media_asset_cover.dart'; + +import 'package:cutdex_ui/theme.dart'; + +import '../media/audio_asset_tile.dart'; + +/// Compact project-media preview shared by the composer and sent messages. +class AgentAttachmentCard extends StatelessWidget { + const AgentAttachmentCard({super.key, required this.asset, this.onRemove}); + + final AssetDocument asset; + final VoidCallback? onRemove; + + @override + Widget build(BuildContext context) { + final kind = asset.metadata['kind']; + final colors = Theme.of(context).colorScheme; + final preview = switch (kind) { + 'image' || 'video' => SizedBox.expand( + child: MediaAssetCover( + asset: asset, + fit: BoxFit.cover, + fallback: Center( + child: Icon( + kind == 'image' ? Icons.image_outlined : Icons.movie_outlined, + color: colors.onSurfaceVariant, + ), + ), + errorFallback: Center( + child: Icon( + Icons.broken_image_outlined, + color: colors.onSurfaceVariant, + ), + ), + ), + ), + 'audio' => AudioAssetTile( + asset: asset, + showName: false, + aspectRatio: 132 / 96, + ), + _ => Center( + child: Icon( + Icons.insert_drive_file_outlined, + color: colors.onSurfaceVariant, + ), + ), + }; + return SizedBox( + width: 132, + height: 122, + child: Stack( + clipBehavior: Clip.none, + children: [ + ClipRRect( + borderRadius: BorderRadius.circular(8), + child: ColoredBox( + color: AppSurfaces.of(context).previewBackground, + child: Column( + children: [ + Expanded(child: SizedBox.expand(child: preview)), + Padding( + padding: const EdgeInsets.symmetric( + horizontal: 8, + vertical: 5, + ), + child: Text( + asset.name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: Theme.of(context).textTheme.bodySmall, + ), + ), + ], + ), + ), + ), + if (onRemove != null) + Positioned( + top: -4, + right: -4, + child: IconButton.filled( + key: Key('agent-attachment-remove-${asset.id}'), + tooltip: MaterialLocalizations.of(context).deleteButtonTooltip, + onPressed: onRemove, + style: IconButton.styleFrom( + minimumSize: const Size(20, 20), + maximumSize: const Size(20, 20), + padding: EdgeInsets.zero, + backgroundColor: colors.surface, + foregroundColor: colors.onSurface, + ), + icon: const Icon(Icons.close, size: 13), + ), + ), + ], + ), + ); + } +} diff --git a/lib/features/assistant/agent_chat_panel.dart b/lib/features/assistant/agent_chat_panel.dart new file mode 100644 index 0000000..ce49864 --- /dev/null +++ b/lib/features/assistant/agent_chat_panel.dart @@ -0,0 +1,1164 @@ +import '../../shared/layout/composer_layout.dart'; +import '../../shared/theme/composer_style.dart'; + +import 'package:cutdex/l10n/l10n.dart'; + +import 'package:cutdex_sdk/project.dart'; + +import '../../integrations/platform/platform_capabilities.dart'; +import 'agent_composer_controller.dart'; +import 'agent_composer_store.dart'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../integrations/agent/agent_provider.dart'; + +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex_ui/widgets.dart'; + +import '../../shared/widgets/drop_to_add_overlay.dart'; +import '../settings/settings_dialog.dart'; +import 'chat_controller.dart'; +import 'chat_state.dart'; +import '../../integrations/agent/conversation_repository.dart'; +import '../../integrations/platform/native_project_drop_region.dart'; +import '../../integrations/platform/native_file_drop_policy.dart'; +import '../../workspace/media_import.dart'; +import '../../workspace/external_media_import.dart'; +import '../../settings/settings_operation.dart'; +import '../../workspace/projects.dart'; +import '../media/media_asset_drag.dart'; +import '../media/media_browser_feedback.dart'; +import 'agent_attachment_card.dart'; +import 'agent_media_attachments.dart'; +import 'agent_message_codec.dart'; +import 'breakable_selectable_text.dart'; +import 'composer_document.dart'; +import 'composer_reference_validator.dart'; +import 'composer_suggestion_surface.dart'; + +const _userTurnGap = 56.0; +const _replyTurnGap = 48.0; + +String _elapsedLabel(BuildContext context, int elapsedMs) { + final totalSeconds = ((elapsedMs + 999) ~/ 1000).clamp(1, 86400000); + final minutes = totalSeconds ~/ 60; + final seconds = totalSeconds % 60; + final duration = minutes == 0 + ? context.l10n.durationSeconds(totalSeconds) + : context.l10n.durationMinutesSeconds(minutes, seconds); + return context.l10n.agentElapsedTime(duration); +} + +class AgentChatPanel extends ConsumerStatefulWidget { + const AgentChatPanel({ + super.key, + this.projectId, + this.timelineId, + this.projectSelector, + this.inputController, + this.composer, + this.conversationId, + this.draftKey, + this.onConversationCreated, + this.onConversationUpdated, + this.composerColor, + }); + + final String? projectId; + final String? timelineId; + final Widget? projectSelector; + final ComposerDocumentController? inputController; + final AgentComposerController? composer; + final String? conversationId; + final String? draftKey; + final Color? composerColor; + final ValueChanged? onConversationCreated; + final ValueChanged? onConversationUpdated; + + @override + ConsumerState createState() => _AgentChatPanelState(); +} + +class _AgentChatPanelState extends ConsumerState { + late final ComposerDocumentController _input = + widget.inputController ?? ComposerDocumentController(); + final _scroll = ScrollController(); + final _inputScroll = ScrollController(); + final _footerKey = GlobalKey(); + double _footerHeight = 0; + bool _footerMeasureScheduled = false; + bool _inputOverflows = false; + bool _follow = true; + String get _modelOperation => + 'agent-model-${widget.projectId}-${widget.conversationId ?? widget.draftKey ?? 'new'}'; + bool get _choosingModel => + ref.read(settingsOperationProvider(_modelOperation)).isLoading; + bool _usingDraftModel = false; + bool _dropHovering = false; + bool get _importingAttachments => + _composer.busy || + widget.projectId != null && + ref.read(externalMediaImportProvider(widget.projectId!)).isLoading; + late AgentComposerController _composer; + List get _attachments => _composer.attachments; + AgentComposerController _resolveComposer() => + widget.composer ?? + ref + .read(agentComposerStoreProvider) + .composer( + widget.projectId, + widget.conversationId ?? widget.draftKey ?? 'new', + ); + void _composerChanged() { + if (mounted) setState(() {}); + } + + void _scheduleFooterMeasure() { + if (_footerMeasureScheduled) return; + _footerMeasureScheduled = true; + WidgetsBinding.instance.addPostFrameCallback((_) { + _footerMeasureScheduled = false; + if (!mounted) return; + final height = _footerKey.currentContext?.size?.height ?? 0; + if ((_footerHeight - height).abs() > 0.5) { + setState(() => _footerHeight = height); + if (_follow) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted && _scroll.hasClients) { + _scroll.jumpTo(_scroll.position.maxScrollExtent); + } + }); + } + } + }); + } + + @override + void didUpdateWidget(covariant AgentChatPanel oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.conversationId != widget.conversationId || + oldWidget.projectId != widget.projectId || + oldWidget.draftKey != widget.draftKey) { + _usingDraftModel = false; + _composer.removeListener(_composerChanged); + _composer = _resolveComposer(); + _composer.addListener(_composerChanged); + } + } + + String _errorMessage(BuildContext context, AgentChatError error) => + switch (error) { + AgentChatError.configurationReadFailed => + context.l10n.agentConfigurationReadFailed, + AgentChatError.configurationRequired => + context.l10n.agentConfigurationRequired, + AgentChatError.sessionRestoreFailed => + context.l10n.agentSessionRestoreFailed, + AgentChatError.contextBudget => context.l10n.agentContextBudgetExceeded, + AgentChatError.authentication => context.l10n.agentAuthenticationFailed, + AgentChatError.exportReplyFailed => context.l10n.agentExportReplyFailed, + AgentChatError.connection => context.l10n.agentConnectionFailed, + AgentChatError.protocol => context.l10n.agentProtocolFailed, + AgentChatError.turnLimit => context.l10n.agentTurnLimitReached, + AgentChatError.interrupted => context.l10n.agentTaskInterrupted, + AgentChatError.recoveryRequired => context.l10n.agentRecoveryRequired, + AgentChatError.replyFailed => context.l10n.replyFailed, + AgentChatError.requestFailed => context.l10n.chatFailed, + }; + + @override + void initState() { + super.initState(); + _composer = _resolveComposer(); + _composer.addListener(_composerChanged); + _scroll.addListener(() { + _follow = _scroll.position.extentAfter < 80; + }); + } + + @override + void dispose() { + _composer.removeListener(_composerChanged); + if (widget.inputController == null) _input.dispose(); + _scroll.dispose(); + _inputScroll.dispose(); + super.dispose(); + } + + bool _canAttach(MediaAssetDrag drag) { + final workspace = ref.read(projectsProvider).asData?.value; + return widget.projectId == drag.projectId && + workspace?.activeProject?.id == drag.projectId && + !_attachments.any((item) => item.id == drag.assetId) && + workspace!.assets.any((asset) => asset.id == drag.assetId); + } + + bool _canAttachExternalFiles(List files) { + if (files.isEmpty) return true; + final assets = ref.read(projectsProvider).asData?.value.assets; + if (assets == null) return false; + final attachedIds = {for (final item in _attachments) item.id}; + final attachedLocations = { + for (final asset in assets) + if (attachedIds.contains(asset.id)) ?mediaSourceLocation(asset), + }; + return files.any( + (file) => !attachedLocations.contains(file.sourceUri.toString()), + ); + } + + void _attachAsset(AssetDocument asset) => _composer.attach(asset); + + bool get _desktop => ref.read(platformCapabilitiesProvider).nativeFileDrop; + + Future _dropExternalFiles(List files) async { + setState(() => _dropHovering = false); + try { + await _composer.importAttachments(files); + } catch (_) { + // Feedback belongs to the composer even if this panel is hidden. + } + } + + Future _pickAttachments() async { + try { + await _composer.pickAttachments(); + } catch (_) { + // Feedback belongs to the composer even if this panel is hidden. + } + } + + Widget _agentDropRegion(Widget child) { + final workspace = ref.watch(projectsProvider).asData?.value; + final enabled = + _desktop && + widget.projectId != null && + workspace?.activeProject?.id == widget.projectId && + (workspace?.projectBusy == false || _importingAttachments); + final internal = DragTarget( + key: const Key('agent-panel-drop-target'), + hitTestBehavior: HitTestBehavior.opaque, + onWillAcceptWithDetails: (details) => _canAttach(details.data), + onAcceptWithDetails: (details) { + final drag = details.data; + if (!_canAttach(drag)) return; + final asset = ref + .read(projectsProvider) + .asData! + .value + .assets + .firstWhere((item) => item.id == drag.assetId); + _attachAsset(asset); + }, + builder: (context, candidates, rejected) => Stack( + fit: StackFit.expand, + children: [ + child, + if (candidates.isNotEmpty || _dropHovering) + const Positioned.fill( + child: DropToAddOverlay(key: Key('agent-drop-overlay')), + ), + ], + ), + ); + if (!_desktop) return internal; + return NativeProjectDropRegion( + regionId: 'attachments', + policy: NativeFileDropPolicy.attachments, + enabled: enabled, + onEnter: (files) { + if (!_importingAttachments && _canAttachExternalFiles(files)) { + setState(() => _dropHovering = true); + } + }, + onExit: () { + if (mounted && _dropHovering) setState(() => _dropHovering = false); + }, + onDrop: _dropExternalFiles, + child: internal, + ); + } + + @override + Widget build(BuildContext context) { + ref.watch(settingsOperationProvider(_modelOperation)); + if (widget.projectId != null) { + ref.watch(externalMediaImportProvider(widget.projectId!)); + } + final workspace = ref.watch(projectsProvider).asData?.value; + final referenceValidator = ComposerReferenceValidator( + workspace: workspace, + projectId: widget.projectId, + ); + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + referenceValidator.validate(_input); + }); + final provider = widget.projectId != null + ? chatControllerProvider( + widget.projectId!, + conversationId: widget.conversationId, + draftKey: widget.draftKey, + ) + : null; + final state = provider == null ? const ChatState() : ref.watch(provider); + final settings = ref.watch(agentSettingsProvider).asData?.value; + final available = + settings?.providers + .where( + (item) => + item.enabled && + AgentApiType.values.any( + (type) => type.name == item.apiType, + ) && + item.models.isNotEmpty, + ) + .toList() ?? + const []; + final conversation = state.conversation; + final showProjectSelector = + widget.projectSelector != null && + widget.conversationId == null && + conversation == null && + state.messages.isEmpty && + !state.busy; + final providerId = conversation?.providerId ?? settings?.selectedProviderId; + final modelId = conversation?.modelId ?? settings?.selectedModelId; + final selectedProvider = available + .where((item) => item.id == providerId) + .firstOrNull; + final selectedModel = selectedProvider?.models + .where((item) => item.id == modelId) + .firstOrNull; + final usingExisting = + conversation != null || + (widget.conversationId != null && !_usingDraftModel); + final configured = usingExisting + ? conversation != null && + settings?.enabled == true && + selectedModel != null + : ref.watch(agentRuntimeProvider).asData?.value != null; + + Future chooseModel(String providerId, String modelId) async { + if (_choosingModel || state.busy) return; + final saved = await ref + .read(settingsOperationProvider(_modelOperation).notifier) + .run(() async { + if (provider == null) { + await ref + .read(agentSettingsProvider.notifier) + .selectModel(providerId, modelId); + } else { + await ref + .read(provider.notifier) + .selectModel(providerId, modelId); + } + }); + if (!mounted || !context.mounted) return; + if (saved) { + setState(() => _usingDraftModel = true); + } else { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(context.l10n.agentSaveSettingsFailed)), + ); + } + } + + final compactButtonStyle = AppComposerStyle.controlButton(context); + final compactIconStyle = AppComposerStyle.controlIcon(context); + + Widget modelPicker() { + if (available.isEmpty) { + return TextButton.icon( + key: const Key('agent-configure-model'), + style: compactButtonStyle, + onPressed: () => showSettingsDialog(context, initialTab: 1), + icon: const Icon(Icons.tune, size: 16), + label: Text(context.l10n.agentConfigureModel), + ); + } + return AppDropdownMenu( + minWidth: 220, + maxHeight: 320, + items: [ + if (usingExisting) AppMenuLabel(context.l10n.agentModelChangeSession), + for (final item in available) ...[ + AppMenuLabel(item.name), + for (final model in item.models) + AppMenuItem( + label: model.id, + selectOption: true, + selected: item.id == providerId && model.id == modelId, + onPressed: () => chooseModel(item.id, model.id), + ), + ], + const Divider(height: 1), + AppMenuItem( + label: context.l10n.agentConfigureModel, + selectOption: true, + onPressed: () => showSettingsDialog(context, initialTab: 1), + ), + ], + builder: (context, toggle, focus) => TextButton( + key: const Key('agent-model-picker'), + focusNode: focus, + onPressed: () { + if (!state.busy && !_choosingModel) toggle?.call(); + }, + style: compactButtonStyle, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Flexible( + child: Text( + selectedModel?.id ?? context.l10n.agentSelectModel, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + const SizedBox(width: 4), + const Icon(Icons.expand_more, size: 14), + ], + ), + ), + ); + } + + if (provider != null) { + ref.listen(provider, (previous, next) { + if (_follow) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted && _scroll.hasClients) { + _scroll.jumpTo(_scroll.position.maxScrollExtent); + } + }); + } + }); + } + void send() { + referenceValidator.validate(_input); + if (provider == null || + widget.timelineId == null || + !configured || + _choosingModel || + state.busy || + _importingAttachments || + _input.hasInvalidReferences || + (_input.text.trim().isEmpty && _attachments.isEmpty)) { + return; + } + final text = AgentComposerMessage.encodeDocument( + _input.segments, + _attachments, + ); + _input.clearDocument(); + _composer.clear(); + _follow = true; + ref + .read(provider.notifier) + .send( + text, + timelineId: widget.timelineId!, + onCreated: widget.onConversationCreated, + onUpdated: widget.onConversationUpdated, + ); + } + + final theme = Theme.of(context); + final content = _agentDropRegion( + LayoutBuilder( + builder: (context, constraints) { + final panelWidth = + (constraints.maxWidth - ComposerLayout.horizontalInset * 2) + .clamp(0.0, ComposerLayout.maxWidth) + .toDouble(); + _scheduleFooterMeasure(); + final footerInset = + _footerHeight + ComposerLayout.bottomInset + AppSpacing.small; + return Stack( + children: [ + Positioned.fill( + child: Scrollbar( + key: const Key('agent-conversation-scrollbar'), + controller: _scroll, + notificationPredicate: (notification) => + notification.depth == 0 && + notification.context + ?.findAncestorWidgetOfExactType< + ScrollEdgeFade + >() != + null, + child: SizedBox( + key: const Key('agent-conversation'), + child: state.messages.isEmpty + ? const SizedBox.expand() + : ScrollEdgeFade( + controller: _scroll, + bottomInset: footerInset, + child: ScrollConfiguration( + behavior: const _NoAutomaticScrollbarBehavior(), + child: ListView( + controller: _scroll, + padding: EdgeInsets.only(bottom: footerInset), + children: [ + Center( + child: SizedBox( + key: const Key( + 'agent-conversation-content', + ), + width: panelWidth, + child: Padding( + padding: const EdgeInsets.symmetric( + vertical: AppSpacing.compact, + ), + child: Column( + crossAxisAlignment: + CrossAxisAlignment.stretch, + children: [ + for (final message + in state.messages) + Padding( + padding: EdgeInsets.only( + bottom: message.isUser + ? _userTurnGap + : _replyTurnGap, + ), + child: Column( + crossAxisAlignment: + message.isUser + ? CrossAxisAlignment.end + : CrossAxisAlignment + .start, + children: [ + if (!message.isUser) ...[ + if (message.elapsedMs + case final elapsed?) + Padding( + padding: + const EdgeInsets.only( + bottom: + AppSpacing + .tiny, + ), + child: Row( + mainAxisSize: + MainAxisSize + .min, + children: [ + Text( + _elapsedLabel( + context, + elapsed, + ), + style: + AppTheme.chatMetaTextStyle( + context, + ), + ), + Icon( + Icons + .chevron_right, + size: 14, + color: + AppTheme.chatMetaTextStyle( + context, + ).color, + ), + ], + ), + ), + Divider( + height: 1, + thickness: 1, + color: + theme.dividerColor, + ), + const SizedBox( + height: + AppSpacing.medium, + ), + ], + if (AgentComposerMessage.decode( + message.text, + ).text.isNotEmpty) + if (message.isUser) + Container( + decoration: + AppTheme.userMessageDecoration( + context, + ), + padding: const EdgeInsets.symmetric( + horizontal: + AppSpacing + .medium, + vertical: AppSpacing + .itemVertical, + ), + child: BreakableSelectableText( + text: + AgentComposerMessage.decode( + message.text, + ).text, + style: + AppTheme.chatMessageTextStyle( + context, + ), + ), + ) + else + SelectableText( + message.text, + style: + AppTheme.chatMessageTextStyle( + context, + ), + ), + if (message.isUser && + AgentComposerMessage.decode( + message.text, + ) + .attachments + .isNotEmpty) + Padding( + padding: + const EdgeInsets.only( + top: 8, + ), + child: Wrap( + spacing: 8, + runSpacing: 8, + alignment: + WrapAlignment.end, + children: [ + for (final attachment + in AgentComposerMessage.decode( + message.text, + ).attachments) + if (ref + .watch( + projectsProvider, + ) + .asData + ?.value + .assets + .where( + ( + asset, + ) => + asset.id == + attachment.id, + ) + .firstOrNull + case final asset?) + AgentAttachmentCard( + asset: asset, + ) + else + Chip( + label: Text( + attachment + .name, + ), + ), + ], + ), + ), + if (message.interrupted) + Text( + context + .l10n + .replyInterrupted, + style: theme + .textTheme + .bodySmall, + ), + ], + ), + ), + if (state.busy) ...[ + if (state + .partialResponse + .isNotEmpty) + SelectableText( + state.partialResponse, + style: + AppTheme.chatMessageTextStyle( + context, + ), + ), + Text( + state.stopping + ? context.l10n.stopping + : switch (state.activity) { + AgentChatActivity + .compacting => + context + .l10n + .agentCompacting, + AgentChatActivity + .editing => + context + .l10n + .agentEditing, + AgentChatActivity + .verifying => + context + .l10n + .agentVerifying, + AgentChatActivity + .replying => + context.l10n.replying, + }, + style: + theme.textTheme.bodySmall, + ), + ], + ], + ), + ), + ), + ), + ], + ), + ), + ), + ), + ), + ), + Positioned( + left: ComposerLayout.horizontalInset, + right: ComposerLayout.horizontalInset, + bottom: ComposerLayout.bottomInset, + child: NotificationListener( + onNotification: (_) { + _scheduleFooterMeasure(); + return false; + }, + child: SizeChangedLayoutNotifier( + key: _footerKey, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + if (state.error case final error?) + Padding( + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.compact, + ), + child: Text( + _errorMessage(context, error), + style: theme.textTheme.bodySmall, + ), + ), + if ({ + AgentChatError.recoveryRequired, + AgentChatError.interrupted, + AgentChatError.turnLimit, + }.contains(state.error)) + TextButton( + onPressed: state.busy || widget.timelineId == null + ? null + : () => ref + .read(provider!.notifier) + .send( + context.l10n.agentResumeTask, + timelineId: widget.timelineId!, + resumeOnly: true, + onUpdated: widget.onConversationUpdated, + ), + child: Text(context.l10n.agentResumeTask), + ), + if (state.error == AgentChatError.exportReplyFailed) + TextButton( + onPressed: state.busy || widget.timelineId == null + ? null + : () => ref + .read(provider!.notifier) + .send( + context.l10n.agentRetrySummary, + timelineId: widget.timelineId!, + summaryOnly: true, + onUpdated: widget.onConversationUpdated, + ), + child: Text(context.l10n.agentRetrySummary), + ), + if (usingExisting && + !configured && + conversation != null) + Padding( + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.compact, + ), + child: Text( + context.l10n.agentModelUnavailable, + style: theme.textTheme.bodySmall, + ), + ), + Align( + alignment: Alignment.bottomCenter, + child: SizedBox( + width: panelWidth, + child: Stack( + children: [ + if (showProjectSelector) + Positioned( + top: ComposerLayout.utilityTopGap, + left: ComposerLayout.utilityInset, + right: ComposerLayout.utilityInset, + child: widget.projectSelector!, + ), + Padding( + padding: EdgeInsets.only( + top: !showProjectSelector + ? AppSpacing.small + : ComposerLayout.composerTopWithUtility, + ), + child: Align( + alignment: Alignment.bottomCenter, + child: SizedBox( + width: panelWidth, + child: ComposerSuggestionSurface( + controller: _input, + width: panelWidth, + projectId: workspace?.activeProject?.id, + assets: + workspace?.assets ?? + const [], + timelines: + workspace?.timelines ?? + const [], + onSend: send, + builder: (context, inputFocus) => Card( + key: const Key('agent-composer'), + color: + widget.composerColor ?? + AppSurfaces.of(context) + .composerBackground, + margin: EdgeInsets.zero, + elevation: 0, + surfaceTintColor: Colors.transparent, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular( + ComposerLayout.radius, + ), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + if (_attachments.isNotEmpty) + SizedBox( + height: 138, + child: ListView.separated( + key: const Key( + 'agent-composer-attachments', + ), + scrollDirection: + Axis.horizontal, + padding: + const EdgeInsets.fromLTRB( + 12, + 12, + 12, + 4, + ), + itemCount: + _attachments.length, + separatorBuilder: (_, _) => + const SizedBox( + width: 8, + ), + itemBuilder: (context, index) { + final attachment = + _attachments[index]; + final asset = ref + .watch( + projectsProvider, + ) + .asData + ?.value + .assets + .where( + (item) => + item.id == + attachment.id, + ) + .firstOrNull; + if (asset == null) { + return const SizedBox.shrink(); + } + return AgentAttachmentCard( + key: Key( + 'agent-attachment-${asset.id}', + ), + asset: asset, + onRemove: () => + _composer.remove( + asset.id, + ), + ); + }, + ), + ), + ConstrainedBox( + // Leave room for messages and composer actions when this + // panel shares a short window with the timeline. + constraints: BoxConstraints( + maxHeight: + (constraints.maxHeight * + ComposerLayout + .inputMaxHeightFraction) + .clamp( + ComposerLayout + .inputMinHeight, + double.infinity, + ), + ), + child: NotificationListener( + onNotification: (_) { + WidgetsBinding.instance + .addPostFrameCallback(( + _, + ) { + if (!mounted || + !_inputScroll + .hasClients) { + return; + } + final overflows = + _inputScroll + .position + .maxScrollExtent > + 0; + if (overflows != + _inputOverflows) { + setState( + () => + _inputOverflows = + overflows, + ); + } + }); + return false; + }, + child: Scrollbar( + key: const Key( + 'agent-input-scrollbar', + ), + controller: _inputScroll, + thumbVisibility: + _inputOverflows, + child: ScrollConfiguration( + behavior: + const _NoAutomaticScrollbarBehavior(), + child: TextField( + controller: _input, + focusNode: inputFocus, + scrollController: + _inputScroll, + style: + AppTheme.composerTextStyle( + context, + ), + cursorHeight: + AppTheme.composerCursorHeight( + context, + ), + textAlignVertical: + TextAlignVertical + .top, + minLines: 1, + maxLines: 12, + keyboardType: + TextInputType + .multiline, + textInputAction: + TextInputAction + .newline, + decoration: + AppComposerStyle.inputDecoration( + context, + hintText: context + .l10n + .assistantHint, + ), + ), + ), + ), + ), + ), + ValueListenableBuilder< + TextEditingValue + >( + valueListenable: _input, + builder: (context, _, _) => + _input.hasInvalidReferences + ? Padding( + padding: + const EdgeInsets.symmetric( + horizontal: 14, + vertical: 4, + ), + child: Align( + alignment: Alignment + .centerLeft, + child: Text( + context + .l10n + .composerReferenceInvalid, + style: theme + .textTheme + .bodySmall + ?.copyWith( + color: theme + .colorScheme + .error, + ), + ), + ), + ) + : const SizedBox.shrink(), + ), + Padding( + padding: AppComposerStyle + .controlsPadding, + child: Row( + children: [ + IconButton( + style: compactIconStyle, + tooltip: context + .l10n + .addAttachment, + onPressed: + widget.projectId != + null && + !_importingAttachments && + ref + .watch( + platformCapabilitiesProvider, + ) + .localFileSelection + ? _pickAttachments + : null, + icon: const Icon( + Icons.add, + ), + ), + const SizedBox( + width: ComposerLayout + .controlGap, + ), + Expanded( + child: Align( + alignment: + AlignmentDirectional + .centerStart, + child: modelPicker(), + ), + ), + const SizedBox( + width: ComposerLayout + .controlGap, + ), + if (state.busy) + IconButton.filled( + style: + AppTheme.primaryIconButtonStyle( + context, + ).merge( + compactIconStyle, + ), + tooltip: context + .l10n + .stopReply, + onPressed: + state.stopping + ? null + : ref + .read( + provider! + .notifier, + ) + .stop, + icon: const Icon( + Icons.stop, + ), + ) + else + ValueListenableBuilder< + TextEditingValue + >( + valueListenable: _input, + builder: (context, value, child) => IconButton.filled( + style: + AppComposerStyle.composerSendButtonStyle( + context, + ).merge( + compactIconStyle, + ), + tooltip: context + .l10n + .sendMessage, + onPressed: + provider != + null && + widget.timelineId != + null && + configured && + !_importingAttachments && + !_input + .hasInvalidReferences && + (value.text + .trim() + .isNotEmpty || + _attachments + .isNotEmpty) + ? send + : null, + icon: const Icon( + Icons.arrow_upward, + ), + ), + ), + ], + ), + ), + ], + ), + ), + ), + ), + ), + ), + ], + ), + ), + ), + ], + ), + ), + ), + ), + ], + ); + }, + ), + ); + return MediaImportFeedbackListener( + feedback: _composer.feedback, + child: content, + ); + } +} + +/// Explicit scrollbars own their track instead of the desktop default wrapper. +class _NoAutomaticScrollbarBehavior extends MaterialScrollBehavior { + const _NoAutomaticScrollbarBehavior(); + + @override + Widget buildScrollbar( + BuildContext context, + Widget child, + ScrollableDetails details, + ) => child; +} diff --git a/lib/features/assistant/agent_composer_controller.dart b/lib/features/assistant/agent_composer_controller.dart new file mode 100644 index 0000000..76d3f4f --- /dev/null +++ b/lib/features/assistant/agent_composer_controller.dart @@ -0,0 +1,84 @@ +import 'package:cutdex_sdk/project.dart'; +import 'package:flutter/foundation.dart'; + +import '../../workspace/external_media_import.dart'; +import '../../workspace/media_import.dart'; +import '../../workspace/media_import_feedback.dart'; +import 'agent_media_attachments.dart'; + +/// Owns attachment operations for one conversation or draft, even while hidden. +class AgentComposerController extends ChangeNotifier { + AgentComposerController({ + required this.canImport, + required this.pickFiles, + required this.importMedia, + List? attachments, + }) : attachments = attachments ?? []; + + final bool Function() canImport; + final Future> Function() pickFiles; + final Future Function(List) + importMedia; + final List attachments; + final feedback = MediaImportFeedbackController(); + bool _busy = false; + bool _disposed = false; + bool get busy => _busy; + + void attach(AssetDocument asset) { + if (_disposed || attachments.any((item) => item.id == asset.id)) return; + attachments.add(AgentMediaAttachment.fromAsset(asset)); + notifyListeners(); + } + + void remove(String id) { + attachments.removeWhere((item) => item.id == id); + notifyListeners(); + } + + void clear() { + attachments.clear(); + notifyListeners(); + } + + Future pickAttachments() => _run(pickFiles); + + Future importAttachments( + List files, + ) => _run(() async => files); + + Future _run( + Future> Function() select, + ) async { + if (_disposed || _busy || !canImport()) return null; + _busy = true; + notifyListeners(); + try { + final files = await select(); + if (_disposed || files.isEmpty || !canImport()) return null; + final result = await importMedia(files); + // Deleting the conversation invalidates this destination. Hiding its + // presentation does not, so completed imports still populate the draft. + if (!_disposed) { + for (final asset in result?.selected ?? []) { + attach(asset); + } + feedback.recordResult(result); + } + return result; + } catch (_) { + if (!_disposed) feedback.recordFailure(); + rethrow; + } finally { + _busy = false; + if (!_disposed) notifyListeners(); + } + } + + @override + void dispose() { + _disposed = true; + feedback.dispose(); + super.dispose(); + } +} diff --git a/lib/features/assistant/agent_composer_store.dart b/lib/features/assistant/agent_composer_store.dart new file mode 100644 index 0000000..1b9d423 --- /dev/null +++ b/lib/features/assistant/agent_composer_store.dart @@ -0,0 +1,89 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../integrations/platform/file_picker.dart'; +import '../../integrations/platform/platform_capabilities.dart'; +import '../../workspace/media_file_extensions.dart'; +import '../../workspace/external_media_import.dart'; +import '../../workspace/projects.dart'; +import 'agent_composer_controller.dart'; +import 'agent_media_attachments.dart'; +import 'composer_document.dart'; + +/// Composition survives presentation changes, including temporarily hidden chat. +final agentComposerStoreProvider = Provider((ref) { + final store = AgentComposerStore( + createComposer: (projectId) => AgentComposerController( + canImport: () => + ref.mounted && + projectId != null && + ref.read(platformCapabilitiesProvider).localFileSelection && + ref.read(projectsProvider).value?.activeProject?.id == projectId && + ref.read(projectsProvider).value?.projectBusy == false && + !ref.read(externalMediaImportProvider(projectId)).isLoading, + pickFiles: () => ref + .read(filePickerProvider) + .pickFiles(allowedExtensions: selectableMediaFileExtensions), + importMedia: (files) => ref + .read(externalMediaImportProvider(projectId!).notifier) + .importFiles(files), + ), + ); + ref.onDispose(store.dispose); + return store; +}); + +final class AgentComposerStore { + AgentComposerStore({required this.createComposer}); + final AgentComposerController Function(String?) createComposer; + ComposerDocumentController _draft = ComposerDocumentController(); + ComposerDocumentController get draft => _draft; + final _inputs = <(String?, String), ComposerDocumentController>{}; + final _composers = <(String?, String), AgentComposerController>{}; + + ComposerDocumentController input(String? projectId, String? conversationId) => + conversationId == null + ? draft + : _inputs.putIfAbsent(( + projectId, + conversationId, + ), ComposerDocumentController.new); + + List attachments(String? projectId, String key) => + composer(projectId, key).attachments; + + AgentComposerController composer(String? projectId, String key) => + _composers.putIfAbsent((projectId, key), () => createComposer(projectId)); + + void promoteDraft(String projectId, String draftKey, String conversationId) { + final destination = (projectId, conversationId); + _inputs.remove(destination)?.dispose(); + _inputs[destination] = _draft; + _draft = ComposerDocumentController(); + final composer = _composers.remove((projectId, draftKey)); + if (composer != null) { + _composers.remove(destination)?.dispose(); + _composers[destination] = composer; + } + } + + void removeConversation(String projectId, String conversationId) { + _inputs.remove((projectId, conversationId))?.dispose(); + _composers.remove((projectId, conversationId))?.dispose(); + } + + void removeDraft(String? projectId, String draftKey) { + _composers.remove((projectId, draftKey))?.dispose(); + } + + void dispose() { + draft.dispose(); + for (final input in _inputs.values) { + input.dispose(); + } + _inputs.clear(); + for (final composer in _composers.values) { + composer.dispose(); + } + _composers.clear(); + } +} diff --git a/lib/features/assistant/agent_conversation_service.dart b/lib/features/assistant/agent_conversation_service.dart new file mode 100644 index 0000000..41e9547 --- /dev/null +++ b/lib/features/assistant/agent_conversation_service.dart @@ -0,0 +1,718 @@ +import 'package:cutdex/errors/app_failure.dart'; + +import 'dart:async'; +import 'dart:convert'; + +import 'package:cutdex_agent/cutdex_agent.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:uuid/uuid.dart'; + +import '../../diagnostics/agent_request_diagnostics.dart'; +import '../../diagnostics/app_diagnostics.dart'; +import '../../integrations/agent/agent_prompt_policy.dart'; +import '../../integrations/agent/agent_provider.dart'; +import '../../integrations/agent/agent_runtime_factory.dart'; +import '../../integrations/agent/conversation_repository.dart'; +import '../../integrations/editor_tools.dart'; +import 'agent_message_codec.dart'; +import 'chat_state.dart'; +import 'composer_document.dart'; + +part 'agent_conversation_service.g.dart'; +part 'agent_conversation_service.freezed.dart'; + +enum AgentConversationFailure { + configurationRead, + notConfigured, + contextBudget, + authentication, + connection, + protocol, + request, +} + +class AgentConversationException implements Exception { + const AgentConversationException(this.failure); + final AgentConversationFailure failure; +} + +@freezed +abstract class AgentConversationMessage with _$AgentConversationMessage { + const AgentConversationMessage._(); + + const factory AgentConversationMessage({ + required String text, + required bool isUser, + int? elapsedMs, + }) = _AgentConversationMessage; +} + +@freezed +abstract class AgentConversationHistory with _$AgentConversationHistory { + const factory AgentConversationHistory( + List messages, { + @Default(false) bool exportReplyFailed, + @Default(false) bool recoveryRequired, + @Default(false) bool resumeAvailable, + }) = _AgentConversationHistory; +} + +@freezed +abstract class AgentConversationPreparation + with _$AgentConversationPreparation { + const factory AgentConversationPreparation( + List messages, { + required bool sessionChanged, + }) = _AgentConversationPreparation; +} + +@freezed +abstract class AgentConversationOutcome with _$AgentConversationOutcome { + const AgentConversationOutcome._(); + + const factory AgentConversationOutcome({ + required String response, + required bool completed, + required bool failed, + ConversationMetadata? conversation, + RunFailure? failure, + @Default(false) bool paused, + @Default(false) bool recoveryRequired, + @Default(false) bool exportReplyFailed, + int? elapsedMs, + }) = _AgentConversationOutcome; +} + +@Riverpod(keepAlive: true) +AgentConversationRegistry agentConversationRegistry(Ref ref) { + final registry = AgentConversationRegistry(); + ref.onDispose(registry.dispose); + return registry; +} + +@Riverpod(keepAlive: true) +Future Function(ConversationMetadata?) +agentConversationRuntimeResolver(Ref ref) { + return (item) async { + if (item == null) return ref.read(agentRuntimeProvider.future); + final settings = await ref.read(agentSettingsProvider.future); + return ref + .read(agentRuntimeFactoryProvider) + .createFor( + settings, + providerId: item.providerId, + modelId: item.modelId, + ); + }; +} + +@Riverpod(keepAlive: true) +Future Function(String, String) +agentConversationToolsResolver(Ref ref) { + return (projectId, timelineId) => + createEditorAgentBinding(ref, projectId, timelineId); +} + +class AgentConversationRegistry { + final _services = {}; + bool _paused = false; + bool get hasRunning => _services.values.any((service) => service.busy); + bool get canStart => !_paused; + + Future whilePaused(Future Function() action) async { + if (_paused || hasRunning) { + throw AppException(AppErrorCode.agentLocationBusy); + } + _paused = true; + try { + return await action(); + } finally { + _paused = false; + } + } + + String _key(String projectId, String id) => '$projectId\u0000$id'; + + AgentConversationService obtain( + String projectId, + String key, + String? conversationId, + AgentConversationService Function(void Function(String) published) create, + ) { + final lookup = _key(projectId, conversationId ?? 'draft:$key'); + return _services.putIfAbsent(lookup, () { + late final AgentConversationService service; + service = create((id) => _services[_key(projectId, id)] = service); + return service; + }); + } + + Future cancel(String projectId, String id) async => + _services[_key(projectId, id)]?.cancelAndWait(); + + Future cancelAll() async { + await Future.wait([ + for (final service in _services.values.toSet()) service.cancelAndWait(), + ]); + } + + void dispose() { + for (final service in _services.values.toSet()) { + service.dispose(); + } + _services.clear(); + } +} + +/// Not auto-disposed: switching the visible conversation must not stop a run. +@Riverpod(keepAlive: true) +AgentConversationService agentConversationService( + Ref ref, + String projectId, + String key, + String? conversationId, +) { + return ref + .read(agentConversationRegistryProvider) + .obtain( + projectId, + key, + conversationId, + (published) => AgentConversationService( + projectId: projectId, + conversationId: conversationId, + canStart: () => ref.read(agentConversationRegistryProvider).canStart, + onPublished: published, + loadRepository: () => ref.read(conversationRepositoryProvider.future), + loadRuntime: ref.read(agentConversationRuntimeResolverProvider), + loadTools: (timelineId) => ref.read( + agentConversationToolsResolverProvider, + )(projectId, timelineId), + ), + ); +} + +/// Owns one explicit conversation identity, checkpoint recovery and Agent run. +class AgentConversationService { + AgentConversationService({ + required this.projectId, + required this.conversationId, + required this.loadRepository, + required this.loadRuntime, + required this.loadTools, + this.onPublished, + this.canStart, + }); + + final String projectId; + final String? conversationId; + final Future Function() loadRepository; + final Future Function(ConversationMetadata?) loadRuntime; + final Future Function(String timelineId) loadTools; + final void Function(String id)? onPublished; + final bool Function()? canStart; + final _changes = StreamController.broadcast(); + Stream get changes => _changes.stream; + AgentChatActivity _activity = AgentChatActivity.replying; + AgentChatActivity get activity => _activity; + String _partialResponse = ''; + String get partialResponse => _partialResponse; + bool get busy => _busy; + + void _notify() { + if (!_changes.isClosed) _changes.add(null); + } + + AgentRun? _run; + Completer? _settled; + bool _cancelRequested = false; + bool _disposed = false; + bool _busy = false; + ConversationMetadata? _created; + bool _startingNewConversation = false; + int _identityRevision = 0; + ConversationMetadata? get metadata => _created; + + void startNewConversation() { + if (_busy) throw AppException(AppErrorCode.agentLocationBusy); + _identityRevision++; + _created = null; + _startingNewConversation = true; + _partialResponse = ''; + } + + void _checkActive() { + if (_disposed || _cancelRequested) throw const _PreparationCancelled(); + } + + List _messages( + SessionSnapshot snapshot, { + List responseDurationsMs = const [], + }) { + final history = snapshot.history; + final result = snapshot.completionEvidence?['result']; + final rejectedFinal = result is Map && result['isError'] == true; + final visible = []; + var responseIndex = 0; + for (var i = 0; i < history.length; i++) { + final message = history[i]; + if (message.role == MessageRole.tool || + message.runtimeNotice || + message.text.isEmpty || + (message.role == MessageRole.assistant && + ((i + 1 < history.length && + history[i + 1].runtimeNotice && + history[i + 1].text.startsWith( + '[Runtime artifact verification,', + )) || + (i == history.length - 1 && rejectedFinal)))) { + continue; + } + final isUser = message.role == MessageRole.user; + visible.add( + AgentConversationMessage( + text: message.text, + isUser: isUser, + elapsedMs: isUser || responseIndex >= responseDurationsMs.length + ? null + : responseDurationsMs[responseIndex], + ), + ); + if (!isUser) responseIndex++; + } + return visible; + } + + Future restore() async { + final identityRevision = _identityRevision; + final id = + _created?.id ?? (_startingNewConversation ? null : conversationId); + if (id == null) return null; + try { + final repository = await loadRepository(); + final item = await repository.read(projectId, id); + if (item == null) return null; + final snapshot = await repository.store(item).read(item.id); + if (identityRevision != _identityRevision) return null; + _created = item; + return snapshot == null + ? null + : AgentConversationHistory( + _messages( + snapshot, + responseDurationsMs: item.responseDurationsMs, + ), + exportReplyFailed: _exportReplyFailed(snapshot), + resumeAvailable: + !_busy && + (snapshot.pending.isNotEmpty || + snapshot.status == RunStatus.running || + snapshot.status == RunStatus.paused), + recoveryRequired: + !_busy && + (snapshot.status == RunStatus.waiting || + snapshot.pending.any( + (call) => call.status == CallStatus.started, + )), + ); + } catch (_) { + throw const AgentConversationException(AgentConversationFailure.request); + } + } + + Future send( + String text, { + required String timelineId, + bool summaryOnly = false, + bool resumeOnly = false, + required void Function(AgentConversationPreparation value) onPrepared, + required void Function(String text) onTextDelta, + void Function(ConversationMetadata value)? onCreated, + }) { + final requestId = const Uuid().v4(); + return withDiagnosticContext( + { + 'requestId': requestId, + 'projectId': projectId, + 'timelineId': timelineId, + }, + () => _send( + text, + requestId: requestId, + timelineId: timelineId, + summaryOnly: summaryOnly, + resumeOnly: resumeOnly, + onPrepared: onPrepared, + onTextDelta: onTextDelta, + onCreated: onCreated, + ), + ); + } + + Future _send( + String text, { + required String requestId, + required String timelineId, + bool summaryOnly = false, + bool resumeOnly = false, + required void Function(AgentConversationPreparation value) onPrepared, + required void Function(String text) onTextDelta, + void Function(ConversationMetadata value)? onCreated, + }) async { + if (canStart?.call() == false) { + throw const AgentConversationException(AgentConversationFailure.request); + } + if (_busy) throw AppException(AppErrorCode.agentLocationBusy); + _busy = true; + _activity = AgentChatActivity.replying; + _settled = Completer(); + _cancelRequested = false; + _partialResponse = ''; + _notify(); + final elapsed = Stopwatch()..start(); + final diagnostics = AgentRequestDiagnostics(requestId: requestId); + AgentRun? measuredRun; + StreamSubscription? subscription; + EditorAgentBinding? binding; + ConversationRepository? repository; + ConversationMetadata? item; + try { + binding = summaryOnly + // Each run needs a distinct ownership token. + // ignore: prefer_const_constructors + ? EditorAgentBinding(owner: Object(), tools: const []) + : await loadTools(timelineId); + _checkActive(); + if (!summaryOnly) { + final references = AgentComposerMessage.decode(text).references; + for (final reference in references) { + if (reference.kind == ComposerReferenceKind.timeline && + reference.projectId == projectId) { + await binding.ensureTimeline?.call(reference.id); + _checkActive(); + } + } + } + repository = await loadRepository(); + _checkActive(); + final savedId = + _created?.id ?? (_startingNewConversation ? null : conversationId); + item = savedId == null ? null : await repository.read(projectId, savedId); + if ((savedId != null || summaryOnly || resumeOnly) && item == null) { + throw const AgentConversationException( + AgentConversationFailure.request, + ); + } + final AgentRuntime? runtime; + try { + runtime = await loadRuntime(item); + } catch (_) { + throw const AgentConversationException( + AgentConversationFailure.configurationRead, + ); + } + _checkActive(); + if (runtime == null) { + throw const AgentConversationException( + AgentConversationFailure.notConfigured, + ); + } + final system = summaryOnly + ? _summaryOnlyInstruction + : AgentPromptPolicy.forTimeline(projectId, timelineId); + final runTools = summaryOnly ? [] : binding.tools; + // Check the mandatory payload before committing a new user turn. + try { + await runtime.contextBuilder.build( + system: system, + history: [AgentMessage(role: MessageRole.user, text: text)], + tools: [ + ...runTools, + ...runtime.contextBuilder.runtimeTools( + () => SessionSnapshot(id: 'preflight'), + runTools, + ), + ], + cancellation: CancellationToken(), + ); + } on ContextOverflow { + throw const AgentConversationException( + AgentConversationFailure.contextBudget, + ); + } + _checkActive(); + item ??= await repository.begin( + projectId: projectId, + timelineId: timelineId, + providerId: runtime.providerId ?? runtime.sessionIdentity, + modelId: runtime.modelId ?? runtime.sessionIdentity, + title: () { + final prompt = AgentComposerMessage.decode(text); + final visible = prompt.text.isNotEmpty + ? prompt.text + : prompt.attachments.firstOrNull?.name ?? text; + return visible.length <= 64 + ? visible + : '${visible.substring(0, 64)}…'; + }(), + ); + _created = item; + final store = repository.store(item); + final manager = SessionManager( + model: runtime.model, + store: store, + tools: runTools, + contextBuilder: runtime.contextBuilder, + completionCheck: summaryOnly ? null : binding.completionCheck, + ); + var snapshot = await store.read(item.id); + _checkActive(); + snapshot ??= await manager.create(id: item.id, system: system); + _checkActive(); + if (summaryOnly && + (!_exportReplyFailed(snapshot) || + snapshot.pending.isNotEmpty || + snapshot.queued.isNotEmpty)) { + throw const AgentConversationException( + AgentConversationFailure.request, + ); + } + final unfinished = + snapshot.pending.isNotEmpty || + snapshot.queued.isNotEmpty || + snapshot.status == RunStatus.running || + snapshot.status == RunStatus.waiting || + snapshot.status == RunStatus.paused; + if (resumeOnly && !unfinished) { + throw const AgentConversationException( + AgentConversationFailure.request, + ); + } + onPrepared( + AgentConversationPreparation( + _messages(snapshot, responseDurationsMs: item.responseDurationsMs), + sessionChanged: conversationId == null || _startingNewConversation, + ), + ); + if (!resumeOnly && unfinished) { + return AgentConversationOutcome( + response: '', + completed: false, + failed: true, + recoveryRequired: true, + conversation: item, + ); + } + final run = resumeOnly + ? await manager.resume(item.id, maxTurns: snapshot.turns + 80) + : await manager.prompt(item.id, text, system: system, maxTurns: 80); + _run = run; + measuredRun = run; + diagnostics.prepared(); + _activity = run.phase == AgentRunPhase.compacting + ? AgentChatActivity.compacting + : AgentChatActivity.replying; + _notify(); + subscription = run.events.listen((event) { + if (_disposed) return; + if (event.kind == AgentEventKind.phase) { + _activity = event.text == AgentRunPhase.compacting.name + ? AgentChatActivity.compacting + : AgentChatActivity.replying; + _notify(); + } else if (event.kind == AgentEventKind.toolStarted) { + _activity = + event.text.endsWith('_query') || + event.text.endsWith('_list') || + event.text == 'cutdex_workspaces' || + event.text == 'completion_check' + ? AgentChatActivity.verifying + : AgentChatActivity.editing; + _notify(); + } + if (!_disposed && event.kind == AgentEventKind.textDelta) { + _activity = AgentChatActivity.replying; + _partialResponse += event.text; + _notify(); + onTextDelta(event.text); + } + }); + if (item.pending) { + item = await repository.publish(item); + _created = item; + onPublished?.call(item.id); + onCreated?.call(item); + } + if (_cancelRequested || _disposed) unawaited(run.cancel()); + final result = await run.done; + diagnostics.outcome = result.status.name; + if (result.status == RunStatus.failed || + result.status == RunStatus.waiting) { + reportDiagnostic( + AppDiagnostics.report, + DiagnosticEvent( + component: 'agent', + operation: 'run', + error: StateError( + 'Agent run ${result.status.name}: ${result.failure?.name ?? 'request'}', + ), + context: {'failure': result.failure?.name}, + ), + ); + } + final completed = + result.status == RunStatus.completed && !_cancelRequested; + final response = + completed && result.history.last.role == MessageRole.assistant + ? result.history.last.text + : ''; + final responseIndex = + _messages(result).where((message) => !message.isUser).length - 1; + final elapsedMs = completed && response.isNotEmpty + ? elapsed.elapsedMilliseconds + : null; + final responseDurationsMs = [...item.responseDurationsMs]; + if (elapsedMs != null && responseIndex >= 0) { + while (responseDurationsMs.length <= responseIndex) { + responseDurationsMs.add(null); + } + responseDurationsMs[responseIndex] = elapsedMs; + } + item = await repository.update( + item.copyWith( + timelineId: timelineId, + responseDurationsMs: responseDurationsMs, + ), + ); + _created = item; + _partialResponse = ''; + _notify(); + return AgentConversationOutcome( + response: response, + completed: completed, + failed: + result.status == RunStatus.failed || + result.status == RunStatus.waiting, + conversation: item, + paused: result.status == RunStatus.paused && !_cancelRequested, + recoveryRequired: result.status == RunStatus.waiting, + failure: result.failure, + exportReplyFailed: _exportReplyFailed(result), + elapsedMs: elapsedMs, + ); + } on _PreparationCancelled { + diagnostics.outcome = 'cancelled'; + return AgentConversationOutcome( + response: '', + completed: false, + failed: false, + conversation: item, + ); + } on AgentConversationException catch (error, stack) { + AppDiagnostics.failure('agent', 'send', error, stack); + rethrow; + } catch (error, stack) { + AppDiagnostics.failure('agent', 'send', error, stack); + if (repository != null && item != null && item.pending) { + try { + final published = await repository.publish(item); + _created = published; + onPublished?.call(published.id); + onCreated?.call(published); + } catch (_) { + // No user message committed; startup recovery ignores this draft. + } + } + throw const AgentConversationException(AgentConversationFailure.request); + } finally { + if (measuredRun != null) { + diagnostics.runs.add(measuredRun.diagnostics.toJson()); + } + final report = diagnostics.stop(); + reportDiagnostic( + AppDiagnostics.report, + DiagnosticEvent( + component: 'agent', + operation: 'requestFinished', + level: DiagnosticSeverity.info, + context: {'outcome': report.outcome, 'elapsedUs': report.elapsedUs}, + ), + ); + unawaited( + AppDiagnostics.instance?.request(report, requestId) ?? + Future.value(), + ); + if (repository != null) { + await AgentRequestDiagnostics.persist(repository.root, report); + } + _run = null; + _busy = false; + _notify(); + try { + await subscription?.cancel(); + await binding?.release?.call(); + } finally { + _settled?.complete(); + _settled = null; + } + } + } + + Future cancel() async { + _cancelRequested = true; + final run = _run; + if (run != null) { + await run.cancel(); + await _settled?.future; + } + } + + Future cancelAndWait() async { + await cancel(); + await _settled?.future; + } + + void dispose() { + _disposed = true; + unawaited(cancel()); + unawaited(_changes.close()); + } +} + +class _PreparationCancelled implements Exception { + const _PreparationCancelled(); +} + +const _summaryOnlyInstruction = + 'Summarize the already completed export and edits from successful tool results. No tools are available. Never claim a new edit or export occurred. State the saved destination and confirmed results in the user language.'; + +bool _exportReplyFailed(SessionSnapshot snapshot) { + if (snapshot.status != RunStatus.failed || + snapshot.pending.isNotEmpty || + snapshot.queued.isNotEmpty) { + return false; + } + final start = snapshot.system == _summaryOnlyInstruction + ? 0 + : snapshot.runStart; + final history = snapshot.history.skip(start).toList(); + final tool = history.where((m) => m.role == MessageRole.tool).lastOrNull; + if (tool == null || tool.isError) return false; + final calls = history.expand((m) => m.calls); + if (!calls.any((c) => c.id == tool.callId && c.name == 'project_export')) { + return false; + } + try { + final result = jsonDecode(tool.text) as Map; + final data = result['data'] as Map; + return result['isError'] != true && + data['status'] == 'succeeded' && + (data['data'] as Map)['destination'] is String; + } on FormatException { + return false; + } on TypeError { + return false; + } +} diff --git a/lib/features/assistant/agent_conversation_service.freezed.dart b/lib/features/assistant/agent_conversation_service.freezed.dart new file mode 100644 index 0000000..6c2c5b8 --- /dev/null +++ b/lib/features/assistant/agent_conversation_service.freezed.dart @@ -0,0 +1,1723 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'agent_conversation_service.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +T _$identity(T value) => value; + +/// @nodoc +mixin _$AgentConversationMessage { + String get text; + bool get isUser; + int? get elapsedMs; + + /// Create a copy of AgentConversationMessage + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $AgentConversationMessageCopyWith get copyWith => + _$AgentConversationMessageCopyWithImpl( + this as AgentConversationMessage, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as AgentConversationMessage; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is AgentConversationMessage && + (identical(other.text, _this.text) || other.text == _this.text) && + (identical(other.isUser, _this.isUser) || + other.isUser == _this.isUser) && + (identical(other.elapsedMs, _this.elapsedMs) || + other.elapsedMs == _this.elapsedMs)); + } + + @override + int get hashCode { + final _this = this as AgentConversationMessage; + return Object.hash(runtimeType, _this.text, _this.isUser, _this.elapsedMs); + } + + @override + String toString() { + final _this = this as AgentConversationMessage; + return 'AgentConversationMessage(text: ${_this.text}, isUser: ${_this.isUser}, elapsedMs: ${_this.elapsedMs})'; + } +} + +/// @nodoc +abstract mixin class $AgentConversationMessageCopyWith<$Res> { + factory $AgentConversationMessageCopyWith( + AgentConversationMessage value, + $Res Function(AgentConversationMessage) _then, + ) = _$AgentConversationMessageCopyWithImpl; + @useResult + $Res call({String text, bool isUser, int? elapsedMs}); +} + +/// @nodoc +class _$AgentConversationMessageCopyWithImpl<$Res> + implements $AgentConversationMessageCopyWith<$Res> { + _$AgentConversationMessageCopyWithImpl(this._self, this._then); + + final AgentConversationMessage _self; + final $Res Function(AgentConversationMessage) _then; + + /// Create a copy of AgentConversationMessage + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? text = null, + Object? isUser = null, + Object? elapsedMs = freezed, + }) { + return _then( + AgentConversationMessage( + text: null == text + ? _self.text + : text // ignore: cast_nullable_to_non_nullable + as String, + isUser: null == isUser + ? _self.isUser + : isUser // ignore: cast_nullable_to_non_nullable + as bool, + elapsedMs: freezed == elapsedMs + ? _self.elapsedMs + : elapsedMs // ignore: cast_nullable_to_non_nullable + as int?, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [AgentConversationMessage]. +extension AgentConversationMessagePatterns on AgentConversationMessage { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_AgentConversationMessage value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _AgentConversationMessage() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_AgentConversationMessage value) $default, + ) { + final _that = this; + switch (_that) { + case _AgentConversationMessage(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_AgentConversationMessage value)? $default, + ) { + final _that = this; + switch (_that) { + case _AgentConversationMessage() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function(String text, bool isUser, int? elapsedMs)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _AgentConversationMessage() when $default != null: + return $default(_that.text, _that.isUser, _that.elapsedMs); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function(String text, bool isUser, int? elapsedMs) $default, + ) { + final _that = this; + switch (_that) { + case _AgentConversationMessage(): + return $default(_that.text, _that.isUser, _that.elapsedMs); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function(String text, bool isUser, int? elapsedMs)? $default, + ) { + final _that = this; + switch (_that) { + case _AgentConversationMessage() when $default != null: + return $default(_that.text, _that.isUser, _that.elapsedMs); + case _: + return null; + } + } +} + +/// @nodoc + +class _AgentConversationMessage extends AgentConversationMessage { + const _AgentConversationMessage({ + required this.text, + required this.isUser, + this.elapsedMs, + }) : super._(); + + @override + final String text; + @override + final bool isUser; + @override + final int? elapsedMs; + + /// Create a copy of AgentConversationMessage + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$AgentConversationMessageCopyWith<_AgentConversationMessage> get copyWith => + __$AgentConversationMessageCopyWithImpl<_AgentConversationMessage>( + this, + _$identity, + ); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _AgentConversationMessage && + (identical(other.text, text) || other.text == text) && + (identical(other.isUser, isUser) || other.isUser == isUser) && + (identical(other.elapsedMs, elapsedMs) || + other.elapsedMs == elapsedMs)); + } + + @override + int get hashCode { + return Object.hash(runtimeType, text, isUser, elapsedMs); + } + + @override + String toString() { + return 'AgentConversationMessage(text: $text, isUser: $isUser, elapsedMs: $elapsedMs)'; + } +} + +/// @nodoc +abstract mixin class _$AgentConversationMessageCopyWith<$Res> + implements $AgentConversationMessageCopyWith<$Res> { + factory _$AgentConversationMessageCopyWith( + _AgentConversationMessage value, + $Res Function(_AgentConversationMessage) _then, + ) = __$AgentConversationMessageCopyWithImpl; + @override + @useResult + $Res call({String text, bool isUser, int? elapsedMs}); +} + +/// @nodoc +class __$AgentConversationMessageCopyWithImpl<$Res> + implements _$AgentConversationMessageCopyWith<$Res> { + __$AgentConversationMessageCopyWithImpl(this._self, this._then); + + final _AgentConversationMessage _self; + final $Res Function(_AgentConversationMessage) _then; + + /// Create a copy of AgentConversationMessage + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? text = null, + Object? isUser = null, + Object? elapsedMs = freezed, + }) { + return _then( + _AgentConversationMessage( + text: null == text + ? _self.text + : text // ignore: cast_nullable_to_non_nullable + as String, + isUser: null == isUser + ? _self.isUser + : isUser // ignore: cast_nullable_to_non_nullable + as bool, + elapsedMs: freezed == elapsedMs + ? _self.elapsedMs + : elapsedMs // ignore: cast_nullable_to_non_nullable + as int?, + ), + ); + } +} + +/// @nodoc +mixin _$AgentConversationHistory { + List get messages; + bool get exportReplyFailed; + bool get recoveryRequired; + bool get resumeAvailable; + + /// Create a copy of AgentConversationHistory + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $AgentConversationHistoryCopyWith get copyWith => + _$AgentConversationHistoryCopyWithImpl( + this as AgentConversationHistory, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as AgentConversationHistory; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is AgentConversationHistory && + const DeepCollectionEquality().equals( + other.messages, + _this.messages, + ) && + (identical(other.exportReplyFailed, _this.exportReplyFailed) || + other.exportReplyFailed == _this.exportReplyFailed) && + (identical(other.recoveryRequired, _this.recoveryRequired) || + other.recoveryRequired == _this.recoveryRequired) && + (identical(other.resumeAvailable, _this.resumeAvailable) || + other.resumeAvailable == _this.resumeAvailable)); + } + + @override + int get hashCode { + final _this = this as AgentConversationHistory; + return Object.hash( + runtimeType, + const DeepCollectionEquality().hash(_this.messages), + _this.exportReplyFailed, + _this.recoveryRequired, + _this.resumeAvailable, + ); + } + + @override + String toString() { + final _this = this as AgentConversationHistory; + return 'AgentConversationHistory(messages: ${_this.messages}, exportReplyFailed: ${_this.exportReplyFailed}, recoveryRequired: ${_this.recoveryRequired}, resumeAvailable: ${_this.resumeAvailable})'; + } +} + +/// @nodoc +abstract mixin class $AgentConversationHistoryCopyWith<$Res> { + factory $AgentConversationHistoryCopyWith( + AgentConversationHistory value, + $Res Function(AgentConversationHistory) _then, + ) = _$AgentConversationHistoryCopyWithImpl; + @useResult + $Res call({ + List messages, + bool exportReplyFailed, + bool recoveryRequired, + bool resumeAvailable, + }); +} + +/// @nodoc +class _$AgentConversationHistoryCopyWithImpl<$Res> + implements $AgentConversationHistoryCopyWith<$Res> { + _$AgentConversationHistoryCopyWithImpl(this._self, this._then); + + final AgentConversationHistory _self; + final $Res Function(AgentConversationHistory) _then; + + /// Create a copy of AgentConversationHistory + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? messages = null, + Object? exportReplyFailed = null, + Object? recoveryRequired = null, + Object? resumeAvailable = null, + }) { + return _then( + AgentConversationHistory( + null == messages + ? _self.messages + : messages // ignore: cast_nullable_to_non_nullable + as List, + exportReplyFailed: null == exportReplyFailed + ? _self.exportReplyFailed + : exportReplyFailed // ignore: cast_nullable_to_non_nullable + as bool, + recoveryRequired: null == recoveryRequired + ? _self.recoveryRequired + : recoveryRequired // ignore: cast_nullable_to_non_nullable + as bool, + resumeAvailable: null == resumeAvailable + ? _self.resumeAvailable + : resumeAvailable // ignore: cast_nullable_to_non_nullable + as bool, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [AgentConversationHistory]. +extension AgentConversationHistoryPatterns on AgentConversationHistory { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_AgentConversationHistory value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _AgentConversationHistory() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_AgentConversationHistory value) $default, + ) { + final _that = this; + switch (_that) { + case _AgentConversationHistory(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_AgentConversationHistory value)? $default, + ) { + final _that = this; + switch (_that) { + case _AgentConversationHistory() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + List messages, + bool exportReplyFailed, + bool recoveryRequired, + bool resumeAvailable, + )? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _AgentConversationHistory() when $default != null: + return $default( + _that.messages, + _that.exportReplyFailed, + _that.recoveryRequired, + _that.resumeAvailable, + ); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function( + List messages, + bool exportReplyFailed, + bool recoveryRequired, + bool resumeAvailable, + ) + $default, + ) { + final _that = this; + switch (_that) { + case _AgentConversationHistory(): + return $default( + _that.messages, + _that.exportReplyFailed, + _that.recoveryRequired, + _that.resumeAvailable, + ); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + List messages, + bool exportReplyFailed, + bool recoveryRequired, + bool resumeAvailable, + )? + $default, + ) { + final _that = this; + switch (_that) { + case _AgentConversationHistory() when $default != null: + return $default( + _that.messages, + _that.exportReplyFailed, + _that.recoveryRequired, + _that.resumeAvailable, + ); + case _: + return null; + } + } +} + +/// @nodoc + +class _AgentConversationHistory implements AgentConversationHistory { + const _AgentConversationHistory( + List messages, { + this.exportReplyFailed = false, + this.recoveryRequired = false, + this.resumeAvailable = false, + }) : _messages = messages; + + final List _messages; + @override + List get messages { + if (_messages is EqualUnmodifiableListView) return _messages; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_messages); + } + + @override + @JsonKey() + final bool exportReplyFailed; + @override + @JsonKey() + final bool recoveryRequired; + @override + @JsonKey() + final bool resumeAvailable; + + /// Create a copy of AgentConversationHistory + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$AgentConversationHistoryCopyWith<_AgentConversationHistory> get copyWith => + __$AgentConversationHistoryCopyWithImpl<_AgentConversationHistory>( + this, + _$identity, + ); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _AgentConversationHistory && + const DeepCollectionEquality().equals(other.messages, _messages) && + (identical(other.exportReplyFailed, exportReplyFailed) || + other.exportReplyFailed == exportReplyFailed) && + (identical(other.recoveryRequired, recoveryRequired) || + other.recoveryRequired == recoveryRequired) && + (identical(other.resumeAvailable, resumeAvailable) || + other.resumeAvailable == resumeAvailable)); + } + + @override + int get hashCode { + return Object.hash( + runtimeType, + const DeepCollectionEquality().hash(_messages), + exportReplyFailed, + recoveryRequired, + resumeAvailable, + ); + } + + @override + String toString() { + return 'AgentConversationHistory(messages: $messages, exportReplyFailed: $exportReplyFailed, recoveryRequired: $recoveryRequired, resumeAvailable: $resumeAvailable)'; + } +} + +/// @nodoc +abstract mixin class _$AgentConversationHistoryCopyWith<$Res> + implements $AgentConversationHistoryCopyWith<$Res> { + factory _$AgentConversationHistoryCopyWith( + _AgentConversationHistory value, + $Res Function(_AgentConversationHistory) _then, + ) = __$AgentConversationHistoryCopyWithImpl; + @override + @useResult + $Res call({ + List messages, + bool exportReplyFailed, + bool recoveryRequired, + bool resumeAvailable, + }); +} + +/// @nodoc +class __$AgentConversationHistoryCopyWithImpl<$Res> + implements _$AgentConversationHistoryCopyWith<$Res> { + __$AgentConversationHistoryCopyWithImpl(this._self, this._then); + + final _AgentConversationHistory _self; + final $Res Function(_AgentConversationHistory) _then; + + /// Create a copy of AgentConversationHistory + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? messages = null, + Object? exportReplyFailed = null, + Object? recoveryRequired = null, + Object? resumeAvailable = null, + }) { + return _then( + _AgentConversationHistory( + null == messages + ? _self._messages + : messages // ignore: cast_nullable_to_non_nullable + as List, + exportReplyFailed: null == exportReplyFailed + ? _self.exportReplyFailed + : exportReplyFailed // ignore: cast_nullable_to_non_nullable + as bool, + recoveryRequired: null == recoveryRequired + ? _self.recoveryRequired + : recoveryRequired // ignore: cast_nullable_to_non_nullable + as bool, + resumeAvailable: null == resumeAvailable + ? _self.resumeAvailable + : resumeAvailable // ignore: cast_nullable_to_non_nullable + as bool, + ), + ); + } +} + +/// @nodoc +mixin _$AgentConversationPreparation { + List get messages; + bool get sessionChanged; + + /// Create a copy of AgentConversationPreparation + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $AgentConversationPreparationCopyWith + get copyWith => + _$AgentConversationPreparationCopyWithImpl( + this as AgentConversationPreparation, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as AgentConversationPreparation; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is AgentConversationPreparation && + const DeepCollectionEquality().equals( + other.messages, + _this.messages, + ) && + (identical(other.sessionChanged, _this.sessionChanged) || + other.sessionChanged == _this.sessionChanged)); + } + + @override + int get hashCode { + final _this = this as AgentConversationPreparation; + return Object.hash( + runtimeType, + const DeepCollectionEquality().hash(_this.messages), + _this.sessionChanged, + ); + } + + @override + String toString() { + final _this = this as AgentConversationPreparation; + return 'AgentConversationPreparation(messages: ${_this.messages}, sessionChanged: ${_this.sessionChanged})'; + } +} + +/// @nodoc +abstract mixin class $AgentConversationPreparationCopyWith<$Res> { + factory $AgentConversationPreparationCopyWith( + AgentConversationPreparation value, + $Res Function(AgentConversationPreparation) _then, + ) = _$AgentConversationPreparationCopyWithImpl; + @useResult + $Res call({List messages, bool sessionChanged}); +} + +/// @nodoc +class _$AgentConversationPreparationCopyWithImpl<$Res> + implements $AgentConversationPreparationCopyWith<$Res> { + _$AgentConversationPreparationCopyWithImpl(this._self, this._then); + + final AgentConversationPreparation _self; + final $Res Function(AgentConversationPreparation) _then; + + /// Create a copy of AgentConversationPreparation + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({Object? messages = null, Object? sessionChanged = null}) { + return _then( + AgentConversationPreparation( + null == messages + ? _self.messages + : messages // ignore: cast_nullable_to_non_nullable + as List, + sessionChanged: null == sessionChanged + ? _self.sessionChanged + : sessionChanged // ignore: cast_nullable_to_non_nullable + as bool, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [AgentConversationPreparation]. +extension AgentConversationPreparationPatterns on AgentConversationPreparation { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_AgentConversationPreparation value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _AgentConversationPreparation() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_AgentConversationPreparation value) $default, + ) { + final _that = this; + switch (_that) { + case _AgentConversationPreparation(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_AgentConversationPreparation value)? $default, + ) { + final _that = this; + switch (_that) { + case _AgentConversationPreparation() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + List messages, + bool sessionChanged, + )? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _AgentConversationPreparation() when $default != null: + return $default(_that.messages, _that.sessionChanged); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function( + List messages, + bool sessionChanged, + ) + $default, + ) { + final _that = this; + switch (_that) { + case _AgentConversationPreparation(): + return $default(_that.messages, _that.sessionChanged); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + List messages, + bool sessionChanged, + )? + $default, + ) { + final _that = this; + switch (_that) { + case _AgentConversationPreparation() when $default != null: + return $default(_that.messages, _that.sessionChanged); + case _: + return null; + } + } +} + +/// @nodoc + +class _AgentConversationPreparation implements AgentConversationPreparation { + const _AgentConversationPreparation( + List messages, { + required this.sessionChanged, + }) : _messages = messages; + + final List _messages; + @override + List get messages { + if (_messages is EqualUnmodifiableListView) return _messages; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_messages); + } + + @override + final bool sessionChanged; + + /// Create a copy of AgentConversationPreparation + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$AgentConversationPreparationCopyWith<_AgentConversationPreparation> + get copyWith => + __$AgentConversationPreparationCopyWithImpl< + _AgentConversationPreparation + >(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _AgentConversationPreparation && + const DeepCollectionEquality().equals(other.messages, _messages) && + (identical(other.sessionChanged, sessionChanged) || + other.sessionChanged == sessionChanged)); + } + + @override + int get hashCode { + return Object.hash( + runtimeType, + const DeepCollectionEquality().hash(_messages), + sessionChanged, + ); + } + + @override + String toString() { + return 'AgentConversationPreparation(messages: $messages, sessionChanged: $sessionChanged)'; + } +} + +/// @nodoc +abstract mixin class _$AgentConversationPreparationCopyWith<$Res> + implements $AgentConversationPreparationCopyWith<$Res> { + factory _$AgentConversationPreparationCopyWith( + _AgentConversationPreparation value, + $Res Function(_AgentConversationPreparation) _then, + ) = __$AgentConversationPreparationCopyWithImpl; + @override + @useResult + $Res call({List messages, bool sessionChanged}); +} + +/// @nodoc +class __$AgentConversationPreparationCopyWithImpl<$Res> + implements _$AgentConversationPreparationCopyWith<$Res> { + __$AgentConversationPreparationCopyWithImpl(this._self, this._then); + + final _AgentConversationPreparation _self; + final $Res Function(_AgentConversationPreparation) _then; + + /// Create a copy of AgentConversationPreparation + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({Object? messages = null, Object? sessionChanged = null}) { + return _then( + _AgentConversationPreparation( + null == messages + ? _self._messages + : messages // ignore: cast_nullable_to_non_nullable + as List, + sessionChanged: null == sessionChanged + ? _self.sessionChanged + : sessionChanged // ignore: cast_nullable_to_non_nullable + as bool, + ), + ); + } +} + +/// @nodoc +mixin _$AgentConversationOutcome { + String get response; + bool get completed; + bool get failed; + ConversationMetadata? get conversation; + RunFailure? get failure; + bool get paused; + bool get recoveryRequired; + bool get exportReplyFailed; + int? get elapsedMs; + + /// Create a copy of AgentConversationOutcome + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $AgentConversationOutcomeCopyWith get copyWith => + _$AgentConversationOutcomeCopyWithImpl( + this as AgentConversationOutcome, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as AgentConversationOutcome; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is AgentConversationOutcome && + (identical(other.response, _this.response) || + other.response == _this.response) && + (identical(other.completed, _this.completed) || + other.completed == _this.completed) && + (identical(other.failed, _this.failed) || + other.failed == _this.failed) && + (identical(other.conversation, _this.conversation) || + other.conversation == _this.conversation) && + (identical(other.failure, _this.failure) || + other.failure == _this.failure) && + (identical(other.paused, _this.paused) || + other.paused == _this.paused) && + (identical(other.recoveryRequired, _this.recoveryRequired) || + other.recoveryRequired == _this.recoveryRequired) && + (identical(other.exportReplyFailed, _this.exportReplyFailed) || + other.exportReplyFailed == _this.exportReplyFailed) && + (identical(other.elapsedMs, _this.elapsedMs) || + other.elapsedMs == _this.elapsedMs)); + } + + @override + int get hashCode { + final _this = this as AgentConversationOutcome; + return Object.hash( + runtimeType, + _this.response, + _this.completed, + _this.failed, + _this.conversation, + _this.failure, + _this.paused, + _this.recoveryRequired, + _this.exportReplyFailed, + _this.elapsedMs, + ); + } + + @override + String toString() { + final _this = this as AgentConversationOutcome; + return 'AgentConversationOutcome(response: ${_this.response}, completed: ${_this.completed}, failed: ${_this.failed}, conversation: ${_this.conversation}, failure: ${_this.failure}, paused: ${_this.paused}, recoveryRequired: ${_this.recoveryRequired}, exportReplyFailed: ${_this.exportReplyFailed}, elapsedMs: ${_this.elapsedMs})'; + } +} + +/// @nodoc +abstract mixin class $AgentConversationOutcomeCopyWith<$Res> { + factory $AgentConversationOutcomeCopyWith( + AgentConversationOutcome value, + $Res Function(AgentConversationOutcome) _then, + ) = _$AgentConversationOutcomeCopyWithImpl; + @useResult + $Res call({ + String response, + bool completed, + bool failed, + ConversationMetadata? conversation, + RunFailure? failure, + bool paused, + bool recoveryRequired, + bool exportReplyFailed, + int? elapsedMs, + }); + + $ConversationMetadataCopyWith<$Res>? get conversation; +} + +/// @nodoc +class _$AgentConversationOutcomeCopyWithImpl<$Res> + implements $AgentConversationOutcomeCopyWith<$Res> { + _$AgentConversationOutcomeCopyWithImpl(this._self, this._then); + + final AgentConversationOutcome _self; + final $Res Function(AgentConversationOutcome) _then; + + /// Create a copy of AgentConversationOutcome + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? response = null, + Object? completed = null, + Object? failed = null, + Object? conversation = freezed, + Object? failure = freezed, + Object? paused = null, + Object? recoveryRequired = null, + Object? exportReplyFailed = null, + Object? elapsedMs = freezed, + }) { + return _then( + AgentConversationOutcome( + response: null == response + ? _self.response + : response // ignore: cast_nullable_to_non_nullable + as String, + completed: null == completed + ? _self.completed + : completed // ignore: cast_nullable_to_non_nullable + as bool, + failed: null == failed + ? _self.failed + : failed // ignore: cast_nullable_to_non_nullable + as bool, + conversation: freezed == conversation + ? _self.conversation + : conversation // ignore: cast_nullable_to_non_nullable + as ConversationMetadata?, + failure: freezed == failure + ? _self.failure + : failure // ignore: cast_nullable_to_non_nullable + as RunFailure?, + paused: null == paused + ? _self.paused + : paused // ignore: cast_nullable_to_non_nullable + as bool, + recoveryRequired: null == recoveryRequired + ? _self.recoveryRequired + : recoveryRequired // ignore: cast_nullable_to_non_nullable + as bool, + exportReplyFailed: null == exportReplyFailed + ? _self.exportReplyFailed + : exportReplyFailed // ignore: cast_nullable_to_non_nullable + as bool, + elapsedMs: freezed == elapsedMs + ? _self.elapsedMs + : elapsedMs // ignore: cast_nullable_to_non_nullable + as int?, + ), + ); + } + + /// Create a copy of AgentConversationOutcome + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $ConversationMetadataCopyWith<$Res>? get conversation { + if (_self.conversation == null) { + return null; + } + + return $ConversationMetadataCopyWith<$Res>(_self.conversation!, (value) { + return _then(_self.copyWith(conversation: value)); + }); + } +} + +/// Adds pattern-matching-related methods to [AgentConversationOutcome]. +extension AgentConversationOutcomePatterns on AgentConversationOutcome { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_AgentConversationOutcome value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _AgentConversationOutcome() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_AgentConversationOutcome value) $default, + ) { + final _that = this; + switch (_that) { + case _AgentConversationOutcome(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_AgentConversationOutcome value)? $default, + ) { + final _that = this; + switch (_that) { + case _AgentConversationOutcome() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + String response, + bool completed, + bool failed, + ConversationMetadata? conversation, + RunFailure? failure, + bool paused, + bool recoveryRequired, + bool exportReplyFailed, + int? elapsedMs, + )? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _AgentConversationOutcome() when $default != null: + return $default( + _that.response, + _that.completed, + _that.failed, + _that.conversation, + _that.failure, + _that.paused, + _that.recoveryRequired, + _that.exportReplyFailed, + _that.elapsedMs, + ); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function( + String response, + bool completed, + bool failed, + ConversationMetadata? conversation, + RunFailure? failure, + bool paused, + bool recoveryRequired, + bool exportReplyFailed, + int? elapsedMs, + ) + $default, + ) { + final _that = this; + switch (_that) { + case _AgentConversationOutcome(): + return $default( + _that.response, + _that.completed, + _that.failed, + _that.conversation, + _that.failure, + _that.paused, + _that.recoveryRequired, + _that.exportReplyFailed, + _that.elapsedMs, + ); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + String response, + bool completed, + bool failed, + ConversationMetadata? conversation, + RunFailure? failure, + bool paused, + bool recoveryRequired, + bool exportReplyFailed, + int? elapsedMs, + )? + $default, + ) { + final _that = this; + switch (_that) { + case _AgentConversationOutcome() when $default != null: + return $default( + _that.response, + _that.completed, + _that.failed, + _that.conversation, + _that.failure, + _that.paused, + _that.recoveryRequired, + _that.exportReplyFailed, + _that.elapsedMs, + ); + case _: + return null; + } + } +} + +/// @nodoc + +class _AgentConversationOutcome extends AgentConversationOutcome { + const _AgentConversationOutcome({ + required this.response, + required this.completed, + required this.failed, + this.conversation, + this.failure, + this.paused = false, + this.recoveryRequired = false, + this.exportReplyFailed = false, + this.elapsedMs, + }) : super._(); + + @override + final String response; + @override + final bool completed; + @override + final bool failed; + @override + final ConversationMetadata? conversation; + @override + final RunFailure? failure; + @override + @JsonKey() + final bool paused; + @override + @JsonKey() + final bool recoveryRequired; + @override + @JsonKey() + final bool exportReplyFailed; + @override + final int? elapsedMs; + + /// Create a copy of AgentConversationOutcome + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$AgentConversationOutcomeCopyWith<_AgentConversationOutcome> get copyWith => + __$AgentConversationOutcomeCopyWithImpl<_AgentConversationOutcome>( + this, + _$identity, + ); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _AgentConversationOutcome && + (identical(other.response, response) || + other.response == response) && + (identical(other.completed, completed) || + other.completed == completed) && + (identical(other.failed, failed) || other.failed == failed) && + (identical(other.conversation, conversation) || + other.conversation == conversation) && + (identical(other.failure, failure) || other.failure == failure) && + (identical(other.paused, paused) || other.paused == paused) && + (identical(other.recoveryRequired, recoveryRequired) || + other.recoveryRequired == recoveryRequired) && + (identical(other.exportReplyFailed, exportReplyFailed) || + other.exportReplyFailed == exportReplyFailed) && + (identical(other.elapsedMs, elapsedMs) || + other.elapsedMs == elapsedMs)); + } + + @override + int get hashCode { + return Object.hash( + runtimeType, + response, + completed, + failed, + conversation, + failure, + paused, + recoveryRequired, + exportReplyFailed, + elapsedMs, + ); + } + + @override + String toString() { + return 'AgentConversationOutcome(response: $response, completed: $completed, failed: $failed, conversation: $conversation, failure: $failure, paused: $paused, recoveryRequired: $recoveryRequired, exportReplyFailed: $exportReplyFailed, elapsedMs: $elapsedMs)'; + } +} + +/// @nodoc +abstract mixin class _$AgentConversationOutcomeCopyWith<$Res> + implements $AgentConversationOutcomeCopyWith<$Res> { + factory _$AgentConversationOutcomeCopyWith( + _AgentConversationOutcome value, + $Res Function(_AgentConversationOutcome) _then, + ) = __$AgentConversationOutcomeCopyWithImpl; + @override + @useResult + $Res call({ + String response, + bool completed, + bool failed, + ConversationMetadata? conversation, + RunFailure? failure, + bool paused, + bool recoveryRequired, + bool exportReplyFailed, + int? elapsedMs, + }); + + @override + $ConversationMetadataCopyWith<$Res>? get conversation; +} + +/// @nodoc +class __$AgentConversationOutcomeCopyWithImpl<$Res> + implements _$AgentConversationOutcomeCopyWith<$Res> { + __$AgentConversationOutcomeCopyWithImpl(this._self, this._then); + + final _AgentConversationOutcome _self; + final $Res Function(_AgentConversationOutcome) _then; + + /// Create a copy of AgentConversationOutcome + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? response = null, + Object? completed = null, + Object? failed = null, + Object? conversation = freezed, + Object? failure = freezed, + Object? paused = null, + Object? recoveryRequired = null, + Object? exportReplyFailed = null, + Object? elapsedMs = freezed, + }) { + return _then( + _AgentConversationOutcome( + response: null == response + ? _self.response + : response // ignore: cast_nullable_to_non_nullable + as String, + completed: null == completed + ? _self.completed + : completed // ignore: cast_nullable_to_non_nullable + as bool, + failed: null == failed + ? _self.failed + : failed // ignore: cast_nullable_to_non_nullable + as bool, + conversation: freezed == conversation + ? _self.conversation + : conversation // ignore: cast_nullable_to_non_nullable + as ConversationMetadata?, + failure: freezed == failure + ? _self.failure + : failure // ignore: cast_nullable_to_non_nullable + as RunFailure?, + paused: null == paused + ? _self.paused + : paused // ignore: cast_nullable_to_non_nullable + as bool, + recoveryRequired: null == recoveryRequired + ? _self.recoveryRequired + : recoveryRequired // ignore: cast_nullable_to_non_nullable + as bool, + exportReplyFailed: null == exportReplyFailed + ? _self.exportReplyFailed + : exportReplyFailed // ignore: cast_nullable_to_non_nullable + as bool, + elapsedMs: freezed == elapsedMs + ? _self.elapsedMs + : elapsedMs // ignore: cast_nullable_to_non_nullable + as int?, + ), + ); + } + + /// Create a copy of AgentConversationOutcome + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $ConversationMetadataCopyWith<$Res>? get conversation { + if (_self.conversation == null) { + return null; + } + + return $ConversationMetadataCopyWith<$Res>(_self.conversation!, (value) { + return _then(_self.copyWith(conversation: value)); + }); + } +} diff --git a/lib/features/assistant/agent_conversation_service.g.dart b/lib/features/assistant/agent_conversation_service.g.dart new file mode 100644 index 0000000..37a0501 --- /dev/null +++ b/lib/features/assistant/agent_conversation_service.g.dart @@ -0,0 +1,268 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'agent_conversation_service.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(agentConversationRegistry) +final agentConversationRegistryProvider = AgentConversationRegistryProvider._(); + +final class AgentConversationRegistryProvider + extends + $FunctionalProvider< + AgentConversationRegistry, + AgentConversationRegistry, + AgentConversationRegistry + > + with $Provider { + AgentConversationRegistryProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'agentConversationRegistryProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$agentConversationRegistryHash(); + + @$internal + @override + $ProviderElement $createElement( + $ProviderPointer pointer, + ) => $ProviderElement(pointer); + + @override + AgentConversationRegistry create(Ref ref) { + return agentConversationRegistry(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(AgentConversationRegistry value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$agentConversationRegistryHash() => + r'3e4660057c1e9c91cb6432391f22f528a3589f40'; + +@ProviderFor(agentConversationRuntimeResolver) +final agentConversationRuntimeResolverProvider = + AgentConversationRuntimeResolverProvider._(); + +final class AgentConversationRuntimeResolverProvider + extends + $FunctionalProvider< + Future Function(ConversationMetadata?), + Future Function(ConversationMetadata?), + Future Function(ConversationMetadata?) + > + with $Provider Function(ConversationMetadata?)> { + AgentConversationRuntimeResolverProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'agentConversationRuntimeResolverProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$agentConversationRuntimeResolverHash(); + + @$internal + @override + $ProviderElement Function(ConversationMetadata?)> + $createElement($ProviderPointer pointer) => $ProviderElement(pointer); + + @override + Future Function(ConversationMetadata?) create(Ref ref) { + return agentConversationRuntimeResolver(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue( + Future Function(ConversationMetadata?) value, + ) { + return $ProviderOverride( + origin: this, + providerOverride: + $SyncValueProvider< + Future Function(ConversationMetadata?) + >(value), + ); + } +} + +String _$agentConversationRuntimeResolverHash() => + r'5a74962d3d1c50771fe2a0743a71abbc8868405a'; + +@ProviderFor(agentConversationToolsResolver) +final agentConversationToolsResolverProvider = + AgentConversationToolsResolverProvider._(); + +final class AgentConversationToolsResolverProvider + extends + $FunctionalProvider< + Future Function(String, String), + Future Function(String, String), + Future Function(String, String) + > + with $Provider Function(String, String)> { + AgentConversationToolsResolverProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'agentConversationToolsResolverProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$agentConversationToolsResolverHash(); + + @$internal + @override + $ProviderElement Function(String, String)> + $createElement($ProviderPointer pointer) => $ProviderElement(pointer); + + @override + Future Function(String, String) create(Ref ref) { + return agentConversationToolsResolver(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue( + Future Function(String, String) value, + ) { + return $ProviderOverride( + origin: this, + providerOverride: + $SyncValueProvider< + Future Function(String, String) + >(value), + ); + } +} + +String _$agentConversationToolsResolverHash() => + r'45a68e8151a75e872f48f6bc151046bf1720ae28'; + +/// Not auto-disposed: switching the visible conversation must not stop a run. + +@ProviderFor(agentConversationService) +final agentConversationServiceProvider = AgentConversationServiceFamily._(); + +/// Not auto-disposed: switching the visible conversation must not stop a run. + +final class AgentConversationServiceProvider + extends + $FunctionalProvider< + AgentConversationService, + AgentConversationService, + AgentConversationService + > + with $Provider { + /// Not auto-disposed: switching the visible conversation must not stop a run. + AgentConversationServiceProvider._({ + required AgentConversationServiceFamily super.from, + required (String, String, String?) super.argument, + }) : super( + retry: null, + name: r'agentConversationServiceProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$agentConversationServiceHash(); + + @override + String toString() { + return r'agentConversationServiceProvider' + '' + '$argument'; + } + + @$internal + @override + $ProviderElement $createElement( + $ProviderPointer pointer, + ) => $ProviderElement(pointer); + + @override + AgentConversationService create(Ref ref) { + final argument = this.argument as (String, String, String?); + return agentConversationService(ref, argument.$1, argument.$2, argument.$3); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(AgentConversationService value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } + + @override + bool operator ==(Object other) { + return other is AgentConversationServiceProvider && + other.argument == argument; + } + + @override + int get hashCode { + return argument.hashCode; + } +} + +String _$agentConversationServiceHash() => + r'35f3a11cae37f2ab35527e851f468d2fb3467941'; + +/// Not auto-disposed: switching the visible conversation must not stop a run. + +final class AgentConversationServiceFamily extends $Family + with + $FunctionalFamilyOverride< + AgentConversationService, + (String, String, String?) + > { + AgentConversationServiceFamily._() + : super( + retry: null, + name: r'agentConversationServiceProvider', + dependencies: null, + $allTransitiveDependencies: null, + isAutoDispose: false, + ); + + /// Not auto-disposed: switching the visible conversation must not stop a run. + + AgentConversationServiceProvider call( + String projectId, + String key, + String? conversationId, + ) => AgentConversationServiceProvider._( + argument: (projectId, key, conversationId), + from: this, + ); + + @override + String toString() => r'agentConversationServiceProvider'; +} diff --git a/lib/features/assistant/agent_media_attachments.dart b/lib/features/assistant/agent_media_attachments.dart new file mode 100644 index 0000000..d13cf78 --- /dev/null +++ b/lib/features/assistant/agent_media_attachments.dart @@ -0,0 +1,27 @@ +import 'package:cutdex_sdk/project.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'agent_media_attachments.freezed.dart'; +part 'agent_media_attachments.g.dart'; + +/// A project-media reference shown in chat and resolved through editor tools. +@freezed +abstract class AgentMediaAttachment with _$AgentMediaAttachment { + const AgentMediaAttachment._(); + + const factory AgentMediaAttachment({ + required String id, + required String name, + required String kind, + }) = _AgentMediaAttachment; + + factory AgentMediaAttachment.fromAsset(AssetDocument asset) => + AgentMediaAttachment( + id: asset.id, + name: asset.name, + kind: asset.metadata['kind'] as String? ?? 'file', + ); + + factory AgentMediaAttachment.fromJson(Map json) => + _$AgentMediaAttachmentFromJson(json); +} diff --git a/lib/features/assistant/agent_media_attachments.freezed.dart b/lib/features/assistant/agent_media_attachments.freezed.dart new file mode 100644 index 0000000..5201cdc --- /dev/null +++ b/lib/features/assistant/agent_media_attachments.freezed.dart @@ -0,0 +1,356 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'agent_media_attachments.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +T _$identity(T value) => value; + +/// @nodoc +mixin _$AgentMediaAttachment { + String get id; + String get name; + String get kind; + + /// Create a copy of AgentMediaAttachment + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $AgentMediaAttachmentCopyWith get copyWith => + _$AgentMediaAttachmentCopyWithImpl( + this as AgentMediaAttachment, + _$identity, + ); + + /// Serializes this AgentMediaAttachment to a JSON map. + Map toJson(); + + @override + bool operator ==(Object other) { + final _this = this as AgentMediaAttachment; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is AgentMediaAttachment && + (identical(other.id, _this.id) || other.id == _this.id) && + (identical(other.name, _this.name) || other.name == _this.name) && + (identical(other.kind, _this.kind) || other.kind == _this.kind)); + } + + @JsonKey(includeFromJson: false, includeToJson: false) + @override + int get hashCode { + final _this = this as AgentMediaAttachment; + return Object.hash(runtimeType, _this.id, _this.name, _this.kind); + } + + @override + String toString() { + final _this = this as AgentMediaAttachment; + return 'AgentMediaAttachment(id: ${_this.id}, name: ${_this.name}, kind: ${_this.kind})'; + } +} + +/// @nodoc +abstract mixin class $AgentMediaAttachmentCopyWith<$Res> { + factory $AgentMediaAttachmentCopyWith( + AgentMediaAttachment value, + $Res Function(AgentMediaAttachment) _then, + ) = _$AgentMediaAttachmentCopyWithImpl; + @useResult + $Res call({String id, String name, String kind}); +} + +/// @nodoc +class _$AgentMediaAttachmentCopyWithImpl<$Res> + implements $AgentMediaAttachmentCopyWith<$Res> { + _$AgentMediaAttachmentCopyWithImpl(this._self, this._then); + + final AgentMediaAttachment _self; + final $Res Function(AgentMediaAttachment) _then; + + /// Create a copy of AgentMediaAttachment + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({Object? id = null, Object? name = null, Object? kind = null}) { + return _then( + AgentMediaAttachment( + id: null == id + ? _self.id + : id // ignore: cast_nullable_to_non_nullable + as String, + name: null == name + ? _self.name + : name // ignore: cast_nullable_to_non_nullable + as String, + kind: null == kind + ? _self.kind + : kind // ignore: cast_nullable_to_non_nullable + as String, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [AgentMediaAttachment]. +extension AgentMediaAttachmentPatterns on AgentMediaAttachment { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_AgentMediaAttachment value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _AgentMediaAttachment() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_AgentMediaAttachment value) $default, + ) { + final _that = this; + switch (_that) { + case _AgentMediaAttachment(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_AgentMediaAttachment value)? $default, + ) { + final _that = this; + switch (_that) { + case _AgentMediaAttachment() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function(String id, String name, String kind)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _AgentMediaAttachment() when $default != null: + return $default(_that.id, _that.name, _that.kind); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function(String id, String name, String kind) $default, + ) { + final _that = this; + switch (_that) { + case _AgentMediaAttachment(): + return $default(_that.id, _that.name, _that.kind); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function(String id, String name, String kind)? $default, + ) { + final _that = this; + switch (_that) { + case _AgentMediaAttachment() when $default != null: + return $default(_that.id, _that.name, _that.kind); + case _: + return null; + } + } +} + +/// @nodoc +@JsonSerializable() +class _AgentMediaAttachment extends AgentMediaAttachment { + const _AgentMediaAttachment({ + required this.id, + required this.name, + required this.kind, + }) : super._(); + factory _AgentMediaAttachment.fromJson(Map json) => + _$AgentMediaAttachmentFromJson(json); + + @override + final String id; + @override + final String name; + @override + final String kind; + + /// Create a copy of AgentMediaAttachment + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$AgentMediaAttachmentCopyWith<_AgentMediaAttachment> get copyWith => + __$AgentMediaAttachmentCopyWithImpl<_AgentMediaAttachment>( + this, + _$identity, + ); + + @override + Map toJson() { + return _$AgentMediaAttachmentToJson(this); + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _AgentMediaAttachment && + (identical(other.id, id) || other.id == id) && + (identical(other.name, name) || other.name == name) && + (identical(other.kind, kind) || other.kind == kind)); + } + + @JsonKey(includeFromJson: false, includeToJson: false) + @override + int get hashCode { + return Object.hash(runtimeType, id, name, kind); + } + + @override + String toString() { + return 'AgentMediaAttachment(id: $id, name: $name, kind: $kind)'; + } +} + +/// @nodoc +abstract mixin class _$AgentMediaAttachmentCopyWith<$Res> + implements $AgentMediaAttachmentCopyWith<$Res> { + factory _$AgentMediaAttachmentCopyWith( + _AgentMediaAttachment value, + $Res Function(_AgentMediaAttachment) _then, + ) = __$AgentMediaAttachmentCopyWithImpl; + @override + @useResult + $Res call({String id, String name, String kind}); +} + +/// @nodoc +class __$AgentMediaAttachmentCopyWithImpl<$Res> + implements _$AgentMediaAttachmentCopyWith<$Res> { + __$AgentMediaAttachmentCopyWithImpl(this._self, this._then); + + final _AgentMediaAttachment _self; + final $Res Function(_AgentMediaAttachment) _then; + + /// Create a copy of AgentMediaAttachment + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({Object? id = null, Object? name = null, Object? kind = null}) { + return _then( + _AgentMediaAttachment( + id: null == id + ? _self.id + : id // ignore: cast_nullable_to_non_nullable + as String, + name: null == name + ? _self.name + : name // ignore: cast_nullable_to_non_nullable + as String, + kind: null == kind + ? _self.kind + : kind // ignore: cast_nullable_to_non_nullable + as String, + ), + ); + } +} diff --git a/lib/features/assistant/agent_media_attachments.g.dart b/lib/features/assistant/agent_media_attachments.g.dart new file mode 100644 index 0000000..60c9310 --- /dev/null +++ b/lib/features/assistant/agent_media_attachments.g.dart @@ -0,0 +1,23 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'agent_media_attachments.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_AgentMediaAttachment _$AgentMediaAttachmentFromJson( + Map json, +) => _AgentMediaAttachment( + id: json['id'] as String, + name: json['name'] as String, + kind: json['kind'] as String, +); + +Map _$AgentMediaAttachmentToJson( + _AgentMediaAttachment instance, +) => { + 'id': instance.id, + 'name': instance.name, + 'kind': instance.kind, +}; diff --git a/lib/features/assistant/agent_message_codec.dart b/lib/features/assistant/agent_message_codec.dart new file mode 100644 index 0000000..546e1c4 --- /dev/null +++ b/lib/features/assistant/agent_message_codec.dart @@ -0,0 +1,79 @@ +import 'dart:convert'; + +import 'package:freezed_annotation/freezed_annotation.dart'; + +import 'agent_media_attachments.dart'; +import 'composer_document.dart'; + +part 'agent_message_codec.freezed.dart'; +part 'agent_message_codec.g.dart'; + +@freezed +abstract class AgentComposerMessage with _$AgentComposerMessage { + const AgentComposerMessage._(); + + const factory AgentComposerMessage({ + required String text, + required List attachments, + required List segments, + }) = _AgentComposerMessage; + + factory AgentComposerMessage.fromJson(Map json) => + _$AgentComposerMessageFromJson(json); + + List get references => [ + for (final segment in segments) + if (segment case ComposerReferenceSegment(:final value)) value, + ]; + + static const _prefix = '[Cutdex composer message] '; + static const _separator = '\n\n'; + + static String encodeDocument( + List segments, + List attachments, + ) => _encode( + AgentComposerMessage( + text: segments.map((segment) => segment.displayText).join().trim(), + attachments: attachments, + segments: segments, + ), + ); + + static String _encode(AgentComposerMessage message) { + if (message.attachments.isEmpty && message.references.isEmpty) { + return message.text; + } + final data = jsonEncode(message.toJson()); + return '$_prefix$data$_separator' + 'These references identify project resources by stable ID, not file ' + 'contents. A referenced timeline is context, not an instruction to ' + "switch the user's current timeline. Resolve each ID with media_query " + 'or the relevant project tool when needed.$_separator${message.text}'; + } + + static AgentComposerMessage decode(String value) { + AgentComposerMessage plain() => AgentComposerMessage( + text: value, + attachments: const [], + segments: const [], + ); + if (!value.startsWith(_prefix)) return plain(); + final end = value.indexOf(_separator, _prefix.length); + if (end < 0) return plain(); + try { + final data = jsonDecode(value.substring(_prefix.length, end)); + return AgentComposerMessage.fromJson( + (data as Map).cast(), + ); + } on FormatException { + return plain(); + } on CheckedFromJsonException { + return plain(); + } on TypeError { + return plain(); + } on ArgumentError { + return plain(); + } + } +} diff --git a/lib/features/assistant/agent_message_codec.freezed.dart b/lib/features/assistant/agent_message_codec.freezed.dart new file mode 100644 index 0000000..a84f5a9 --- /dev/null +++ b/lib/features/assistant/agent_message_codec.freezed.dart @@ -0,0 +1,419 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'agent_message_codec.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +T _$identity(T value) => value; + +/// @nodoc +mixin _$AgentComposerMessage { + String get text; + List get attachments; + List get segments; + + /// Create a copy of AgentComposerMessage + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $AgentComposerMessageCopyWith get copyWith => + _$AgentComposerMessageCopyWithImpl( + this as AgentComposerMessage, + _$identity, + ); + + /// Serializes this AgentComposerMessage to a JSON map. + Map toJson(); + + @override + bool operator ==(Object other) { + final _this = this as AgentComposerMessage; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is AgentComposerMessage && + (identical(other.text, _this.text) || other.text == _this.text) && + const DeepCollectionEquality().equals( + other.attachments, + _this.attachments, + ) && + const DeepCollectionEquality().equals( + other.segments, + _this.segments, + )); + } + + @JsonKey(includeFromJson: false, includeToJson: false) + @override + int get hashCode { + final _this = this as AgentComposerMessage; + return Object.hash( + runtimeType, + _this.text, + const DeepCollectionEquality().hash(_this.attachments), + const DeepCollectionEquality().hash(_this.segments), + ); + } + + @override + String toString() { + final _this = this as AgentComposerMessage; + return 'AgentComposerMessage(text: ${_this.text}, attachments: ${_this.attachments}, segments: ${_this.segments})'; + } +} + +/// @nodoc +abstract mixin class $AgentComposerMessageCopyWith<$Res> { + factory $AgentComposerMessageCopyWith( + AgentComposerMessage value, + $Res Function(AgentComposerMessage) _then, + ) = _$AgentComposerMessageCopyWithImpl; + @useResult + $Res call({ + String text, + List attachments, + List segments, + }); +} + +/// @nodoc +class _$AgentComposerMessageCopyWithImpl<$Res> + implements $AgentComposerMessageCopyWith<$Res> { + _$AgentComposerMessageCopyWithImpl(this._self, this._then); + + final AgentComposerMessage _self; + final $Res Function(AgentComposerMessage) _then; + + /// Create a copy of AgentComposerMessage + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? text = null, + Object? attachments = null, + Object? segments = null, + }) { + return _then( + AgentComposerMessage( + text: null == text + ? _self.text + : text // ignore: cast_nullable_to_non_nullable + as String, + attachments: null == attachments + ? _self.attachments + : attachments // ignore: cast_nullable_to_non_nullable + as List, + segments: null == segments + ? _self.segments + : segments // ignore: cast_nullable_to_non_nullable + as List, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [AgentComposerMessage]. +extension AgentComposerMessagePatterns on AgentComposerMessage { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_AgentComposerMessage value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _AgentComposerMessage() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_AgentComposerMessage value) $default, + ) { + final _that = this; + switch (_that) { + case _AgentComposerMessage(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_AgentComposerMessage value)? $default, + ) { + final _that = this; + switch (_that) { + case _AgentComposerMessage() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + String text, + List attachments, + List segments, + )? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _AgentComposerMessage() when $default != null: + return $default(_that.text, _that.attachments, _that.segments); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function( + String text, + List attachments, + List segments, + ) + $default, + ) { + final _that = this; + switch (_that) { + case _AgentComposerMessage(): + return $default(_that.text, _that.attachments, _that.segments); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + String text, + List attachments, + List segments, + )? + $default, + ) { + final _that = this; + switch (_that) { + case _AgentComposerMessage() when $default != null: + return $default(_that.text, _that.attachments, _that.segments); + case _: + return null; + } + } +} + +/// @nodoc +@JsonSerializable() +class _AgentComposerMessage extends AgentComposerMessage { + const _AgentComposerMessage({ + required this.text, + required List attachments, + required List segments, + }) : _attachments = attachments, + _segments = segments, + super._(); + factory _AgentComposerMessage.fromJson(Map json) => + _$AgentComposerMessageFromJson(json); + + @override + final String text; + final List _attachments; + @override + List get attachments { + if (_attachments is EqualUnmodifiableListView) return _attachments; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_attachments); + } + + final List _segments; + @override + List get segments { + if (_segments is EqualUnmodifiableListView) return _segments; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_segments); + } + + /// Create a copy of AgentComposerMessage + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$AgentComposerMessageCopyWith<_AgentComposerMessage> get copyWith => + __$AgentComposerMessageCopyWithImpl<_AgentComposerMessage>( + this, + _$identity, + ); + + @override + Map toJson() { + return _$AgentComposerMessageToJson(this); + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _AgentComposerMessage && + (identical(other.text, text) || other.text == text) && + const DeepCollectionEquality().equals( + other.attachments, + _attachments, + ) && + const DeepCollectionEquality().equals(other.segments, _segments)); + } + + @JsonKey(includeFromJson: false, includeToJson: false) + @override + int get hashCode { + return Object.hash( + runtimeType, + text, + const DeepCollectionEquality().hash(_attachments), + const DeepCollectionEquality().hash(_segments), + ); + } + + @override + String toString() { + return 'AgentComposerMessage(text: $text, attachments: $attachments, segments: $segments)'; + } +} + +/// @nodoc +abstract mixin class _$AgentComposerMessageCopyWith<$Res> + implements $AgentComposerMessageCopyWith<$Res> { + factory _$AgentComposerMessageCopyWith( + _AgentComposerMessage value, + $Res Function(_AgentComposerMessage) _then, + ) = __$AgentComposerMessageCopyWithImpl; + @override + @useResult + $Res call({ + String text, + List attachments, + List segments, + }); +} + +/// @nodoc +class __$AgentComposerMessageCopyWithImpl<$Res> + implements _$AgentComposerMessageCopyWith<$Res> { + __$AgentComposerMessageCopyWithImpl(this._self, this._then); + + final _AgentComposerMessage _self; + final $Res Function(_AgentComposerMessage) _then; + + /// Create a copy of AgentComposerMessage + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? text = null, + Object? attachments = null, + Object? segments = null, + }) { + return _then( + _AgentComposerMessage( + text: null == text + ? _self.text + : text // ignore: cast_nullable_to_non_nullable + as String, + attachments: null == attachments + ? _self._attachments + : attachments // ignore: cast_nullable_to_non_nullable + as List, + segments: null == segments + ? _self._segments + : segments // ignore: cast_nullable_to_non_nullable + as List, + ), + ); + } +} diff --git a/lib/features/assistant/agent_message_codec.g.dart b/lib/features/assistant/agent_message_codec.g.dart new file mode 100644 index 0000000..032419e --- /dev/null +++ b/lib/features/assistant/agent_message_codec.g.dart @@ -0,0 +1,27 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'agent_message_codec.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_AgentComposerMessage _$AgentComposerMessageFromJson( + Map json, +) => _AgentComposerMessage( + text: json['text'] as String, + attachments: (json['attachments'] as List) + .map((e) => AgentMediaAttachment.fromJson(e as Map)) + .toList(), + segments: (json['segments'] as List) + .map((e) => ComposerSegment.fromJson(e as Map)) + .toList(), +); + +Map _$AgentComposerMessageToJson( + _AgentComposerMessage instance, +) => { + 'text': instance.text, + 'attachments': instance.attachments.map((e) => e.toJson()).toList(), + 'segments': instance.segments.map((e) => e.toJson()).toList(), +}; diff --git a/lib/features/assistant/breakable_selectable_text.dart b/lib/features/assistant/breakable_selectable_text.dart new file mode 100644 index 0000000..c667d60 --- /dev/null +++ b/lib/features/assistant/breakable_selectable_text.dart @@ -0,0 +1,100 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +const _softBreak = '\u200B'; + +String _breakLongAsciiRuns(String text) { + final result = StringBuffer(); + int? previous; + for (final rune in text.runes) { + if (previous != null && + previous >= 0x21 && + previous <= 0x7e && + rune >= 0x21 && + rune <= 0x7e) { + result.write(_softBreak); + } + result.writeCharCode(rune); + previous = rune; + } + return result.toString(); +} + +class _CopyPlainTextIntent extends Intent { + const _CopyPlainTextIntent(); +} + +/// Allows paths and other long ASCII runs to wrap without changing copied text. +class BreakableSelectableText extends StatefulWidget { + const BreakableSelectableText({ + super.key, + required this.text, + required this.style, + }); + + final String text; + final TextStyle style; + + @override + State createState() => + _BreakableSelectableTextState(); +} + +class _BreakableSelectableTextState extends State { + TextSelection _selection = const TextSelection.collapsed(offset: -1); + + void _copySelection(String displayText, TextSelection selection) { + if (!selection.isValid || selection.isCollapsed) return; + final text = selection.textInside(displayText).replaceAll(_softBreak, ''); + Clipboard.setData(ClipboardData(text: text)); + } + + @override + Widget build(BuildContext context) { + final displayText = _breakLongAsciiRuns(widget.text); + return Shortcuts( + shortcuts: const { + SingleActivator(LogicalKeyboardKey.keyC, meta: true): + _CopyPlainTextIntent(), + SingleActivator(LogicalKeyboardKey.keyC, control: true): + _CopyPlainTextIntent(), + }, + child: Actions( + actions: { + _CopyPlainTextIntent: CallbackAction<_CopyPlainTextIntent>( + onInvoke: (_) { + _copySelection(displayText, _selection); + return null; + }, + ), + }, + child: SelectableText( + displayText, + style: widget.style, + textAlign: TextAlign.start, + semanticsLabel: widget.text, + onSelectionChanged: (selection, _) => _selection = selection, + contextMenuBuilder: (context, editable) => + AdaptiveTextSelectionToolbar.buttonItems( + anchors: editable.contextMenuAnchors, + buttonItems: [ + for (final button in editable.contextMenuButtonItems) + if (button.type == ContextMenuButtonType.copy) + button.copyWith( + onPressed: () { + _copySelection( + displayText, + editable.textEditingValue.selection, + ); + editable.hideToolbar(); + }, + ) + else + button, + ], + ), + ), + ), + ); + } +} diff --git a/lib/features/assistant/chat_controller.dart b/lib/features/assistant/chat_controller.dart new file mode 100644 index 0000000..ccb7835 --- /dev/null +++ b/lib/features/assistant/chat_controller.dart @@ -0,0 +1,253 @@ +import 'dart:async'; + +import 'package:cutdex_agent/cutdex_agent.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import '../../integrations/agent/agent_settings.dart'; +import '../../integrations/agent/conversation_repository.dart'; +import 'agent_conversation_service.dart'; +import 'chat_state.dart'; + +part 'chat_controller.g.dart'; + +/// Presentation state for one project conversation. +@riverpod +class ChatController extends _$ChatController { + late AgentConversationService _conversation; + AgentConversationService? _activeConversation; + int _sendRevision = 0; + + @override + ChatState build( + String projectId, { + String? conversationId, + String? draftKey, + }) { + _conversation = ref.watch( + agentConversationServiceProvider( + projectId, + draftKey ?? conversationId ?? 'new', + conversationId, + ), + ); + final subscription = _conversation.changes.listen((_) { + if (!ref.mounted) return; + state = state.copyWith( + busy: _conversation.busy, + partialResponse: _conversation.partialResponse, + activity: _conversation.activity, + ); + if (!_conversation.busy && _activeConversation == null) { + unawaited(_restore(force: true)); + } + }); + ref.onDispose(subscription.cancel); + unawaited(Future.microtask(_restore)); + return ChatState( + busy: _conversation.busy, + partialResponse: _conversation.partialResponse, + activity: _conversation.activity, + ); + } + + List _messages(List messages) => [ + for (final message in messages) + ChatMessage( + text: message.text, + isUser: message.isUser, + elapsedMs: message.elapsedMs, + ), + ]; + + Future _restore({bool force = false}) async { + if ((_sendRevision != 0 && !force) || !ref.mounted) return; + final revision = _sendRevision; + try { + final history = await _conversation.restore(); + if (!ref.mounted || revision != _sendRevision) return; + state = state.copyWith( + messages: history == null + ? state.messages + : _messages(history.messages), + conversation: _conversation.metadata, + error: history?.exportReplyFailed == true + ? AgentChatError.exportReplyFailed + : history?.recoveryRequired == true + ? AgentChatError.recoveryRequired + : history?.resumeAvailable == true + ? AgentChatError.interrupted + : null, + ); + } on AgentConversationException catch (error) { + if (ref.mounted && revision == _sendRevision) { + state = state.copyWith( + error: error.failure == AgentConversationFailure.configurationRead + ? AgentChatError.configurationReadFailed + : AgentChatError.sessionRestoreFailed, + ); + } + } catch (_) { + if (ref.mounted && revision == _sendRevision) { + state = state.copyWith(error: AgentChatError.sessionRestoreFailed); + } + } + } + + Future selectModel(String providerId, String modelId) async { + if (state.busy) return; + final previous = state.conversation; + await ref + .read(agentSettingsProvider.notifier) + .selectModel(providerId, modelId); + if (!ref.mounted) return; + if ((previous != null && + (previous.providerId != providerId || + previous.modelId != modelId)) || + (previous == null && conversationId != null)) { + _sendRevision++; + _conversation.startNewConversation(); + state = const ChatState(); + } + } + + Future send( + String input, { + required String timelineId, + bool summaryOnly = false, + bool resumeOnly = false, + void Function(ConversationMetadata value)? onCreated, + void Function(ConversationMetadata value)? onUpdated, + }) async { + final text = input.trim(); + if (text.isEmpty || state.busy) return; + _sendRevision++; + state = state.copyWith( + messages: [ + ...state.messages, + if (!resumeOnly) ChatMessage(text: text, isUser: true), + ], + partialResponse: '', + busy: true, + stopping: false, + error: null, + ); + final conversation = _conversation; + _activeConversation = conversation; + var streamed = ''; + try { + final outcome = await conversation.send( + text, + timelineId: timelineId, + summaryOnly: summaryOnly, + resumeOnly: resumeOnly, + onCreated: (item) { + if (ref.mounted) state = state.copyWith(conversation: item); + onCreated?.call(item); + }, + onPrepared: (preparation) { + if (!ref.mounted || !preparation.sessionChanged) return; + state = state.copyWith( + messages: [ + ..._messages(preparation.messages), + if (!resumeOnly) ChatMessage(text: text, isUser: true), + ], + ); + }, + onTextDelta: (delta) { + streamed += delta; + if (ref.mounted) { + state = state.copyWith( + partialResponse: state.partialResponse + delta, + ); + } + }, + ); + if (outcome.conversation case final item?) { + if (ref.mounted) state = state.copyWith(conversation: item); + onUpdated?.call(item); + } + if (outcome.recoveryRequired) { + final history = await conversation.restore(); + if (ref.mounted && history != null) { + state = state.copyWith(messages: _messages(history.messages)); + } + } + if (!ref.mounted) return; + final response = outcome.completed && outcome.response.isNotEmpty + ? outcome.response + : streamed; + state = state.copyWith( + messages: [ + ...state.messages, + if (response.isNotEmpty) + ChatMessage( + text: response, + interrupted: !outcome.completed, + elapsedMs: outcome.elapsedMs, + ), + ], + partialResponse: '', + error: outcome.exportReplyFailed + ? AgentChatError.exportReplyFailed + : outcome.recoveryRequired + ? AgentChatError.recoveryRequired + : outcome.paused + ? AgentChatError.turnLimit + : outcome.failed + ? switch (outcome.failure) { + RunFailure.contextBudget => AgentChatError.contextBudget, + RunFailure.authentication => AgentChatError.authentication, + RunFailure.connection => AgentChatError.connection, + RunFailure.protocol => AgentChatError.protocol, + _ => AgentChatError.replyFailed, + } + : null, + ); + } on AgentConversationException catch (error) { + if (ref.mounted) { + state = state.copyWith( + messages: [ + ...state.messages, + if (streamed.isNotEmpty) + ChatMessage(text: streamed, interrupted: true), + ], + partialResponse: '', + error: switch (error.failure) { + AgentConversationFailure.configurationRead => + AgentChatError.configurationReadFailed, + AgentConversationFailure.notConfigured => + AgentChatError.configurationRequired, + AgentConversationFailure.contextBudget => + AgentChatError.contextBudget, + AgentConversationFailure.authentication => + AgentChatError.authentication, + AgentConversationFailure.connection => AgentChatError.connection, + AgentConversationFailure.protocol => AgentChatError.protocol, + AgentConversationFailure.request => AgentChatError.requestFailed, + }, + ); + } + } catch (_) { + if (ref.mounted) { + state = state.copyWith( + partialResponse: '', + error: AgentChatError.requestFailed, + ); + } + } finally { + if (identical(_activeConversation, conversation)) { + _activeConversation = null; + } + if (ref.mounted) { + state = state.copyWith(busy: false, stopping: false); + } + } + } + + Future stop() async { + if (!state.busy) return; + state = state.copyWith(stopping: true); + final conversation = _activeConversation ?? _conversation; + await conversation.cancel(); + } +} diff --git a/lib/features/assistant/chat_controller.g.dart b/lib/features/assistant/chat_controller.g.dart new file mode 100644 index 0000000..e86e68b --- /dev/null +++ b/lib/features/assistant/chat_controller.g.dart @@ -0,0 +1,133 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'chat_controller.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning +/// Presentation state for one project conversation. + +@ProviderFor(ChatController) +final chatControllerProvider = ChatControllerFamily._(); + +/// Presentation state for one project conversation. +final class ChatControllerProvider + extends $NotifierProvider { + /// Presentation state for one project conversation. + ChatControllerProvider._({ + required ChatControllerFamily super.from, + required (String, {String? conversationId, String? draftKey}) + super.argument, + }) : super( + retry: null, + name: r'chatControllerProvider', + isAutoDispose: true, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$chatControllerHash(); + + @override + String toString() { + return r'chatControllerProvider' + '' + '$argument'; + } + + @$internal + @override + ChatController create() => ChatController(); + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(ChatState value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } + + @override + bool operator ==(Object other) { + return other is ChatControllerProvider && other.argument == argument; + } + + @override + int get hashCode { + return argument.hashCode; + } +} + +String _$chatControllerHash() => r'b10209ff2924c59cc7c70c57db289a73837aa257'; + +/// Presentation state for one project conversation. + +final class ChatControllerFamily extends $Family + with + $ClassFamilyOverride< + ChatController, + ChatState, + ChatState, + ChatState, + (String, {String? conversationId, String? draftKey}) + > { + ChatControllerFamily._() + : super( + retry: null, + name: r'chatControllerProvider', + dependencies: null, + $allTransitiveDependencies: null, + isAutoDispose: true, + ); + + /// Presentation state for one project conversation. + + ChatControllerProvider call( + String projectId, { + String? conversationId, + String? draftKey, + }) => ChatControllerProvider._( + argument: (projectId, conversationId: conversationId, draftKey: draftKey), + from: this, + ); + + @override + String toString() => r'chatControllerProvider'; +} + +/// Presentation state for one project conversation. + +abstract class _$ChatController extends $Notifier { + late final _$args = + ref.$arg as (String, {String? conversationId, String? draftKey}); + String get projectId => _$args.$1; + String? get conversationId => _$args.conversationId; + String? get draftKey => _$args.draftKey; + + ChatState build(String projectId, {String? conversationId, String? draftKey}); + @$mustCallSuper + @override + WhenComplete runBuild() { + final ref = this.ref as $Ref; + final element = + ref.element + as $ClassProviderElement< + AnyNotifier, + ChatState, + Object?, + Object? + >; + return element.handleCreate( + ref, + () => build( + _$args.$1, + conversationId: _$args.conversationId, + draftKey: _$args.draftKey, + ), + ); + } +} diff --git a/lib/features/assistant/chat_state.dart b/lib/features/assistant/chat_state.dart new file mode 100644 index 0000000..2af4971 --- /dev/null +++ b/lib/features/assistant/chat_state.dart @@ -0,0 +1,46 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +import '../../integrations/agent/conversation_repository.dart'; + +part 'chat_state.freezed.dart'; + +enum AgentChatActivity { replying, compacting, editing, verifying } + +enum AgentChatError { + configurationReadFailed, + configurationRequired, + sessionRestoreFailed, + contextBudget, + authentication, + connection, + protocol, + replyFailed, + turnLimit, + recoveryRequired, + interrupted, + exportReplyFailed, + requestFailed, +} + +@freezed +abstract class ChatMessage with _$ChatMessage { + const factory ChatMessage({ + required String text, + @Default(false) bool isUser, + @Default(false) bool interrupted, + int? elapsedMs, + }) = _ChatMessage; +} + +@freezed +abstract class ChatState with _$ChatState { + const factory ChatState({ + @Default([]) List messages, + @Default('') String partialResponse, + @Default(AgentChatActivity.replying) AgentChatActivity activity, + @Default(false) bool busy, + @Default(false) bool stopping, + AgentChatError? error, + ConversationMetadata? conversation, + }) = _ChatState; +} diff --git a/lib/features/assistant/chat_state.freezed.dart b/lib/features/assistant/chat_state.freezed.dart new file mode 100644 index 0000000..2f540c2 --- /dev/null +++ b/lib/features/assistant/chat_state.freezed.dart @@ -0,0 +1,935 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'chat_state.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +T _$identity(T value) => value; + +/// @nodoc +mixin _$ChatMessage { + String get text; + bool get isUser; + bool get interrupted; + int? get elapsedMs; + + /// Create a copy of ChatMessage + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $ChatMessageCopyWith get copyWith => + _$ChatMessageCopyWithImpl(this as ChatMessage, _$identity); + + @override + bool operator ==(Object other) { + final _this = this as ChatMessage; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is ChatMessage && + (identical(other.text, _this.text) || other.text == _this.text) && + (identical(other.isUser, _this.isUser) || + other.isUser == _this.isUser) && + (identical(other.interrupted, _this.interrupted) || + other.interrupted == _this.interrupted) && + (identical(other.elapsedMs, _this.elapsedMs) || + other.elapsedMs == _this.elapsedMs)); + } + + @override + int get hashCode { + final _this = this as ChatMessage; + return Object.hash( + runtimeType, + _this.text, + _this.isUser, + _this.interrupted, + _this.elapsedMs, + ); + } + + @override + String toString() { + final _this = this as ChatMessage; + return 'ChatMessage(text: ${_this.text}, isUser: ${_this.isUser}, interrupted: ${_this.interrupted}, elapsedMs: ${_this.elapsedMs})'; + } +} + +/// @nodoc +abstract mixin class $ChatMessageCopyWith<$Res> { + factory $ChatMessageCopyWith( + ChatMessage value, + $Res Function(ChatMessage) _then, + ) = _$ChatMessageCopyWithImpl; + @useResult + $Res call({String text, bool isUser, bool interrupted, int? elapsedMs}); +} + +/// @nodoc +class _$ChatMessageCopyWithImpl<$Res> implements $ChatMessageCopyWith<$Res> { + _$ChatMessageCopyWithImpl(this._self, this._then); + + final ChatMessage _self; + final $Res Function(ChatMessage) _then; + + /// Create a copy of ChatMessage + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? text = null, + Object? isUser = null, + Object? interrupted = null, + Object? elapsedMs = freezed, + }) { + return _then( + ChatMessage( + text: null == text + ? _self.text + : text // ignore: cast_nullable_to_non_nullable + as String, + isUser: null == isUser + ? _self.isUser + : isUser // ignore: cast_nullable_to_non_nullable + as bool, + interrupted: null == interrupted + ? _self.interrupted + : interrupted // ignore: cast_nullable_to_non_nullable + as bool, + elapsedMs: freezed == elapsedMs + ? _self.elapsedMs + : elapsedMs // ignore: cast_nullable_to_non_nullable + as int?, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [ChatMessage]. +extension ChatMessagePatterns on ChatMessage { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_ChatMessage value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ChatMessage() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_ChatMessage value) $default, + ) { + final _that = this; + switch (_that) { + case _ChatMessage(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_ChatMessage value)? $default, + ) { + final _that = this; + switch (_that) { + case _ChatMessage() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + String text, + bool isUser, + bool interrupted, + int? elapsedMs, + )? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ChatMessage() when $default != null: + return $default( + _that.text, + _that.isUser, + _that.interrupted, + _that.elapsedMs, + ); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function(String text, bool isUser, bool interrupted, int? elapsedMs) + $default, + ) { + final _that = this; + switch (_that) { + case _ChatMessage(): + return $default( + _that.text, + _that.isUser, + _that.interrupted, + _that.elapsedMs, + ); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + String text, + bool isUser, + bool interrupted, + int? elapsedMs, + )? + $default, + ) { + final _that = this; + switch (_that) { + case _ChatMessage() when $default != null: + return $default( + _that.text, + _that.isUser, + _that.interrupted, + _that.elapsedMs, + ); + case _: + return null; + } + } +} + +/// @nodoc + +class _ChatMessage implements ChatMessage { + const _ChatMessage({ + required this.text, + this.isUser = false, + this.interrupted = false, + this.elapsedMs, + }); + + @override + final String text; + @override + @JsonKey() + final bool isUser; + @override + @JsonKey() + final bool interrupted; + @override + final int? elapsedMs; + + /// Create a copy of ChatMessage + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$ChatMessageCopyWith<_ChatMessage> get copyWith => + __$ChatMessageCopyWithImpl<_ChatMessage>(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _ChatMessage && + (identical(other.text, text) || other.text == text) && + (identical(other.isUser, isUser) || other.isUser == isUser) && + (identical(other.interrupted, interrupted) || + other.interrupted == interrupted) && + (identical(other.elapsedMs, elapsedMs) || + other.elapsedMs == elapsedMs)); + } + + @override + int get hashCode { + return Object.hash(runtimeType, text, isUser, interrupted, elapsedMs); + } + + @override + String toString() { + return 'ChatMessage(text: $text, isUser: $isUser, interrupted: $interrupted, elapsedMs: $elapsedMs)'; + } +} + +/// @nodoc +abstract mixin class _$ChatMessageCopyWith<$Res> + implements $ChatMessageCopyWith<$Res> { + factory _$ChatMessageCopyWith( + _ChatMessage value, + $Res Function(_ChatMessage) _then, + ) = __$ChatMessageCopyWithImpl; + @override + @useResult + $Res call({String text, bool isUser, bool interrupted, int? elapsedMs}); +} + +/// @nodoc +class __$ChatMessageCopyWithImpl<$Res> implements _$ChatMessageCopyWith<$Res> { + __$ChatMessageCopyWithImpl(this._self, this._then); + + final _ChatMessage _self; + final $Res Function(_ChatMessage) _then; + + /// Create a copy of ChatMessage + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? text = null, + Object? isUser = null, + Object? interrupted = null, + Object? elapsedMs = freezed, + }) { + return _then( + _ChatMessage( + text: null == text + ? _self.text + : text // ignore: cast_nullable_to_non_nullable + as String, + isUser: null == isUser + ? _self.isUser + : isUser // ignore: cast_nullable_to_non_nullable + as bool, + interrupted: null == interrupted + ? _self.interrupted + : interrupted // ignore: cast_nullable_to_non_nullable + as bool, + elapsedMs: freezed == elapsedMs + ? _self.elapsedMs + : elapsedMs // ignore: cast_nullable_to_non_nullable + as int?, + ), + ); + } +} + +/// @nodoc +mixin _$ChatState { + List get messages; + String get partialResponse; + AgentChatActivity get activity; + bool get busy; + bool get stopping; + AgentChatError? get error; + ConversationMetadata? get conversation; + + /// Create a copy of ChatState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $ChatStateCopyWith get copyWith => + _$ChatStateCopyWithImpl(this as ChatState, _$identity); + + @override + bool operator ==(Object other) { + final _this = this as ChatState; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is ChatState && + const DeepCollectionEquality().equals( + other.messages, + _this.messages, + ) && + (identical(other.partialResponse, _this.partialResponse) || + other.partialResponse == _this.partialResponse) && + (identical(other.activity, _this.activity) || + other.activity == _this.activity) && + (identical(other.busy, _this.busy) || other.busy == _this.busy) && + (identical(other.stopping, _this.stopping) || + other.stopping == _this.stopping) && + (identical(other.error, _this.error) || + other.error == _this.error) && + (identical(other.conversation, _this.conversation) || + other.conversation == _this.conversation)); + } + + @override + int get hashCode { + final _this = this as ChatState; + return Object.hash( + runtimeType, + const DeepCollectionEquality().hash(_this.messages), + _this.partialResponse, + _this.activity, + _this.busy, + _this.stopping, + _this.error, + _this.conversation, + ); + } + + @override + String toString() { + final _this = this as ChatState; + return 'ChatState(messages: ${_this.messages}, partialResponse: ${_this.partialResponse}, activity: ${_this.activity}, busy: ${_this.busy}, stopping: ${_this.stopping}, error: ${_this.error}, conversation: ${_this.conversation})'; + } +} + +/// @nodoc +abstract mixin class $ChatStateCopyWith<$Res> { + factory $ChatStateCopyWith(ChatState value, $Res Function(ChatState) _then) = + _$ChatStateCopyWithImpl; + @useResult + $Res call({ + List messages, + String partialResponse, + AgentChatActivity activity, + bool busy, + bool stopping, + AgentChatError? error, + ConversationMetadata? conversation, + }); + + $ConversationMetadataCopyWith<$Res>? get conversation; +} + +/// @nodoc +class _$ChatStateCopyWithImpl<$Res> implements $ChatStateCopyWith<$Res> { + _$ChatStateCopyWithImpl(this._self, this._then); + + final ChatState _self; + final $Res Function(ChatState) _then; + + /// Create a copy of ChatState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? messages = null, + Object? partialResponse = null, + Object? activity = null, + Object? busy = null, + Object? stopping = null, + Object? error = freezed, + Object? conversation = freezed, + }) { + return _then( + ChatState( + messages: null == messages + ? _self.messages + : messages // ignore: cast_nullable_to_non_nullable + as List, + partialResponse: null == partialResponse + ? _self.partialResponse + : partialResponse // ignore: cast_nullable_to_non_nullable + as String, + activity: null == activity + ? _self.activity + : activity // ignore: cast_nullable_to_non_nullable + as AgentChatActivity, + busy: null == busy + ? _self.busy + : busy // ignore: cast_nullable_to_non_nullable + as bool, + stopping: null == stopping + ? _self.stopping + : stopping // ignore: cast_nullable_to_non_nullable + as bool, + error: freezed == error + ? _self.error + : error // ignore: cast_nullable_to_non_nullable + as AgentChatError?, + conversation: freezed == conversation + ? _self.conversation + : conversation // ignore: cast_nullable_to_non_nullable + as ConversationMetadata?, + ), + ); + } + + /// Create a copy of ChatState + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $ConversationMetadataCopyWith<$Res>? get conversation { + if (_self.conversation == null) { + return null; + } + + return $ConversationMetadataCopyWith<$Res>(_self.conversation!, (value) { + return _then(_self.copyWith(conversation: value)); + }); + } +} + +/// Adds pattern-matching-related methods to [ChatState]. +extension ChatStatePatterns on ChatState { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_ChatState value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ChatState() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_ChatState value) $default, + ) { + final _that = this; + switch (_that) { + case _ChatState(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_ChatState value)? $default, + ) { + final _that = this; + switch (_that) { + case _ChatState() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + List messages, + String partialResponse, + AgentChatActivity activity, + bool busy, + bool stopping, + AgentChatError? error, + ConversationMetadata? conversation, + )? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ChatState() when $default != null: + return $default( + _that.messages, + _that.partialResponse, + _that.activity, + _that.busy, + _that.stopping, + _that.error, + _that.conversation, + ); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function( + List messages, + String partialResponse, + AgentChatActivity activity, + bool busy, + bool stopping, + AgentChatError? error, + ConversationMetadata? conversation, + ) + $default, + ) { + final _that = this; + switch (_that) { + case _ChatState(): + return $default( + _that.messages, + _that.partialResponse, + _that.activity, + _that.busy, + _that.stopping, + _that.error, + _that.conversation, + ); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + List messages, + String partialResponse, + AgentChatActivity activity, + bool busy, + bool stopping, + AgentChatError? error, + ConversationMetadata? conversation, + )? + $default, + ) { + final _that = this; + switch (_that) { + case _ChatState() when $default != null: + return $default( + _that.messages, + _that.partialResponse, + _that.activity, + _that.busy, + _that.stopping, + _that.error, + _that.conversation, + ); + case _: + return null; + } + } +} + +/// @nodoc + +class _ChatState implements ChatState { + const _ChatState({ + List messages = const [], + this.partialResponse = '', + this.activity = AgentChatActivity.replying, + this.busy = false, + this.stopping = false, + this.error, + this.conversation, + }) : _messages = messages; + + final List _messages; + @override + @JsonKey() + List get messages { + if (_messages is EqualUnmodifiableListView) return _messages; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_messages); + } + + @override + @JsonKey() + final String partialResponse; + @override + @JsonKey() + final AgentChatActivity activity; + @override + @JsonKey() + final bool busy; + @override + @JsonKey() + final bool stopping; + @override + final AgentChatError? error; + @override + final ConversationMetadata? conversation; + + /// Create a copy of ChatState + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$ChatStateCopyWith<_ChatState> get copyWith => + __$ChatStateCopyWithImpl<_ChatState>(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _ChatState && + const DeepCollectionEquality().equals(other.messages, _messages) && + (identical(other.partialResponse, partialResponse) || + other.partialResponse == partialResponse) && + (identical(other.activity, activity) || + other.activity == activity) && + (identical(other.busy, busy) || other.busy == busy) && + (identical(other.stopping, stopping) || + other.stopping == stopping) && + (identical(other.error, error) || other.error == error) && + (identical(other.conversation, conversation) || + other.conversation == conversation)); + } + + @override + int get hashCode { + return Object.hash( + runtimeType, + const DeepCollectionEquality().hash(_messages), + partialResponse, + activity, + busy, + stopping, + error, + conversation, + ); + } + + @override + String toString() { + return 'ChatState(messages: $messages, partialResponse: $partialResponse, activity: $activity, busy: $busy, stopping: $stopping, error: $error, conversation: $conversation)'; + } +} + +/// @nodoc +abstract mixin class _$ChatStateCopyWith<$Res> + implements $ChatStateCopyWith<$Res> { + factory _$ChatStateCopyWith( + _ChatState value, + $Res Function(_ChatState) _then, + ) = __$ChatStateCopyWithImpl; + @override + @useResult + $Res call({ + List messages, + String partialResponse, + AgentChatActivity activity, + bool busy, + bool stopping, + AgentChatError? error, + ConversationMetadata? conversation, + }); + + @override + $ConversationMetadataCopyWith<$Res>? get conversation; +} + +/// @nodoc +class __$ChatStateCopyWithImpl<$Res> implements _$ChatStateCopyWith<$Res> { + __$ChatStateCopyWithImpl(this._self, this._then); + + final _ChatState _self; + final $Res Function(_ChatState) _then; + + /// Create a copy of ChatState + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? messages = null, + Object? partialResponse = null, + Object? activity = null, + Object? busy = null, + Object? stopping = null, + Object? error = freezed, + Object? conversation = freezed, + }) { + return _then( + _ChatState( + messages: null == messages + ? _self._messages + : messages // ignore: cast_nullable_to_non_nullable + as List, + partialResponse: null == partialResponse + ? _self.partialResponse + : partialResponse // ignore: cast_nullable_to_non_nullable + as String, + activity: null == activity + ? _self.activity + : activity // ignore: cast_nullable_to_non_nullable + as AgentChatActivity, + busy: null == busy + ? _self.busy + : busy // ignore: cast_nullable_to_non_nullable + as bool, + stopping: null == stopping + ? _self.stopping + : stopping // ignore: cast_nullable_to_non_nullable + as bool, + error: freezed == error + ? _self.error + : error // ignore: cast_nullable_to_non_nullable + as AgentChatError?, + conversation: freezed == conversation + ? _self.conversation + : conversation // ignore: cast_nullable_to_non_nullable + as ConversationMetadata?, + ), + ); + } + + /// Create a copy of ChatState + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $ConversationMetadataCopyWith<$Res>? get conversation { + if (_self.conversation == null) { + return null; + } + + return $ConversationMetadataCopyWith<$Res>(_self.conversation!, (value) { + return _then(_self.copyWith(conversation: value)); + }); + } +} diff --git a/lib/features/assistant/composer_document.dart b/lib/features/assistant/composer_document.dart new file mode 100644 index 0000000..33d312c --- /dev/null +++ b/lib/features/assistant/composer_document.dart @@ -0,0 +1,346 @@ +import 'package:flutter/material.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +import 'package:cutdex_ui/theme.dart'; + +part 'composer_document.freezed.dart'; +part 'composer_document.g.dart'; + +enum ComposerReferenceKind { media, timeline } + +@freezed +abstract class ComposerReference with _$ComposerReference { + const ComposerReference._(); + + const factory ComposerReference({ + required ComposerReferenceKind kind, + required String projectId, + required String id, + required String label, + }) = _ComposerReference; + + String get display => '@$label'; + + factory ComposerReference.fromJson(Map json) => + _$ComposerReferenceFromJson(json); +} + +@freezed +abstract class ComposerMark with _$ComposerMark { + const ComposerMark._(); + + const factory ComposerMark({ + required int start, + required int end, + required ComposerReference reference, + @Default(true) bool valid, + }) = _ComposerMark; + + ComposerMark shift(int delta) => + copyWith(start: start + delta, end: end + delta); + + ComposerMark withValidity(bool value) => copyWith(valid: value); +} + +@freezed +sealed class ComposerSegment with _$ComposerSegment { + const ComposerSegment._(); + const factory ComposerSegment.text(String value) = ComposerText; + const factory ComposerSegment.reference(ComposerReference value) = + ComposerReferenceSegment; + + factory ComposerSegment.fromJson(Map json) => + _$ComposerSegmentFromJson(json); + + String get displayText => switch (this) { + ComposerText(:final value) => value, + ComposerReferenceSegment(:final value) => value.label, + }; +} + +@freezed +abstract class _ComposerSnapshot with _$ComposerSnapshot { + const factory _ComposerSnapshot( + TextEditingValue value, + List marks, + ) = _ComposerHistorySnapshot; +} + +/// Keeps Flutter's text offsets and stable resource references in one draft. +class ComposerDocumentController extends TextEditingController { + ComposerDocumentController({super.text}) { + _history.add(_ComposerSnapshot(value, const [])); + } + + List _marks = []; + final List<_ComposerSnapshot> _history = []; + int _historyIndex = 0; + bool _applying = false; + + List get marks => List.unmodifiable(_marks); + bool get hasInvalidReferences => _marks.any((mark) => !mark.valid); + + void _record() { + if (_historyIndex + 1 < _history.length) { + _history.removeRange(_historyIndex + 1, _history.length); + } + _history.add(_ComposerSnapshot(value, List.unmodifiable(_marks))); + _historyIndex = _history.length - 1; + } + + void _apply( + TextEditingValue next, + List marks, { + bool record = true, + }) { + _applying = true; + _marks = List.of(marks); + super.value = next; + _applying = false; + if (record) _record(); + } + + @override + set value(TextEditingValue next) { + if (_applying) { + super.value = next; + return; + } + final old = super.value; + if (old.text == next.text) { + final selection = next.selection; + if (selection.isCollapsed) { + for (final mark in _marks) { + if (selection.baseOffset > mark.start && + selection.baseOffset < mark.end) { + final left = selection.baseOffset - mark.start; + final right = mark.end - selection.baseOffset; + final previous = old.selection; + final boundary = previous.isValid && previous.isCollapsed + ? previous.extentOffset == mark.end && + selection.baseOffset == mark.end - 1 + ? mark.start + : previous.extentOffset == mark.start && + selection.baseOffset == mark.start + 1 + ? mark.end + : null + : null; + super.value = next.copyWith( + selection: TextSelection.collapsed( + offset: boundary ?? (left < right ? mark.start : mark.end), + ), + ); + return; + } + } + } else if (selection.isValid) { + var start = selection.start; + var end = selection.end; + for (final mark in _marks) { + if (start < mark.end && end > mark.start) { + if (start > mark.start) start = mark.start; + if (end < mark.end) end = mark.end; + } + } + if (start != selection.start || end != selection.end) { + super.value = next.copyWith( + selection: TextSelection(baseOffset: start, extentOffset: end), + ); + return; + } + } + super.value = next; + return; + } + + var prefix = 0; + while (prefix < old.text.length && + prefix < next.text.length && + old.text.codeUnitAt(prefix) == next.text.codeUnitAt(prefix)) { + prefix++; + } + var suffix = 0; + while (suffix < old.text.length - prefix && + suffix < next.text.length - prefix && + old.text.codeUnitAt(old.text.length - suffix - 1) == + next.text.codeUnitAt(next.text.length - suffix - 1)) { + suffix++; + } + var start = prefix; + var end = old.text.length - suffix; + final inserted = next.text.substring(prefix, next.text.length - suffix); + final insertion = start == end; + var touchedMark = false; + if (insertion) { + for (final mark in _marks) { + if (start > mark.start && start < mark.end) { + touchedMark = true; + start = mark.end; + end = mark.end; + break; + } + } + } else { + for (final mark in _marks) { + if (start < mark.end && end > mark.start) { + touchedMark = true; + if (mark.start < start) start = mark.start; + if (mark.end > end) end = mark.end; + } + } + } + final changed = old.text.replaceRange(start, end, inserted); + final delta = inserted.length - (end - start); + final marks = [ + for (final mark in _marks) + if (mark.end <= start) + mark + else if (mark.start >= end) + mark.shift(delta), + ]; + _apply( + next.copyWith( + text: changed, + selection: touchedMark + ? TextSelection.collapsed(offset: start + inserted.length) + : next.selection, + composing: touchedMark ? TextRange.empty : next.composing, + ), + marks, + ); + } + + void insertReference(int start, int end, ComposerReference reference) { + final current = value; + if (start < 0 || end < start || end > current.text.length) return; + final display = reference.display; + final nextCharacter = end < current.text.length + ? current.text.substring(end, end + 1) + : ''; + final hasFollowingWhitespace = RegExp(r'^\s$').hasMatch(nextCharacter); + final inserted = '$display${hasFollowingWhitespace ? '' : ' '}'; + final delta = inserted.length - (end - start); + final marks = [ + for (final mark in _marks) + if (mark.end <= start) + mark + else if (mark.start >= end) + mark.shift(delta), + ComposerMark( + start: start, + end: start + display.length, + reference: reference, + ), + ]..sort((a, b) => a.start.compareTo(b.start)); + _apply( + current.copyWith( + text: current.text.replaceRange(start, end, inserted), + selection: TextSelection.collapsed( + offset: + start + + inserted.length + + (nextCharacter == ' ' || nextCharacter == '\t' ? 1 : 0), + ), + composing: TextRange.empty, + ), + marks, + ); + } + + void updateValidity(bool Function(ComposerReference reference) isValid) { + final updated = [ + for (final mark in _marks) mark.withValidity(isValid(mark.reference)), + ]; + if (updated.asMap().entries.every( + (entry) => entry.value.valid == _marks[entry.key].valid, + )) { + return; + } + _marks = updated; + notifyListeners(); + } + + List get segments { + final result = []; + var offset = 0; + for (final mark in _marks) { + if (mark.start > offset) { + result.add(ComposerSegment.text(text.substring(offset, mark.start))); + } + result.add(ComposerSegment.reference(mark.reference)); + offset = mark.end; + } + if (offset < text.length) { + result.add(ComposerSegment.text(text.substring(offset))); + } + return result; + } + + void clearDocument() => _apply(const TextEditingValue(), const []); + + void undoDocument() { + if (_historyIndex == 0) return; + _historyIndex--; + final snapshot = _history[_historyIndex]; + _apply(snapshot.value, snapshot.marks, record: false); + } + + void redoDocument() { + if (_historyIndex >= _history.length - 1) return; + _historyIndex++; + final snapshot = _history[_historyIndex]; + _apply(snapshot.value, snapshot.marks, record: false); + } + + @override + TextSpan buildTextSpan({ + required BuildContext context, + TextStyle? style, + required bool withComposing, + }) { + if (_marks.isEmpty) { + return super.buildTextSpan( + context: context, + style: style, + withComposing: withComposing, + ); + } + final theme = Theme.of(context); + final children = []; + var offset = 0; + for (final mark in _marks) { + if (mark.start > offset) { + children.add(TextSpan(text: text.substring(offset, mark.start))); + } + final color = mark.valid + ? AppTheme.composerReferenceColor(context) + : theme.colorScheme.error; + children.add( + WidgetSpan( + alignment: PlaceholderAlignment.middle, + child: Padding( + padding: const EdgeInsets.only(right: 4), + child: Icon( + mark.reference.kind == ComposerReferenceKind.timeline + ? Icons.view_timeline_outlined + : Icons.attach_file, + size: 14, + color: color, + ), + ), + ), + ); + children.add( + TextSpan( + text: text.substring(mark.start + 1, mark.end), + style: TextStyle(color: color, fontWeight: FontWeight.w600), + ), + ); + offset = mark.end; + } + if (offset < text.length) { + children.add(TextSpan(text: text.substring(offset))); + } + return TextSpan(style: style, children: children); + } +} diff --git a/lib/features/assistant/composer_document.freezed.dart b/lib/features/assistant/composer_document.freezed.dart new file mode 100644 index 0000000..2b7796e --- /dev/null +++ b/lib/features/assistant/composer_document.freezed.dart @@ -0,0 +1,1555 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'composer_document.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +T _$identity(T value) => value; + +/// @nodoc +mixin _$ComposerReference { + ComposerReferenceKind get kind; + String get projectId; + String get id; + String get label; + + /// Create a copy of ComposerReference + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $ComposerReferenceCopyWith get copyWith => + _$ComposerReferenceCopyWithImpl( + this as ComposerReference, + _$identity, + ); + + /// Serializes this ComposerReference to a JSON map. + Map toJson(); + + @override + bool operator ==(Object other) { + final _this = this as ComposerReference; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is ComposerReference && + (identical(other.kind, _this.kind) || other.kind == _this.kind) && + (identical(other.projectId, _this.projectId) || + other.projectId == _this.projectId) && + (identical(other.id, _this.id) || other.id == _this.id) && + (identical(other.label, _this.label) || + other.label == _this.label)); + } + + @JsonKey(includeFromJson: false, includeToJson: false) + @override + int get hashCode { + final _this = this as ComposerReference; + return Object.hash( + runtimeType, + _this.kind, + _this.projectId, + _this.id, + _this.label, + ); + } + + @override + String toString() { + final _this = this as ComposerReference; + return 'ComposerReference(kind: ${_this.kind}, projectId: ${_this.projectId}, id: ${_this.id}, label: ${_this.label})'; + } +} + +/// @nodoc +abstract mixin class $ComposerReferenceCopyWith<$Res> { + factory $ComposerReferenceCopyWith( + ComposerReference value, + $Res Function(ComposerReference) _then, + ) = _$ComposerReferenceCopyWithImpl; + @useResult + $Res call({ + ComposerReferenceKind kind, + String projectId, + String id, + String label, + }); +} + +/// @nodoc +class _$ComposerReferenceCopyWithImpl<$Res> + implements $ComposerReferenceCopyWith<$Res> { + _$ComposerReferenceCopyWithImpl(this._self, this._then); + + final ComposerReference _self; + final $Res Function(ComposerReference) _then; + + /// Create a copy of ComposerReference + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? kind = null, + Object? projectId = null, + Object? id = null, + Object? label = null, + }) { + return _then( + ComposerReference( + kind: null == kind + ? _self.kind + : kind // ignore: cast_nullable_to_non_nullable + as ComposerReferenceKind, + projectId: null == projectId + ? _self.projectId + : projectId // ignore: cast_nullable_to_non_nullable + as String, + id: null == id + ? _self.id + : id // ignore: cast_nullable_to_non_nullable + as String, + label: null == label + ? _self.label + : label // ignore: cast_nullable_to_non_nullable + as String, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [ComposerReference]. +extension ComposerReferencePatterns on ComposerReference { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_ComposerReference value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ComposerReference() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_ComposerReference value) $default, + ) { + final _that = this; + switch (_that) { + case _ComposerReference(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_ComposerReference value)? $default, + ) { + final _that = this; + switch (_that) { + case _ComposerReference() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + ComposerReferenceKind kind, + String projectId, + String id, + String label, + )? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ComposerReference() when $default != null: + return $default(_that.kind, _that.projectId, _that.id, _that.label); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function( + ComposerReferenceKind kind, + String projectId, + String id, + String label, + ) + $default, + ) { + final _that = this; + switch (_that) { + case _ComposerReference(): + return $default(_that.kind, _that.projectId, _that.id, _that.label); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + ComposerReferenceKind kind, + String projectId, + String id, + String label, + )? + $default, + ) { + final _that = this; + switch (_that) { + case _ComposerReference() when $default != null: + return $default(_that.kind, _that.projectId, _that.id, _that.label); + case _: + return null; + } + } +} + +/// @nodoc +@JsonSerializable() +class _ComposerReference extends ComposerReference { + const _ComposerReference({ + required this.kind, + required this.projectId, + required this.id, + required this.label, + }) : super._(); + factory _ComposerReference.fromJson(Map json) => + _$ComposerReferenceFromJson(json); + + @override + final ComposerReferenceKind kind; + @override + final String projectId; + @override + final String id; + @override + final String label; + + /// Create a copy of ComposerReference + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$ComposerReferenceCopyWith<_ComposerReference> get copyWith => + __$ComposerReferenceCopyWithImpl<_ComposerReference>(this, _$identity); + + @override + Map toJson() { + return _$ComposerReferenceToJson(this); + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _ComposerReference && + (identical(other.kind, kind) || other.kind == kind) && + (identical(other.projectId, projectId) || + other.projectId == projectId) && + (identical(other.id, id) || other.id == id) && + (identical(other.label, label) || other.label == label)); + } + + @JsonKey(includeFromJson: false, includeToJson: false) + @override + int get hashCode { + return Object.hash(runtimeType, kind, projectId, id, label); + } + + @override + String toString() { + return 'ComposerReference(kind: $kind, projectId: $projectId, id: $id, label: $label)'; + } +} + +/// @nodoc +abstract mixin class _$ComposerReferenceCopyWith<$Res> + implements $ComposerReferenceCopyWith<$Res> { + factory _$ComposerReferenceCopyWith( + _ComposerReference value, + $Res Function(_ComposerReference) _then, + ) = __$ComposerReferenceCopyWithImpl; + @override + @useResult + $Res call({ + ComposerReferenceKind kind, + String projectId, + String id, + String label, + }); +} + +/// @nodoc +class __$ComposerReferenceCopyWithImpl<$Res> + implements _$ComposerReferenceCopyWith<$Res> { + __$ComposerReferenceCopyWithImpl(this._self, this._then); + + final _ComposerReference _self; + final $Res Function(_ComposerReference) _then; + + /// Create a copy of ComposerReference + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? kind = null, + Object? projectId = null, + Object? id = null, + Object? label = null, + }) { + return _then( + _ComposerReference( + kind: null == kind + ? _self.kind + : kind // ignore: cast_nullable_to_non_nullable + as ComposerReferenceKind, + projectId: null == projectId + ? _self.projectId + : projectId // ignore: cast_nullable_to_non_nullable + as String, + id: null == id + ? _self.id + : id // ignore: cast_nullable_to_non_nullable + as String, + label: null == label + ? _self.label + : label // ignore: cast_nullable_to_non_nullable + as String, + ), + ); + } +} + +/// @nodoc +mixin _$ComposerMark { + int get start; + int get end; + ComposerReference get reference; + bool get valid; + + /// Create a copy of ComposerMark + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $ComposerMarkCopyWith get copyWith => + _$ComposerMarkCopyWithImpl( + this as ComposerMark, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as ComposerMark; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is ComposerMark && + (identical(other.start, _this.start) || + other.start == _this.start) && + (identical(other.end, _this.end) || other.end == _this.end) && + (identical(other.reference, _this.reference) || + other.reference == _this.reference) && + (identical(other.valid, _this.valid) || + other.valid == _this.valid)); + } + + @override + int get hashCode { + final _this = this as ComposerMark; + return Object.hash( + runtimeType, + _this.start, + _this.end, + _this.reference, + _this.valid, + ); + } + + @override + String toString() { + final _this = this as ComposerMark; + return 'ComposerMark(start: ${_this.start}, end: ${_this.end}, reference: ${_this.reference}, valid: ${_this.valid})'; + } +} + +/// @nodoc +abstract mixin class $ComposerMarkCopyWith<$Res> { + factory $ComposerMarkCopyWith( + ComposerMark value, + $Res Function(ComposerMark) _then, + ) = _$ComposerMarkCopyWithImpl; + @useResult + $Res call({int start, int end, ComposerReference reference, bool valid}); + + $ComposerReferenceCopyWith<$Res> get reference; +} + +/// @nodoc +class _$ComposerMarkCopyWithImpl<$Res> implements $ComposerMarkCopyWith<$Res> { + _$ComposerMarkCopyWithImpl(this._self, this._then); + + final ComposerMark _self; + final $Res Function(ComposerMark) _then; + + /// Create a copy of ComposerMark + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? start = null, + Object? end = null, + Object? reference = null, + Object? valid = null, + }) { + return _then( + ComposerMark( + start: null == start + ? _self.start + : start // ignore: cast_nullable_to_non_nullable + as int, + end: null == end + ? _self.end + : end // ignore: cast_nullable_to_non_nullable + as int, + reference: null == reference + ? _self.reference + : reference // ignore: cast_nullable_to_non_nullable + as ComposerReference, + valid: null == valid + ? _self.valid + : valid // ignore: cast_nullable_to_non_nullable + as bool, + ), + ); + } + + /// Create a copy of ComposerMark + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $ComposerReferenceCopyWith<$Res> get reference { + return $ComposerReferenceCopyWith<$Res>(_self.reference, (value) { + return _then(_self.copyWith(reference: value)); + }); + } +} + +/// Adds pattern-matching-related methods to [ComposerMark]. +extension ComposerMarkPatterns on ComposerMark { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_ComposerMark value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ComposerMark() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_ComposerMark value) $default, + ) { + final _that = this; + switch (_that) { + case _ComposerMark(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_ComposerMark value)? $default, + ) { + final _that = this; + switch (_that) { + case _ComposerMark() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + int start, + int end, + ComposerReference reference, + bool valid, + )? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ComposerMark() when $default != null: + return $default(_that.start, _that.end, _that.reference, _that.valid); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function( + int start, + int end, + ComposerReference reference, + bool valid, + ) + $default, + ) { + final _that = this; + switch (_that) { + case _ComposerMark(): + return $default(_that.start, _that.end, _that.reference, _that.valid); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + int start, + int end, + ComposerReference reference, + bool valid, + )? + $default, + ) { + final _that = this; + switch (_that) { + case _ComposerMark() when $default != null: + return $default(_that.start, _that.end, _that.reference, _that.valid); + case _: + return null; + } + } +} + +/// @nodoc + +class _ComposerMark extends ComposerMark { + const _ComposerMark({ + required this.start, + required this.end, + required this.reference, + this.valid = true, + }) : super._(); + + @override + final int start; + @override + final int end; + @override + final ComposerReference reference; + @override + @JsonKey() + final bool valid; + + /// Create a copy of ComposerMark + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$ComposerMarkCopyWith<_ComposerMark> get copyWith => + __$ComposerMarkCopyWithImpl<_ComposerMark>(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _ComposerMark && + (identical(other.start, start) || other.start == start) && + (identical(other.end, end) || other.end == end) && + (identical(other.reference, reference) || + other.reference == reference) && + (identical(other.valid, valid) || other.valid == valid)); + } + + @override + int get hashCode { + return Object.hash(runtimeType, start, end, reference, valid); + } + + @override + String toString() { + return 'ComposerMark(start: $start, end: $end, reference: $reference, valid: $valid)'; + } +} + +/// @nodoc +abstract mixin class _$ComposerMarkCopyWith<$Res> + implements $ComposerMarkCopyWith<$Res> { + factory _$ComposerMarkCopyWith( + _ComposerMark value, + $Res Function(_ComposerMark) _then, + ) = __$ComposerMarkCopyWithImpl; + @override + @useResult + $Res call({int start, int end, ComposerReference reference, bool valid}); + + @override + $ComposerReferenceCopyWith<$Res> get reference; +} + +/// @nodoc +class __$ComposerMarkCopyWithImpl<$Res> + implements _$ComposerMarkCopyWith<$Res> { + __$ComposerMarkCopyWithImpl(this._self, this._then); + + final _ComposerMark _self; + final $Res Function(_ComposerMark) _then; + + /// Create a copy of ComposerMark + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? start = null, + Object? end = null, + Object? reference = null, + Object? valid = null, + }) { + return _then( + _ComposerMark( + start: null == start + ? _self.start + : start // ignore: cast_nullable_to_non_nullable + as int, + end: null == end + ? _self.end + : end // ignore: cast_nullable_to_non_nullable + as int, + reference: null == reference + ? _self.reference + : reference // ignore: cast_nullable_to_non_nullable + as ComposerReference, + valid: null == valid + ? _self.valid + : valid // ignore: cast_nullable_to_non_nullable + as bool, + ), + ); + } + + /// Create a copy of ComposerMark + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $ComposerReferenceCopyWith<$Res> get reference { + return $ComposerReferenceCopyWith<$Res>(_self.reference, (value) { + return _then(_self.copyWith(reference: value)); + }); + } +} + +ComposerSegment _$ComposerSegmentFromJson(Map json) { + switch (json['runtimeType']) { + case 'text': + return ComposerText.fromJson(json); + case 'reference': + return ComposerReferenceSegment.fromJson(json); + + default: + throw CheckedFromJsonException( + json, + 'runtimeType', + 'ComposerSegment', + 'Invalid union type "${json['runtimeType']}"!', + ); + } +} + +/// @nodoc +mixin _$ComposerSegment { + Object get value; + + /// Serializes this ComposerSegment to a JSON map. + Map toJson(); + + @override + bool operator ==(Object other) { + final _this = this as ComposerSegment; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is ComposerSegment && + const DeepCollectionEquality().equals(other.value, _this.value)); + } + + @JsonKey(includeFromJson: false, includeToJson: false) + @override + int get hashCode { + final _this = this as ComposerSegment; + return Object.hash( + runtimeType, + const DeepCollectionEquality().hash(_this.value), + ); + } + + @override + String toString() { + final _this = this as ComposerSegment; + return 'ComposerSegment(value: ${_this.value})'; + } +} + +/// @nodoc +class $ComposerSegmentCopyWith<$Res> { + $ComposerSegmentCopyWith( + ComposerSegment _, + $Res Function(ComposerSegment) __, + ); +} + +/// Adds pattern-matching-related methods to [ComposerSegment]. +extension ComposerSegmentPatterns on ComposerSegment { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap({ + TResult Function(ComposerText value)? text, + TResult Function(ComposerReferenceSegment value)? reference, + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case ComposerText() when text != null: + return text(_that); + case ComposerReferenceSegment() when reference != null: + return reference(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map({ + required TResult Function(ComposerText value) text, + required TResult Function(ComposerReferenceSegment value) reference, + }) { + final _that = this; + switch (_that) { + case ComposerText(): + return text(_that); + case ComposerReferenceSegment(): + return reference(_that); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(ComposerText value)? text, + TResult? Function(ComposerReferenceSegment value)? reference, + }) { + final _that = this; + switch (_that) { + case ComposerText() when text != null: + return text(_that); + case ComposerReferenceSegment() when reference != null: + return reference(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen({ + TResult Function(String value)? text, + TResult Function(ComposerReference value)? reference, + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case ComposerText() when text != null: + return text(_that.value); + case ComposerReferenceSegment() when reference != null: + return reference(_that.value); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when({ + required TResult Function(String value) text, + required TResult Function(ComposerReference value) reference, + }) { + final _that = this; + switch (_that) { + case ComposerText(): + return text(_that.value); + case ComposerReferenceSegment(): + return reference(_that.value); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function(String value)? text, + TResult? Function(ComposerReference value)? reference, + }) { + final _that = this; + switch (_that) { + case ComposerText() when text != null: + return text(_that.value); + case ComposerReferenceSegment() when reference != null: + return reference(_that.value); + case _: + return null; + } + } +} + +/// @nodoc +@JsonSerializable() +class ComposerText extends ComposerSegment { + const ComposerText(this.value, {String? $type}) + : $type = $type ?? 'text', + super._(); + factory ComposerText.fromJson(Map json) => + _$ComposerTextFromJson(json); + + @override + final String value; + + @JsonKey(name: 'runtimeType') + final String $type; + + /// Create a copy of ComposerSegment + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $ComposerTextCopyWith get copyWith => + _$ComposerTextCopyWithImpl(this, _$identity); + + @override + Map toJson() { + return _$ComposerTextToJson(this); + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is ComposerText && + (identical(other.value, value) || other.value == value)); + } + + @JsonKey(includeFromJson: false, includeToJson: false) + @override + int get hashCode { + return Object.hash(runtimeType, value); + } + + @override + String toString() { + return 'ComposerSegment.text(value: $value)'; + } +} + +/// @nodoc +abstract mixin class $ComposerTextCopyWith<$Res> + implements $ComposerSegmentCopyWith<$Res> { + factory $ComposerTextCopyWith( + ComposerText value, + $Res Function(ComposerText) _then, + ) = _$ComposerTextCopyWithImpl; + @useResult + $Res call({String value}); +} + +/// @nodoc +class _$ComposerTextCopyWithImpl<$Res> implements $ComposerTextCopyWith<$Res> { + _$ComposerTextCopyWithImpl(this._self, this._then); + + final ComposerText _self; + final $Res Function(ComposerText) _then; + + /// Create a copy of ComposerSegment + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({Object? value = null}) { + return _then( + ComposerText( + null == value + ? _self.value + : value // ignore: cast_nullable_to_non_nullable + as String, + ), + ); + } +} + +/// @nodoc +@JsonSerializable() +class ComposerReferenceSegment extends ComposerSegment { + const ComposerReferenceSegment(this.value, {String? $type}) + : $type = $type ?? 'reference', + super._(); + factory ComposerReferenceSegment.fromJson(Map json) => + _$ComposerReferenceSegmentFromJson(json); + + @override + final ComposerReference value; + + @JsonKey(name: 'runtimeType') + final String $type; + + /// Create a copy of ComposerSegment + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $ComposerReferenceSegmentCopyWith get copyWith => + _$ComposerReferenceSegmentCopyWithImpl( + this, + _$identity, + ); + + @override + Map toJson() { + return _$ComposerReferenceSegmentToJson(this); + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is ComposerReferenceSegment && + (identical(other.value, value) || other.value == value)); + } + + @JsonKey(includeFromJson: false, includeToJson: false) + @override + int get hashCode { + return Object.hash(runtimeType, value); + } + + @override + String toString() { + return 'ComposerSegment.reference(value: $value)'; + } +} + +/// @nodoc +abstract mixin class $ComposerReferenceSegmentCopyWith<$Res> + implements $ComposerSegmentCopyWith<$Res> { + factory $ComposerReferenceSegmentCopyWith( + ComposerReferenceSegment value, + $Res Function(ComposerReferenceSegment) _then, + ) = _$ComposerReferenceSegmentCopyWithImpl; + @useResult + $Res call({ComposerReference value}); + + $ComposerReferenceCopyWith<$Res> get value; +} + +/// @nodoc +class _$ComposerReferenceSegmentCopyWithImpl<$Res> + implements $ComposerReferenceSegmentCopyWith<$Res> { + _$ComposerReferenceSegmentCopyWithImpl(this._self, this._then); + + final ComposerReferenceSegment _self; + final $Res Function(ComposerReferenceSegment) _then; + + /// Create a copy of ComposerSegment + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({Object? value = null}) { + return _then( + ComposerReferenceSegment( + null == value + ? _self.value + : value // ignore: cast_nullable_to_non_nullable + as ComposerReference, + ), + ); + } + + /// Create a copy of ComposerSegment + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $ComposerReferenceCopyWith<$Res> get value { + return $ComposerReferenceCopyWith<$Res>(_self.value, (value) { + return _then(_self.copyWith(value: value)); + }); + } +} + +/// @nodoc +mixin _$ComposerSnapshot { + TextEditingValue get value; + List get marks; + + /// Create a copy of _ComposerSnapshot + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$ComposerSnapshotCopyWith<_ComposerSnapshot> get copyWith => + __$ComposerSnapshotCopyWithImpl<_ComposerSnapshot>( + this as _ComposerSnapshot, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as _ComposerSnapshot; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _ComposerSnapshot && + (identical(other.value, _this.value) || + other.value == _this.value) && + const DeepCollectionEquality().equals(other.marks, _this.marks)); + } + + @override + int get hashCode { + final _this = this as _ComposerSnapshot; + return Object.hash( + runtimeType, + _this.value, + const DeepCollectionEquality().hash(_this.marks), + ); + } + + @override + String toString() { + final _this = this as _ComposerSnapshot; + return '_ComposerSnapshot(value: ${_this.value}, marks: ${_this.marks})'; + } +} + +/// @nodoc +abstract mixin class _$ComposerSnapshotCopyWith<$Res> { + factory _$ComposerSnapshotCopyWith( + _ComposerSnapshot value, + $Res Function(_ComposerSnapshot) _then, + ) = __$ComposerSnapshotCopyWithImpl; + @useResult + $Res call({TextEditingValue value, List marks}); +} + +/// @nodoc +class __$ComposerSnapshotCopyWithImpl<$Res> + implements _$ComposerSnapshotCopyWith<$Res> { + __$ComposerSnapshotCopyWithImpl(this._self, this._then); + + final _ComposerSnapshot _self; + final $Res Function(_ComposerSnapshot) _then; + + /// Create a copy of _ComposerSnapshot + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({Object? value = null, Object? marks = null}) { + return _then( + _ComposerSnapshot( + null == value + ? _self.value + : value // ignore: cast_nullable_to_non_nullable + as TextEditingValue, + null == marks + ? _self.marks + : marks // ignore: cast_nullable_to_non_nullable + as List, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [_ComposerSnapshot]. +extension _ComposerSnapshotPatterns on _ComposerSnapshot { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_ComposerHistorySnapshot value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ComposerHistorySnapshot() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_ComposerHistorySnapshot value) $default, + ) { + final _that = this; + switch (_that) { + case _ComposerHistorySnapshot(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_ComposerHistorySnapshot value)? $default, + ) { + final _that = this; + switch (_that) { + case _ComposerHistorySnapshot() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function(TextEditingValue value, List marks)? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ComposerHistorySnapshot() when $default != null: + return $default(_that.value, _that.marks); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function(TextEditingValue value, List marks) $default, + ) { + final _that = this; + switch (_that) { + case _ComposerHistorySnapshot(): + return $default(_that.value, _that.marks); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function(TextEditingValue value, List marks)? + $default, + ) { + final _that = this; + switch (_that) { + case _ComposerHistorySnapshot() when $default != null: + return $default(_that.value, _that.marks); + case _: + return null; + } + } +} + +/// @nodoc + +class _ComposerHistorySnapshot implements _ComposerSnapshot { + const _ComposerHistorySnapshot(this.value, List marks) + : _marks = marks; + + @override + final TextEditingValue value; + final List _marks; + @override + List get marks { + if (_marks is EqualUnmodifiableListView) return _marks; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_marks); + } + + /// Create a copy of _ComposerSnapshot + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$ComposerHistorySnapshotCopyWith<_ComposerHistorySnapshot> get copyWith => + __$ComposerHistorySnapshotCopyWithImpl<_ComposerHistorySnapshot>( + this, + _$identity, + ); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _ComposerHistorySnapshot && + (identical(other.value, value) || other.value == value) && + const DeepCollectionEquality().equals(other.marks, _marks)); + } + + @override + int get hashCode { + return Object.hash( + runtimeType, + value, + const DeepCollectionEquality().hash(_marks), + ); + } + + @override + String toString() { + return '_ComposerSnapshot(value: $value, marks: $marks)'; + } +} + +/// @nodoc +abstract mixin class _$ComposerHistorySnapshotCopyWith<$Res> + implements _$ComposerSnapshotCopyWith<$Res> { + factory _$ComposerHistorySnapshotCopyWith( + _ComposerHistorySnapshot value, + $Res Function(_ComposerHistorySnapshot) _then, + ) = __$ComposerHistorySnapshotCopyWithImpl; + @override + @useResult + $Res call({TextEditingValue value, List marks}); +} + +/// @nodoc +class __$ComposerHistorySnapshotCopyWithImpl<$Res> + implements _$ComposerHistorySnapshotCopyWith<$Res> { + __$ComposerHistorySnapshotCopyWithImpl(this._self, this._then); + + final _ComposerHistorySnapshot _self; + final $Res Function(_ComposerHistorySnapshot) _then; + + /// Create a copy of _ComposerSnapshot + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({Object? value = null, Object? marks = null}) { + return _then( + _ComposerHistorySnapshot( + null == value + ? _self.value + : value // ignore: cast_nullable_to_non_nullable + as TextEditingValue, + null == marks + ? _self._marks + : marks // ignore: cast_nullable_to_non_nullable + as List, + ), + ); + } +} diff --git a/lib/features/assistant/composer_document.g.dart b/lib/features/assistant/composer_document.g.dart new file mode 100644 index 0000000..bf7edf5 --- /dev/null +++ b/lib/features/assistant/composer_document.g.dart @@ -0,0 +1,50 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'composer_document.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_ComposerReference _$ComposerReferenceFromJson(Map json) => + _ComposerReference( + kind: $enumDecode(_$ComposerReferenceKindEnumMap, json['kind']), + projectId: json['projectId'] as String, + id: json['id'] as String, + label: json['label'] as String, + ); + +Map _$ComposerReferenceToJson(_ComposerReference instance) => + { + 'kind': _$ComposerReferenceKindEnumMap[instance.kind]!, + 'projectId': instance.projectId, + 'id': instance.id, + 'label': instance.label, + }; + +const _$ComposerReferenceKindEnumMap = { + ComposerReferenceKind.media: 'media', + ComposerReferenceKind.timeline: 'timeline', +}; + +ComposerText _$ComposerTextFromJson(Map json) => ComposerText( + json['value'] as String, + $type: json['runtimeType'] as String?, +); + +Map _$ComposerTextToJson(ComposerText instance) => + {'value': instance.value, 'runtimeType': instance.$type}; + +ComposerReferenceSegment _$ComposerReferenceSegmentFromJson( + Map json, +) => ComposerReferenceSegment( + ComposerReference.fromJson(json['value'] as Map), + $type: json['runtimeType'] as String?, +); + +Map _$ComposerReferenceSegmentToJson( + ComposerReferenceSegment instance, +) => { + 'value': instance.value.toJson(), + 'runtimeType': instance.$type, +}; diff --git a/lib/features/assistant/composer_project_selector.dart b/lib/features/assistant/composer_project_selector.dart new file mode 100644 index 0000000..d00e90b --- /dev/null +++ b/lib/features/assistant/composer_project_selector.dart @@ -0,0 +1,214 @@ +import 'package:flutter/material.dart'; + +import '../../l10n/l10n.dart'; +import '../../shared/layout/composer_layout.dart'; +import '../../shared/theme/composer_style.dart'; + +import 'package:cutdex_ui/theme.dart'; + +import '../../workspace/project_state.dart'; + +class ComposerProjectSelector extends StatefulWidget { + const ComposerProjectSelector({ + super.key, + required this.projects, + required this.selected, + required this.busy, + required this.onSelect, + required this.onCreate, + required this.backgroundColor, + }); + + final List projects; + final RecentProject? selected; + final bool busy; + final ValueChanged onSelect; + final VoidCallback? onCreate; + final Color backgroundColor; + + @override + State createState() => + _ComposerProjectSelectorState(); +} + +class _ComposerProjectSelectorState extends State { + final _menu = MenuController(); + final _search = TextEditingController(); + + @override + void dispose() { + _search.dispose(); + super.dispose(); + } + + Widget _item({ + required Key key, + required String label, + required IconData icon, + bool? selected, + bool secondary = false, + VoidCallback? onPressed, + }) { + final colors = Theme.of(context).colorScheme; + return MenuItemButton( + key: key, + onPressed: onPressed, + style: AppComposerStyle.projectMenuItem(context, secondary: secondary), + child: Semantics( + selected: selected, + child: Row( + children: [ + Icon( + icon, + size: ComposerLayout.menuIconSize, + color: onPressed == null + ? Theme.of(context).disabledColor + : colors.onSurfaceVariant, + ), + const SizedBox(width: ComposerLayout.menuIconGap), + Expanded( + child: Text(label, maxLines: 1, overflow: TextOverflow.ellipsis), + ), + if (selected == true) ...[ + const SizedBox(width: ComposerLayout.menuIconGap), + Icon( + Icons.check, + size: ComposerLayout.menuIconSize, + color: colors.onSurfaceVariant, + ), + ], + ], + ), + ), + ); + } + + Widget _separator() => const Padding( + padding: AppComposerStyle.menuSeparatorPadding, + child: Divider( + height: 1, + thickness: AppComposerStyle.menuSeparatorThickness, + ), + ); + + @override + Widget build(BuildContext context) { + final query = _search.text.trim().toLowerCase(); + final projects = widget.projects + .where((project) => project.name.toLowerCase().contains(query)) + .toList(); + return Material( + key: const Key('composer-project-bar'), + color: widget.backgroundColor, + borderRadius: const BorderRadius.vertical( + top: Radius.circular(ComposerLayout.utilityRadius), + ), + child: Padding( + padding: AppComposerStyle.utilityPadding, + child: Align( + alignment: AlignmentDirectional.centerStart, + child: MenuAnchor( + controller: _menu, + consumeOutsideTap: false, + onClose: () => setState(_search.clear), + style: AppComposerStyle.projectMenu(context), + menuChildren: [ + SizedBox( + width: ComposerLayout.menuContentWidth, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + SizedBox( + height: ComposerLayout.menuRowHeight, + child: TextField( + key: const Key('composer-project-search'), + controller: _search, + autofocus: true, + style: AppTheme.composerTextStyle(context), + onChanged: (_) => setState(() {}), + decoration: AppComposerStyle.projectSearchDecoration( + context, + hintText: context.l10n.searchProjects, + ), + ), + ), + _separator(), + ConstrainedBox( + constraints: const BoxConstraints( + maxHeight: ComposerLayout.menuListMaxHeight, + ), + child: SingleChildScrollView( + primary: false, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (projects.isEmpty) + Padding( + padding: AppComposerStyle.menuEmptyPadding, + child: Text( + query.isEmpty + ? context.l10n.projectsNone + : context.l10n.noMatchingProjects, + style: Theme.of(context).textTheme.bodySmall, + ), + ), + for (final project in projects) + _item( + key: ValueKey('composer-project-${project.id}'), + label: project.name, + icon: Icons.folder_outlined, + selected: project.id == widget.selected?.id, + onPressed: + widget.busy || !project.availability.canOpen + ? null + : () { + _menu.close(); + widget.onSelect(project); + }, + ), + ], + ), + ), + ), + _separator(), + _item( + key: const Key('composer-new-project'), + secondary: true, + label: context.l10n.newProject, + icon: Icons.add, + onPressed: widget.busy || widget.onCreate == null + ? null + : () { + _menu.close(); + widget.onCreate!(); + }, + ), + ], + ), + ), + ], + builder: (context, controller, _) => TextButton.icon( + key: const Key('composer-project-trigger'), + onPressed: widget.busy + ? null + : () => controller.isOpen + ? controller.close() + : controller.open(), + style: AppComposerStyle.projectTrigger(context), + icon: const Icon( + Icons.folder_outlined, + size: ComposerLayout.menuIconSize, + ), + label: Text( + widget.selected?.name ?? context.l10n.selectProject, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + ), + ), + ), + ); + } +} diff --git a/lib/features/assistant/composer_reference_validator.dart b/lib/features/assistant/composer_reference_validator.dart new file mode 100644 index 0000000..a56df1f --- /dev/null +++ b/lib/features/assistant/composer_reference_validator.dart @@ -0,0 +1,32 @@ +import '../../workspace/project_state.dart'; +import 'composer_document.dart'; + +/// Checks draft references against the project currently open in the composer. +final class ComposerReferenceValidator { + const ComposerReferenceValidator({ + required this.workspace, + required this.projectId, + }); + + final ProjectState? workspace; + final String? projectId; + + bool isValid(ComposerReference reference) { + if (projectId != reference.projectId || + workspace?.activeProject?.id != reference.projectId) { + return false; + } + return switch (reference.kind) { + ComposerReferenceKind.media => workspace!.assets.any( + (asset) => asset.id == reference.id, + ), + ComposerReferenceKind.timeline => workspace!.timelines.any( + (timeline) => timeline.id == reference.id, + ), + }; + } + + void validate(ComposerDocumentController document) { + document.updateValidity(isValid); + } +} diff --git a/lib/features/assistant/composer_suggestion_surface.dart b/lib/features/assistant/composer_suggestion_surface.dart new file mode 100644 index 0000000..506d51a --- /dev/null +++ b/lib/features/assistant/composer_suggestion_surface.dart @@ -0,0 +1,506 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../../l10n/app_localizations.dart'; + +import 'package:cutdex_ui/theme.dart'; + +import 'composer_document.dart'; +import 'composer_suggestions.dart'; + +part 'composer_suggestion_surface.freezed.dart'; + +/// Owns suggestion focus, keyboard navigation, selection and the anchored menu. +/// The caller supplies the composer body and the action used when Enter sends. +class ComposerSuggestionSurface extends StatefulWidget { + const ComposerSuggestionSurface({ + super.key, + required this.controller, + required this.width, + required this.projectId, + required this.assets, + required this.timelines, + required this.onSend, + required this.builder, + }); + + final ComposerDocumentController controller; + final double width; + final String? projectId; + final Iterable assets; + final Iterable timelines; + final VoidCallback onSend; + final Widget Function(BuildContext context, FocusNode inputFocus) builder; + + @override + State createState() => + _ComposerSuggestionSurfaceState(); +} + +class _ComposerSuggestionSurfaceState extends State { + final _focus = FocusNode(); + final _link = LayerLink(); + final _portal = OverlayPortalController(); + final _anchorKey = GlobalKey(); + final _tapGroup = Object(); + final _menuScrollController = ScrollController(keepScrollOffset: false); + ComposerTriggerQuery? _trigger; + int _selected = 0; + ComposerTriggerQuery? _suppressedQuery; + + @override + void initState() { + super.initState(); + widget.controller.addListener(_onDocumentChanged); + } + + @override + void didUpdateWidget(covariant ComposerSuggestionSurface oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.controller != widget.controller) { + oldWidget.controller.removeListener(_onDocumentChanged); + widget.controller.addListener(_onDocumentChanged); + _onDocumentChanged(); + } + } + + @override + void dispose() { + widget.controller.removeListener(_onDocumentChanged); + _menuScrollController.dispose(); + _focus.dispose(); + super.dispose(); + } + + void _onDocumentChanged() { + final candidate = findComposerTrigger( + widget.controller.value, + widget.controller.marks, + ); + final suppressed = _suppressedQuery; + final stillSuppressed = + candidate != null && + suppressed != null && + candidate.start == suppressed.start && + candidate.trigger == suppressed.trigger && + candidate.query == suppressed.query; + if (!stillSuppressed) _suppressedQuery = null; + final next = stillSuppressed ? null : candidate; + if (next?.start == _trigger?.start && + next?.query == _trigger?.query && + next?.trigger == _trigger?.trigger) { + return; + } + if (!mounted) return; + setState(() { + _trigger = next; + _selected = 0; + }); + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + if (_menuScrollController.hasClients) _menuScrollController.jumpTo(0); + if (_trigger == null) { + if (_portal.isShowing) _portal.hide(); + } else if (!_portal.isShowing) { + _portal.show(); + } + }); + } + + void _dismiss({bool suppress = false}) { + if (suppress) _suppressedQuery = _trigger; + setState(() => _trigger = null); + if (_portal.isShowing) _portal.hide(); + } + + List _options(ComposerTriggerQuery query) => + filterComposerOptions( + ComposerOptionCatalog.forTrigger( + query.trigger, + l10n: AppLocalizations.of(context)!, + projectId: widget.projectId, + assets: widget.assets, + timelines: widget.timelines, + ), + query.query, + ); + + void _select(ComposerOption option) { + final query = _trigger; + if (query == null) return; + _dismiss(); + switch (option) { + case ComposerReferenceOption(:final reference): + widget.controller.insertReference(query.start, query.end, reference); + case ComposerTextOption(:final text): + widget.controller.value = widget.controller.value.copyWith( + text: widget.controller.text.replaceRange( + query.start, + query.end, + text, + ), + selection: TextSelection.collapsed(offset: query.start + text.length), + ); + case ComposerPickerOption(:final onInvoke): + case ComposerInvokeOption(:final onInvoke): + onInvoke(); + } + _focus.requestFocus(); + } + + void _selectCurrent() { + final query = _trigger; + if (query == null) return; + final options = _options(query); + if (options.isNotEmpty) { + _select(options[_selected.clamp(0, options.length - 1)]); + } + } + + void _move(int delta) { + final query = _trigger; + if (query == null) return; + final options = _options(query); + final count = options.length; + if (count > 0) { + setState(() => _selected = (_selected + delta + count) % count); + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted || !_menuScrollController.hasClients) return; + final currentQuery = _trigger; + if (currentQuery == null) return; + final rows = _rows(_options(currentQuery)); + var top = AppMenuMetrics.gutter; + for (final row in rows) { + if (row case _SuggestionOption(optionIndex: final index) + when index == _selected) { + final position = _menuScrollController.position; + final bottom = top + row.height; + final visibleTop = position.pixels; + final visibleBottom = visibleTop + position.viewportDimension; + final target = top < visibleTop + ? top - 4 + : bottom > visibleBottom + ? bottom - position.viewportDimension + 4 + : null; + if (target != null) { + _menuScrollController.animateTo( + target.clamp( + position.minScrollExtent, + position.maxScrollExtent, + ), + duration: const Duration(milliseconds: 120), + curve: Curves.easeOut, + ); + } + return; + } + top += row.height; + } + }); + } + } + + List<_SuggestionRow> _rows(List options) { + final rows = <_SuggestionRow>[]; + for (final group in ComposerOptionGroup.values) { + final grouped = options.indexed.where((entry) => entry.$2.group == group); + if (grouped.isEmpty) continue; + rows.add(_SuggestionRow.header(group, rows.isEmpty ? 28 : 36)); + for (final (index, option) in grouped) { + rows.add(_SuggestionRow.option(option, index)); + } + } + for (final (index, option) in options.indexed) { + if (option.group == null) { + rows.add(_SuggestionRow.option(option, index)); + } + } + return rows; + } + + Widget _menu(BuildContext context) { + final query = _trigger; + if (query == null) return const SizedBox.shrink(); + final options = _options(query); + final rows = _rows(options); + final anchor = _anchorKey.currentContext?.findRenderObject(); + final availableAbove = anchor is RenderBox + ? anchor.localToGlobal(Offset.zero).dy - 16 + : MediaQuery.sizeOf(context).height / 2; + final placeBelow = availableAbove < 100; + final maxHeight = placeBelow + ? (MediaQuery.sizeOf(context).height - availableAbove - 120).clamp( + 72.0, + 320.0, + ) + : availableAbove.clamp(72.0, 320.0); + final theme = Theme.of(context); + return Stack( + children: [ + CompositedTransformFollower( + link: _link, + showWhenUnlinked: false, + targetAnchor: placeBelow ? Alignment.bottomLeft : Alignment.topLeft, + followerAnchor: placeBelow ? Alignment.topLeft : Alignment.bottomLeft, + offset: Offset(0, placeBelow ? 4 : -4), + child: TapRegion( + groupId: _tapGroup, + child: Material( + color: AppTheme.popoverBackground(context), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(AppMenuMetrics.radius), + side: BorderSide( + color: theme.colorScheme.outlineVariant, + width: AppMenuMetrics.borderWidth, + ), + ), + clipBehavior: Clip.antiAlias, + child: SizedBox( + key: const Key('agent-composer-suggestions'), + width: widget.width, + child: ConstrainedBox( + constraints: BoxConstraints(maxHeight: maxHeight), + child: options.isEmpty + ? Padding( + padding: const EdgeInsets.all(12), + child: Text( + AppLocalizations.of(context)!.noAvailableOptions, + ), + ) + : ListView.builder( + key: const Key('agent-composer-suggestion-list'), + controller: _menuScrollController, + shrinkWrap: true, + padding: const EdgeInsets.all(AppMenuMetrics.gutter), + itemCount: rows.length, + itemBuilder: (context, index) { + final row = rows[index]; + if (row case _SuggestionHeader(:final group)) { + final labels = AppLocalizations.of(context)!; + return Container( + key: Key( + 'agent-suggestion-group-${group.name}', + ), + height: row.height, + alignment: Alignment.centerLeft, + padding: EdgeInsets.fromLTRB( + 10, + index == 0 ? 4 : 12, + 10, + 5, + ), + child: Text( + switch (group) { + ComposerOptionGroup.media => + labels.materials, + ComposerOptionGroup.timeline => + labels.timelines, + }, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ); + } + final _SuggestionOption(:option, :optionIndex) = + row as _SuggestionOption; + final selected = optionIndex == _selected; + return InkWell( + key: Key( + 'agent-suggestion-${option is ComposerReferenceOption ? option.reference.kind.name : option.trigger}-${option is ComposerReferenceOption ? option.reference.id : index}', + ), + borderRadius: BorderRadius.circular( + AppMenuMetrics.itemRadius, + ), + onTap: () => _select(option), + child: Container( + height: 40, + padding: const EdgeInsets.symmetric( + horizontal: 10, + ), + decoration: BoxDecoration( + color: selected + ? theme.colorScheme.onSurface.withValues( + alpha: .1, + ) + : null, + borderRadius: BorderRadius.circular( + AppMenuMetrics.itemRadius, + ), + ), + child: Row( + children: [ + Icon(option.icon, size: 15), + const SizedBox( + width: AppMenuMetrics.iconGap, + ), + Expanded( + child: Text( + option.title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: theme.textTheme.bodyMedium, + ), + ), + if (option.group == null && + option.subtitle.isNotEmpty) ...[ + const SizedBox(width: 8), + Text( + option.subtitle, + style: theme.textTheme.bodySmall, + ), + ], + ], + ), + ), + ); + }, + ), + ), + ), + ), + ), + ), + ], + ); + } + + @override + Widget build(BuildContext context) { + final content = widget.builder(context, _focus); + return OverlayPortal( + controller: _portal, + overlayChildBuilder: _menu, + child: TapRegion( + groupId: _tapGroup, + onTapOutside: (_) { + if (_trigger != null) _dismiss(suppress: true); + }, + child: CompositedTransformTarget( + key: _anchorKey, + link: _link, + child: ValueListenableBuilder( + valueListenable: widget.controller, + child: content, + builder: (context, value, child) { + final composing = + value.composing.isValid && !value.composing.isCollapsed; + final enter = composing + ? const DoNothingAndStopPropagationIntent() + : _trigger != null + ? const _SelectSuggestionIntent() + : const _SendComposerIntent(); + return Shortcuts( + shortcuts: { + const SingleActivator(LogicalKeyboardKey.enter): enter, + const SingleActivator(LogicalKeyboardKey.numpadEnter): enter, + if (_trigger != null) ...{ + const SingleActivator(LogicalKeyboardKey.arrowDown): + const _MoveSuggestionIntent(1), + const SingleActivator(LogicalKeyboardKey.arrowUp): + const _MoveSuggestionIntent(-1), + const SingleActivator(LogicalKeyboardKey.escape): + const _DismissSuggestionIntent(), + }, + const SingleActivator(LogicalKeyboardKey.keyZ, meta: true): + const _UndoComposerIntent(), + const SingleActivator( + LogicalKeyboardKey.keyZ, + meta: true, + shift: true, + ): const _RedoComposerIntent(), + }, + child: Actions( + actions: { + _SendComposerIntent: CallbackAction<_SendComposerIntent>( + onInvoke: (_) { + widget.onSend(); + return null; + }, + ), + _SelectSuggestionIntent: + CallbackAction<_SelectSuggestionIntent>( + onInvoke: (_) { + _selectCurrent(); + return null; + }, + ), + _MoveSuggestionIntent: + CallbackAction<_MoveSuggestionIntent>( + onInvoke: (intent) { + _move(intent.delta); + return null; + }, + ), + _DismissSuggestionIntent: + CallbackAction<_DismissSuggestionIntent>( + onInvoke: (_) { + _dismiss(suppress: true); + return null; + }, + ), + _UndoComposerIntent: CallbackAction<_UndoComposerIntent>( + onInvoke: (_) { + widget.controller.undoDocument(); + return null; + }, + ), + _RedoComposerIntent: CallbackAction<_RedoComposerIntent>( + onInvoke: (_) { + widget.controller.redoDocument(); + return null; + }, + ), + }, + child: child!, + ), + ); + }, + ), + ), + ), + ); + } +} + +class _SendComposerIntent extends Intent { + const _SendComposerIntent(); +} + +class _SelectSuggestionIntent extends Intent { + const _SelectSuggestionIntent(); +} + +class _MoveSuggestionIntent extends Intent { + const _MoveSuggestionIntent(this.delta); + final int delta; +} + +class _DismissSuggestionIntent extends Intent { + const _DismissSuggestionIntent(); +} + +class _UndoComposerIntent extends Intent { + const _UndoComposerIntent(); +} + +class _RedoComposerIntent extends Intent { + const _RedoComposerIntent(); +} + +@freezed +sealed class _SuggestionRow with _$SuggestionRow { + const _SuggestionRow._(); + const factory _SuggestionRow.header( + ComposerOptionGroup group, + double height, + ) = _SuggestionHeader; + const factory _SuggestionRow.option(ComposerOption option, int optionIndex) = + _SuggestionOption; + double get height => switch (this) { + _SuggestionHeader(:final height) => height, + _SuggestionOption() => 40, + }; +} diff --git a/lib/features/assistant/composer_suggestion_surface.freezed.dart b/lib/features/assistant/composer_suggestion_surface.freezed.dart new file mode 100644 index 0000000..77de798 --- /dev/null +++ b/lib/features/assistant/composer_suggestion_surface.freezed.dart @@ -0,0 +1,365 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'composer_suggestion_surface.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +T _$identity(T value) => value; + +/// @nodoc +mixin _$SuggestionRow { + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is _SuggestionRow); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + String toString() { + return '_SuggestionRow()'; + } +} + +/// @nodoc +class _$SuggestionRowCopyWith<$Res> { + _$SuggestionRowCopyWith(_SuggestionRow _, $Res Function(_SuggestionRow) __); +} + +/// Adds pattern-matching-related methods to [_SuggestionRow]. +extension _SuggestionRowPatterns on _SuggestionRow { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_SuggestionHeader value)? header, + TResult Function(_SuggestionOption value)? option, + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _SuggestionHeader() when header != null: + return header(_that); + case _SuggestionOption() when option != null: + return option(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map({ + required TResult Function(_SuggestionHeader value) header, + required TResult Function(_SuggestionOption value) option, + }) { + final _that = this; + switch (_that) { + case _SuggestionHeader(): + return header(_that); + case _SuggestionOption(): + return option(_that); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_SuggestionHeader value)? header, + TResult? Function(_SuggestionOption value)? option, + }) { + final _that = this; + switch (_that) { + case _SuggestionHeader() when header != null: + return header(_that); + case _SuggestionOption() when option != null: + return option(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen({ + TResult Function(ComposerOptionGroup group, double height)? header, + TResult Function(ComposerOption option, int optionIndex)? option, + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _SuggestionHeader() when header != null: + return header(_that.group, _that.height); + case _SuggestionOption() when option != null: + return option(_that.option, _that.optionIndex); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when({ + required TResult Function(ComposerOptionGroup group, double height) header, + required TResult Function(ComposerOption option, int optionIndex) option, + }) { + final _that = this; + switch (_that) { + case _SuggestionHeader(): + return header(_that.group, _that.height); + case _SuggestionOption(): + return option(_that.option, _that.optionIndex); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function(ComposerOptionGroup group, double height)? header, + TResult? Function(ComposerOption option, int optionIndex)? option, + }) { + final _that = this; + switch (_that) { + case _SuggestionHeader() when header != null: + return header(_that.group, _that.height); + case _SuggestionOption() when option != null: + return option(_that.option, _that.optionIndex); + case _: + return null; + } + } +} + +/// @nodoc + +class _SuggestionHeader extends _SuggestionRow { + const _SuggestionHeader(this.group, this.height) : super._(); + + final ComposerOptionGroup group; + final double height; + + /// Create a copy of _SuggestionRow + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$SuggestionHeaderCopyWith<_SuggestionHeader> get copyWith => + __$SuggestionHeaderCopyWithImpl<_SuggestionHeader>(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _SuggestionHeader && + (identical(other.group, group) || other.group == group) && + (identical(other.height, height) || other.height == height)); + } + + @override + int get hashCode { + return Object.hash(runtimeType, group, height); + } + + @override + String toString() { + return '_SuggestionRow.header(group: $group, height: $height)'; + } +} + +/// @nodoc +abstract mixin class _$SuggestionHeaderCopyWith<$Res> + implements _$SuggestionRowCopyWith<$Res> { + factory _$SuggestionHeaderCopyWith( + _SuggestionHeader value, + $Res Function(_SuggestionHeader) _then, + ) = __$SuggestionHeaderCopyWithImpl; + @useResult + $Res call({ComposerOptionGroup group, double height}); +} + +/// @nodoc +class __$SuggestionHeaderCopyWithImpl<$Res> + implements _$SuggestionHeaderCopyWith<$Res> { + __$SuggestionHeaderCopyWithImpl(this._self, this._then); + + final _SuggestionHeader _self; + final $Res Function(_SuggestionHeader) _then; + + /// Create a copy of _SuggestionRow + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({Object? group = null, Object? height = null}) { + return _then( + _SuggestionHeader( + null == group + ? _self.group + : group // ignore: cast_nullable_to_non_nullable + as ComposerOptionGroup, + null == height + ? _self.height + : height // ignore: cast_nullable_to_non_nullable + as double, + ), + ); + } +} + +/// @nodoc + +class _SuggestionOption extends _SuggestionRow { + const _SuggestionOption(this.option, this.optionIndex) : super._(); + + final ComposerOption option; + final int optionIndex; + + /// Create a copy of _SuggestionRow + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$SuggestionOptionCopyWith<_SuggestionOption> get copyWith => + __$SuggestionOptionCopyWithImpl<_SuggestionOption>(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _SuggestionOption && + (identical(other.option, option) || other.option == option) && + (identical(other.optionIndex, optionIndex) || + other.optionIndex == optionIndex)); + } + + @override + int get hashCode { + return Object.hash(runtimeType, option, optionIndex); + } + + @override + String toString() { + return '_SuggestionRow.option(option: $option, optionIndex: $optionIndex)'; + } +} + +/// @nodoc +abstract mixin class _$SuggestionOptionCopyWith<$Res> + implements _$SuggestionRowCopyWith<$Res> { + factory _$SuggestionOptionCopyWith( + _SuggestionOption value, + $Res Function(_SuggestionOption) _then, + ) = __$SuggestionOptionCopyWithImpl; + @useResult + $Res call({ComposerOption option, int optionIndex}); + + $ComposerOptionCopyWith<$Res> get option; +} + +/// @nodoc +class __$SuggestionOptionCopyWithImpl<$Res> + implements _$SuggestionOptionCopyWith<$Res> { + __$SuggestionOptionCopyWithImpl(this._self, this._then); + + final _SuggestionOption _self; + final $Res Function(_SuggestionOption) _then; + + /// Create a copy of _SuggestionRow + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({Object? option = null, Object? optionIndex = null}) { + return _then( + _SuggestionOption( + null == option + ? _self.option + : option // ignore: cast_nullable_to_non_nullable + as ComposerOption, + null == optionIndex + ? _self.optionIndex + : optionIndex // ignore: cast_nullable_to_non_nullable + as int, + ), + ); + } + + /// Create a copy of _SuggestionRow + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $ComposerOptionCopyWith<$Res> get option { + return $ComposerOptionCopyWith<$Res>(_self.option, (value) { + return _then(_self.copyWith(option: value)); + }); + } +} diff --git a/lib/features/assistant/composer_suggestions.dart b/lib/features/assistant/composer_suggestions.dart new file mode 100644 index 0000000..f00a7e2 --- /dev/null +++ b/lib/features/assistant/composer_suggestions.dart @@ -0,0 +1,151 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:flutter/material.dart'; + +import '../../l10n/app_localizations.dart'; +import 'composer_document.dart'; + +part 'composer_suggestions.freezed.dart'; + +enum ComposerOptionGroup { media, timeline } + +@freezed +sealed class ComposerOption with _$ComposerOption { + const factory ComposerOption.reference({ + required String trigger, + required String title, + required String subtitle, + required IconData icon, + ComposerOptionGroup? group, + required ComposerReference reference, + }) = ComposerReferenceOption; + const factory ComposerOption.text({ + required String trigger, + required String title, + required String subtitle, + required IconData icon, + ComposerOptionGroup? group, + required String text, + }) = ComposerTextOption; + const factory ComposerOption.invoke({ + required String trigger, + required String title, + required String subtitle, + required IconData icon, + ComposerOptionGroup? group, + required VoidCallback onInvoke, + }) = ComposerInvokeOption; + const factory ComposerOption.openPicker({ + required String trigger, + required String title, + required String subtitle, + required IconData icon, + ComposerOptionGroup? group, + required VoidCallback onInvoke, + }) = ComposerPickerOption; +} + +/// System-owned entries. More triggers and actions register here later. +abstract final class ComposerOptionCatalog { + static List forTrigger( + String trigger, { + required AppLocalizations l10n, + required String? projectId, + required Iterable assets, + required Iterable timelines, + }) { + if (trigger != '@' || projectId == null) return const []; + return [ + for (final asset in assets) + ComposerOption.reference( + trigger: '@', + title: asset.name, + subtitle: l10n.materials, + icon: switch (asset.metadata['kind']) { + 'video' => Icons.movie_outlined, + 'audio' => Icons.audiotrack_outlined, + 'image' => Icons.image_outlined, + _ => Icons.insert_drive_file_outlined, + }, + group: ComposerOptionGroup.media, + reference: ComposerReference( + kind: ComposerReferenceKind.media, + projectId: projectId, + id: asset.id, + label: asset.name, + ), + ), + for (final timeline in timelines) + ComposerOption.reference( + trigger: '@', + title: timeline.name, + subtitle: l10n.timelines, + icon: Icons.view_timeline_outlined, + group: ComposerOptionGroup.timeline, + reference: ComposerReference( + kind: ComposerReferenceKind.timeline, + projectId: projectId, + id: timeline.id, + label: timeline.name, + ), + ), + ]; + } +} + +@freezed +abstract class ComposerTriggerQuery with _$ComposerTriggerQuery { + const factory ComposerTriggerQuery({ + required String trigger, + required int start, + required int end, + required String query, + }) = _ComposerTriggerQuery; +} + +ComposerTriggerQuery? findComposerTrigger( + TextEditingValue value, + Iterable marks, +) { + if (!value.selection.isValid || !value.selection.isCollapsed) return null; + if (value.composing.isValid && !value.composing.isCollapsed) return null; + final caret = value.selection.extentOffset; + if (caret <= 0 || caret > value.text.length) return null; + for (final mark in marks) { + if (caret > mark.start && caret <= mark.end) return null; + } + final lineStart = value.text.lastIndexOf('\n', caret - 1) + 1; + for (var i = caret - 1; i >= lineStart; i--) { + final char = value.text[i]; + if (char != '@' && char != '/' && char != r'$') continue; + if (i > 0 && + !RegExp(r'[\s(\[{,;:!?,。!?;:、(“\u3400-\u9fff]') + .hasMatch(value.text[i - 1])) { + continue; + } + if (caret - i > 128) return null; + if (marks.any((mark) => i >= mark.start && i < mark.end)) return null; + final query = value.text.substring(i + 1, caret); + if (char == '/' && (query.contains('/') || query.contains('\\'))) { + return null; + } + return ComposerTriggerQuery( + trigger: char, + start: i, + end: caret, + query: query, + ); + } + return null; +} + +List filterComposerOptions( + Iterable options, + String query, +) { + final normalized = query.trim().toLowerCase(); + if (normalized.isEmpty) return options.toList(); + return options + .where((option) => option.title.toLowerCase().contains(normalized)) + .toList(); +} diff --git a/lib/features/assistant/composer_suggestions.freezed.dart b/lib/features/assistant/composer_suggestions.freezed.dart new file mode 100644 index 0000000..c3e89ca --- /dev/null +++ b/lib/features/assistant/composer_suggestions.freezed.dart @@ -0,0 +1,1447 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'composer_suggestions.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +T _$identity(T value) => value; + +/// @nodoc +mixin _$ComposerOption { + String get trigger; + String get title; + String get subtitle; + IconData get icon; + ComposerOptionGroup? get group; + + /// Create a copy of ComposerOption + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $ComposerOptionCopyWith get copyWith => + _$ComposerOptionCopyWithImpl( + this as ComposerOption, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as ComposerOption; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is ComposerOption && + (identical(other.trigger, _this.trigger) || + other.trigger == _this.trigger) && + (identical(other.title, _this.title) || + other.title == _this.title) && + (identical(other.subtitle, _this.subtitle) || + other.subtitle == _this.subtitle) && + (identical(other.icon, _this.icon) || other.icon == _this.icon) && + (identical(other.group, _this.group) || + other.group == _this.group)); + } + + @override + int get hashCode { + final _this = this as ComposerOption; + return Object.hash( + runtimeType, + _this.trigger, + _this.title, + _this.subtitle, + _this.icon, + _this.group, + ); + } + + @override + String toString() { + final _this = this as ComposerOption; + return 'ComposerOption(trigger: ${_this.trigger}, title: ${_this.title}, subtitle: ${_this.subtitle}, icon: ${_this.icon}, group: ${_this.group})'; + } +} + +/// @nodoc +abstract mixin class $ComposerOptionCopyWith<$Res> { + factory $ComposerOptionCopyWith( + ComposerOption value, + $Res Function(ComposerOption) _then, + ) = _$ComposerOptionCopyWithImpl; + @useResult + $Res call({ + String trigger, + String title, + String subtitle, + IconData icon, + ComposerOptionGroup? group, + }); +} + +/// @nodoc +class _$ComposerOptionCopyWithImpl<$Res> + implements $ComposerOptionCopyWith<$Res> { + _$ComposerOptionCopyWithImpl(this._self, this._then); + + final ComposerOption _self; + final $Res Function(ComposerOption) _then; + + /// Create a copy of ComposerOption + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? trigger = null, + Object? title = null, + Object? subtitle = null, + Object? icon = null, + Object? group = freezed, + }) { + return _then( + _self.copyWith( + trigger: null == trigger + ? _self.trigger + : trigger // ignore: cast_nullable_to_non_nullable + as String, + title: null == title + ? _self.title + : title // ignore: cast_nullable_to_non_nullable + as String, + subtitle: null == subtitle + ? _self.subtitle + : subtitle // ignore: cast_nullable_to_non_nullable + as String, + icon: null == icon + ? _self.icon + : icon // ignore: cast_nullable_to_non_nullable + as IconData, + group: freezed == group + ? _self.group + : group // ignore: cast_nullable_to_non_nullable + as ComposerOptionGroup?, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [ComposerOption]. +extension ComposerOptionPatterns on ComposerOption { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap({ + TResult Function(ComposerReferenceOption value)? reference, + TResult Function(ComposerTextOption value)? text, + TResult Function(ComposerInvokeOption value)? invoke, + TResult Function(ComposerPickerOption value)? openPicker, + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case ComposerReferenceOption() when reference != null: + return reference(_that); + case ComposerTextOption() when text != null: + return text(_that); + case ComposerInvokeOption() when invoke != null: + return invoke(_that); + case ComposerPickerOption() when openPicker != null: + return openPicker(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map({ + required TResult Function(ComposerReferenceOption value) reference, + required TResult Function(ComposerTextOption value) text, + required TResult Function(ComposerInvokeOption value) invoke, + required TResult Function(ComposerPickerOption value) openPicker, + }) { + final _that = this; + switch (_that) { + case ComposerReferenceOption(): + return reference(_that); + case ComposerTextOption(): + return text(_that); + case ComposerInvokeOption(): + return invoke(_that); + case ComposerPickerOption(): + return openPicker(_that); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(ComposerReferenceOption value)? reference, + TResult? Function(ComposerTextOption value)? text, + TResult? Function(ComposerInvokeOption value)? invoke, + TResult? Function(ComposerPickerOption value)? openPicker, + }) { + final _that = this; + switch (_that) { + case ComposerReferenceOption() when reference != null: + return reference(_that); + case ComposerTextOption() when text != null: + return text(_that); + case ComposerInvokeOption() when invoke != null: + return invoke(_that); + case ComposerPickerOption() when openPicker != null: + return openPicker(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen({ + TResult Function( + String trigger, + String title, + String subtitle, + IconData icon, + ComposerOptionGroup? group, + ComposerReference reference, + )? + reference, + TResult Function( + String trigger, + String title, + String subtitle, + IconData icon, + ComposerOptionGroup? group, + String text, + )? + text, + TResult Function( + String trigger, + String title, + String subtitle, + IconData icon, + ComposerOptionGroup? group, + VoidCallback onInvoke, + )? + invoke, + TResult Function( + String trigger, + String title, + String subtitle, + IconData icon, + ComposerOptionGroup? group, + VoidCallback onInvoke, + )? + openPicker, + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case ComposerReferenceOption() when reference != null: + return reference( + _that.trigger, + _that.title, + _that.subtitle, + _that.icon, + _that.group, + _that.reference, + ); + case ComposerTextOption() when text != null: + return text( + _that.trigger, + _that.title, + _that.subtitle, + _that.icon, + _that.group, + _that.text, + ); + case ComposerInvokeOption() when invoke != null: + return invoke( + _that.trigger, + _that.title, + _that.subtitle, + _that.icon, + _that.group, + _that.onInvoke, + ); + case ComposerPickerOption() when openPicker != null: + return openPicker( + _that.trigger, + _that.title, + _that.subtitle, + _that.icon, + _that.group, + _that.onInvoke, + ); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when({ + required TResult Function( + String trigger, + String title, + String subtitle, + IconData icon, + ComposerOptionGroup? group, + ComposerReference reference, + ) + reference, + required TResult Function( + String trigger, + String title, + String subtitle, + IconData icon, + ComposerOptionGroup? group, + String text, + ) + text, + required TResult Function( + String trigger, + String title, + String subtitle, + IconData icon, + ComposerOptionGroup? group, + VoidCallback onInvoke, + ) + invoke, + required TResult Function( + String trigger, + String title, + String subtitle, + IconData icon, + ComposerOptionGroup? group, + VoidCallback onInvoke, + ) + openPicker, + }) { + final _that = this; + switch (_that) { + case ComposerReferenceOption(): + return reference( + _that.trigger, + _that.title, + _that.subtitle, + _that.icon, + _that.group, + _that.reference, + ); + case ComposerTextOption(): + return text( + _that.trigger, + _that.title, + _that.subtitle, + _that.icon, + _that.group, + _that.text, + ); + case ComposerInvokeOption(): + return invoke( + _that.trigger, + _that.title, + _that.subtitle, + _that.icon, + _that.group, + _that.onInvoke, + ); + case ComposerPickerOption(): + return openPicker( + _that.trigger, + _that.title, + _that.subtitle, + _that.icon, + _that.group, + _that.onInvoke, + ); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function( + String trigger, + String title, + String subtitle, + IconData icon, + ComposerOptionGroup? group, + ComposerReference reference, + )? + reference, + TResult? Function( + String trigger, + String title, + String subtitle, + IconData icon, + ComposerOptionGroup? group, + String text, + )? + text, + TResult? Function( + String trigger, + String title, + String subtitle, + IconData icon, + ComposerOptionGroup? group, + VoidCallback onInvoke, + )? + invoke, + TResult? Function( + String trigger, + String title, + String subtitle, + IconData icon, + ComposerOptionGroup? group, + VoidCallback onInvoke, + )? + openPicker, + }) { + final _that = this; + switch (_that) { + case ComposerReferenceOption() when reference != null: + return reference( + _that.trigger, + _that.title, + _that.subtitle, + _that.icon, + _that.group, + _that.reference, + ); + case ComposerTextOption() when text != null: + return text( + _that.trigger, + _that.title, + _that.subtitle, + _that.icon, + _that.group, + _that.text, + ); + case ComposerInvokeOption() when invoke != null: + return invoke( + _that.trigger, + _that.title, + _that.subtitle, + _that.icon, + _that.group, + _that.onInvoke, + ); + case ComposerPickerOption() when openPicker != null: + return openPicker( + _that.trigger, + _that.title, + _that.subtitle, + _that.icon, + _that.group, + _that.onInvoke, + ); + case _: + return null; + } + } +} + +/// @nodoc + +class ComposerReferenceOption implements ComposerOption { + const ComposerReferenceOption({ + required this.trigger, + required this.title, + required this.subtitle, + required this.icon, + this.group, + required this.reference, + }); + + @override + final String trigger; + @override + final String title; + @override + final String subtitle; + @override + final IconData icon; + @override + final ComposerOptionGroup? group; + final ComposerReference reference; + + /// Create a copy of ComposerOption + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $ComposerReferenceOptionCopyWith get copyWith => + _$ComposerReferenceOptionCopyWithImpl( + this, + _$identity, + ); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is ComposerReferenceOption && + (identical(other.trigger, trigger) || other.trigger == trigger) && + (identical(other.title, title) || other.title == title) && + (identical(other.subtitle, subtitle) || + other.subtitle == subtitle) && + (identical(other.icon, icon) || other.icon == icon) && + (identical(other.group, group) || other.group == group) && + (identical(other.reference, reference) || + other.reference == reference)); + } + + @override + int get hashCode { + return Object.hash( + runtimeType, + trigger, + title, + subtitle, + icon, + group, + reference, + ); + } + + @override + String toString() { + return 'ComposerOption.reference(trigger: $trigger, title: $title, subtitle: $subtitle, icon: $icon, group: $group, reference: $reference)'; + } +} + +/// @nodoc +abstract mixin class $ComposerReferenceOptionCopyWith<$Res> + implements $ComposerOptionCopyWith<$Res> { + factory $ComposerReferenceOptionCopyWith( + ComposerReferenceOption value, + $Res Function(ComposerReferenceOption) _then, + ) = _$ComposerReferenceOptionCopyWithImpl; + @override + @useResult + $Res call({ + String trigger, + String title, + String subtitle, + IconData icon, + ComposerOptionGroup? group, + ComposerReference reference, + }); + + $ComposerReferenceCopyWith<$Res> get reference; +} + +/// @nodoc +class _$ComposerReferenceOptionCopyWithImpl<$Res> + implements $ComposerReferenceOptionCopyWith<$Res> { + _$ComposerReferenceOptionCopyWithImpl(this._self, this._then); + + final ComposerReferenceOption _self; + final $Res Function(ComposerReferenceOption) _then; + + /// Create a copy of ComposerOption + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? trigger = null, + Object? title = null, + Object? subtitle = null, + Object? icon = null, + Object? group = freezed, + Object? reference = null, + }) { + return _then( + ComposerReferenceOption( + trigger: null == trigger + ? _self.trigger + : trigger // ignore: cast_nullable_to_non_nullable + as String, + title: null == title + ? _self.title + : title // ignore: cast_nullable_to_non_nullable + as String, + subtitle: null == subtitle + ? _self.subtitle + : subtitle // ignore: cast_nullable_to_non_nullable + as String, + icon: null == icon + ? _self.icon + : icon // ignore: cast_nullable_to_non_nullable + as IconData, + group: freezed == group + ? _self.group + : group // ignore: cast_nullable_to_non_nullable + as ComposerOptionGroup?, + reference: null == reference + ? _self.reference + : reference // ignore: cast_nullable_to_non_nullable + as ComposerReference, + ), + ); + } + + /// Create a copy of ComposerOption + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $ComposerReferenceCopyWith<$Res> get reference { + return $ComposerReferenceCopyWith<$Res>(_self.reference, (value) { + return _then(_self.copyWith(reference: value)); + }); + } +} + +/// @nodoc + +class ComposerTextOption implements ComposerOption { + const ComposerTextOption({ + required this.trigger, + required this.title, + required this.subtitle, + required this.icon, + this.group, + required this.text, + }); + + @override + final String trigger; + @override + final String title; + @override + final String subtitle; + @override + final IconData icon; + @override + final ComposerOptionGroup? group; + final String text; + + /// Create a copy of ComposerOption + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $ComposerTextOptionCopyWith get copyWith => + _$ComposerTextOptionCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is ComposerTextOption && + (identical(other.trigger, trigger) || other.trigger == trigger) && + (identical(other.title, title) || other.title == title) && + (identical(other.subtitle, subtitle) || + other.subtitle == subtitle) && + (identical(other.icon, icon) || other.icon == icon) && + (identical(other.group, group) || other.group == group) && + (identical(other.text, text) || other.text == text)); + } + + @override + int get hashCode { + return Object.hash( + runtimeType, + trigger, + title, + subtitle, + icon, + group, + text, + ); + } + + @override + String toString() { + return 'ComposerOption.text(trigger: $trigger, title: $title, subtitle: $subtitle, icon: $icon, group: $group, text: $text)'; + } +} + +/// @nodoc +abstract mixin class $ComposerTextOptionCopyWith<$Res> + implements $ComposerOptionCopyWith<$Res> { + factory $ComposerTextOptionCopyWith( + ComposerTextOption value, + $Res Function(ComposerTextOption) _then, + ) = _$ComposerTextOptionCopyWithImpl; + @override + @useResult + $Res call({ + String trigger, + String title, + String subtitle, + IconData icon, + ComposerOptionGroup? group, + String text, + }); +} + +/// @nodoc +class _$ComposerTextOptionCopyWithImpl<$Res> + implements $ComposerTextOptionCopyWith<$Res> { + _$ComposerTextOptionCopyWithImpl(this._self, this._then); + + final ComposerTextOption _self; + final $Res Function(ComposerTextOption) _then; + + /// Create a copy of ComposerOption + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? trigger = null, + Object? title = null, + Object? subtitle = null, + Object? icon = null, + Object? group = freezed, + Object? text = null, + }) { + return _then( + ComposerTextOption( + trigger: null == trigger + ? _self.trigger + : trigger // ignore: cast_nullable_to_non_nullable + as String, + title: null == title + ? _self.title + : title // ignore: cast_nullable_to_non_nullable + as String, + subtitle: null == subtitle + ? _self.subtitle + : subtitle // ignore: cast_nullable_to_non_nullable + as String, + icon: null == icon + ? _self.icon + : icon // ignore: cast_nullable_to_non_nullable + as IconData, + group: freezed == group + ? _self.group + : group // ignore: cast_nullable_to_non_nullable + as ComposerOptionGroup?, + text: null == text + ? _self.text + : text // ignore: cast_nullable_to_non_nullable + as String, + ), + ); + } +} + +/// @nodoc + +class ComposerInvokeOption implements ComposerOption { + const ComposerInvokeOption({ + required this.trigger, + required this.title, + required this.subtitle, + required this.icon, + this.group, + required this.onInvoke, + }); + + @override + final String trigger; + @override + final String title; + @override + final String subtitle; + @override + final IconData icon; + @override + final ComposerOptionGroup? group; + final VoidCallback onInvoke; + + /// Create a copy of ComposerOption + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $ComposerInvokeOptionCopyWith get copyWith => + _$ComposerInvokeOptionCopyWithImpl( + this, + _$identity, + ); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is ComposerInvokeOption && + (identical(other.trigger, trigger) || other.trigger == trigger) && + (identical(other.title, title) || other.title == title) && + (identical(other.subtitle, subtitle) || + other.subtitle == subtitle) && + (identical(other.icon, icon) || other.icon == icon) && + (identical(other.group, group) || other.group == group) && + (identical(other.onInvoke, onInvoke) || + other.onInvoke == onInvoke)); + } + + @override + int get hashCode { + return Object.hash( + runtimeType, + trigger, + title, + subtitle, + icon, + group, + onInvoke, + ); + } + + @override + String toString() { + return 'ComposerOption.invoke(trigger: $trigger, title: $title, subtitle: $subtitle, icon: $icon, group: $group, onInvoke: $onInvoke)'; + } +} + +/// @nodoc +abstract mixin class $ComposerInvokeOptionCopyWith<$Res> + implements $ComposerOptionCopyWith<$Res> { + factory $ComposerInvokeOptionCopyWith( + ComposerInvokeOption value, + $Res Function(ComposerInvokeOption) _then, + ) = _$ComposerInvokeOptionCopyWithImpl; + @override + @useResult + $Res call({ + String trigger, + String title, + String subtitle, + IconData icon, + ComposerOptionGroup? group, + VoidCallback onInvoke, + }); +} + +/// @nodoc +class _$ComposerInvokeOptionCopyWithImpl<$Res> + implements $ComposerInvokeOptionCopyWith<$Res> { + _$ComposerInvokeOptionCopyWithImpl(this._self, this._then); + + final ComposerInvokeOption _self; + final $Res Function(ComposerInvokeOption) _then; + + /// Create a copy of ComposerOption + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? trigger = null, + Object? title = null, + Object? subtitle = null, + Object? icon = null, + Object? group = freezed, + Object? onInvoke = null, + }) { + return _then( + ComposerInvokeOption( + trigger: null == trigger + ? _self.trigger + : trigger // ignore: cast_nullable_to_non_nullable + as String, + title: null == title + ? _self.title + : title // ignore: cast_nullable_to_non_nullable + as String, + subtitle: null == subtitle + ? _self.subtitle + : subtitle // ignore: cast_nullable_to_non_nullable + as String, + icon: null == icon + ? _self.icon + : icon // ignore: cast_nullable_to_non_nullable + as IconData, + group: freezed == group + ? _self.group + : group // ignore: cast_nullable_to_non_nullable + as ComposerOptionGroup?, + onInvoke: null == onInvoke + ? _self.onInvoke + : onInvoke // ignore: cast_nullable_to_non_nullable + as VoidCallback, + ), + ); + } +} + +/// @nodoc + +class ComposerPickerOption implements ComposerOption { + const ComposerPickerOption({ + required this.trigger, + required this.title, + required this.subtitle, + required this.icon, + this.group, + required this.onInvoke, + }); + + @override + final String trigger; + @override + final String title; + @override + final String subtitle; + @override + final IconData icon; + @override + final ComposerOptionGroup? group; + final VoidCallback onInvoke; + + /// Create a copy of ComposerOption + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $ComposerPickerOptionCopyWith get copyWith => + _$ComposerPickerOptionCopyWithImpl( + this, + _$identity, + ); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is ComposerPickerOption && + (identical(other.trigger, trigger) || other.trigger == trigger) && + (identical(other.title, title) || other.title == title) && + (identical(other.subtitle, subtitle) || + other.subtitle == subtitle) && + (identical(other.icon, icon) || other.icon == icon) && + (identical(other.group, group) || other.group == group) && + (identical(other.onInvoke, onInvoke) || + other.onInvoke == onInvoke)); + } + + @override + int get hashCode { + return Object.hash( + runtimeType, + trigger, + title, + subtitle, + icon, + group, + onInvoke, + ); + } + + @override + String toString() { + return 'ComposerOption.openPicker(trigger: $trigger, title: $title, subtitle: $subtitle, icon: $icon, group: $group, onInvoke: $onInvoke)'; + } +} + +/// @nodoc +abstract mixin class $ComposerPickerOptionCopyWith<$Res> + implements $ComposerOptionCopyWith<$Res> { + factory $ComposerPickerOptionCopyWith( + ComposerPickerOption value, + $Res Function(ComposerPickerOption) _then, + ) = _$ComposerPickerOptionCopyWithImpl; + @override + @useResult + $Res call({ + String trigger, + String title, + String subtitle, + IconData icon, + ComposerOptionGroup? group, + VoidCallback onInvoke, + }); +} + +/// @nodoc +class _$ComposerPickerOptionCopyWithImpl<$Res> + implements $ComposerPickerOptionCopyWith<$Res> { + _$ComposerPickerOptionCopyWithImpl(this._self, this._then); + + final ComposerPickerOption _self; + final $Res Function(ComposerPickerOption) _then; + + /// Create a copy of ComposerOption + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? trigger = null, + Object? title = null, + Object? subtitle = null, + Object? icon = null, + Object? group = freezed, + Object? onInvoke = null, + }) { + return _then( + ComposerPickerOption( + trigger: null == trigger + ? _self.trigger + : trigger // ignore: cast_nullable_to_non_nullable + as String, + title: null == title + ? _self.title + : title // ignore: cast_nullable_to_non_nullable + as String, + subtitle: null == subtitle + ? _self.subtitle + : subtitle // ignore: cast_nullable_to_non_nullable + as String, + icon: null == icon + ? _self.icon + : icon // ignore: cast_nullable_to_non_nullable + as IconData, + group: freezed == group + ? _self.group + : group // ignore: cast_nullable_to_non_nullable + as ComposerOptionGroup?, + onInvoke: null == onInvoke + ? _self.onInvoke + : onInvoke // ignore: cast_nullable_to_non_nullable + as VoidCallback, + ), + ); + } +} + +/// @nodoc +mixin _$ComposerTriggerQuery { + String get trigger; + int get start; + int get end; + String get query; + + /// Create a copy of ComposerTriggerQuery + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $ComposerTriggerQueryCopyWith get copyWith => + _$ComposerTriggerQueryCopyWithImpl( + this as ComposerTriggerQuery, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as ComposerTriggerQuery; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is ComposerTriggerQuery && + (identical(other.trigger, _this.trigger) || + other.trigger == _this.trigger) && + (identical(other.start, _this.start) || + other.start == _this.start) && + (identical(other.end, _this.end) || other.end == _this.end) && + (identical(other.query, _this.query) || + other.query == _this.query)); + } + + @override + int get hashCode { + final _this = this as ComposerTriggerQuery; + return Object.hash( + runtimeType, + _this.trigger, + _this.start, + _this.end, + _this.query, + ); + } + + @override + String toString() { + final _this = this as ComposerTriggerQuery; + return 'ComposerTriggerQuery(trigger: ${_this.trigger}, start: ${_this.start}, end: ${_this.end}, query: ${_this.query})'; + } +} + +/// @nodoc +abstract mixin class $ComposerTriggerQueryCopyWith<$Res> { + factory $ComposerTriggerQueryCopyWith( + ComposerTriggerQuery value, + $Res Function(ComposerTriggerQuery) _then, + ) = _$ComposerTriggerQueryCopyWithImpl; + @useResult + $Res call({String trigger, int start, int end, String query}); +} + +/// @nodoc +class _$ComposerTriggerQueryCopyWithImpl<$Res> + implements $ComposerTriggerQueryCopyWith<$Res> { + _$ComposerTriggerQueryCopyWithImpl(this._self, this._then); + + final ComposerTriggerQuery _self; + final $Res Function(ComposerTriggerQuery) _then; + + /// Create a copy of ComposerTriggerQuery + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? trigger = null, + Object? start = null, + Object? end = null, + Object? query = null, + }) { + return _then( + ComposerTriggerQuery( + trigger: null == trigger + ? _self.trigger + : trigger // ignore: cast_nullable_to_non_nullable + as String, + start: null == start + ? _self.start + : start // ignore: cast_nullable_to_non_nullable + as int, + end: null == end + ? _self.end + : end // ignore: cast_nullable_to_non_nullable + as int, + query: null == query + ? _self.query + : query // ignore: cast_nullable_to_non_nullable + as String, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [ComposerTriggerQuery]. +extension ComposerTriggerQueryPatterns on ComposerTriggerQuery { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_ComposerTriggerQuery value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ComposerTriggerQuery() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_ComposerTriggerQuery value) $default, + ) { + final _that = this; + switch (_that) { + case _ComposerTriggerQuery(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_ComposerTriggerQuery value)? $default, + ) { + final _that = this; + switch (_that) { + case _ComposerTriggerQuery() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function(String trigger, int start, int end, String query)? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ComposerTriggerQuery() when $default != null: + return $default(_that.trigger, _that.start, _that.end, _that.query); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function(String trigger, int start, int end, String query) $default, + ) { + final _that = this; + switch (_that) { + case _ComposerTriggerQuery(): + return $default(_that.trigger, _that.start, _that.end, _that.query); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function(String trigger, int start, int end, String query)? + $default, + ) { + final _that = this; + switch (_that) { + case _ComposerTriggerQuery() when $default != null: + return $default(_that.trigger, _that.start, _that.end, _that.query); + case _: + return null; + } + } +} + +/// @nodoc + +class _ComposerTriggerQuery implements ComposerTriggerQuery { + const _ComposerTriggerQuery({ + required this.trigger, + required this.start, + required this.end, + required this.query, + }); + + @override + final String trigger; + @override + final int start; + @override + final int end; + @override + final String query; + + /// Create a copy of ComposerTriggerQuery + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$ComposerTriggerQueryCopyWith<_ComposerTriggerQuery> get copyWith => + __$ComposerTriggerQueryCopyWithImpl<_ComposerTriggerQuery>( + this, + _$identity, + ); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _ComposerTriggerQuery && + (identical(other.trigger, trigger) || other.trigger == trigger) && + (identical(other.start, start) || other.start == start) && + (identical(other.end, end) || other.end == end) && + (identical(other.query, query) || other.query == query)); + } + + @override + int get hashCode { + return Object.hash(runtimeType, trigger, start, end, query); + } + + @override + String toString() { + return 'ComposerTriggerQuery(trigger: $trigger, start: $start, end: $end, query: $query)'; + } +} + +/// @nodoc +abstract mixin class _$ComposerTriggerQueryCopyWith<$Res> + implements $ComposerTriggerQueryCopyWith<$Res> { + factory _$ComposerTriggerQueryCopyWith( + _ComposerTriggerQuery value, + $Res Function(_ComposerTriggerQuery) _then, + ) = __$ComposerTriggerQueryCopyWithImpl; + @override + @useResult + $Res call({String trigger, int start, int end, String query}); +} + +/// @nodoc +class __$ComposerTriggerQueryCopyWithImpl<$Res> + implements _$ComposerTriggerQueryCopyWith<$Res> { + __$ComposerTriggerQueryCopyWithImpl(this._self, this._then); + + final _ComposerTriggerQuery _self; + final $Res Function(_ComposerTriggerQuery) _then; + + /// Create a copy of ComposerTriggerQuery + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? trigger = null, + Object? start = null, + Object? end = null, + Object? query = null, + }) { + return _then( + _ComposerTriggerQuery( + trigger: null == trigger + ? _self.trigger + : trigger // ignore: cast_nullable_to_non_nullable + as String, + start: null == start + ? _self.start + : start // ignore: cast_nullable_to_non_nullable + as int, + end: null == end + ? _self.end + : end // ignore: cast_nullable_to_non_nullable + as int, + query: null == query + ? _self.query + : query // ignore: cast_nullable_to_non_nullable + as String, + ), + ); + } +} diff --git a/lib/features/assistant/workspace_agent_surface.dart b/lib/features/assistant/workspace_agent_surface.dart new file mode 100644 index 0000000..b23a4e8 --- /dev/null +++ b/lib/features/assistant/workspace_agent_surface.dart @@ -0,0 +1,64 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import 'package:cutdex_ui/theme.dart'; + +import '../../workspace/project_state.dart'; + +import '../projects/conversation_sidebar.dart'; +import 'agent_chat_panel.dart'; +import 'agent_composer_store.dart'; +import 'composer_project_selector.dart'; + +/// Shared conversation presentation, independent of the navigation sidebar. +class WorkspaceAgentSurface extends ConsumerWidget { + const WorkspaceAgentSurface({ + super.key, + required this.state, + required this.onSelectProject, + required this.onCreateProject, + }); + + final ProjectState state; + final ValueChanged? onSelectProject; + final VoidCallback? onCreateProject; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final selection = ref.watch( + conversationSelectionProvider(state.activeProject?.id), + ); + final conversations = ref.read(conversationSidebarProvider.notifier); + final composers = ref.watch(agentComposerStoreProvider); + final projectId = state.activeProject?.id; + final conversationId = selection.selectedId; + return AgentChatPanel( + key: ValueKey((projectId, conversationId ?? selection.draftKey)), + inputController: composers.input(projectId, conversationId), + composer: composers.composer( + projectId, + conversationId ?? selection.draftKey, + ), + projectSelector: ComposerProjectSelector( + backgroundColor: AppTheme.composerUtilityBackground(context), + projects: state.recent, + selected: state.activeProject, + busy: state.projectBusy, + onSelect: (project) => onSelectProject?.call(project), + onCreate: onCreateProject, + ), + composerColor: AppSurfaces.of(context).composerBackground, + projectId: projectId, + timelineId: state.timeline?.id, + conversationId: conversationId, + draftKey: conversationId == null ? selection.draftKey : null, + onConversationCreated: (item) => unawaited( + conversations.updateListing(item, selectIfDraftKey: selection.draftKey), + ), + onConversationUpdated: (item) => + unawaited(conversations.updateListing(item)), + ); + } +} diff --git a/lib/features/editor/background_tasks_button.dart b/lib/features/editor/background_tasks_button.dart new file mode 100644 index 0000000..40171ef --- /dev/null +++ b/lib/features/editor/background_tasks_button.dart @@ -0,0 +1,52 @@ +import 'package:cutdex/l10n/l10n.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import 'package:cutdex_ui/theme.dart'; + +import '../../integrations/runtime/processing_resource_repository.dart'; +import '../../workspace/background_task_registry.dart'; +import '../../workspace/background_task_state.dart'; +import '../../integrations/runtime/processing_resource_state.dart'; + +import 'package:cutdex_ui/widgets.dart'; + +import '../media/background_tasks_dialog.dart'; + +class BackgroundTasksButton extends ConsumerWidget { + const BackgroundTasksButton({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + final registry = ref.watch(backgroundTaskRegistryProvider); + final resources = ref + .watch(processingResourceRepositoryProvider) + .asData + ?.value; + final tasks = ref.watch(backgroundTasksProvider(registry: registry)); + final downloads = resources == null + ? null + : ref.watch(processingResourcesProvider(resources)); + bool hasRunningTasks() => + tasks.runningCount > 0 || + downloads?.subtitleDownloading == true || + (downloads?.installs.any( + (install) => install.state == ProcessingResourceState.downloading, + ) ?? + false); + Widget button(VoidCallback toggle) => IconButton( + key: const ValueKey('background-tasks-button'), + tooltip: context.l10n.backgroundTasks, + onPressed: toggle, + icon: Badge( + isLabelVisible: hasRunningTasks(), + child: const Icon(Icons.task_alt_outlined, size: AppIconSize.header), + ), + ); + return AppPopover( + width: 384, + builder: (_, toggle) => button(toggle), + child: BackgroundTasksContent(registry: registry, repository: resources), + ); + } +} diff --git a/lib/features/editor/editor_page.dart b/lib/features/editor/editor_page.dart new file mode 100644 index 0000000..cd1d006 --- /dev/null +++ b/lib/features/editor/editor_page.dart @@ -0,0 +1,359 @@ +import 'dart:async'; + +import 'package:cutdex/l10n/l10n.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../integrations/platform/device_experience.dart'; + +import 'package:cutdex_native/cutdex_native.dart'; + +import '../../persistence/app_settings_repositories.dart'; +import '../../shared/layout/workspace_layout_metrics.dart'; + +import 'package:cutdex_ui/theme.dart'; + +import '../../workspace/timeline_provider.dart'; +import '../../workspace/view_settings.dart'; +import '../media/media_browser_page.dart'; +import '../media/media_panel.dart'; +import '../preview/preview_panel.dart'; +import '../properties/properties_editor_page.dart'; +import '../properties/properties_panel.dart'; +import '../timeline/timeline_panel.dart'; +import 'editor_presentation_controller.dart'; +import 'layouts/bounded_editor_layout.dart'; +import 'layouts/expanded_editor_layout.dart'; + +/// The single editing surface shown beside the project/timeline navigation. +class EditorWorkspace extends ConsumerStatefulWidget { + const EditorWorkspace({ + super.key, + required this.projectId, + required this.timelineId, + required this.projectName, + required this.integratedTitlebar, + required this.headerLeading, + this.showProjectName = true, + this.experience = DeviceExperience.desktop, + }); + + final String projectId; + final String timelineId; + final String projectName; + final bool integratedTitlebar; + final Widget headerLeading; + final bool showProjectName; + final DeviceExperience experience; + + @override + ConsumerState createState() => _EditorWorkspaceState(); +} + +class _EditorWorkspaceState extends ConsumerState { + final _previewKey = GlobalKey(); + EditorPresentationController get _presentation => + ref.read(editorPresentationProvider(widget.projectId)); + ProjectViewSettingsData get _viewSettings => + ref.read(projectViewSettingsProvider(widget.projectId)).value ?? + const ProjectViewSettingsData(); + ProjectViewSettings get _viewController => + ref.read(projectViewSettingsProvider(widget.projectId).notifier); + bool get _propertiesOpen => _viewSettings.propertiesOpen; + double? get _timelineHeight => _viewSettings.timelineHeight; + + void _saveViewSettings() { + if (!ref.read(projectViewSettingsProvider(widget.projectId)).hasValue) { + return; + } + unawaited(_viewController.save()); + } + + @override + Widget build(BuildContext context) { + final viewSettings = ref.watch( + projectViewSettingsProvider(widget.projectId), + ); + final preview = KeyedSubtree( + key: _previewKey, + child: EditorPreviewPanel( + projectId: widget.projectId, + timelineId: widget.timelineId, + ), + ); + final timeline = EditorTimelinePanel( + projectId: widget.projectId, + timelineId: widget.timelineId, + ); + final properties = EditorPropertiesPanel( + projectId: widget.projectId, + timelineId: widget.timelineId, + ); + final media = MediaPanel(projectId: widget.projectId); + return ListenableBuilder( + listenable: ref.watch(editorPresentationProvider(widget.projectId)), + builder: (context, _) => LayoutBuilder( + builder: (context, constraints) { + final desktop = widget.experience == DeviceExperience.desktop; + final sideWidth = + (_presentation.mediaOpen + ? WorkspaceLayoutMetrics.mediaPanelWidth + 1 + : 0) + + (_propertiesOpen + ? WorkspaceLayoutMetrics.propertiesPanelWidth + 1 + : 0); + final dockPanels = + desktop && + constraints.maxWidth >= + WorkspaceLayoutMetrics.previewMinimumWidth + sideWidth; + final desktopTool = sideWidth == 0 + ? null + : _presentation.desktopTool(propertiesOpen: _propertiesOpen); + final headerHeight = desktop ? AppControlSize.panelHeader : 48.0; + final mediaOpen = desktop + ? dockPanels + ? _presentation.mediaOpen + : desktopTool == EditorTool.media + : _presentation.activeTool == EditorTool.media; + final propertiesOpen = desktop + ? dockPanels + ? _propertiesOpen + : desktopTool == EditorTool.properties + : _presentation.activeTool == EditorTool.properties; + Widget dockedEditing({required bool showTools}) => + ExpandedEditorLayout( + preview: preview, + properties: properties, + media: media, + showMedia: showTools && _presentation.mediaOpen, + showProperties: showTools && _propertiesOpen, + timelineHeight: _timelineHeight, + onTimelineHeightChanged: (height) { + if (viewSettings.hasValue) { + _viewController.setTimelineHeight(height); + } + }, + onTimelineHeightChangeEnd: _saveViewSettings, + timeline: timeline, + ); + return Stack( + fit: StackFit.expand, + children: [ + Column( + children: [ + Material( + color: Theme.of(context).colorScheme.surface, + child: SizedBox( + key: const Key('editor-content-header'), + height: headerHeight, + child: WindowHeaderPadding( + child: Row( + children: [ + widget.headerLeading, + Expanded( + child: widget.showProjectName + ? Row( + children: [ + Flexible( + fit: FlexFit.loose, + child: Text( + widget.projectName, + key: const Key( + 'workspace-project-title', + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: Theme.of(context) + .textTheme + .titleSmall, + ), + ), + Flexible( + fit: FlexFit.loose, + child: _TimelineSaveStatus( + projectId: widget.projectId, + timelineId: widget.timelineId, + ), + ), + ], + ) + : const SizedBox.shrink(), + ), + HeaderControlRegion( + child: SizedBox.square( + dimension: desktop + ? AppControlSize.headerButton + : 48, + child: IconButton( + key: const Key('editor-media-button'), + tooltip: context.l10n.materials, + isSelected: mediaOpen, + onPressed: () { + if (desktop) { + if (!dockPanels && + desktopTool != EditorTool.media && + _presentation.mediaOpen) { + _presentation.preferDesktopTool( + EditorTool.media, + ); + } else { + _presentation.toggleMedia(); + } + } else { + _presentation.toggleTool( + EditorTool.media, + ); + } + }, + icon: const Icon(Icons.perm_media_outlined), + ), + ), + ), + const SizedBox(width: AppSpacing.tiny), + HeaderControlRegion( + child: SizedBox.square( + dimension: desktop + ? AppControlSize.headerButton + : 48, + child: IconButton( + key: const Key('editor-properties-button'), + tooltip: propertiesOpen + ? context.l10n.collapseProperties + : context.l10n.expandProperties, + isSelected: propertiesOpen, + onPressed: !viewSettings.hasValue + ? null + : () { + if (desktop) { + if (dockPanels || + desktopTool == + EditorTool.properties || + !_propertiesOpen) { + _viewController.setPropertiesOpen( + !_propertiesOpen, + ); + _saveViewSettings(); + } + _presentation.preferDesktopTool( + EditorTool.properties, + ); + } else { + _presentation.toggleTool( + EditorTool.properties, + ); + } + }, + icon: const Icon( + Icons.tune, + size: AppIconSize.header, + ), + ), + ), + ), + const SizedBox(width: AppSpacing.compact), + ], + ), + ), + ), + ), + Expanded( + child: dockPanels + ? dockedEditing(showTools: true) + : BoundedEditorLayout( + experience: widget.experience, + editing: desktop + ? dockedEditing(showTools: false) + : TouchEditingLayout( + preview: preview, + timeline: timeline, + ), + tool: desktop + ? desktopTool + : _presentation.activeTool, + media: switch (widget.experience) { + DeviceExperience.desktop => media, + DeviceExperience.tablet => MediaBrowserDrawer( + projectId: widget.projectId, + ), + DeviceExperience.phone => MediaBrowserPage( + projectId: widget.projectId, + ), + }, + properties: switch (widget.experience) { + DeviceExperience.desktop => properties, + DeviceExperience.tablet => PropertiesToolPanel( + projectId: widget.projectId, + timelineId: widget.timelineId, + ), + DeviceExperience.phone => PropertiesEditorPage( + projectId: widget.projectId, + timelineId: widget.timelineId, + ), + }, + onCloseTool: () { + if (!desktop) { + _presentation.closeTool(); + } else if (desktopTool == EditorTool.media) { + _presentation.toggleMedia(); + } else { + _viewController.setPropertiesOpen(false); + _saveViewSettings(); + } + }, + ), + ), + ], + ), + Positioned( + key: const Key('editing-top-divider'), + top: headerHeight, + left: 0, + right: 0, + height: 1, + child: const Divider(height: 1), + ), + ], + ); + }, + ), + ); + } +} + +class _TimelineSaveStatus extends ConsumerWidget { + const _TimelineSaveStatus({ + required this.projectId, + required this.timelineId, + }); + + final String projectId; + final String timelineId; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final session = ref + .watch(editorTimelineProvider(projectId, timelineId)) + .asData + ?.value; + if (session == null) return const SizedBox.shrink(); + return ListenableBuilder( + listenable: session, + builder: (context, _) => Padding( + padding: const EdgeInsets.only(left: AppSpacing.small), + child: Text( + session.error != null + ? context.l10n.unsaved + : session.saving + ? context.l10n.saving + : session.dirty + ? context.l10n.pendingSave + : context.l10n.saved, + key: const Key('timeline-save-status'), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: Theme.of(context).textTheme.bodySmall?.copyWith(fontSize: 10), + ), + ), + ); + } +} diff --git a/lib/features/editor/editor_presentation_controller.dart b/lib/features/editor/editor_presentation_controller.dart new file mode 100644 index 0000000..3cd205a --- /dev/null +++ b/lib/features/editor/editor_presentation_controller.dart @@ -0,0 +1,48 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +enum EditorTool { media, properties } + +final editorPresentationProvider = + Provider.family((ref, projectId) { + final controller = EditorPresentationController(); + ref.onDispose(controller.dispose); + return controller; + }); + +/// Presentation choices survive shell changes without changing project data. +class EditorPresentationController extends ChangeNotifier { + bool _mediaOpen = false; + EditorTool? _activeTool; + EditorTool _preferredDesktopTool = EditorTool.properties; + + bool get mediaOpen => _mediaOpen; + EditorTool? get activeTool => _activeTool; + EditorTool desktopTool({required bool propertiesOpen}) => + _preferredDesktopTool == EditorTool.media && _mediaOpen + ? EditorTool.media + : propertiesOpen + ? EditorTool.properties + : EditorTool.media; + + void preferDesktopTool(EditorTool tool) { + _preferredDesktopTool = tool; + notifyListeners(); + } + + void toggleMedia() { + _mediaOpen = !_mediaOpen; + if (_mediaOpen) _preferredDesktopTool = EditorTool.media; + notifyListeners(); + } + + void toggleTool(EditorTool tool) { + _activeTool = _activeTool == tool ? null : tool; + notifyListeners(); + } + + void closeTool() { + _activeTool = null; + notifyListeners(); + } +} diff --git a/lib/features/editor/layouts/bounded_editor_layout.dart b/lib/features/editor/layouts/bounded_editor_layout.dart new file mode 100644 index 0000000..f1da5cb --- /dev/null +++ b/lib/features/editor/layouts/bounded_editor_layout.dart @@ -0,0 +1,146 @@ +import 'dart:math' as math; + +import 'package:flutter/material.dart'; + +import '../../../integrations/platform/device_experience.dart'; +import '../../../l10n/l10n.dart'; + +import 'package:cutdex_ui/theme.dart'; + +import '../editor_presentation_controller.dart'; + +/// Space changes the tool bounds; device experience determines its interactions. +class BoundedEditorLayout extends StatelessWidget { + const BoundedEditorLayout({ + super.key, + required this.experience, + required this.editing, + required this.tool, + required this.media, + required this.properties, + required this.onCloseTool, + }); + + final DeviceExperience experience; + final Widget editing; + final EditorTool? tool; + final Widget media; + final Widget properties; + final VoidCallback onCloseTool; + + @override + Widget build(BuildContext context) => LayoutBuilder( + builder: (context, constraints) { + final page = experience == DeviceExperience.phone; + final desktop = experience == DeviceExperience.desktop; + Widget toolSurface() => Column( + children: [ + SizedBox( + height: desktop ? AppControlSize.panelHeader : 48, + child: Row( + children: [ + SizedBox.square( + dimension: desktop ? AppControlSize.headerButton : 48, + child: IconButton( + key: const Key('editor-tool-close'), + tooltip: MaterialLocalizations.of(context) + .closeButtonTooltip, + onPressed: onCloseTool, + icon: Icon(page ? Icons.arrow_back : Icons.close), + ), + ), + Expanded( + child: Text( + tool == EditorTool.media + ? context.l10n.materials + : context.l10n.expandProperties, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + ), + const Divider(height: 1), + Expanded(child: tool == EditorTool.media ? media : properties), + ], + ); + return PopScope( + canPop: desktop || tool == null, + onPopInvokedWithResult: (didPop, result) { + if (didPop || desktop || tool == null) return; + final scaffold = Scaffold.maybeOf(context); + if (scaffold?.isDrawerOpen ?? false) { + scaffold!.closeDrawer(); + } else { + onCloseTool(); + } + }, + child: Stack( + key: Key('${experience.name}-editor-tools'), + fit: StackFit.expand, + children: [ + ExcludeFocus( + excluding: page && tool != null, + child: IgnorePointer( + ignoring: page && tool != null, + child: TickerMode( + enabled: !page || tool == null, + child: editing, + ), + ), + ), + if (tool != null) + Positioned( + top: 0, + bottom: 0, + right: 0, + width: page + ? constraints.maxWidth + : math.min(320, constraints.maxWidth), + child: Material( + key: const Key('editor-tool-surface'), + elevation: page ? 0 : 8, + color: Theme.of(context).colorScheme.surface, + child: toolSurface(), + ), + ), + ], + ), + ); + }, + ); +} + +/// A shared preview/timeline arrangement for touch experiences. +class TouchEditingLayout extends StatelessWidget { + const TouchEditingLayout({ + super.key, + required this.preview, + required this.timeline, + }); + final Widget preview; + final Widget timeline; + + @override + Widget build(BuildContext context) => LayoutBuilder( + builder: (context, constraints) { + final short = constraints.maxHeight < 340 && constraints.maxWidth >= 600; + return short + ? Row( + children: [ + Expanded(child: preview), + const VerticalDivider(width: 1), + Expanded(child: timeline), + ], + ) + : Column( + children: [ + Expanded(flex: 3, child: preview), + const Divider(height: 1), + Expanded(flex: 2, child: timeline), + ], + ); + }, + ); +} diff --git a/lib/features/editor/layouts/expanded_editor_layout.dart b/lib/features/editor/layouts/expanded_editor_layout.dart new file mode 100644 index 0000000..44abf4b --- /dev/null +++ b/lib/features/editor/layouts/expanded_editor_layout.dart @@ -0,0 +1,145 @@ +import 'dart:math' as math; + +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; + +import '../../../shared/layout/workspace_layout_metrics.dart'; + +class ExpandedEditorLayout extends StatefulWidget { + const ExpandedEditorLayout({ + super.key, + required this.preview, + required this.properties, + required this.media, + required this.showMedia, + required this.showProperties, + required this.timelineHeight, + required this.onTimelineHeightChanged, + required this.onTimelineHeightChangeEnd, + required this.timeline, + }); + + final Widget preview; + final Widget properties; + final Widget media; + final bool showMedia; + final bool showProperties; + final double? timelineHeight; + final ValueChanged onTimelineHeightChanged; + final VoidCallback onTimelineHeightChangeEnd; + final Widget timeline; + + @override + State createState() => _ExpandedEditorLayoutState(); +} + +class _ExpandedEditorLayoutState extends State { + double? _timelineDragStartY; + double _timelineDragStartHeight = 0; + + @override + Widget build(BuildContext context) => LayoutBuilder( + builder: (context, constraints) { + final maximum = math.max( + 0.0, + constraints.maxHeight - WorkspaceLayoutMetrics.timelineMinimumHeight, + ); + final minimum = math.min( + WorkspaceLayoutMetrics.timelineMinimumHeight, + maximum, + ); + final timelineHeight = + (widget.timelineHeight ?? + constraints.maxHeight * + WorkspaceLayoutMetrics.timelineDefaultHeightFraction) + .clamp(minimum, maximum) + .toDouble(); + final mediaWidth = widget.showMedia + ? WorkspaceLayoutMetrics.mediaPanelWidth + : 0.0; + final propertiesWidth = widget.showProperties + ? WorkspaceLayoutMetrics.propertiesPanelWidth + : 0.0; + return Stack( + fit: StackFit.expand, + children: [ + Column( + children: [ + Expanded( + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (widget.showMedia) ...[ + SizedBox( + key: const Key('editor-media-region'), + width: mediaWidth, + child: widget.media, + ), + const VerticalDivider(width: 1), + ], + Expanded(child: widget.preview), + if (widget.showProperties) ...[ + const VerticalDivider(width: 1), + SizedBox( + key: const Key('editor-properties-region'), + width: propertiesWidth, + child: widget.properties, + ), + ], + ], + ), + ), + const SizedBox(height: 1), + SizedBox(height: timelineHeight, child: widget.timeline), + ], + ), + Positioned( + key: const Key('editor-timeline-divider'), + left: 0, + right: 0, + bottom: timelineHeight - 4, + height: 8, + child: MouseRegion( + cursor: SystemMouseCursors.resizeRow, + child: GestureDetector( + key: const Key('editor-timeline-resize'), + behavior: HitTestBehavior.opaque, + dragStartBehavior: DragStartBehavior.down, + onVerticalDragStart: (details) { + _timelineDragStartY = details.globalPosition.dy; + _timelineDragStartHeight = timelineHeight; + }, + onVerticalDragUpdate: (details) { + final start = _timelineDragStartY; + if (start == null) return; + widget.onTimelineHeightChanged( + (_timelineDragStartHeight + + start - + details.globalPosition.dy) + .clamp(minimum, maximum) + .toDouble(), + ); + }, + onVerticalDragEnd: (_) { + _timelineDragStartY = null; + widget.onTimelineHeightChangeEnd(); + }, + onVerticalDragCancel: () { + _timelineDragStartY = null; + widget.onTimelineHeightChangeEnd(); + }, + child: const Center( + child: SizedBox( + height: 1, + width: double.infinity, + child: Divider(height: 1), + ), + ), + ), + ), + ), + ], + ); + }, + ); +} diff --git a/lib/features/media/audio_asset_tile.dart b/lib/features/media/audio_asset_tile.dart new file mode 100644 index 0000000..2b9ae7a --- /dev/null +++ b/lib/features/media/audio_asset_tile.dart @@ -0,0 +1,134 @@ +import 'dart:math' as math; + +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:cutdex_sdk/timeline_ui.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../integrations/runtime/media_presentations.dart'; + +import 'package:cutdex_ui/theme.dart'; + +class AudioAssetTile extends StatelessWidget { + const AudioAssetTile({ + super.key, + required this.asset, + this.showName = true, + this.aspectRatio = 16 / 9, + }); + final AssetDocument asset; + final bool showName; + final double aspectRatio; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + AspectRatio( + key: ValueKey('audio-cover-${asset.id}'), + aspectRatio: aspectRatio, + child: ColoredBox( + color: AppSurfaces.of(context).previewBackground, + child: _AudioWaveformCover(asset), + ), + ), + if (showName) ...[ + const SizedBox(height: AppSpacing.small), + Tooltip( + message: asset.name, + child: Text( + asset.name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: theme.textTheme.bodySmall, + ), + ), + ], + ], + ); + } +} + +class _AudioWaveformCover extends ConsumerWidget { + const _AudioWaveformCover(this.asset); + final AssetDocument asset; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final waveform = ref.watch(mediaWaveformProvider(asset)).value; + final theme = Theme.of(context); + if (waveform == null) { + return Center( + child: Icon( + Icons.audio_file_outlined, + size: AppIconSize.emptyState, + color: theme.colorScheme.onSurfaceVariant, + ), + ); + } + return CustomPaint( + key: ValueKey('audio-waveform-${asset.id}'), + painter: _AudioCoverPainter( + waveform, + theme.extension()?.audioAccentColor ?? + theme.colorScheme.primary, + MediaQuery.devicePixelRatioOf(context), + ), + ); + } +} + +class _AudioCoverPainter extends CustomPainter { + const _AudioCoverPainter(this.waveform, this.color, this.devicePixelRatio); + final TimelineWaveform waveform; + final Color color; + final double devicePixelRatio; + + @override + void paint(Canvas canvas, Size size) { + if (size.isEmpty) return; + final columns = math.max(1, (size.width / 2).floor()); + final start = waveform.sourceStartSeconds * TimelineClock.ticksPerSecond; + final duration = + waveform.frameCount / + waveform.sampleRate * + TimelineClock.ticksPerSecond; + final paint = Paint() + ..color = color + ..style = PaintingStyle.fill + ..isAntiAlias = false; + final strokePixels = math.max(1, devicePixelRatio.round()); + final bottomPixels = math.max(1, (size.height * devicePixelRatio).floor()); + for (var column = 0; column < columns; column++) { + final envelope = waveform.envelope( + (start + duration * column / columns).round(), + (start + duration * (column + 1) / columns).round(), + ); + final peak = math.max(envelope.minimum.abs(), envelope.maximum.abs()); + final height = math.min(size.height, math.max(1.0, peak * size.height)); + final x = (column + 0.5) * size.width / columns; + final leftPixels = (x * devicePixelRatio - strokePixels / 2).round(); + final topPixels = ((size.height - height) * devicePixelRatio) + .round() + .clamp(0, bottomPixels - 1); + canvas.drawRect( + Rect.fromLTWH( + leftPixels / devicePixelRatio, + topPixels / devicePixelRatio, + strokePixels / devicePixelRatio, + (bottomPixels - topPixels) / devicePixelRatio, + ), + paint, + ); + } + } + + @override + bool shouldRepaint(_AudioCoverPainter oldDelegate) => + oldDelegate.waveform != waveform || + oldDelegate.color != color || + oldDelegate.devicePixelRatio != devicePixelRatio; +} diff --git a/lib/features/media/background_removal_controller.dart b/lib/features/media/background_removal_controller.dart new file mode 100644 index 0000000..4060ffe --- /dev/null +++ b/lib/features/media/background_removal_controller.dart @@ -0,0 +1,130 @@ +import 'package:cutdex/diagnostics/app_diagnostics.dart'; +import 'package:cutdex/errors/app_failure.dart'; + +import 'package:cutdex_sdk/editor.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import '../../integrations/runtime/processing_configuration.dart'; +import '../../integrations/runtime/processing_resource_repository.dart'; +import '../../workspace/timeline_session.dart'; +import 'processing_targets.dart'; + +part 'background_removal_controller.g.dart'; +part 'background_removal_controller.freezed.dart'; + +enum BackgroundRemovalFailure { download, start, rejected } + +@freezed +sealed class BackgroundRemovalState with _$BackgroundRemovalState { + const factory BackgroundRemovalState.idle() = RemovalIdle; + const factory BackgroundRemovalState.downloading() = RemovalDownloading; + const factory BackgroundRemovalState.starting() = RemovalStarting; + const factory BackgroundRemovalState.started() = RemovalStarted; + const factory BackgroundRemovalState.cancelled() = RemovalCancelled; + const factory BackgroundRemovalState.failed( + BackgroundRemovalFailure failure, { + String? message, + }) = RemovalFailed; +} + +@riverpod +class BackgroundRemovalController extends _$BackgroundRemovalController { + bool _cancelled = false; + ProcessingResourceRepository? _repository; + + @override + BackgroundRemovalState build( + EditorTimelineSession session, + BackgroundRemovalClipTarget target, + ) { + ref.onDispose(() { + _cancelled = true; + }); + return const BackgroundRemovalState.idle(); + } + + Future start( + ProcessingResourceRepository repository, { + bool download = false, + }) async { + if (state is RemovalDownloading || state is RemovalStarting) return; + final lease = ref.keepAlive(); + final release = session.retainViews(); + _repository = repository; + _cancelled = false; + var installed = !download; + state = download + ? const BackgroundRemovalState.downloading() + : const BackgroundRemovalState.starting(); + try { + if (download) { + await repository.ensureAvailable( + ProcessingCapability.backgroundRemoval, + ); + installed = true; + } + if (_cancelled || !ref.mounted || !session.acceptsEdits) return; + state = const BackgroundRemovalState.starting(); + final processing = ProcessingConfiguration.configured( + diagnostics: AppDiagnostics.report, + resourcesRoot: repository.root.parent.path, + ); + final model = processing?.backgroundRemovalModel; + if (processing == null || model == null) { + throw AppException(AppErrorCode.startBackgroundRemovalFailed); + } + session.backgroundRemovals.configure( + backend: processing.backend.execute, + model: model, + ); + await session.backgroundRemovals.start( + sequence: target.sequence, + clipId: target.clipId, + mediaId: target.mediaId, + name: target.name, + backend: processing.backend.execute, + model: model, + ); + if (ref.mounted) state = const BackgroundRemovalState.started(); + } on ProcessingResourceCancelledException { + if (ref.mounted) state = const BackgroundRemovalState.cancelled(); + } on CommandRejected catch (error) { + if (ref.mounted) { + state = BackgroundRemovalState.failed( + BackgroundRemovalFailure.rejected, + message: error.message, + ); + } + } catch (_) { + if (ref.mounted) { + state = BackgroundRemovalState.failed( + installed + ? BackgroundRemovalFailure.start + : BackgroundRemovalFailure.download, + ); + } + } finally { + if (ref.mounted && + (state is RemovalDownloading || state is RemovalStarting)) { + state = const BackgroundRemovalState.cancelled(); + } + _repository = null; + release(); + lease.close(); + } + } + + void cancel(ProcessingResourceRepository repository) { + _cancelled = true; + (_repository ?? repository).cancel(ProcessingCapability.backgroundRemoval); + } + + void togglePause(ProcessingResourceRepository repository) { + if (repository.downloadPausedFor(ProcessingCapability.backgroundRemoval)) { + repository.resumeDownload(ProcessingCapability.backgroundRemoval); + } else { + repository.pauseDownload(ProcessingCapability.backgroundRemoval); + } + } +} diff --git a/lib/features/media/background_removal_controller.freezed.dart b/lib/features/media/background_removal_controller.freezed.dart new file mode 100644 index 0000000..0f8d694 --- /dev/null +++ b/lib/features/media/background_removal_controller.freezed.dart @@ -0,0 +1,456 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'background_removal_controller.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +T _$identity(T value) => value; + +/// @nodoc +mixin _$BackgroundRemovalState { + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is BackgroundRemovalState); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + String toString() { + return 'BackgroundRemovalState()'; + } +} + +/// @nodoc +class $BackgroundRemovalStateCopyWith<$Res> { + $BackgroundRemovalStateCopyWith( + BackgroundRemovalState _, + $Res Function(BackgroundRemovalState) __, + ); +} + +/// Adds pattern-matching-related methods to [BackgroundRemovalState]. +extension BackgroundRemovalStatePatterns on BackgroundRemovalState { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap({ + TResult Function(RemovalIdle value)? idle, + TResult Function(RemovalDownloading value)? downloading, + TResult Function(RemovalStarting value)? starting, + TResult Function(RemovalStarted value)? started, + TResult Function(RemovalCancelled value)? cancelled, + TResult Function(RemovalFailed value)? failed, + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case RemovalIdle() when idle != null: + return idle(_that); + case RemovalDownloading() when downloading != null: + return downloading(_that); + case RemovalStarting() when starting != null: + return starting(_that); + case RemovalStarted() when started != null: + return started(_that); + case RemovalCancelled() when cancelled != null: + return cancelled(_that); + case RemovalFailed() when failed != null: + return failed(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map({ + required TResult Function(RemovalIdle value) idle, + required TResult Function(RemovalDownloading value) downloading, + required TResult Function(RemovalStarting value) starting, + required TResult Function(RemovalStarted value) started, + required TResult Function(RemovalCancelled value) cancelled, + required TResult Function(RemovalFailed value) failed, + }) { + final _that = this; + switch (_that) { + case RemovalIdle(): + return idle(_that); + case RemovalDownloading(): + return downloading(_that); + case RemovalStarting(): + return starting(_that); + case RemovalStarted(): + return started(_that); + case RemovalCancelled(): + return cancelled(_that); + case RemovalFailed(): + return failed(_that); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(RemovalIdle value)? idle, + TResult? Function(RemovalDownloading value)? downloading, + TResult? Function(RemovalStarting value)? starting, + TResult? Function(RemovalStarted value)? started, + TResult? Function(RemovalCancelled value)? cancelled, + TResult? Function(RemovalFailed value)? failed, + }) { + final _that = this; + switch (_that) { + case RemovalIdle() when idle != null: + return idle(_that); + case RemovalDownloading() when downloading != null: + return downloading(_that); + case RemovalStarting() when starting != null: + return starting(_that); + case RemovalStarted() when started != null: + return started(_that); + case RemovalCancelled() when cancelled != null: + return cancelled(_that); + case RemovalFailed() when failed != null: + return failed(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? idle, + TResult Function()? downloading, + TResult Function()? starting, + TResult Function()? started, + TResult Function()? cancelled, + TResult Function(BackgroundRemovalFailure failure, String? message)? failed, + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case RemovalIdle() when idle != null: + return idle(); + case RemovalDownloading() when downloading != null: + return downloading(); + case RemovalStarting() when starting != null: + return starting(); + case RemovalStarted() when started != null: + return started(); + case RemovalCancelled() when cancelled != null: + return cancelled(); + case RemovalFailed() when failed != null: + return failed(_that.failure, _that.message); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when({ + required TResult Function() idle, + required TResult Function() downloading, + required TResult Function() starting, + required TResult Function() started, + required TResult Function() cancelled, + required TResult Function(BackgroundRemovalFailure failure, String? message) + failed, + }) { + final _that = this; + switch (_that) { + case RemovalIdle(): + return idle(); + case RemovalDownloading(): + return downloading(); + case RemovalStarting(): + return starting(); + case RemovalStarted(): + return started(); + case RemovalCancelled(): + return cancelled(); + case RemovalFailed(): + return failed(_that.failure, _that.message); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? idle, + TResult? Function()? downloading, + TResult? Function()? starting, + TResult? Function()? started, + TResult? Function()? cancelled, + TResult? Function(BackgroundRemovalFailure failure, String? message)? + failed, + }) { + final _that = this; + switch (_that) { + case RemovalIdle() when idle != null: + return idle(); + case RemovalDownloading() when downloading != null: + return downloading(); + case RemovalStarting() when starting != null: + return starting(); + case RemovalStarted() when started != null: + return started(); + case RemovalCancelled() when cancelled != null: + return cancelled(); + case RemovalFailed() when failed != null: + return failed(_that.failure, _that.message); + case _: + return null; + } + } +} + +/// @nodoc + +class RemovalIdle implements BackgroundRemovalState { + const RemovalIdle(); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is RemovalIdle); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + String toString() { + return 'BackgroundRemovalState.idle()'; + } +} + +/// @nodoc + +class RemovalDownloading implements BackgroundRemovalState { + const RemovalDownloading(); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is RemovalDownloading); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + String toString() { + return 'BackgroundRemovalState.downloading()'; + } +} + +/// @nodoc + +class RemovalStarting implements BackgroundRemovalState { + const RemovalStarting(); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is RemovalStarting); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + String toString() { + return 'BackgroundRemovalState.starting()'; + } +} + +/// @nodoc + +class RemovalStarted implements BackgroundRemovalState { + const RemovalStarted(); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is RemovalStarted); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + String toString() { + return 'BackgroundRemovalState.started()'; + } +} + +/// @nodoc + +class RemovalCancelled implements BackgroundRemovalState { + const RemovalCancelled(); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is RemovalCancelled); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + String toString() { + return 'BackgroundRemovalState.cancelled()'; + } +} + +/// @nodoc + +class RemovalFailed implements BackgroundRemovalState { + const RemovalFailed(this.failure, {this.message}); + + final BackgroundRemovalFailure failure; + final String? message; + + /// Create a copy of BackgroundRemovalState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $RemovalFailedCopyWith get copyWith => + _$RemovalFailedCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is RemovalFailed && + (identical(other.failure, failure) || other.failure == failure) && + (identical(other.message, message) || other.message == message)); + } + + @override + int get hashCode { + return Object.hash(runtimeType, failure, message); + } + + @override + String toString() { + return 'BackgroundRemovalState.failed(failure: $failure, message: $message)'; + } +} + +/// @nodoc +abstract mixin class $RemovalFailedCopyWith<$Res> + implements $BackgroundRemovalStateCopyWith<$Res> { + factory $RemovalFailedCopyWith( + RemovalFailed value, + $Res Function(RemovalFailed) _then, + ) = _$RemovalFailedCopyWithImpl; + @useResult + $Res call({BackgroundRemovalFailure failure, String? message}); +} + +/// @nodoc +class _$RemovalFailedCopyWithImpl<$Res> + implements $RemovalFailedCopyWith<$Res> { + _$RemovalFailedCopyWithImpl(this._self, this._then); + + final RemovalFailed _self; + final $Res Function(RemovalFailed) _then; + + /// Create a copy of BackgroundRemovalState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({Object? failure = null, Object? message = freezed}) { + return _then( + RemovalFailed( + null == failure + ? _self.failure + : failure // ignore: cast_nullable_to_non_nullable + as BackgroundRemovalFailure, + message: freezed == message + ? _self.message + : message // ignore: cast_nullable_to_non_nullable + as String?, + ), + ); + } +} diff --git a/lib/features/media/background_removal_controller.g.dart b/lib/features/media/background_removal_controller.g.dart new file mode 100644 index 0000000..e48e203 --- /dev/null +++ b/lib/features/media/background_removal_controller.g.dart @@ -0,0 +1,124 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'background_removal_controller.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(BackgroundRemovalController) +final backgroundRemovalControllerProvider = + BackgroundRemovalControllerFamily._(); + +final class BackgroundRemovalControllerProvider + extends + $NotifierProvider { + BackgroundRemovalControllerProvider._({ + required BackgroundRemovalControllerFamily super.from, + required (EditorTimelineSession, BackgroundRemovalClipTarget) + super.argument, + }) : super( + retry: null, + name: r'backgroundRemovalControllerProvider', + isAutoDispose: true, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$backgroundRemovalControllerHash(); + + @override + String toString() { + return r'backgroundRemovalControllerProvider' + '' + '$argument'; + } + + @$internal + @override + BackgroundRemovalController create() => BackgroundRemovalController(); + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(BackgroundRemovalState value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } + + @override + bool operator ==(Object other) { + return other is BackgroundRemovalControllerProvider && + other.argument == argument; + } + + @override + int get hashCode { + return argument.hashCode; + } +} + +String _$backgroundRemovalControllerHash() => + r'429add9c699b92fdba9c553810f17f4a6859f4e6'; + +final class BackgroundRemovalControllerFamily extends $Family + with + $ClassFamilyOverride< + BackgroundRemovalController, + BackgroundRemovalState, + BackgroundRemovalState, + BackgroundRemovalState, + (EditorTimelineSession, BackgroundRemovalClipTarget) + > { + BackgroundRemovalControllerFamily._() + : super( + retry: null, + name: r'backgroundRemovalControllerProvider', + dependencies: null, + $allTransitiveDependencies: null, + isAutoDispose: true, + ); + + BackgroundRemovalControllerProvider call( + EditorTimelineSession session, + BackgroundRemovalClipTarget target, + ) => BackgroundRemovalControllerProvider._( + argument: (session, target), + from: this, + ); + + @override + String toString() => r'backgroundRemovalControllerProvider'; +} + +abstract class _$BackgroundRemovalController + extends $Notifier { + late final _$args = + ref.$arg as (EditorTimelineSession, BackgroundRemovalClipTarget); + EditorTimelineSession get session => _$args.$1; + BackgroundRemovalClipTarget get target => _$args.$2; + + BackgroundRemovalState build( + EditorTimelineSession session, + BackgroundRemovalClipTarget target, + ); + @$mustCallSuper + @override + WhenComplete runBuild() { + final ref = + this.ref as $Ref; + final element = + ref.element + as $ClassProviderElement< + AnyNotifier, + BackgroundRemovalState, + Object?, + Object? + >; + return element.handleCreate(ref, () => build(_$args.$1, _$args.$2)); + } +} diff --git a/lib/features/media/background_removal_dialog.dart b/lib/features/media/background_removal_dialog.dart new file mode 100644 index 0000000..008edea --- /dev/null +++ b/lib/features/media/background_removal_dialog.dart @@ -0,0 +1,202 @@ +import 'package:cutdex/l10n/l10n.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../integrations/runtime/processing_configuration.dart'; +import '../../integrations/runtime/processing_resource_repository.dart'; +import '../../integrations/runtime/processing_resource_state.dart'; + +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex_ui/widgets.dart'; + +import '../../shared/widgets/confirm_resource_download_cancel.dart'; +import '../../shared/widgets/processing_resource_download_dialog.dart'; +import '../../workspace/timeline_session.dart'; + +import 'processing_targets.dart'; +import 'background_removal_controller.dart'; +export 'processing_targets.dart'; + +class BackgroundRemovalDialog extends ConsumerStatefulWidget { + const BackgroundRemovalDialog({ + super.key, + required this.session, + required this.target, + }); + + final EditorTimelineSession session; + final BackgroundRemovalClipTarget target; + + @override + ConsumerState createState() => + _BackgroundRemovalDialogState(); +} + +class _BackgroundRemovalDialogState + extends ConsumerState { + late final VoidCallback _release; + bool _closing = false; + BackgroundRemovalControllerProvider get _provider => + backgroundRemovalControllerProvider(widget.session, widget.target); + BackgroundRemovalState get _state => ref.read(_provider); + bool get _installing => _state is RemovalDownloading; + bool get _starting => _state is RemovalStarting; + String? get _error => switch (_state) { + RemovalFailed(:final failure, :final message) => switch (failure) { + BackgroundRemovalFailure.download => + context.l10n.processingResourceDownloadFailed, + BackgroundRemovalFailure.start => + context.l10n.startBackgroundRemovalFailed, + BackgroundRemovalFailure.rejected => message, + }, + _ => null, + }; + @override + void initState() { + super.initState(); + _release = widget.session.retainViews(); + } + + @override + void dispose() { + _release(); + super.dispose(); + } + + Future _start(ProcessingResourceRepository repository) => + ref.read(_provider.notifier).start(repository); + Future _downloadAndStart(ProcessingResourceRepository repository) => + ref.read(_provider.notifier).start(repository, download: true); + + @override + Widget build(BuildContext context) { + ref.watch(_provider); + ref.listen(_provider, (previous, next) { + if (next is! RemovalStarted || _closing) return; + _closing = true; + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + final messenger = ScaffoldMessenger.maybeOf(context); + final message = context.l10n.backgroundRemovalTaskStarted; + Navigator.of(context).pop(); + messenger?.showSnackBar(SnackBar(content: Text(message))); + }); + }); + return ref + .watch(processingResourceRepositoryProvider) + .when( + loading: () => const DelayedLoadingIndicator( + child: AppDialog( + title: '', + width: 520, + child: Center(child: CircularProgressIndicator()), + ), + ), + error: (_, _) => AppDialog( + title: context.l10n.removeBackground, + width: 520, + child: Text(context.l10n.loadResourceLocationFailed), + ), + data: (repository) => Consumer( + builder: (context, ref, _) { + final resources = ref.watch( + processingResourcesProvider(repository), + ); + final install = + resources.installs + .where( + (item) => + item.package.capability == + ProcessingCapability.backgroundRemoval, + ) + .firstOrNull ?? + repository.installFor(ProcessingCapability.backgroundRemoval); + final installed = + install.state == ProcessingResourceState.installed || + ProcessingConfiguration.configured( + resourcesRoot: repository.root.parent.path, + )?.backgroundRemovalModel != + null; + final downloading = + install.state == ProcessingResourceState.downloading; + if (!installed) { + return ProcessingResourceDownloadDialog( + title: context.l10n.backgroundRemovalDownloadTask, + description: context.l10n.backgroundRemovalResourceRequired, + resourceName: context.l10n.backgroundRemovalResourceName, + downloadSize: context.l10n.subtitleResourcesDownloadSize( + formatResourceBytes(install.package.bytes), + ), + downloading: downloading, + paused: resources.paused.contains( + ProcessingCapability.backgroundRemoval, + ), + downloadedBytes: install.downloadedBytes, + totalBytes: install.package.bytes, + bytesPerSecond: + resources.rates[ProcessingCapability.backgroundRemoval] ?? + 0, + error: _error, + downloadButtonKey: const Key( + 'download-background-removal-resource', + ), + pauseButtonKey: const Key( + 'pause-background-removal-resource', + ), + backgroundButtonKey: const Key( + 'background-background-removal-resource', + ), + onCancel: () async { + if (downloading && + !await confirmResourceDownloadCancellation(context)) { + return; + } + if (!mounted || !context.mounted) return; + if (downloading) { + ref.read(_provider.notifier).cancel(repository); + } + Navigator.of(context).pop(); + }, + onDownload: () { + if (!_installing && !downloading) { + _downloadAndStart(repository); + } + }, + onTogglePause: () => + ref.read(_provider.notifier).togglePause(repository), + onBackground: () => Navigator.of(context).pop(), + ); + } + return AppDialog( + title: context.l10n.removeBackground, + width: 520, + description: context.l10n.backgroundRemovalDestructiveHint, + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: Text(context.l10n.close), + ), + FilledButton( + onPressed: + _installing || _starting || !widget.session.acceptsEdits + ? null + : () => _start(repository), + child: Text(context.l10n.startBackgroundRemoval), + ), + ], + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + if (_error case final error?) ...[ + const SizedBox(height: AppSpacing.compact), + Text(error), + ], + ], + ), + ); + }, + ), + ); + } +} diff --git a/lib/features/media/background_tasks_dialog.dart b/lib/features/media/background_tasks_dialog.dart new file mode 100644 index 0000000..a310b7b --- /dev/null +++ b/lib/features/media/background_tasks_dialog.dart @@ -0,0 +1,862 @@ +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import 'subtitle_download.dart'; +import 'subtitle_task_actions.dart'; + +import 'package:cutdex/l10n/l10n.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:flutter/material.dart'; + +import '../../integrations/runtime/processing_resource_repository.dart'; + +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex_ui/widgets.dart'; + +import '../../shared/widgets/confirm_resource_download_cancel.dart'; +import '../../workspace/background_task_registry.dart'; +import '../../workspace/background_task_state.dart'; +import '../../integrations/runtime/processing_resource_state.dart'; +import '../../workspace/timeline_session.dart'; +import 'transcription_dialog.dart'; + +class BackgroundTasksDialog extends StatelessWidget { + const BackgroundTasksDialog({super.key, required this.session}); + final EditorTimelineSession session; + @override + Widget build(BuildContext context) => AppDialog( + title: context.l10n.backgroundTasks, + width: 560, + height: 520, + child: BackgroundTasksContent(session: session), + ); +} + +class BackgroundTasksContent extends ConsumerWidget { + const BackgroundTasksContent({ + super.key, + this.session, + this.registry, + this.repository, + }) : assert(session != null || registry != null); + final EditorTimelineSession? session; + final BackgroundTaskRegistry? registry; + final ProcessingResourceRepository? repository; + @override + Widget build(BuildContext context, WidgetRef ref) { + final snapshot = ref.watch( + backgroundTasksProvider(registry: registry, session: session), + ); + final resources = repository == null + ? null + : ref.watch(processingResourcesProvider(repository!)); + final subtitleEntries = snapshot.subtitles; + final removalEntries = snapshot.removals; + final subtitleDownloading = resources?.subtitleDownloading == true; + final resourceDownloads = + resources?.installs + .where( + (install) => + (install.state == ProcessingResourceState.downloading && + !(subtitleDownloading && + ProcessingResourceRepository.subtitleCapabilities + .contains(install.package.capability))) || + install.state == ProcessingResourceState.failed, + ) + .toList() ?? + []; + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (subtitleEntries.isEmpty && + !subtitleDownloading && + resourceDownloads.isEmpty && + removalEntries.isEmpty) + SizedBox( + key: const Key('background-tasks-empty-state'), + height: AppMenuMetrics.rowHeight, + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: AppMenuMetrics.iconGap, + ), + child: Align( + alignment: AlignmentDirectional.centerStart, + child: Text( + context.l10n.noBackgroundTasks, + style: Theme.of(context).textTheme.bodyMedium?.copyWith( + color: Theme.of(context).colorScheme.onSurfaceVariant, + fontSize: AppMenuMetrics.fontSize, + height: AppMenuMetrics.lineHeight / AppMenuMetrics.fontSize, + ), + ), + ), + ), + ) + else + Flexible( + child: SingleChildScrollView( + primary: false, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + if (subtitleDownloading) + _ResourceDownloadCard( + repository: repository!, + subtitleBundle: true, + ), + for (final (index, install) in resourceDownloads.indexed) ...[ + if (index > 0 || subtitleDownloading) + const SizedBox(height: 2), + _ResourceDownloadCard( + repository: repository!, + install: install, + ), + ], + for (final (index, entry) in removalEntries.indexed) ...[ + if (index > 0 || + resourceDownloads.isNotEmpty || + subtitleDownloading) + const SizedBox(height: 2), + _BackgroundRemovalTaskCard( + key: ValueKey(entry.task.id), + entry: entry, + ), + ], + for (final (index, entry) + in subtitleEntries.reversed.indexed) ...[ + if (index > 0 || + resourceDownloads.isNotEmpty || + removalEntries.isNotEmpty || + subtitleDownloading) + const SizedBox(height: 2), + _SubtitleTaskCard( + key: ValueKey(entry.job.recognition.id), + entry: entry, + ), + ], + ], + ), + ), + ), + ], + ); + } +} + +String _ownerName(BackgroundTaskSession owner) => owner.projectName.isEmpty + ? owner.timelineName + : '${owner.projectName} · ${owner.timelineName}'; + +Future _showTaskDetails( + BuildContext context, { + required WidgetBuilder builder, + EditorTimelineSession? session, +}) async { + final release = session?.retainViews(); + try { + await showAppDialog( + context: context, + builder: (context) => AppDialog( + title: context.l10n.backgroundTaskDetails, + width: 560, + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: Text(context.l10n.close), + ), + ], + child: builder(context), + ), + ); + } finally { + release?.call(); + } +} + +class _SubtitleTaskDetails extends ConsumerWidget { + const _SubtitleTaskDetails(this.initial); + final SubtitleTaskEntry initial; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final latest = ref.watch( + backgroundTasksProvider(session: initial.owner.session).select( + (snapshot) => snapshot.subtitles + .where((entry) => entry.job.id == initial.job.id) + .firstOrNull, + ), + ); + if (latest == null) return Text(context.l10n.noBackgroundTasks); + return _SubtitleTaskCard( + entry: latest.copyWith(owner: initial.owner), + details: true, + ); + } +} + +class _RemovalTaskDetails extends ConsumerWidget { + const _RemovalTaskDetails(this.initial); + final RemovalTaskEntry initial; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final latest = ref.watch( + backgroundTasksProvider(session: initial.owner.session).select( + (snapshot) => snapshot.removals + .where((entry) => entry.task.id == initial.task.id) + .firstOrNull, + ), + ); + if (latest == null) return Text(context.l10n.noBackgroundTasks); + return _BackgroundRemovalTaskCard( + entry: latest.copyWith(owner: initial.owner), + details: true, + ); + } +} + +class _TaskSummary extends StatelessWidget { + const _TaskSummary({ + required this.name, + required this.status, + required this.onTap, + this.active = false, + this.progress, + this.progressDetails, + this.action, + }); + final String name, status; + final VoidCallback onTap; + final bool active; + final double? progress; + final Widget? progressDetails; + final Widget? action; + + @override + Widget build(BuildContext context) => Material( + type: MaterialType.transparency, + borderRadius: BorderRadius.circular(AppMenuMetrics.itemRadius), + clipBehavior: Clip.antiAlias, + child: InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(AppMenuMetrics.itemRadius), + hoverColor: AppSidebarColors.of(context).hover, + highlightColor: Colors.transparent, + splashColor: Colors.transparent, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8), + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text(name, maxLines: 1, overflow: TextOverflow.ellipsis), + const SizedBox(height: 4), + if (progressDetails case final details?) + details + else ...[ + Text( + '$status${active && progress != null ? " · ${(progress! * 100).floor()}%" : ""}', + style: Theme.of(context).textTheme.bodySmall, + ), + if (active) ...[ + const SizedBox(height: 6), + LinearProgressIndicator(value: progress), + ], + ], + ], + ), + ), + ?action, + ], + ), + ), + ), + ); +} + +class _BackgroundRemovalTaskCard extends StatelessWidget { + const _BackgroundRemovalTaskCard({ + super.key, + required this.entry, + this.details = false, + }); + + final RemovalTaskEntry entry; + final bool details; + + @override + Widget build(BuildContext context) { + final total = entry.total; + final completed = entry.completed; + final progressValue = total == null || total <= 0 || completed == null + ? null + : completed / total; + final active = !entry.terminal; + final status = switch (entry.status) { + BackgroundRemovalStatus.queued => context.l10n.preparingMedia, + BackgroundRemovalStatus.running => context.l10n.removeBackground, + BackgroundRemovalStatus.applying => + context.l10n.backgroundRemovalApplying, + BackgroundRemovalStatus.succeeded => + context.l10n.backgroundRemovalComplete, + BackgroundRemovalStatus.failed => context.l10n.backgroundRemovalFailed, + BackgroundRemovalStatus.cancelling => context.l10n.cancelling, + BackgroundRemovalStatus.cancelled => context.l10n.cancelled, + BackgroundRemovalStatus.interrupted => context.l10n.interruptedTask, + }; + if (!details) { + return _TaskSummary( + name: entry.name, + status: status, + active: active, + progress: progressValue, + action: active + ? TextButton( + onPressed: entry.status == BackgroundRemovalStatus.cancelling + ? null + : () => entry.owner.session.backgroundRemovals.cancel( + entry.task.id, + ), + child: Text(context.l10n.cancel), + ) + : null, + onTap: () => _showTaskDetails( + context, + session: entry.owner.session, + builder: (_) => _RemovalTaskDetails(entry), + ), + ); + } + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + Text(entry.name, style: Theme.of(context).textTheme.titleSmall), + Text( + _ownerName(entry.owner), + style: Theme.of(context).textTheme.bodySmall, + ), + const SizedBox(height: AppSpacing.small), + Text(status), + if (entry.error case final error?) + Text( + context.l10n.errorMessage(error), + style: TextStyle(color: Theme.of(context).colorScheme.error), + ), + if (active) ...[ + const SizedBox(height: AppSpacing.small), + LinearProgressIndicator(value: progressValue), + if (progressValue != null) + Align( + alignment: Alignment.centerRight, + child: Text('${(progressValue * 100).floor()}%'), + ), + Align( + alignment: Alignment.centerRight, + child: TextButton( + onPressed: entry.status == BackgroundRemovalStatus.cancelling + ? null + : () => entry.owner.session.backgroundRemovals.cancel( + entry.task.id, + ), + child: Text(context.l10n.cancel), + ), + ), + ], + ], + ); + } +} + +class _ResourceDownloadCard extends ConsumerWidget { + const _ResourceDownloadCard({ + required this.repository, + this.install, + this.subtitleBundle = false, + this.details = false, + }) : assert(subtitleBundle || install != null); + + final ProcessingResourceRepository repository; + final ProcessingResourceInstall? install; + final bool subtitleBundle; + final bool details; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final snapshot = ref.watch(processingResourcesProvider(repository)); + final install = this.install == null + ? null + : snapshot.installs + .where((item) => item.package.id == this.install!.package.id) + .firstOrNull ?? + this.install; + final downloading = subtitleBundle + ? snapshot.subtitleDownloading + : install!.state == ProcessingResourceState.downloading; + final paused = + downloading && + (subtitleBundle + ? snapshot.subtitlePaused + : snapshot.paused.contains(install!.package.capability)); + final label = paused + ? context.l10n.downloadPaused + : subtitleBundle + ? downloading + ? context.l10n.downloadingResource + : context.l10n.backgroundTaskCompleted + : switch (install!.state) { + ProcessingResourceState.downloading => + context.l10n.downloadingResource, + ProcessingResourceState.installed => + context.l10n.backgroundTaskCompleted, + ProcessingResourceState.notInstalled => context.l10n.cancelled, + ProcessingResourceState.failed => context.l10n.backgroundTaskFailed, + }; + final name = subtitleBundle + ? context.l10n.subtitleResourceDownloadTask + : install!.package.capability == ProcessingCapability.backgroundRemoval + ? context.l10n.backgroundRemovalDownloadTask + : install.package.name; + final downloadedBytes = subtitleBundle + ? snapshot.subtitleDownloadedBytes + : install!.downloadedBytes; + final totalBytes = subtitleBundle + ? snapshot.subtitleTotalBytes + : install!.package.bytes; + Future cancel() async { + if (!await confirmResourceDownloadCancellation(context)) return; + if (subtitleBundle) { + if (repository.subtitleDownloading) { + repository.cancelSubtitleResources(); + } + } else if (repository.installFor(install!.package.capability).state == + ProcessingResourceState.downloading) { + repository.cancel(install.package.capability); + } + } + + Future retry() async { + try { + await repository.ensureAvailable(install!.package.capability); + } catch (_) { + // Repository publishes the error in task details. + } + } + + void togglePause() { + if (subtitleBundle) { + if (paused) { + repository.resumeSubtitleResources(); + } else { + repository.pauseSubtitleResources(); + } + } else if (paused) { + repository.resumeDownload(install!.package.capability); + } else { + repository.pauseDownload(install!.package.capability); + } + } + + if (!details) { + return _TaskSummary( + name: name, + status: label, + active: downloading, + progressDetails: downloading + ? ResourceDownloadProgress( + downloadedBytes: downloadedBytes, + totalBytes: totalBytes, + bytesPerSecond: subtitleBundle + ? snapshot.subtitleBytesPerSecond + : snapshot.rates[install!.package.capability] ?? 0, + status: paused ? label : '', + paused: paused, + ) + : null, + action: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (downloading) + TextButton( + key: const Key('background-download-pause-button'), + onPressed: togglePause, + child: Text( + paused + ? context.l10n.resumeDownload + : context.l10n.pauseDownload, + ), + ), + TextButton( + onPressed: downloading ? cancel : retry, + child: Text( + downloading ? context.l10n.cancel : context.l10n.retryTask, + ), + ), + ], + ), + onTap: () { + final download = ref.read(subtitleDownloadProvider); + final activeDownload = + subtitleBundle && + download.running && + download.request?.session.acceptsEdits == true + ? download.request + : null; + if (activeDownload != null) { + showAppDialog( + context: context, + builder: (_) => TranscriptionDialog.forCurrentTask( + session: activeDownload.session, + ), + ); + return; + } + _showTaskDetails( + context, + builder: (_) => _ResourceDownloadCard( + repository: repository, + install: subtitleBundle + ? null + : repository.installFor(install!.package.capability), + subtitleBundle: subtitleBundle, + details: true, + ), + ); + }, + ); + } + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + Text(name, style: Theme.of(context).textTheme.titleSmall), + const SizedBox(height: AppSpacing.small), + if (!downloading) Text(label), + if (install?.error != null) + Text(context.l10n.failureMessage(install!.error!)), + if (downloading) ...[ + ResourceDownloadProgress( + downloadedBytes: downloadedBytes, + totalBytes: totalBytes, + bytesPerSecond: subtitleBundle + ? snapshot.subtitleBytesPerSecond + : snapshot.rates[install!.package.capability] ?? 0, + status: paused ? label : '', + paused: paused, + ), + ], + if (downloading || install?.state == ProcessingResourceState.failed) + Align( + alignment: Alignment.centerRight, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (downloading) + TextButton( + onPressed: togglePause, + child: Text( + paused + ? context.l10n.resumeDownload + : context.l10n.pauseDownload, + ), + ), + TextButton( + onPressed: downloading ? cancel : retry, + child: Text( + downloading ? context.l10n.cancel : context.l10n.retryTask, + ), + ), + ], + ), + ), + ], + ); + } +} + +class _SubtitleTaskCard extends ConsumerStatefulWidget { + const _SubtitleTaskCard({ + super.key, + required this.entry, + this.details = false, + }); + final SubtitleTaskEntry entry; + EditorTimelineSession get session => entry.owner.session; + SubtitleBackgroundTask get job => entry.job; + final bool details; + TranscriptionClipTarget? get target => job.recognition.command.clipId == null + ? null + : TranscriptionClipTarget( + sequence: job.sequence, + clipId: job.recognition.command.clipId!, + mediaId: job.recognition.command.mediaId, + name: entry.name, + audioStream: job.recognition.command.audioStream, + ); + @override + ConsumerState<_SubtitleTaskCard> createState() => _SubtitleTaskCardState(); +} + +class _SubtitleTaskCardState extends ConsumerState<_SubtitleTaskCard> { + SubtitleTaskActionsProvider get _provider => + subtitleTaskActionsProvider(widget.session, widget.job.id); + SubtitleTaskActions get _actions => ref.read(_provider.notifier); + bool get _picking => ref.read(_provider).isLoading; + String? _validationError; + String? get _error { + final value = ref.read(_provider); + if (_validationError != null) return _validationError; + if (value.error case SubtitleActionException(:final kind, :final cause)) { + if (cause is CommandRejected && cause.code == 'staleVersion') { + return context.l10n.timelineChanged; + } + final message = context.l10n.errorMessage(cause); + return switch (kind) { + SubtitleActionKind.original => context.l10n.applyCaptionsError(message), + SubtitleActionKind.translation => + context.l10n.applyTranslatedCaptionsError(message), + _ => message, + }; + } + final result = value.value; + return switch (result?.kind) { + SubtitleActionKind.original => context.l10n.captionsAdded( + result!.cueCount.toString(), + ), + SubtitleActionKind.translation => context.l10n.translatedCaptionsAdded( + result!.cueCount.toString(), + ), + _ => null, + }; + } + + Future _applyResult({bool translated = false}) async { + if (_picking) return; + final job = widget.job; + final version = widget.session.version; + String? clip = widget.target?.clipId; + if (clip == null) { + final candidates = await _actions.candidates(job, translated: translated); + if (!mounted) return; + if (candidates.isEmpty) { + setState( + () => _validationError = translated + ? context.l10n.placeTranslationMediaFirst + : context.l10n.placeMediaFirst, + ); + return; + } + clip = await showAppDialog( + context: context, + builder: (context) => AppDialog( + title: context.l10n.selectTargetClip, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (final candidate in candidates) + AppDialogOption( + label: + '${candidate.name ?? context.l10n.clip} · ${candidate.id.value}', + onPressed: () => Navigator.pop(context, candidate.id.value), + ), + ], + ), + ), + ); + } + if (clip == null || !mounted) return; + setState(() => _validationError = null); + await _actions.apply( + job, + clip, + expectedVersion: version, + translated: translated, + ); + } + + String _failureMessage(String? code) => switch (code) { + 'notConfigured' => context.l10n.transcriptionAccessFailed, + 'noAudio' => context.l10n.transcriptionNoAudio, + 'invalidResult' => context.l10n.transcriptionInvalidResult, + 'workerExited' => context.l10n.transcriptionWorkerExited, + 'processingFailed' => context.l10n.transcriptionProcessingFailed, + final value? => context.l10n.transcriptionError(value), + null => context.l10n.transcriptionFailed, + }; + + Future _action(Future Function() action) async { + setState(() => _validationError = null); + await action(); + if (mounted && !widget.details && _error != null) { + ScaffoldMessenger.maybeOf(context) + ?.showSnackBar(SnackBar(content: Text(_error!))); + } + } + + @override + Widget build(BuildContext context) { + ref.watch(_provider); + final job = widget.job; + final taskSession = widget.session; + final entry = widget.entry; + final total = entry.total; + final completed = entry.completed; + final value = total == null || total <= 0 || completed == null + ? null + : (completed / total).clamp(0.0, 1.0); + final status = entry.status; + final failure = entry.error; + final label = switch (status) { + TranscriptionStatus.queued => + !entry.hasTranslation + ? context.l10n.preparingMedia + : context.l10n.preparingTranslation, + TranscriptionStatus.running => + !entry.hasTranslation + ? context.l10n.transcribing + : context.l10n.translatingCaptions, + TranscriptionStatus.cancelling => context.l10n.cancelling, + TranscriptionStatus.succeeded => + entry.followingUp + ? context.l10n.preparingTranslation + : context.l10n.captionsGenerated, + TranscriptionStatus.failed => + failure == 'sourceLanguageUnknown' + ? context.l10n.sourceLanguageUnknown + : _failureMessage(failure), + TranscriptionStatus.cancelled => context.l10n.cancelled, + TranscriptionStatus.interrupted => context.l10n.interruptedTask, + }; + if (!widget.details) { + return _TaskSummary( + name: entry.name, + status: status == TranscriptionStatus.failed + ? context.l10n.backgroundTaskFailed + : entry.recognitionAvailable && + entry.terminal && + status == TranscriptionStatus.succeeded + ? '$label · ${context.l10n.captionCount(entry.resultCues.length)}' + : label, + active: !entry.terminal, + progress: entry.followingUp && entry.recognitionTerminal ? null : value, + action: !entry.terminal + ? TextButton( + onPressed: _picking + ? null + : () => _action(() => _actions.cancel(job)), + child: Text(context.l10n.cancel), + ) + : status == TranscriptionStatus.failed || + status == TranscriptionStatus.interrupted || + status == TranscriptionStatus.cancelled + ? TextButton( + onPressed: _picking || !taskSession.acceptsEdits + ? null + : () => _action(() => _actions.retry(job)), + child: Text(context.l10n.retryTask), + ) + : null, + onTap: () => _showTaskDetails( + context, + session: taskSession, + builder: (_) => _SubtitleTaskDetails(entry), + ), + ); + } + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + Text(entry.name, style: Theme.of(context).textTheme.titleSmall), + Text( + _ownerName(entry.owner), + style: Theme.of(context).textTheme.bodySmall, + ), + const SizedBox(height: AppSpacing.small), + Text(label), + if (!entry.terminal) ...[ + const SizedBox(height: AppSpacing.small), + LinearProgressIndicator( + value: entry.followingUp && entry.recognitionTerminal + ? null + : value, + ), + const SizedBox(height: AppSpacing.small), + if (!entry.hasTranslation) + Text(context.l10n.recognizedCaptions(entry.recognizedCues)), + if (value != null && + !(entry.followingUp && entry.recognitionTerminal)) + Text('${(value * 100).floor()}%'), + if (!entry.hasTranslation && entry.recentCues.isNotEmpty) + Text(entry.recentCues.join('\n')), + ], + Text( + '${context.l10n.sourceLanguage}: ${context.l10n.subtitleLanguageName(entry.sourceLanguage)}', + ), + if (entry.targetLanguage != 'none') + Text( + '${context.l10n.translationLanguage}: ${context.l10n.subtitleLanguageName(entry.targetLanguage)}', + ), + if (entry.recognitionAvailable) ...[ + Text(context.l10n.captionCount(entry.recognizedCues)), + const SizedBox(height: AppSpacing.small), + SizedBox( + height: 160, + child: ListView.builder( + primary: false, + itemCount: entry.resultCues.length, + itemBuilder: (context, index) => Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: SelectableText(entry.resultCues[index]), + ), + ), + ), + ], + if (_error != null) ...[ + const SizedBox(height: AppSpacing.small), + Text(_error!), + ], + Wrap( + alignment: WrapAlignment.end, + spacing: 8, + children: [ + if (!entry.terminal) + TextButton( + onPressed: _picking + ? null + : () => _action(() => _actions.cancel(job)), + child: Text(context.l10n.cancel), + ), + if (entry.terminal && + (status == TranscriptionStatus.failed || + status == TranscriptionStatus.interrupted || + status == TranscriptionStatus.cancelled)) + TextButton( + onPressed: _picking || !widget.session.acceptsEdits + ? null + : () => _action(() => _actions.retry(job)), + child: Text(context.l10n.retryTask), + ), + if (entry.recognitionAvailable) + TextButton( + onPressed: _picking || !widget.session.acceptsEdits + ? null + : _applyResult, + child: Text(context.l10n.applyOriginalCaptions), + ), + if (entry.translationAvailable) + TextButton( + onPressed: _picking || !widget.session.acceptsEdits + ? null + : () => _applyResult(translated: true), + child: Text(context.l10n.applyTranslatedCaptions), + ), + ], + ), + ], + ); + } +} diff --git a/lib/features/media/media_asset_cover.dart b/lib/features/media/media_asset_cover.dart new file mode 100644 index 0000000..a50daae --- /dev/null +++ b/lib/features/media/media_asset_cover.dart @@ -0,0 +1,38 @@ +import 'package:cutdex_sdk/project.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../integrations/runtime/media_presentations.dart'; + +/// Subscribes to one cover frame so loading it only rebuilds its image. +class MediaAssetCover extends ConsumerWidget { + const MediaAssetCover({ + super.key, + required this.asset, + required this.fallback, + this.errorFallback, + this.fit = BoxFit.contain, + this.timeMilliseconds = 0, + }); + + final AssetDocument asset; + final Widget fallback; + final Widget? errorFallback; + final BoxFit fit; + final int timeMilliseconds; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final bytes = ref + .watch(mediaCoverProvider(asset, timeMilliseconds: timeMilliseconds)) + .value; + return bytes == null + ? fallback + : Image.memory( + bytes, + fit: fit, + excludeFromSemantics: true, + errorBuilder: (_, _, _) => errorFallback ?? fallback, + ); + } +} diff --git a/lib/features/media/media_asset_drag.dart b/lib/features/media/media_asset_drag.dart new file mode 100644 index 0000000..2b3eb45 --- /dev/null +++ b/lib/features/media/media_asset_drag.dart @@ -0,0 +1,9 @@ +import 'package:flutter/foundation.dart'; + +/// Drag data carries identities; feedback switches off inside the timeline. +class MediaAssetDrag { + MediaAssetDrag({required this.projectId, required this.assetId}); + final String projectId; + final String assetId; + final feedbackVisible = ValueNotifier(true); +} diff --git a/lib/features/media/media_asset_strip.dart b/lib/features/media/media_asset_strip.dart new file mode 100644 index 0000000..d349568 --- /dev/null +++ b/lib/features/media/media_asset_strip.dart @@ -0,0 +1,115 @@ +import 'dart:math' as math; + +import 'package:cutdex_sdk/project.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../integrations/runtime/media_presentations.dart'; + +import 'package:cutdex_ui/theme.dart'; + +import 'audio_asset_tile.dart'; +import 'media_asset_cover.dart'; + +/// Compact full-width preview used by the media library's list layout. +class MediaAssetStrip extends StatelessWidget { + const MediaAssetStrip({super.key, required this.asset}); + static const height = 46.0; + final AssetDocument asset; + + @override + Widget build(BuildContext context) => SizedBox( + height: height, + child: LayoutBuilder( + builder: (context, constraints) { + if (asset.metadata['kind'] == 'audio') { + return AudioAssetTile( + asset: asset, + showName: false, + aspectRatio: constraints.maxWidth / height, + ); + } + + return _VisualAssetStrip(asset: asset, width: constraints.maxWidth); + }, + ), + ); +} + +class _VisualAssetStrip extends ConsumerWidget { + const _VisualAssetStrip({required this.asset, required this.width}); + final AssetDocument asset; + final double width; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final video = asset.metadata['kind'] == 'video'; + final duration = video + ? ref.watch(mediaDurationProvider(asset)).value + : null; + final count = (width / (MediaAssetStrip.height * 16 / 9)).ceil().clamp( + 1, + 16, + ); + return ColoredBox( + color: AppSurfaces.of(context).previewBackground, + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (var index = 0; index < count; index++) + Expanded( + child: MediaAssetCover( + asset: asset, + fit: BoxFit.cover, + timeMilliseconds: video && duration != null + ? (duration * 1000 * index / count).floor() + : 0, + fallback: const Center(child: Icon(Icons.movie_outlined)), + errorFallback: const Center( + child: Icon(Icons.broken_image_outlined), + ), + ), + ), + ], + ), + ); + } +} + +class MediaAssetDuration extends ConsumerWidget { + const MediaAssetDuration({super.key, required this.asset}); + final AssetDocument asset; + + @override + Widget build(BuildContext context, WidgetRef ref) { + if (!const {'audio', 'video'}.contains(asset.metadata['kind'])) { + return const SizedBox.shrink(); + } + final duration = ref.watch(mediaDurationProvider(asset)).value; + if (duration == null) return const SizedBox.shrink(); + final seconds = math.max(0, duration.floor()); + final hours = seconds ~/ 3600; + final minutes = hours > 0 ? (seconds ~/ 60) % 60 : seconds ~/ 60; + final text = + '${hours > 0 ? '$hours:' : ''}' + '${minutes.toString().padLeft(2, '0')}:' + '${(seconds % 60).toString().padLeft(2, '0')}'; + return DecoratedBox( + decoration: BoxDecoration( + color: Colors.black.withValues(alpha: .55), + borderRadius: BorderRadius.circular(4), + ), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 1), + child: Text( + text, + key: ValueKey('media-duration-${asset.id}'), + style: Theme.of(context).textTheme.bodySmall?.copyWith( + color: Colors.white, + fontFeatures: const [FontFeature.tabularFigures()], + ), + ), + ), + ); + } +} diff --git a/lib/features/media/media_browser_body.dart b/lib/features/media/media_browser_body.dart new file mode 100644 index 0000000..ab34e29 --- /dev/null +++ b/lib/features/media/media_browser_body.dart @@ -0,0 +1,505 @@ +import 'package:cutdex/errors/app_failure.dart'; + +import 'dart:math' as math; + +import 'package:cutdex/l10n/l10n.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../integrations/platform/platform_capabilities.dart'; + +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex_ui/widgets.dart'; + +import '../../workspace/external_media_import.dart'; +import '../../workspace/media_availability.dart'; +import '../../workspace/projects.dart'; +import '../../workspace/timeline_provider.dart'; +import 'audio_asset_tile.dart'; +import 'media_asset_drag.dart'; +import 'media_asset_strip.dart'; +import 'media_browser_controller.dart'; +import 'unavailable_media_placeholder.dart'; +import 'visual_asset_tile.dart'; + +extension MediaFilterLabel on MediaFilter { + String label(BuildContext context) => switch (this) { + MediaFilter.all => context.l10n.all, + MediaFilter.image => context.l10n.picture, + MediaFilter.video => context.l10n.video, + MediaFilter.audio => context.l10n.audio, + }; +} + +const maximumMediaGridTileWidth = 160.0; + +class MediaBrowserBody extends ConsumerStatefulWidget { + const MediaBrowserBody({ + super.key, + required this.projectId, + required this.grid, + this.draggable = false, + }); + final String projectId; + final bool grid; + final bool draggable; + @override + ConsumerState createState() => _MediaBrowserBodyState(); +} + +class _MediaBrowserBodyState extends ConsumerState + with WidgetsBindingObserver { + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + super.dispose(); + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state == AppLifecycleState.resumed) { + ref.invalidate(mediaAvailabilityProvider); + } + } + + MediaBrowserController get _browser => + ref.read(mediaBrowserProvider(widget.projectId)); + bool get _checkingDrop => _browser.busy; + String? get _selectedAssetId => _browser.selectedAssetId; + set _selectedAssetId(String? value) => _browser.selectedAssetId = value; + MediaFilter get _filter => _browser.filter; + bool get _isGrid => widget.grid; + bool get _desktop => ref.read(platformCapabilitiesProvider).nativeFileDrop; + + Future _action(Future Function() action) async { + final ok = await action(); + if (!mounted || ok) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + context.l10n.failureMessage( + ref.read(projectsProvider).asData?.value.error ?? + const AppFailure(AppErrorCode.operationFailed), + ), + ), + ), + ); + } + + Future _rename(AssetDocument asset) async { + final controller = TextEditingController(text: asset.name); + final name = await showAppDialog( + context: context, + builder: (context) => AppDialog( + title: context.l10n.renameMedia, + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: Text(context.l10n.cancel), + ), + ListenableBuilder( + listenable: controller, + builder: (context, _) => FilledButton( + onPressed: controller.text.trim().isEmpty + ? null + : () => Navigator.pop(context, controller.text.trim()), + child: Text(context.l10n.save), + ), + ), + ], + child: AppField( + label: context.l10n.name, + child: TextField( + controller: controller, + autofocus: true, + onSubmitted: (value) { + if (value.trim().isNotEmpty) Navigator.pop(context, value.trim()); + }, + ), + ), + ), + ); + // The route's closing animation can still read its text controller. + await Future.delayed(const Duration(milliseconds: 200)); + controller.dispose(); + if (!mounted || name == null) return; + await _action(() => _browser.rename(asset, name)); + } + + Future _remove(AssetDocument asset) async { + final confirmed = await showAppDialog( + context: context, + builder: (context) => AppDialog( + title: context.l10n.removeMedia, + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, false), + child: Text(context.l10n.cancel), + ), + TextButton( + onPressed: () => Navigator.pop(context, true), + style: TextButton.styleFrom( + foregroundColor: Theme.of(context).colorScheme.error, + ), + child: Text(context.l10n.remove), + ), + ], + child: Text(context.l10n.removeMediaConfirmation(asset.name)), + ), + ); + if (!mounted || confirmed != true) return; + await _action(() => _browser.remove(asset)); + } + + @override + Widget build(BuildContext context) => ListenableBuilder( + listenable: ref.watch(mediaBrowserProvider(widget.projectId)), + builder: (context, _) => _buildBrowser(context), + ); + Widget _buildBrowser(BuildContext context) { + ref.watch(externalMediaImportProvider(widget.projectId)); + final workspace = ref.watch(projectsProvider).asData?.value; + final active = workspace?.activeProject?.id == widget.projectId; + final allAssets = active ? workspace!.assets : []; + final assets = _filter == MediaFilter.all + ? allAssets + : allAssets + .where((asset) => asset.metadata['kind'] == _filter.kind) + .toList(); + final timelineId = active ? workspace?.timeline?.id : null; + final timeline = timelineId == null + ? null + : ref + .watch(editorTimelineProvider(widget.projectId, timelineId)) + .asData + ?.value; + return assets.isEmpty + ? Center( + child: Padding( + padding: const EdgeInsets.all(AppSpacing.medium), + child: Text( + _filter != MediaFilter.all + ? context.l10n.noMediaOfType(_filter.label(context)) + : _desktop + ? context.l10n.dragMediaHint + : context.l10n.noMedia, + textAlign: TextAlign.center, + ), + ), + ) + : LayoutBuilder( + builder: (context, constraints) { + const spacing = AppSpacing.small; + final width = math.max( + 1.0, + constraints.maxWidth - AppSpacing.compact * 2, + ); + final columns = math.max( + 1, + ((width + spacing) / (maximumMediaGridTileWidth + spacing)) + .ceil(), + ); + final tileWidth = (width - spacing * (columns - 1)) / columns; + final textStyle = Theme.of(context).textTheme.bodySmall!; + final labelHeight = + MediaQuery.textScalerOf(context).scale(textStyle.fontSize!) * + (textStyle.height ?? 1.2); + Widget item(BuildContext context, int index) { + final asset = assets[index]; + return Consumer( + builder: (context, ref, _) { + final availability = ref + .watch( + mediaAvailabilityProvider(widget.projectId, asset), + ) + .asData + ?.value; + final unavailable = + availability != null && + availability != MediaAvailability.available; + return AppContextMenu( + key: ValueKey(('media-menu', asset.id)), + itemsBuilder: (_) { + final available = ref + .read(projectsProvider) + .asData + ?.value; + final canEdit = + available?.activeProject?.id == widget.projectId && + available?.projectBusy == false && + !_checkingDrop; + final sequence = timeline?.activeSequenceId; + return [ + AppMenuItem( + label: context.l10n.addToTimeline, + icon: Icons.add, + onPressed: + canEdit && + !unavailable && + sequence != null && + available?.timeline?.id == timelineId + ? () => + _action(() => _browser.insertAsset(asset)) + : null, + ), + AppMenuItem( + label: context.l10n.rename, + icon: Icons.drive_file_rename_outline, + onPressed: canEdit ? () => _rename(asset) : null, + ), + AppMenuItem( + label: defaultTargetPlatform == TargetPlatform.macOS + ? context.l10n.revealFinder + : context.l10n.revealFileManager, + icon: Icons.folder_open, + onPressed: canEdit && _desktop + ? () => _action(() => _browser.reveal(asset)) + : null, + ), + const AppMenuSeparator(), + AppMenuItem( + label: context.l10n.removeMedia, + icon: Icons.delete_outline, + destructive: true, + onPressed: canEdit ? () => _remove(asset) : null, + ), + ]; + }, + child: Listener( + onPointerDown: (event) { + if (event.buttons == 2) { + setState(() => _selectedAssetId = asset.id); + } + }, + child: _SelectableAsset( + key: ValueKey(asset.id), + grid: _isGrid, + drag: MediaAssetDrag( + projectId: widget.projectId, + assetId: asset.id, + ), + name: asset.name, + draggable: + widget.draggable && + !workspace!.projectBusy && + !_checkingDrop && + !unavailable, + selected: _selectedAssetId == asset.id, + onTap: () => _browser.selectAsset(asset), + child: _assetTile(asset, availability), + ), + ), + ); + }, + ); + } + + return ScrollEdgeFadeBuilder( + key: ValueKey(('media-scroll-fade', widget.projectId, _isGrid)), + builder: (controller) => !_isGrid + ? ListView.separated( + key: PageStorageKey(('media-list', widget.projectId)), + controller: controller, + padding: const EdgeInsets.all(AppSpacing.compact), + itemCount: assets.length, + itemBuilder: item, + separatorBuilder: (_, _) => + const SizedBox(height: AppSpacing.small), + ) + : GridView.builder( + key: PageStorageKey(('media-grid', widget.projectId)), + controller: controller, + padding: const EdgeInsets.all(AppSpacing.compact), + gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: columns, + crossAxisSpacing: spacing, + mainAxisSpacing: AppSpacing.compact, + mainAxisExtent: + tileWidth * 9 / 16 + + AppSpacing.small + + labelHeight + + 2, + ), + itemCount: assets.length, + itemBuilder: item, + ), + ); + }, + ); + } + + Widget _assetTile(AssetDocument asset, MediaAvailability? availability) { + final unavailable = + availability != null && availability != MediaAvailability.available; + final cover = unavailable + ? AspectRatio( + aspectRatio: 16 / 9, + child: _isGrid + ? UnavailableMediaPlaceholder(availability: availability) + : ColoredBox( + color: AppSurfaces.of(context).previewBackground, + child: Center( + child: Text( + availability == MediaAvailability.missing + ? context.l10n.mediaMissing + : context.l10n.mediaUnavailable, + style: Theme.of(context).textTheme.bodySmall?.copyWith( + color: Theme.of(context).colorScheme.error, + ), + ), + ), + ), + ) + : !_isGrid && + const {'audio', 'video', 'image'}.contains(asset.metadata['kind']) + ? MediaAssetStrip(asset: asset) + : switch (asset.metadata['kind']) { + 'video' || + 'image' => VisualAssetTile(asset: asset, showName: false), + 'audio' => AudioAssetTile(asset: asset, showName: false), + _ => AspectRatio( + aspectRatio: 16 / 9, + child: ColoredBox( + color: AppSurfaces.of(context).previewBackground, + child: const Icon(Icons.insert_drive_file_outlined), + ), + ), + }; + final name = Tooltip( + // Hover still shows the full name; touch long press belongs to actions. + triggerMode: TooltipTriggerMode.manual, + message: asset.name, + child: Text( + asset.name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: Theme.of(context).textTheme.bodySmall, + ), + ); + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + ClipRRect( + borderRadius: BorderRadius.circular(6), + child: Stack( + children: [ + if (!_isGrid) + SizedBox(height: MediaAssetStrip.height, child: cover) + else + cover, + Positioned( + top: 4, + right: 4, + child: MediaAssetDuration(asset: asset), + ), + ], + ), + ), + const SizedBox(height: AppSpacing.small), + name, + ], + ); + } +} + +class _SelectableAsset extends StatelessWidget { + const _SelectableAsset({ + super.key, + required this.grid, + required this.selected, + required this.drag, + required this.name, + required this.draggable, + required this.onTap, + required this.child, + }); + + final bool selected; + final bool grid; + final MediaAssetDrag drag; + final String name; + final bool draggable; + final VoidCallback onTap; + final Widget child; + + @override + Widget build(BuildContext context) { + final selectionDecoration = BoxDecoration( + borderRadius: BorderRadius.circular(6), + border: Border.all(color: Theme.of(context).colorScheme.primary), + ); + final tile = Semantics( + selected: selected, + child: InkWell( + onTap: onTap, + hoverColor: Colors.transparent, + highlightColor: Colors.transparent, + splashFactory: NoSplash.splashFactory, + child: Stack( + children: [ + child, + if (selected && !grid) + Positioned( + top: 0, + left: 0, + right: 0, + height: MediaAssetStrip.height, + child: IgnorePointer( + child: DecoratedBox(decoration: selectionDecoration), + ), + ), + if (selected && grid) + Positioned( + top: 0, + left: 0, + right: 0, + child: IgnorePointer( + child: AspectRatio( + aspectRatio: 16 / 9, + child: DecoratedBox(decoration: selectionDecoration), + ), + ), + ), + ], + ), + ), + ); + return Draggable( + data: drag, + maxSimultaneousDrags: draggable ? 1 : 0, + dragAnchorStrategy: pointerDragAnchorStrategy, + onDragStarted: onTap, + onDragEnd: (_) => drag.feedbackVisible.value = true, + feedback: ValueListenableBuilder( + valueListenable: drag.feedbackVisible, + builder: (context, visible, child) => + visible ? child! : const SizedBox.shrink(), + child: Material( + elevation: 4, + color: Theme.of(context).colorScheme.surfaceContainerHigh, + child: SizedBox( + width: 144, + child: Padding( + padding: const EdgeInsets.all(AppSpacing.small), + child: Text( + name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: Theme.of(context).textTheme.bodySmall, + ), + ), + ), + ), + ), + child: tile, + ); + } +} diff --git a/lib/features/media/media_browser_controller.dart b/lib/features/media/media_browser_controller.dart new file mode 100644 index 0000000..3086561 --- /dev/null +++ b/lib/features/media/media_browser_controller.dart @@ -0,0 +1,194 @@ +import 'package:cutdex_sdk/project.dart'; +import 'package:flutter/foundation.dart'; + +import '../../integrations/platform/file_picker.dart'; +import '../../integrations/platform/platform_capabilities.dart'; +import '../../workspace/media_file_extensions.dart'; +import '../../workspace/external_media_import.dart'; +import '../../workspace/media_availability.dart'; +import '../../workspace/media_import.dart'; +import '../../workspace/media_import_feedback.dart'; +import '../../workspace/preview_target.dart'; +import '../../workspace/projects.dart'; +import '../../workspace/timeline_provider.dart'; + +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +enum MediaFilter { + all(null), + image('image'), + video('video'), + audio('audio'); + + const MediaFilter(this.kind); + final String? kind; +} + +final mediaBrowserProvider = Provider.family(( + ref, + projectId, +) { + final controller = MediaBrowserController(ref, projectId); + ref.onDispose(controller.dispose); + return controller; +}); + +/// Project-specific browsing choices are shared by every media presentation. +class MediaBrowserController extends ChangeNotifier { + MediaBrowserController(this._ref, this.projectId); + final Ref _ref; + final String projectId; + final feedback = MediaImportFeedbackController(); + bool _working = false; + bool _disposed = false; + bool get busy => + _working || _ref.read(externalMediaImportProvider(projectId)).isLoading; + bool get active => + !_disposed && + _ref.mounted && + _ref.read(projectsProvider).value?.activeProject?.id == projectId; + bool get canEdit => + active && + _ref.read(projectsProvider).value?.projectBusy == false && + !busy; + bool get canImport => + canEdit && _ref.read(platformCapabilitiesProvider).localFileSelection; + + Future pickFiles() => _import( + () => _ref + .read(filePickerProvider) + .pickFiles(allowedExtensions: selectableMediaFileExtensions), + ); + + Future importFiles(List files) => + _import(() async => files); + + Future _import( + Future> Function() select, + ) async { + if (!canImport) return null; + _working = true; + notifyListeners(); + try { + final files = await select(); + if (!active || + files.isEmpty || + _ref.read(projectsProvider).value?.projectBusy != false) { + return null; + } + final result = await _ref + .read(externalMediaImportProvider(projectId).notifier) + .importFiles(files); + final asset = result?.selected.firstOrNull; + if (!_disposed && asset != null) { + _selectedAssetId = asset.id; + if (_filter != MediaFilter.all && + asset.metadata['kind'] != _filter.kind) { + _filter = MediaFilter.all; + } + } + if (!_disposed) feedback.recordResult(result); + return result; + } catch (_) { + if (!_disposed) feedback.recordFailure(); + rethrow; + } finally { + _working = false; + if (!_disposed) notifyListeners(); + } + } + + void selectAsset(AssetDocument asset) { + selectedAssetId = asset.id; + _ref.invalidate(mediaAvailabilityProvider(projectId, asset)); + final timeline = _ref.read(projectsProvider).value?.timeline; + if (timeline != null) { + _ref + .read(previewNavigationProvider(projectId, timeline.id).notifier) + .showAsset(asset); + } + } + + Future rename(AssetDocument asset, String name) async => + canEdit && + await _ref + .read(projectsProvider.notifier) + .editMediaAsset(projectId, asset.id, name: name); + + Future remove(AssetDocument asset) async { + if (!canEdit) return false; + final removed = await _ref + .read(projectsProvider.notifier) + .editMediaAsset(projectId, asset.id); + if (removed && !_disposed && _selectedAssetId == asset.id) { + selectedAssetId = null; + } + return removed; + } + + Future reveal(AssetDocument asset) async => + canEdit && + await _ref + .read(projectsProvider.notifier) + .revealMediaAsset(projectId, asset); + + Future insertAsset(AssetDocument asset) async { + if (!canEdit || + _ref.read(mediaAvailabilityProvider(projectId, asset)).value != + MediaAvailability.available) { + return false; + } + final timelineId = _ref.read(projectsProvider).value?.timeline?.id; + if (timelineId == null) return false; + final session = _ref + .read(editorTimelineProvider(projectId, timelineId)) + .value; + final sequence = session?.activeSequenceId; + if (session == null || sequence == null) return false; + final inserted = await _ref + .read(projectsProvider.notifier) + .insertTimelineAsset( + projectId: projectId, + session: session, + sequenceId: sequence, + assetId: asset.id, + position: session.view(sequence).playheadTick, + ); + if (inserted && active) { + _ref + .read(previewNavigationProvider(projectId, timelineId).notifier) + .showTimeline(); + } + return inserted; + } + + @override + void dispose() { + _disposed = true; + feedback.dispose(); + super.dispose(); + } + + String? _selectedAssetId; + MediaFilter _filter = MediaFilter.all; + bool _grid = true; + + String? get selectedAssetId => _selectedAssetId; + MediaFilter get filter => _filter; + bool get grid => _grid; + + set selectedAssetId(String? value) { + _selectedAssetId = value; + notifyListeners(); + } + + set filter(MediaFilter value) { + _filter = value; + notifyListeners(); + } + + set grid(bool value) { + _grid = value; + notifyListeners(); + } +} diff --git a/lib/features/media/media_browser_feedback.dart b/lib/features/media/media_browser_feedback.dart new file mode 100644 index 0000000..7f0b763 --- /dev/null +++ b/lib/features/media/media_browser_feedback.dart @@ -0,0 +1,108 @@ +import 'package:flutter/material.dart'; + +import '../../l10n/l10n.dart'; +import '../../workspace/media_import.dart'; +import '../../workspace/media_import_feedback.dart'; +import 'media_browser_controller.dart'; + +Future pickMediaFiles(MediaBrowserController browser) async { + try { + await browser.pickFiles(); + } catch (_) { + // The controller retains the failure for its next visible presentation. + } +} + +Future importMediaFiles( + MediaBrowserController browser, + List files, +) async { + try { + await browser.importFiles(files); + } catch (_) { + // The controller retains the failure for its next visible presentation. + } +} + +class MediaImportFeedbackListener extends StatefulWidget { + const MediaImportFeedbackListener({ + super.key, + required this.feedback, + required this.child, + }); + + final MediaImportFeedbackController feedback; + final Widget child; + + @override + State createState() => + _MediaImportFeedbackListenerState(); +} + +class _MediaImportFeedbackListenerState + extends State { + bool _scheduled = false; + bool get _visible => + TickerMode.valuesOf(context).enabled && + (ModalRoute.of(context)?.isCurrent ?? true); + + @override + void initState() { + super.initState(); + widget.feedback.addListener(_schedule); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _schedule(); + } + + @override + void didUpdateWidget(covariant MediaImportFeedbackListener oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.feedback != widget.feedback) { + oldWidget.feedback.removeListener(_schedule); + widget.feedback.addListener(_schedule); + } + _schedule(); + } + + void _schedule() { + if (_scheduled || !widget.feedback.hasPending) return; + _scheduled = true; + WidgetsBinding.instance.addPostFrameCallback((_) { + _scheduled = false; + if (!mounted || !_visible || !widget.feedback.hasPending) return; + final messenger = ScaffoldMessenger.maybeOf(context); + if (messenger == null) return; + for (final result in widget.feedback.takePending()) { + final messages = [ + if (result == null) context.l10n.operationFailed, + for (final failure + in result?.result?.failures ?? []) + '${failure.name}: ${context.l10n.failureMessage(failure.failure)}', + if (result?.failed == true) context.l10n.noImportableFiles, + ]; + messenger.showSnackBar( + SnackBar( + content: ConstrainedBox( + constraints: const BoxConstraints(maxHeight: 180), + child: SingleChildScrollView(child: Text(messages.join('\n'))), + ), + ), + ); + } + }); + WidgetsBinding.instance.ensureVisualUpdate(); + } + + @override + void dispose() { + widget.feedback.removeListener(_schedule); + super.dispose(); + } + + @override + Widget build(BuildContext context) => widget.child; +} diff --git a/lib/features/media/media_browser_page.dart b/lib/features/media/media_browser_page.dart new file mode 100644 index 0000000..980a38c --- /dev/null +++ b/lib/features/media/media_browser_page.dart @@ -0,0 +1,168 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../l10n/l10n.dart'; +import '../../workspace/external_media_import.dart'; +import '../../workspace/media_availability.dart'; +import '../../workspace/projects.dart'; +import '../../workspace/timeline_provider.dart'; +import 'media_browser_body.dart'; +import 'media_browser_controller.dart'; +import 'media_browser_feedback.dart'; + +class MediaBrowserPage extends StatelessWidget { + const MediaBrowserPage({super.key, required this.projectId}); + final String projectId; + @override + Widget build(BuildContext context) => TouchMediaBrowser( + key: const Key('media-browser-page'), + projectId: projectId, + ); +} + +class MediaBrowserDrawer extends StatelessWidget { + const MediaBrowserDrawer({super.key, required this.projectId}); + final String projectId; + @override + Widget build(BuildContext context) => TouchMediaBrowser( + key: const Key('media-browser-drawer'), + projectId: projectId, + ); +} + +/// Touch controls share browser commands and item components with desktop. +class TouchMediaBrowser extends ConsumerWidget { + const TouchMediaBrowser({super.key, required this.projectId}); + final String projectId; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final browser = ref.watch(mediaBrowserProvider(projectId)); + ref.watch(externalMediaImportProvider(projectId)); + final workspace = ref.watch(projectsProvider).value; + final timelineId = workspace?.activeProject?.id == projectId + ? workspace?.timeline?.id + : null; + final timeline = timelineId == null + ? null + : ref.watch(editorTimelineProvider(projectId, timelineId)).value; + return ListenableBuilder( + listenable: browser, + builder: (context, _) { + final selected = workspace?.assets + .where((asset) => asset.id == browser.selectedAssetId) + .firstOrNull; + final availability = selected == null + ? null + : ref.watch(mediaAvailabilityProvider(projectId, selected)).value; + final canInsert = + browser.canEdit && + selected != null && + timeline?.activeSequenceId != null && + availability == MediaAvailability.available; + return MediaImportFeedbackListener( + feedback: browser.feedback, + child: Material( + key: const Key('media-panel-surface'), + child: Column( + children: [ + SizedBox( + key: const Key('media-panel-header'), + height: 56, + child: Row( + children: [ + SizedBox.square( + dimension: 48, + child: IconButton( + key: const Key('media-import-button'), + tooltip: context.l10n.importMedia, + onPressed: browser.canImport + ? () => pickMediaFiles(browser) + : null, + icon: const Icon(Icons.add), + ), + ), + Expanded( + child: DropdownButton( + key: const Key('media-category-picker'), + isExpanded: true, + underline: const SizedBox.shrink(), + value: browser.filter, + items: [ + for (final filter in MediaFilter.values) + DropdownMenuItem( + value: filter, + child: Text(filter.label(context)), + ), + ], + onChanged: (filter) { + if (filter != null) browser.filter = filter; + }, + ), + ), + SizedBox.square( + dimension: 48, + child: IconButton( + key: const Key('media-layout-toggle'), + tooltip: browser.grid + ? context.l10n.listLayout + : context.l10n.gridLayout, + icon: Icon( + browser.grid + ? Icons.view_list_outlined + : Icons.grid_view_outlined, + ), + onPressed: () => browser.grid = !browser.grid, + ), + ), + ], + ), + ), + if (browser.busy) const LinearProgressIndicator(), + Expanded( + key: const Key('media-panel-body'), + child: MediaBrowserBody( + projectId: projectId, + grid: browser.grid, + ), + ), + Padding( + padding: const EdgeInsets.all(8), + child: SizedBox( + width: double.infinity, + child: FilledButton.icon( + key: const Key('media-add-selected'), + style: FilledButton.styleFrom( + minimumSize: const Size(0, 48), + ), + onPressed: !canInsert + ? null + : () async { + final inserted = await browser.insertAsset( + selected, + ); + if (!inserted && context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(context.l10n.operationFailed), + ), + ); + } + }, + icon: const Icon(Icons.add), + label: Text( + context.l10n.addToTimeline, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + ), + ), + ], + ), + ), + ); + }, + ); + } +} diff --git a/lib/features/media/media_panel.dart b/lib/features/media/media_panel.dart new file mode 100644 index 0000000..edae867 --- /dev/null +++ b/lib/features/media/media_panel.dart @@ -0,0 +1,213 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../l10n/l10n.dart'; +import '../../integrations/platform/native_project_drop_region.dart'; +import '../../integrations/platform/platform_capabilities.dart'; + +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex_ui/widgets.dart'; + +import '../../shared/widgets/drop_to_add_overlay.dart'; +import '../../workspace/external_media_import.dart'; +import '../../workspace/projects.dart'; +import 'media_browser_body.dart'; +import 'media_browser_controller.dart'; +import 'media_browser_feedback.dart'; + +/// Desktop presentation owns compact controls and native file dragging. +class MediaPanel extends ConsumerStatefulWidget { + const MediaPanel({ + super.key, + required this.projectId, + this.backgroundColor, + this.grid, + this.onGridChanged, + }) : assert((grid == null) == (onGridChanged == null)); + final String projectId; + final Color? backgroundColor; + final bool? grid; + final ValueChanged? onGridChanged; + @override + ConsumerState createState() => _MediaPanelState(); +} + +class _MediaPanelState extends ConsumerState { + bool _hovering = false; + @override + Widget build(BuildContext context) { + ref.watch(projectsProvider); + final browser = ref.watch(mediaBrowserProvider(widget.projectId)); + ref.watch(externalMediaImportProvider(widget.projectId)); + final nativeDrop = ref.watch(platformCapabilitiesProvider).nativeFileDrop; + return ListenableBuilder( + listenable: browser, + builder: (context, _) { + final grid = widget.grid ?? browser.grid; + final visible = + TickerMode.valuesOf(context).enabled && + (ModalRoute.of(context)?.isCurrent ?? true); + final enabled = browser.canImport && visible; + void toggleGrid() { + final next = !grid; + if (widget.onGridChanged case final onChanged?) { + onChanged(next); + } else { + browser.grid = next; + } + } + + final content = MediaImportFeedbackListener( + feedback: browser.feedback, + child: Material( + key: const Key('media-panel-surface'), + color: widget.backgroundColor, + child: Stack( + fit: StackFit.expand, + children: [ + Column( + children: [ + SizedBox( + key: const Key('media-panel-header'), + height: AppControlSize.panelToolbar, + child: Padding( + padding: const EdgeInsets.all(AppSpacing.gap), + child: LayoutBuilder( + builder: (context, constraints) { + final compact = constraints.maxWidth < 180; + final controls = Row( + mainAxisSize: compact + ? MainAxisSize.min + : MainAxisSize.max, + children: [ + if (compact) + SizedBox.square( + dimension: AppControlSize.headerButton, + child: IconButton( + key: const Key('media-import-button'), + tooltip: context.l10n.importMedia, + onPressed: enabled + ? () => pickMediaFiles(browser) + : null, + icon: const Icon( + Icons.add, + size: AppIconSize.header, + ), + ), + ) + else + SizedBox( + height: AppControlSize.headerButton, + child: TextButton.icon( + key: const Key('media-import-button'), + style: AppTheme.toolbarButtonStyle( + context, + ), + onPressed: enabled + ? () => pickMediaFiles(browser) + : null, + icon: const Icon( + Icons.add, + size: AppIconSize.header, + ), + label: Text(context.l10n.importMedia), + ), + ), + if (compact) + const SizedBox(width: AppSpacing.tiny) + else + const Spacer(), + SizedBox( + width: 76, + child: AppSelect( + emptyLabel: context.l10n.noMatchingOptions, + label: context.l10n.mediaCategory, + outlined: false, + controlHeight: AppControlSize.headerButton, + textStyle: AppTheme.toolbarTextStyle( + context, + ), + value: browser.filter, + onChanged: (value) => + browser.filter = value, + options: [ + for (final filter in MediaFilter.values) + AppSelectOption( + filter, + filter.label(context), + ), + ], + ), + ), + const SizedBox(width: AppSpacing.tiny), + SizedBox.square( + dimension: AppControlSize.headerButton, + child: IconButton( + key: const Key('media-layout-toggle'), + onPressed: toggleGrid, + icon: Icon( + grid + ? Icons.view_list_outlined + : Icons.grid_view_outlined, + size: AppIconSize.header, + ), + tooltip: grid + ? context.l10n.listLayout + : context.l10n.gridLayout, + ), + ), + ], + ); + return compact + ? SingleChildScrollView( + key: const Key('media-header-scroll'), + scrollDirection: Axis.horizontal, + child: controls, + ) + : controls; + }, + ), + ), + ), + Expanded( + key: const Key('media-panel-body'), + child: MediaBrowserBody( + projectId: widget.projectId, + grid: grid, + draggable: true, + ), + ), + ], + ), + if (browser.busy) + const DelayedLoadingIndicator( + child: Align( + alignment: Alignment.topCenter, + child: LinearProgressIndicator(), + ), + ), + if (_hovering && enabled) + const DropToAddOverlay(key: Key('media-drop-highlight')), + ], + ), + ), + ); + if (!nativeDrop) return content; + return NativeProjectDropRegion( + enabled: visible && browser.active && (enabled || browser.busy), + onEnter: (_) { + if (enabled) setState(() => _hovering = true); + }, + onExit: () { + if (mounted && _hovering) setState(() => _hovering = false); + }, + onDrop: (files) async { + setState(() => _hovering = false); + await importMediaFiles(browser, files); + }, + child: content, + ); + }, + ); + } +} diff --git a/lib/features/media/processing_targets.dart b/lib/features/media/processing_targets.dart new file mode 100644 index 0000000..f57aa71 --- /dev/null +++ b/lib/features/media/processing_targets.dart @@ -0,0 +1,26 @@ +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'processing_targets.freezed.dart'; + +/// A fixed timeline target, retained even if selection or active sequence changes. +@freezed +abstract class TranscriptionClipTarget with _$TranscriptionClipTarget { + const factory TranscriptionClipTarget({ + required SequenceId sequence, + required String clipId, + required String mediaId, + required String name, + required int audioStream, + }) = _TranscriptionClipTarget; +} + +@freezed +abstract class BackgroundRemovalClipTarget with _$BackgroundRemovalClipTarget { + const factory BackgroundRemovalClipTarget({ + required SequenceId sequence, + required String clipId, + required String mediaId, + required String name, + }) = _BackgroundRemovalClipTarget; +} diff --git a/lib/features/media/processing_targets.freezed.dart b/lib/features/media/processing_targets.freezed.dart new file mode 100644 index 0000000..989636d --- /dev/null +++ b/lib/features/media/processing_targets.freezed.dart @@ -0,0 +1,855 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'processing_targets.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +T _$identity(T value) => value; + +/// @nodoc +mixin _$TranscriptionClipTarget { + SequenceId get sequence; + String get clipId; + String get mediaId; + String get name; + int get audioStream; + + /// Create a copy of TranscriptionClipTarget + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $TranscriptionClipTargetCopyWith get copyWith => + _$TranscriptionClipTargetCopyWithImpl( + this as TranscriptionClipTarget, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as TranscriptionClipTarget; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is TranscriptionClipTarget && + (identical(other.sequence, _this.sequence) || + other.sequence == _this.sequence) && + (identical(other.clipId, _this.clipId) || + other.clipId == _this.clipId) && + (identical(other.mediaId, _this.mediaId) || + other.mediaId == _this.mediaId) && + (identical(other.name, _this.name) || other.name == _this.name) && + (identical(other.audioStream, _this.audioStream) || + other.audioStream == _this.audioStream)); + } + + @override + int get hashCode { + final _this = this as TranscriptionClipTarget; + return Object.hash( + runtimeType, + _this.sequence, + _this.clipId, + _this.mediaId, + _this.name, + _this.audioStream, + ); + } + + @override + String toString() { + final _this = this as TranscriptionClipTarget; + return 'TranscriptionClipTarget(sequence: ${_this.sequence}, clipId: ${_this.clipId}, mediaId: ${_this.mediaId}, name: ${_this.name}, audioStream: ${_this.audioStream})'; + } +} + +/// @nodoc +abstract mixin class $TranscriptionClipTargetCopyWith<$Res> { + factory $TranscriptionClipTargetCopyWith( + TranscriptionClipTarget value, + $Res Function(TranscriptionClipTarget) _then, + ) = _$TranscriptionClipTargetCopyWithImpl; + @useResult + $Res call({ + SequenceId sequence, + String clipId, + String mediaId, + String name, + int audioStream, + }); +} + +/// @nodoc +class _$TranscriptionClipTargetCopyWithImpl<$Res> + implements $TranscriptionClipTargetCopyWith<$Res> { + _$TranscriptionClipTargetCopyWithImpl(this._self, this._then); + + final TranscriptionClipTarget _self; + final $Res Function(TranscriptionClipTarget) _then; + + /// Create a copy of TranscriptionClipTarget + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? sequence = null, + Object? clipId = null, + Object? mediaId = null, + Object? name = null, + Object? audioStream = null, + }) { + return _then( + TranscriptionClipTarget( + sequence: null == sequence + ? _self.sequence + : sequence // ignore: cast_nullable_to_non_nullable + as SequenceId, + clipId: null == clipId + ? _self.clipId + : clipId // ignore: cast_nullable_to_non_nullable + as String, + mediaId: null == mediaId + ? _self.mediaId + : mediaId // ignore: cast_nullable_to_non_nullable + as String, + name: null == name + ? _self.name + : name // ignore: cast_nullable_to_non_nullable + as String, + audioStream: null == audioStream + ? _self.audioStream + : audioStream // ignore: cast_nullable_to_non_nullable + as int, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [TranscriptionClipTarget]. +extension TranscriptionClipTargetPatterns on TranscriptionClipTarget { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_TranscriptionClipTarget value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _TranscriptionClipTarget() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_TranscriptionClipTarget value) $default, + ) { + final _that = this; + switch (_that) { + case _TranscriptionClipTarget(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_TranscriptionClipTarget value)? $default, + ) { + final _that = this; + switch (_that) { + case _TranscriptionClipTarget() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + SequenceId sequence, + String clipId, + String mediaId, + String name, + int audioStream, + )? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _TranscriptionClipTarget() when $default != null: + return $default( + _that.sequence, + _that.clipId, + _that.mediaId, + _that.name, + _that.audioStream, + ); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function( + SequenceId sequence, + String clipId, + String mediaId, + String name, + int audioStream, + ) + $default, + ) { + final _that = this; + switch (_that) { + case _TranscriptionClipTarget(): + return $default( + _that.sequence, + _that.clipId, + _that.mediaId, + _that.name, + _that.audioStream, + ); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + SequenceId sequence, + String clipId, + String mediaId, + String name, + int audioStream, + )? + $default, + ) { + final _that = this; + switch (_that) { + case _TranscriptionClipTarget() when $default != null: + return $default( + _that.sequence, + _that.clipId, + _that.mediaId, + _that.name, + _that.audioStream, + ); + case _: + return null; + } + } +} + +/// @nodoc + +class _TranscriptionClipTarget implements TranscriptionClipTarget { + const _TranscriptionClipTarget({ + required this.sequence, + required this.clipId, + required this.mediaId, + required this.name, + required this.audioStream, + }); + + @override + final SequenceId sequence; + @override + final String clipId; + @override + final String mediaId; + @override + final String name; + @override + final int audioStream; + + /// Create a copy of TranscriptionClipTarget + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$TranscriptionClipTargetCopyWith<_TranscriptionClipTarget> get copyWith => + __$TranscriptionClipTargetCopyWithImpl<_TranscriptionClipTarget>( + this, + _$identity, + ); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _TranscriptionClipTarget && + (identical(other.sequence, sequence) || + other.sequence == sequence) && + (identical(other.clipId, clipId) || other.clipId == clipId) && + (identical(other.mediaId, mediaId) || other.mediaId == mediaId) && + (identical(other.name, name) || other.name == name) && + (identical(other.audioStream, audioStream) || + other.audioStream == audioStream)); + } + + @override + int get hashCode { + return Object.hash( + runtimeType, + sequence, + clipId, + mediaId, + name, + audioStream, + ); + } + + @override + String toString() { + return 'TranscriptionClipTarget(sequence: $sequence, clipId: $clipId, mediaId: $mediaId, name: $name, audioStream: $audioStream)'; + } +} + +/// @nodoc +abstract mixin class _$TranscriptionClipTargetCopyWith<$Res> + implements $TranscriptionClipTargetCopyWith<$Res> { + factory _$TranscriptionClipTargetCopyWith( + _TranscriptionClipTarget value, + $Res Function(_TranscriptionClipTarget) _then, + ) = __$TranscriptionClipTargetCopyWithImpl; + @override + @useResult + $Res call({ + SequenceId sequence, + String clipId, + String mediaId, + String name, + int audioStream, + }); +} + +/// @nodoc +class __$TranscriptionClipTargetCopyWithImpl<$Res> + implements _$TranscriptionClipTargetCopyWith<$Res> { + __$TranscriptionClipTargetCopyWithImpl(this._self, this._then); + + final _TranscriptionClipTarget _self; + final $Res Function(_TranscriptionClipTarget) _then; + + /// Create a copy of TranscriptionClipTarget + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? sequence = null, + Object? clipId = null, + Object? mediaId = null, + Object? name = null, + Object? audioStream = null, + }) { + return _then( + _TranscriptionClipTarget( + sequence: null == sequence + ? _self.sequence + : sequence // ignore: cast_nullable_to_non_nullable + as SequenceId, + clipId: null == clipId + ? _self.clipId + : clipId // ignore: cast_nullable_to_non_nullable + as String, + mediaId: null == mediaId + ? _self.mediaId + : mediaId // ignore: cast_nullable_to_non_nullable + as String, + name: null == name + ? _self.name + : name // ignore: cast_nullable_to_non_nullable + as String, + audioStream: null == audioStream + ? _self.audioStream + : audioStream // ignore: cast_nullable_to_non_nullable + as int, + ), + ); + } +} + +/// @nodoc +mixin _$BackgroundRemovalClipTarget { + SequenceId get sequence; + String get clipId; + String get mediaId; + String get name; + + /// Create a copy of BackgroundRemovalClipTarget + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $BackgroundRemovalClipTargetCopyWith + get copyWith => + _$BackgroundRemovalClipTargetCopyWithImpl( + this as BackgroundRemovalClipTarget, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as BackgroundRemovalClipTarget; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is BackgroundRemovalClipTarget && + (identical(other.sequence, _this.sequence) || + other.sequence == _this.sequence) && + (identical(other.clipId, _this.clipId) || + other.clipId == _this.clipId) && + (identical(other.mediaId, _this.mediaId) || + other.mediaId == _this.mediaId) && + (identical(other.name, _this.name) || other.name == _this.name)); + } + + @override + int get hashCode { + final _this = this as BackgroundRemovalClipTarget; + return Object.hash( + runtimeType, + _this.sequence, + _this.clipId, + _this.mediaId, + _this.name, + ); + } + + @override + String toString() { + final _this = this as BackgroundRemovalClipTarget; + return 'BackgroundRemovalClipTarget(sequence: ${_this.sequence}, clipId: ${_this.clipId}, mediaId: ${_this.mediaId}, name: ${_this.name})'; + } +} + +/// @nodoc +abstract mixin class $BackgroundRemovalClipTargetCopyWith<$Res> { + factory $BackgroundRemovalClipTargetCopyWith( + BackgroundRemovalClipTarget value, + $Res Function(BackgroundRemovalClipTarget) _then, + ) = _$BackgroundRemovalClipTargetCopyWithImpl; + @useResult + $Res call({SequenceId sequence, String clipId, String mediaId, String name}); +} + +/// @nodoc +class _$BackgroundRemovalClipTargetCopyWithImpl<$Res> + implements $BackgroundRemovalClipTargetCopyWith<$Res> { + _$BackgroundRemovalClipTargetCopyWithImpl(this._self, this._then); + + final BackgroundRemovalClipTarget _self; + final $Res Function(BackgroundRemovalClipTarget) _then; + + /// Create a copy of BackgroundRemovalClipTarget + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? sequence = null, + Object? clipId = null, + Object? mediaId = null, + Object? name = null, + }) { + return _then( + BackgroundRemovalClipTarget( + sequence: null == sequence + ? _self.sequence + : sequence // ignore: cast_nullable_to_non_nullable + as SequenceId, + clipId: null == clipId + ? _self.clipId + : clipId // ignore: cast_nullable_to_non_nullable + as String, + mediaId: null == mediaId + ? _self.mediaId + : mediaId // ignore: cast_nullable_to_non_nullable + as String, + name: null == name + ? _self.name + : name // ignore: cast_nullable_to_non_nullable + as String, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [BackgroundRemovalClipTarget]. +extension BackgroundRemovalClipTargetPatterns on BackgroundRemovalClipTarget { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_BackgroundRemovalClipTarget value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _BackgroundRemovalClipTarget() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_BackgroundRemovalClipTarget value) $default, + ) { + final _that = this; + switch (_that) { + case _BackgroundRemovalClipTarget(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_BackgroundRemovalClipTarget value)? $default, + ) { + final _that = this; + switch (_that) { + case _BackgroundRemovalClipTarget() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + SequenceId sequence, + String clipId, + String mediaId, + String name, + )? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _BackgroundRemovalClipTarget() when $default != null: + return $default( + _that.sequence, + _that.clipId, + _that.mediaId, + _that.name, + ); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function( + SequenceId sequence, + String clipId, + String mediaId, + String name, + ) + $default, + ) { + final _that = this; + switch (_that) { + case _BackgroundRemovalClipTarget(): + return $default( + _that.sequence, + _that.clipId, + _that.mediaId, + _that.name, + ); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + SequenceId sequence, + String clipId, + String mediaId, + String name, + )? + $default, + ) { + final _that = this; + switch (_that) { + case _BackgroundRemovalClipTarget() when $default != null: + return $default( + _that.sequence, + _that.clipId, + _that.mediaId, + _that.name, + ); + case _: + return null; + } + } +} + +/// @nodoc + +class _BackgroundRemovalClipTarget implements BackgroundRemovalClipTarget { + const _BackgroundRemovalClipTarget({ + required this.sequence, + required this.clipId, + required this.mediaId, + required this.name, + }); + + @override + final SequenceId sequence; + @override + final String clipId; + @override + final String mediaId; + @override + final String name; + + /// Create a copy of BackgroundRemovalClipTarget + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$BackgroundRemovalClipTargetCopyWith<_BackgroundRemovalClipTarget> + get copyWith => + __$BackgroundRemovalClipTargetCopyWithImpl<_BackgroundRemovalClipTarget>( + this, + _$identity, + ); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _BackgroundRemovalClipTarget && + (identical(other.sequence, sequence) || + other.sequence == sequence) && + (identical(other.clipId, clipId) || other.clipId == clipId) && + (identical(other.mediaId, mediaId) || other.mediaId == mediaId) && + (identical(other.name, name) || other.name == name)); + } + + @override + int get hashCode { + return Object.hash(runtimeType, sequence, clipId, mediaId, name); + } + + @override + String toString() { + return 'BackgroundRemovalClipTarget(sequence: $sequence, clipId: $clipId, mediaId: $mediaId, name: $name)'; + } +} + +/// @nodoc +abstract mixin class _$BackgroundRemovalClipTargetCopyWith<$Res> + implements $BackgroundRemovalClipTargetCopyWith<$Res> { + factory _$BackgroundRemovalClipTargetCopyWith( + _BackgroundRemovalClipTarget value, + $Res Function(_BackgroundRemovalClipTarget) _then, + ) = __$BackgroundRemovalClipTargetCopyWithImpl; + @override + @useResult + $Res call({SequenceId sequence, String clipId, String mediaId, String name}); +} + +/// @nodoc +class __$BackgroundRemovalClipTargetCopyWithImpl<$Res> + implements _$BackgroundRemovalClipTargetCopyWith<$Res> { + __$BackgroundRemovalClipTargetCopyWithImpl(this._self, this._then); + + final _BackgroundRemovalClipTarget _self; + final $Res Function(_BackgroundRemovalClipTarget) _then; + + /// Create a copy of BackgroundRemovalClipTarget + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? sequence = null, + Object? clipId = null, + Object? mediaId = null, + Object? name = null, + }) { + return _then( + _BackgroundRemovalClipTarget( + sequence: null == sequence + ? _self.sequence + : sequence // ignore: cast_nullable_to_non_nullable + as SequenceId, + clipId: null == clipId + ? _self.clipId + : clipId // ignore: cast_nullable_to_non_nullable + as String, + mediaId: null == mediaId + ? _self.mediaId + : mediaId // ignore: cast_nullable_to_non_nullable + as String, + name: null == name + ? _self.name + : name // ignore: cast_nullable_to_non_nullable + as String, + ), + ); + } +} diff --git a/lib/features/media/subtitle_download.dart b/lib/features/media/subtitle_download.dart new file mode 100644 index 0000000..f74648a --- /dev/null +++ b/lib/features/media/subtitle_download.dart @@ -0,0 +1,267 @@ +import 'package:cutdex/diagnostics/app_diagnostics.dart'; +import 'package:cutdex/errors/app_failure.dart'; + +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import '../../integrations/runtime/processing_configuration.dart'; +import '../../integrations/runtime/processing_resource_repository.dart'; +import '../../workspace/timeline_session.dart'; +import 'processing_targets.dart'; + +part 'subtitle_download.g.dart'; +part 'subtitle_download.freezed.dart'; + +enum SubtitleStartFailure { start, download, engine } + +@freezed +abstract class SubtitleRequest with _$SubtitleRequest { + const factory SubtitleRequest({ + required EditorTimelineSession session, + required SequenceId? sequence, + AssetDocument? asset, + TranscriptionClipTarget? target, + @Default('auto') String language, + @Default('none') String targetLanguage, + }) = _SubtitleRequest; +} + +@freezed +sealed class SubtitleDownloadState with _$SubtitleDownloadState { + const SubtitleDownloadState._(); + const factory SubtitleDownloadState.idle() = SubtitleIdle; + const factory SubtitleDownloadState.starting(SubtitleRequest request) = + SubtitleStarting; + const factory SubtitleDownloadState.downloading( + SubtitleRequest request, { + required ProcessingCapability stage, + ProcessingResourceRepository? repository, + @Default(0) double progress, + @Default(false) bool paused, + }) = SubtitleDownloading; + const factory SubtitleDownloadState.started(SubtitleRequest request) = + SubtitleStarted; + const factory SubtitleDownloadState.cancelled(SubtitleRequest request) = + SubtitleCancelled; + const factory SubtitleDownloadState.failed( + SubtitleRequest request, + SubtitleStartFailure failure, + ) = SubtitleFailed; + + SubtitleRequest? get request => switch (this) { + SubtitleIdle() => null, + SubtitleStarting(:final request) || + SubtitleDownloading(:final request) || + SubtitleStarted(:final request) || + SubtitleCancelled(:final request) || + SubtitleFailed(:final request) => request, + }; + bool get running => this is SubtitleStarting || this is SubtitleDownloading; +} + +/// Owns the download and task handoff even when its dialog is closed. +@Riverpod(keepAlive: true) +class SubtitleDownload extends _$SubtitleDownload { + ProcessingResourceRepository? _repository; + bool _cancelled = false; + + @override + SubtitleDownloadState build() { + ref.onDispose(() { + _cancelled = true; + _repository?.cancelSubtitleResources(); + }); + return const SubtitleDownloadState.idle(); + } + + Future start(SubtitleRequest request, {bool download = false}) async { + if (state.running) return; + _cancelled = false; + var resourceInstalled = false; + final session = request.session; + final release = session.retainViews(); + state = download + ? SubtitleDownloadState.downloading( + request, + stage: session.transcriptions?.recognitionAvailable == true + ? ProcessingCapability.translation + : ProcessingCapability.transcription, + ) + : SubtitleDownloadState.starting(request); + ProcessingResourceRepository? repository; + void changed() { + if (!ref.mounted || state is! SubtitleDownloading) return; + final current = state as SubtitleDownloading; + state = current.copyWith( + paused: repository?.subtitlePaused ?? current.paused, + ); + } + + try { + final service = session.transcriptions; + if (download) { + final loaded = await ref.read( + processingResourceRepositoryProvider.future, + ); + repository = loaded; + if (_cancelled || !ref.mounted) { + return; + } + _repository = loaded; + final pausedBeforeLoad = (state as SubtitleDownloading).paused; + state = (state as SubtitleDownloading).copyWith(repository: loaded); + loaded.addListener(changed); + final install = loaded.ensureSubtitleResources( + available: { + if (service?.recognitionAvailable == true) + ProcessingCapability.transcription, + if (service?.translationAvailable == true) + ProcessingCapability.translation, + }, + onProgress: (stage, progress) { + if (!ref.mounted) return; + if (state case SubtitleDownloading(:final paused)) { + state = SubtitleDownloadState.downloading( + request, + stage: stage, + repository: loaded, + progress: progress, + paused: paused, + ); + } + }, + ); + if (pausedBeforeLoad) loaded.pauseSubtitleResources(); + await install; + resourceInstalled = true; + if (_cancelled || !ref.mounted) { + return; + } + final processing = ProcessingConfiguration.configured( + diagnostics: AppDiagnostics.report, + resourcesRoot: loaded.root.parent.path, + ); + final speechBackend = service?.backend ?? processing?.backend; + final speechModel = + service?.modelDirectory ?? processing?.transcriptionModel; + final translationBackend = + service?.translationBackend ?? processing?.backend; + final translationModel = + service?.translationModel ?? processing?.translationModel; + if (speechBackend == null || + speechModel == null || + translationBackend == null || + translationModel == null) { + throw AppException(AppErrorCode.subtitleEngineUnavailable); + } + session.configureProcessing( + transcriptionBackend: speechBackend, + transcriptionModel: speechModel, + translationBackend: translationBackend, + translationModel: translationModel, + ); + } + if (_cancelled || !ref.mounted) { + return; + } + await _startSubtitles(request); + if (ref.mounted) state = SubtitleDownloadState.started(request); + } on ProcessingResourceCancelledException { + if (ref.mounted) state = SubtitleDownloadState.cancelled(request); + } catch (_) { + if (ref.mounted) { + state = SubtitleDownloadState.failed( + request, + !download + ? SubtitleStartFailure.start + : resourceInstalled + ? SubtitleStartFailure.engine + : SubtitleStartFailure.download, + ); + } + } finally { + repository?.removeListener(changed); + _repository = null; + if (ref.mounted && _cancelled && state.running) { + state = SubtitleDownloadState.cancelled(request); + } + release(); + } + } + + void togglePause() { + if (state case SubtitleDownloading(:final paused)) { + state = (state as SubtitleDownloading).copyWith(paused: !paused); + if (paused) { + _repository?.resumeSubtitleResources(); + } else { + _repository?.pauseSubtitleResources(); + } + } + } + + void cancel() { + if (!state.running) return; + _cancelled = true; + _repository?.cancelSubtitleResources(); + } +} + +Future _startSubtitles(SubtitleRequest request) async { + final mediaId = request.target?.mediaId ?? request.asset?.id; + final name = request.target?.name ?? request.asset?.name ?? mediaId; + final sequence = request.sequence; + if (sequence == null || mediaId == null || name == null) { + throw const CommandRejected( + 'missingSequence', + 'Sequence or media does not exist', + ); + } + await request.session.subtitleWorkflows.start( + sequence: sequence, + command: StartTranscription( + mediaId: mediaId, + clipId: request.target?.clipId, + audioStream: request.target?.audioStream ?? 0, + language: request.language, + ), + name: name, + targetLanguage: request.targetLanguage, + ); +} + +/// Configured sessions can start independently of another project's download. +@riverpod +class SubtitleStart extends _$SubtitleStart { + @override + SubtitleDownloadState build(EditorTimelineSession session) => + const SubtitleDownloadState.idle(); + + void reset() { + if (!state.running) state = const SubtitleDownloadState.idle(); + } + + Future start(SubtitleRequest request) async { + if (state.running) return; + final lease = ref.keepAlive(); + final release = session.retainViews(); + state = SubtitleDownloadState.starting(request); + try { + await _startSubtitles(request); + if (ref.mounted) state = SubtitleDownloadState.started(request); + } catch (_) { + if (ref.mounted) { + state = SubtitleDownloadState.failed( + request, + SubtitleStartFailure.start, + ); + } + } finally { + release(); + lease.close(); + } + } +} diff --git a/lib/features/media/subtitle_download.freezed.dart b/lib/features/media/subtitle_download.freezed.dart new file mode 100644 index 0000000..6b8bd61 --- /dev/null +++ b/lib/features/media/subtitle_download.freezed.dart @@ -0,0 +1,1303 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'subtitle_download.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +T _$identity(T value) => value; + +/// @nodoc +mixin _$SubtitleRequest { + EditorTimelineSession get session; + SequenceId? get sequence; + AssetDocument? get asset; + TranscriptionClipTarget? get target; + String get language; + String get targetLanguage; + + /// Create a copy of SubtitleRequest + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $SubtitleRequestCopyWith get copyWith => + _$SubtitleRequestCopyWithImpl( + this as SubtitleRequest, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as SubtitleRequest; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is SubtitleRequest && + (identical(other.session, _this.session) || + other.session == _this.session) && + (identical(other.sequence, _this.sequence) || + other.sequence == _this.sequence) && + (identical(other.asset, _this.asset) || + other.asset == _this.asset) && + (identical(other.target, _this.target) || + other.target == _this.target) && + (identical(other.language, _this.language) || + other.language == _this.language) && + (identical(other.targetLanguage, _this.targetLanguage) || + other.targetLanguage == _this.targetLanguage)); + } + + @override + int get hashCode { + final _this = this as SubtitleRequest; + return Object.hash( + runtimeType, + _this.session, + _this.sequence, + _this.asset, + _this.target, + _this.language, + _this.targetLanguage, + ); + } + + @override + String toString() { + final _this = this as SubtitleRequest; + return 'SubtitleRequest(session: ${_this.session}, sequence: ${_this.sequence}, asset: ${_this.asset}, target: ${_this.target}, language: ${_this.language}, targetLanguage: ${_this.targetLanguage})'; + } +} + +/// @nodoc +abstract mixin class $SubtitleRequestCopyWith<$Res> { + factory $SubtitleRequestCopyWith( + SubtitleRequest value, + $Res Function(SubtitleRequest) _then, + ) = _$SubtitleRequestCopyWithImpl; + @useResult + $Res call({ + EditorTimelineSession session, + SequenceId? sequence, + AssetDocument? asset, + TranscriptionClipTarget? target, + String language, + String targetLanguage, + }); + + $TranscriptionClipTargetCopyWith<$Res>? get target; +} + +/// @nodoc +class _$SubtitleRequestCopyWithImpl<$Res> + implements $SubtitleRequestCopyWith<$Res> { + _$SubtitleRequestCopyWithImpl(this._self, this._then); + + final SubtitleRequest _self; + final $Res Function(SubtitleRequest) _then; + + /// Create a copy of SubtitleRequest + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? session = null, + Object? sequence = freezed, + Object? asset = freezed, + Object? target = freezed, + Object? language = null, + Object? targetLanguage = null, + }) { + return _then( + SubtitleRequest( + session: null == session + ? _self.session + : session // ignore: cast_nullable_to_non_nullable + as EditorTimelineSession, + sequence: freezed == sequence + ? _self.sequence + : sequence // ignore: cast_nullable_to_non_nullable + as SequenceId?, + asset: freezed == asset + ? _self.asset + : asset // ignore: cast_nullable_to_non_nullable + as AssetDocument?, + target: freezed == target + ? _self.target + : target // ignore: cast_nullable_to_non_nullable + as TranscriptionClipTarget?, + language: null == language + ? _self.language + : language // ignore: cast_nullable_to_non_nullable + as String, + targetLanguage: null == targetLanguage + ? _self.targetLanguage + : targetLanguage // ignore: cast_nullable_to_non_nullable + as String, + ), + ); + } + + /// Create a copy of SubtitleRequest + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $TranscriptionClipTargetCopyWith<$Res>? get target { + if (_self.target == null) { + return null; + } + + return $TranscriptionClipTargetCopyWith<$Res>(_self.target!, (value) { + return _then(_self.copyWith(target: value)); + }); + } +} + +/// Adds pattern-matching-related methods to [SubtitleRequest]. +extension SubtitleRequestPatterns on SubtitleRequest { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_SubtitleRequest value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _SubtitleRequest() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_SubtitleRequest value) $default, + ) { + final _that = this; + switch (_that) { + case _SubtitleRequest(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_SubtitleRequest value)? $default, + ) { + final _that = this; + switch (_that) { + case _SubtitleRequest() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + EditorTimelineSession session, + SequenceId? sequence, + AssetDocument? asset, + TranscriptionClipTarget? target, + String language, + String targetLanguage, + )? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _SubtitleRequest() when $default != null: + return $default( + _that.session, + _that.sequence, + _that.asset, + _that.target, + _that.language, + _that.targetLanguage, + ); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function( + EditorTimelineSession session, + SequenceId? sequence, + AssetDocument? asset, + TranscriptionClipTarget? target, + String language, + String targetLanguage, + ) + $default, + ) { + final _that = this; + switch (_that) { + case _SubtitleRequest(): + return $default( + _that.session, + _that.sequence, + _that.asset, + _that.target, + _that.language, + _that.targetLanguage, + ); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + EditorTimelineSession session, + SequenceId? sequence, + AssetDocument? asset, + TranscriptionClipTarget? target, + String language, + String targetLanguage, + )? + $default, + ) { + final _that = this; + switch (_that) { + case _SubtitleRequest() when $default != null: + return $default( + _that.session, + _that.sequence, + _that.asset, + _that.target, + _that.language, + _that.targetLanguage, + ); + case _: + return null; + } + } +} + +/// @nodoc + +class _SubtitleRequest implements SubtitleRequest { + const _SubtitleRequest({ + required this.session, + required this.sequence, + this.asset, + this.target, + this.language = 'auto', + this.targetLanguage = 'none', + }); + + @override + final EditorTimelineSession session; + @override + final SequenceId? sequence; + @override + final AssetDocument? asset; + @override + final TranscriptionClipTarget? target; + @override + @JsonKey() + final String language; + @override + @JsonKey() + final String targetLanguage; + + /// Create a copy of SubtitleRequest + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$SubtitleRequestCopyWith<_SubtitleRequest> get copyWith => + __$SubtitleRequestCopyWithImpl<_SubtitleRequest>(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _SubtitleRequest && + (identical(other.session, session) || other.session == session) && + (identical(other.sequence, sequence) || + other.sequence == sequence) && + (identical(other.asset, asset) || other.asset == asset) && + (identical(other.target, target) || other.target == target) && + (identical(other.language, language) || + other.language == language) && + (identical(other.targetLanguage, targetLanguage) || + other.targetLanguage == targetLanguage)); + } + + @override + int get hashCode { + return Object.hash( + runtimeType, + session, + sequence, + asset, + target, + language, + targetLanguage, + ); + } + + @override + String toString() { + return 'SubtitleRequest(session: $session, sequence: $sequence, asset: $asset, target: $target, language: $language, targetLanguage: $targetLanguage)'; + } +} + +/// @nodoc +abstract mixin class _$SubtitleRequestCopyWith<$Res> + implements $SubtitleRequestCopyWith<$Res> { + factory _$SubtitleRequestCopyWith( + _SubtitleRequest value, + $Res Function(_SubtitleRequest) _then, + ) = __$SubtitleRequestCopyWithImpl; + @override + @useResult + $Res call({ + EditorTimelineSession session, + SequenceId? sequence, + AssetDocument? asset, + TranscriptionClipTarget? target, + String language, + String targetLanguage, + }); + + @override + $TranscriptionClipTargetCopyWith<$Res>? get target; +} + +/// @nodoc +class __$SubtitleRequestCopyWithImpl<$Res> + implements _$SubtitleRequestCopyWith<$Res> { + __$SubtitleRequestCopyWithImpl(this._self, this._then); + + final _SubtitleRequest _self; + final $Res Function(_SubtitleRequest) _then; + + /// Create a copy of SubtitleRequest + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? session = null, + Object? sequence = freezed, + Object? asset = freezed, + Object? target = freezed, + Object? language = null, + Object? targetLanguage = null, + }) { + return _then( + _SubtitleRequest( + session: null == session + ? _self.session + : session // ignore: cast_nullable_to_non_nullable + as EditorTimelineSession, + sequence: freezed == sequence + ? _self.sequence + : sequence // ignore: cast_nullable_to_non_nullable + as SequenceId?, + asset: freezed == asset + ? _self.asset + : asset // ignore: cast_nullable_to_non_nullable + as AssetDocument?, + target: freezed == target + ? _self.target + : target // ignore: cast_nullable_to_non_nullable + as TranscriptionClipTarget?, + language: null == language + ? _self.language + : language // ignore: cast_nullable_to_non_nullable + as String, + targetLanguage: null == targetLanguage + ? _self.targetLanguage + : targetLanguage // ignore: cast_nullable_to_non_nullable + as String, + ), + ); + } + + /// Create a copy of SubtitleRequest + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $TranscriptionClipTargetCopyWith<$Res>? get target { + if (_self.target == null) { + return null; + } + + return $TranscriptionClipTargetCopyWith<$Res>(_self.target!, (value) { + return _then(_self.copyWith(target: value)); + }); + } +} + +/// @nodoc +mixin _$SubtitleDownloadState { + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is SubtitleDownloadState); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + String toString() { + return 'SubtitleDownloadState()'; + } +} + +/// @nodoc +class $SubtitleDownloadStateCopyWith<$Res> { + $SubtitleDownloadStateCopyWith( + SubtitleDownloadState _, + $Res Function(SubtitleDownloadState) __, + ); +} + +/// Adds pattern-matching-related methods to [SubtitleDownloadState]. +extension SubtitleDownloadStatePatterns on SubtitleDownloadState { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap({ + TResult Function(SubtitleIdle value)? idle, + TResult Function(SubtitleStarting value)? starting, + TResult Function(SubtitleDownloading value)? downloading, + TResult Function(SubtitleStarted value)? started, + TResult Function(SubtitleCancelled value)? cancelled, + TResult Function(SubtitleFailed value)? failed, + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case SubtitleIdle() when idle != null: + return idle(_that); + case SubtitleStarting() when starting != null: + return starting(_that); + case SubtitleDownloading() when downloading != null: + return downloading(_that); + case SubtitleStarted() when started != null: + return started(_that); + case SubtitleCancelled() when cancelled != null: + return cancelled(_that); + case SubtitleFailed() when failed != null: + return failed(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map({ + required TResult Function(SubtitleIdle value) idle, + required TResult Function(SubtitleStarting value) starting, + required TResult Function(SubtitleDownloading value) downloading, + required TResult Function(SubtitleStarted value) started, + required TResult Function(SubtitleCancelled value) cancelled, + required TResult Function(SubtitleFailed value) failed, + }) { + final _that = this; + switch (_that) { + case SubtitleIdle(): + return idle(_that); + case SubtitleStarting(): + return starting(_that); + case SubtitleDownloading(): + return downloading(_that); + case SubtitleStarted(): + return started(_that); + case SubtitleCancelled(): + return cancelled(_that); + case SubtitleFailed(): + return failed(_that); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(SubtitleIdle value)? idle, + TResult? Function(SubtitleStarting value)? starting, + TResult? Function(SubtitleDownloading value)? downloading, + TResult? Function(SubtitleStarted value)? started, + TResult? Function(SubtitleCancelled value)? cancelled, + TResult? Function(SubtitleFailed value)? failed, + }) { + final _that = this; + switch (_that) { + case SubtitleIdle() when idle != null: + return idle(_that); + case SubtitleStarting() when starting != null: + return starting(_that); + case SubtitleDownloading() when downloading != null: + return downloading(_that); + case SubtitleStarted() when started != null: + return started(_that); + case SubtitleCancelled() when cancelled != null: + return cancelled(_that); + case SubtitleFailed() when failed != null: + return failed(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? idle, + TResult Function(SubtitleRequest request)? starting, + TResult Function( + SubtitleRequest request, + ProcessingCapability stage, + ProcessingResourceRepository? repository, + double progress, + bool paused, + )? + downloading, + TResult Function(SubtitleRequest request)? started, + TResult Function(SubtitleRequest request)? cancelled, + TResult Function(SubtitleRequest request, SubtitleStartFailure failure)? + failed, + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case SubtitleIdle() when idle != null: + return idle(); + case SubtitleStarting() when starting != null: + return starting(_that.request); + case SubtitleDownloading() when downloading != null: + return downloading( + _that.request, + _that.stage, + _that.repository, + _that.progress, + _that.paused, + ); + case SubtitleStarted() when started != null: + return started(_that.request); + case SubtitleCancelled() when cancelled != null: + return cancelled(_that.request); + case SubtitleFailed() when failed != null: + return failed(_that.request, _that.failure); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when({ + required TResult Function() idle, + required TResult Function(SubtitleRequest request) starting, + required TResult Function( + SubtitleRequest request, + ProcessingCapability stage, + ProcessingResourceRepository? repository, + double progress, + bool paused, + ) + downloading, + required TResult Function(SubtitleRequest request) started, + required TResult Function(SubtitleRequest request) cancelled, + required TResult Function( + SubtitleRequest request, + SubtitleStartFailure failure, + ) + failed, + }) { + final _that = this; + switch (_that) { + case SubtitleIdle(): + return idle(); + case SubtitleStarting(): + return starting(_that.request); + case SubtitleDownloading(): + return downloading( + _that.request, + _that.stage, + _that.repository, + _that.progress, + _that.paused, + ); + case SubtitleStarted(): + return started(_that.request); + case SubtitleCancelled(): + return cancelled(_that.request); + case SubtitleFailed(): + return failed(_that.request, _that.failure); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? idle, + TResult? Function(SubtitleRequest request)? starting, + TResult? Function( + SubtitleRequest request, + ProcessingCapability stage, + ProcessingResourceRepository? repository, + double progress, + bool paused, + )? + downloading, + TResult? Function(SubtitleRequest request)? started, + TResult? Function(SubtitleRequest request)? cancelled, + TResult? Function(SubtitleRequest request, SubtitleStartFailure failure)? + failed, + }) { + final _that = this; + switch (_that) { + case SubtitleIdle() when idle != null: + return idle(); + case SubtitleStarting() when starting != null: + return starting(_that.request); + case SubtitleDownloading() when downloading != null: + return downloading( + _that.request, + _that.stage, + _that.repository, + _that.progress, + _that.paused, + ); + case SubtitleStarted() when started != null: + return started(_that.request); + case SubtitleCancelled() when cancelled != null: + return cancelled(_that.request); + case SubtitleFailed() when failed != null: + return failed(_that.request, _that.failure); + case _: + return null; + } + } +} + +/// @nodoc + +class SubtitleIdle extends SubtitleDownloadState { + const SubtitleIdle() : super._(); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is SubtitleIdle); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + String toString() { + return 'SubtitleDownloadState.idle()'; + } +} + +/// @nodoc + +class SubtitleStarting extends SubtitleDownloadState { + const SubtitleStarting(this.request) : super._(); + + final SubtitleRequest request; + + /// Create a copy of SubtitleDownloadState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $SubtitleStartingCopyWith get copyWith => + _$SubtitleStartingCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is SubtitleStarting && + (identical(other.request, request) || other.request == request)); + } + + @override + int get hashCode { + return Object.hash(runtimeType, request); + } + + @override + String toString() { + return 'SubtitleDownloadState.starting(request: $request)'; + } +} + +/// @nodoc +abstract mixin class $SubtitleStartingCopyWith<$Res> + implements $SubtitleDownloadStateCopyWith<$Res> { + factory $SubtitleStartingCopyWith( + SubtitleStarting value, + $Res Function(SubtitleStarting) _then, + ) = _$SubtitleStartingCopyWithImpl; + @useResult + $Res call({SubtitleRequest request}); + + $SubtitleRequestCopyWith<$Res> get request; +} + +/// @nodoc +class _$SubtitleStartingCopyWithImpl<$Res> + implements $SubtitleStartingCopyWith<$Res> { + _$SubtitleStartingCopyWithImpl(this._self, this._then); + + final SubtitleStarting _self; + final $Res Function(SubtitleStarting) _then; + + /// Create a copy of SubtitleDownloadState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({Object? request = null}) { + return _then( + SubtitleStarting( + null == request + ? _self.request + : request // ignore: cast_nullable_to_non_nullable + as SubtitleRequest, + ), + ); + } + + /// Create a copy of SubtitleDownloadState + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $SubtitleRequestCopyWith<$Res> get request { + return $SubtitleRequestCopyWith<$Res>(_self.request, (value) { + return _then(_self.copyWith(request: value)); + }); + } +} + +/// @nodoc + +class SubtitleDownloading extends SubtitleDownloadState { + const SubtitleDownloading( + this.request, { + required this.stage, + this.repository, + this.progress = 0, + this.paused = false, + }) : super._(); + + final SubtitleRequest request; + final ProcessingCapability stage; + final ProcessingResourceRepository? repository; + @JsonKey() + final double progress; + @JsonKey() + final bool paused; + + /// Create a copy of SubtitleDownloadState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $SubtitleDownloadingCopyWith get copyWith => + _$SubtitleDownloadingCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is SubtitleDownloading && + (identical(other.request, request) || other.request == request) && + (identical(other.stage, stage) || other.stage == stage) && + (identical(other.repository, repository) || + other.repository == repository) && + (identical(other.progress, progress) || + other.progress == progress) && + (identical(other.paused, paused) || other.paused == paused)); + } + + @override + int get hashCode { + return Object.hash( + runtimeType, + request, + stage, + repository, + progress, + paused, + ); + } + + @override + String toString() { + return 'SubtitleDownloadState.downloading(request: $request, stage: $stage, repository: $repository, progress: $progress, paused: $paused)'; + } +} + +/// @nodoc +abstract mixin class $SubtitleDownloadingCopyWith<$Res> + implements $SubtitleDownloadStateCopyWith<$Res> { + factory $SubtitleDownloadingCopyWith( + SubtitleDownloading value, + $Res Function(SubtitleDownloading) _then, + ) = _$SubtitleDownloadingCopyWithImpl; + @useResult + $Res call({ + SubtitleRequest request, + ProcessingCapability stage, + ProcessingResourceRepository? repository, + double progress, + bool paused, + }); + + $SubtitleRequestCopyWith<$Res> get request; +} + +/// @nodoc +class _$SubtitleDownloadingCopyWithImpl<$Res> + implements $SubtitleDownloadingCopyWith<$Res> { + _$SubtitleDownloadingCopyWithImpl(this._self, this._then); + + final SubtitleDownloading _self; + final $Res Function(SubtitleDownloading) _then; + + /// Create a copy of SubtitleDownloadState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({ + Object? request = null, + Object? stage = null, + Object? repository = freezed, + Object? progress = null, + Object? paused = null, + }) { + return _then( + SubtitleDownloading( + null == request + ? _self.request + : request // ignore: cast_nullable_to_non_nullable + as SubtitleRequest, + stage: null == stage + ? _self.stage + : stage // ignore: cast_nullable_to_non_nullable + as ProcessingCapability, + repository: freezed == repository + ? _self.repository + : repository // ignore: cast_nullable_to_non_nullable + as ProcessingResourceRepository?, + progress: null == progress + ? _self.progress + : progress // ignore: cast_nullable_to_non_nullable + as double, + paused: null == paused + ? _self.paused + : paused // ignore: cast_nullable_to_non_nullable + as bool, + ), + ); + } + + /// Create a copy of SubtitleDownloadState + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $SubtitleRequestCopyWith<$Res> get request { + return $SubtitleRequestCopyWith<$Res>(_self.request, (value) { + return _then(_self.copyWith(request: value)); + }); + } +} + +/// @nodoc + +class SubtitleStarted extends SubtitleDownloadState { + const SubtitleStarted(this.request) : super._(); + + final SubtitleRequest request; + + /// Create a copy of SubtitleDownloadState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $SubtitleStartedCopyWith get copyWith => + _$SubtitleStartedCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is SubtitleStarted && + (identical(other.request, request) || other.request == request)); + } + + @override + int get hashCode { + return Object.hash(runtimeType, request); + } + + @override + String toString() { + return 'SubtitleDownloadState.started(request: $request)'; + } +} + +/// @nodoc +abstract mixin class $SubtitleStartedCopyWith<$Res> + implements $SubtitleDownloadStateCopyWith<$Res> { + factory $SubtitleStartedCopyWith( + SubtitleStarted value, + $Res Function(SubtitleStarted) _then, + ) = _$SubtitleStartedCopyWithImpl; + @useResult + $Res call({SubtitleRequest request}); + + $SubtitleRequestCopyWith<$Res> get request; +} + +/// @nodoc +class _$SubtitleStartedCopyWithImpl<$Res> + implements $SubtitleStartedCopyWith<$Res> { + _$SubtitleStartedCopyWithImpl(this._self, this._then); + + final SubtitleStarted _self; + final $Res Function(SubtitleStarted) _then; + + /// Create a copy of SubtitleDownloadState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({Object? request = null}) { + return _then( + SubtitleStarted( + null == request + ? _self.request + : request // ignore: cast_nullable_to_non_nullable + as SubtitleRequest, + ), + ); + } + + /// Create a copy of SubtitleDownloadState + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $SubtitleRequestCopyWith<$Res> get request { + return $SubtitleRequestCopyWith<$Res>(_self.request, (value) { + return _then(_self.copyWith(request: value)); + }); + } +} + +/// @nodoc + +class SubtitleCancelled extends SubtitleDownloadState { + const SubtitleCancelled(this.request) : super._(); + + final SubtitleRequest request; + + /// Create a copy of SubtitleDownloadState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $SubtitleCancelledCopyWith get copyWith => + _$SubtitleCancelledCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is SubtitleCancelled && + (identical(other.request, request) || other.request == request)); + } + + @override + int get hashCode { + return Object.hash(runtimeType, request); + } + + @override + String toString() { + return 'SubtitleDownloadState.cancelled(request: $request)'; + } +} + +/// @nodoc +abstract mixin class $SubtitleCancelledCopyWith<$Res> + implements $SubtitleDownloadStateCopyWith<$Res> { + factory $SubtitleCancelledCopyWith( + SubtitleCancelled value, + $Res Function(SubtitleCancelled) _then, + ) = _$SubtitleCancelledCopyWithImpl; + @useResult + $Res call({SubtitleRequest request}); + + $SubtitleRequestCopyWith<$Res> get request; +} + +/// @nodoc +class _$SubtitleCancelledCopyWithImpl<$Res> + implements $SubtitleCancelledCopyWith<$Res> { + _$SubtitleCancelledCopyWithImpl(this._self, this._then); + + final SubtitleCancelled _self; + final $Res Function(SubtitleCancelled) _then; + + /// Create a copy of SubtitleDownloadState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({Object? request = null}) { + return _then( + SubtitleCancelled( + null == request + ? _self.request + : request // ignore: cast_nullable_to_non_nullable + as SubtitleRequest, + ), + ); + } + + /// Create a copy of SubtitleDownloadState + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $SubtitleRequestCopyWith<$Res> get request { + return $SubtitleRequestCopyWith<$Res>(_self.request, (value) { + return _then(_self.copyWith(request: value)); + }); + } +} + +/// @nodoc + +class SubtitleFailed extends SubtitleDownloadState { + const SubtitleFailed(this.request, this.failure) : super._(); + + final SubtitleRequest request; + final SubtitleStartFailure failure; + + /// Create a copy of SubtitleDownloadState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $SubtitleFailedCopyWith get copyWith => + _$SubtitleFailedCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is SubtitleFailed && + (identical(other.request, request) || other.request == request) && + (identical(other.failure, failure) || other.failure == failure)); + } + + @override + int get hashCode { + return Object.hash(runtimeType, request, failure); + } + + @override + String toString() { + return 'SubtitleDownloadState.failed(request: $request, failure: $failure)'; + } +} + +/// @nodoc +abstract mixin class $SubtitleFailedCopyWith<$Res> + implements $SubtitleDownloadStateCopyWith<$Res> { + factory $SubtitleFailedCopyWith( + SubtitleFailed value, + $Res Function(SubtitleFailed) _then, + ) = _$SubtitleFailedCopyWithImpl; + @useResult + $Res call({SubtitleRequest request, SubtitleStartFailure failure}); + + $SubtitleRequestCopyWith<$Res> get request; +} + +/// @nodoc +class _$SubtitleFailedCopyWithImpl<$Res> + implements $SubtitleFailedCopyWith<$Res> { + _$SubtitleFailedCopyWithImpl(this._self, this._then); + + final SubtitleFailed _self; + final $Res Function(SubtitleFailed) _then; + + /// Create a copy of SubtitleDownloadState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({Object? request = null, Object? failure = null}) { + return _then( + SubtitleFailed( + null == request + ? _self.request + : request // ignore: cast_nullable_to_non_nullable + as SubtitleRequest, + null == failure + ? _self.failure + : failure // ignore: cast_nullable_to_non_nullable + as SubtitleStartFailure, + ), + ); + } + + /// Create a copy of SubtitleDownloadState + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $SubtitleRequestCopyWith<$Res> get request { + return $SubtitleRequestCopyWith<$Res>(_self.request, (value) { + return _then(_self.copyWith(request: value)); + }); + } +} diff --git a/lib/features/media/subtitle_download.g.dart b/lib/features/media/subtitle_download.g.dart new file mode 100644 index 0000000..23860c6 --- /dev/null +++ b/lib/features/media/subtitle_download.g.dart @@ -0,0 +1,174 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'subtitle_download.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning +/// Owns the download and task handoff even when its dialog is closed. + +@ProviderFor(SubtitleDownload) +final subtitleDownloadProvider = SubtitleDownloadProvider._(); + +/// Owns the download and task handoff even when its dialog is closed. +final class SubtitleDownloadProvider + extends $NotifierProvider { + /// Owns the download and task handoff even when its dialog is closed. + SubtitleDownloadProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'subtitleDownloadProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$subtitleDownloadHash(); + + @$internal + @override + SubtitleDownload create() => SubtitleDownload(); + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(SubtitleDownloadState value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$subtitleDownloadHash() => r'2bf89e93b596e3b24f3880279477c91227b261b4'; + +/// Owns the download and task handoff even when its dialog is closed. + +abstract class _$SubtitleDownload extends $Notifier { + SubtitleDownloadState build(); + @$mustCallSuper + @override + WhenComplete runBuild() { + final ref = this.ref as $Ref; + final element = + ref.element + as $ClassProviderElement< + AnyNotifier, + SubtitleDownloadState, + Object?, + Object? + >; + return element.handleCreate(ref, build); + } +} + +/// Configured sessions can start independently of another project's download. + +@ProviderFor(SubtitleStart) +final subtitleStartProvider = SubtitleStartFamily._(); + +/// Configured sessions can start independently of another project's download. +final class SubtitleStartProvider + extends $NotifierProvider { + /// Configured sessions can start independently of another project's download. + SubtitleStartProvider._({ + required SubtitleStartFamily super.from, + required EditorTimelineSession super.argument, + }) : super( + retry: null, + name: r'subtitleStartProvider', + isAutoDispose: true, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$subtitleStartHash(); + + @override + String toString() { + return r'subtitleStartProvider' + '' + '($argument)'; + } + + @$internal + @override + SubtitleStart create() => SubtitleStart(); + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(SubtitleDownloadState value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } + + @override + bool operator ==(Object other) { + return other is SubtitleStartProvider && other.argument == argument; + } + + @override + int get hashCode { + return argument.hashCode; + } +} + +String _$subtitleStartHash() => r'3278b419fd819fa4dcc021815280cc1cce72dbb5'; + +/// Configured sessions can start independently of another project's download. + +final class SubtitleStartFamily extends $Family + with + $ClassFamilyOverride< + SubtitleStart, + SubtitleDownloadState, + SubtitleDownloadState, + SubtitleDownloadState, + EditorTimelineSession + > { + SubtitleStartFamily._() + : super( + retry: null, + name: r'subtitleStartProvider', + dependencies: null, + $allTransitiveDependencies: null, + isAutoDispose: true, + ); + + /// Configured sessions can start independently of another project's download. + + SubtitleStartProvider call(EditorTimelineSession session) => + SubtitleStartProvider._(argument: session, from: this); + + @override + String toString() => r'subtitleStartProvider'; +} + +/// Configured sessions can start independently of another project's download. + +abstract class _$SubtitleStart extends $Notifier { + late final _$args = ref.$arg as EditorTimelineSession; + EditorTimelineSession get session => _$args; + + SubtitleDownloadState build(EditorTimelineSession session); + @$mustCallSuper + @override + WhenComplete runBuild() { + final ref = this.ref as $Ref; + final element = + ref.element + as $ClassProviderElement< + AnyNotifier, + SubtitleDownloadState, + Object?, + Object? + >; + return element.handleCreate(ref, () => build(_$args)); + } +} diff --git a/lib/features/media/subtitle_task_actions.dart b/lib/features/media/subtitle_task_actions.dart new file mode 100644 index 0000000..2199d51 --- /dev/null +++ b/lib/features/media/subtitle_task_actions.dart @@ -0,0 +1,136 @@ +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import '../../workspace/timeline_session.dart'; + +part 'subtitle_task_actions.g.dart'; +part 'subtitle_task_actions.freezed.dart'; + +enum SubtitleActionKind { original, translation, cancel, retry } + +@freezed +abstract class SubtitleActionFeedback with _$SubtitleActionFeedback { + const factory SubtitleActionFeedback({ + required SubtitleActionKind kind, + int? cueCount, + }) = _SubtitleActionFeedback; +} + +@freezed +abstract class SubtitleActionException + with _$SubtitleActionException + implements Exception { + const factory SubtitleActionException(SubtitleActionKind kind, Object cause) = + _SubtitleActionException; +} + +/// One operation state is shared by the compact card and its details dialog. +@riverpod +class SubtitleTaskActions extends _$SubtitleTaskActions { + @override + AsyncValue build( + EditorTimelineSession session, + String jobId, + ) => const AsyncData(null); + + Future> candidates( + SubtitleBackgroundTask job, { + bool translated = false, + }) async { + final recognition = job.recognition; + return session.persistence + .timeline(job.sequence) + .exportDto() + .elements + .where((element) { + final binding = element.payloadRef == null + ? null + : session.mediaBinding(element.payloadRef!); + return (translated + ? binding?.media.uri == recognition.source + : binding?.media.id == recognition.command.mediaId) && + binding?.audioTrackIndex == recognition.command.audioStream; + }) + .toList(); + } + + Future apply( + SubtitleBackgroundTask job, + String clipId, { + required String expectedVersion, + bool translated = false, + }) => _run( + translated ? SubtitleActionKind.translation : SubtitleActionKind.original, + () async { + final recognition = job.recognition; + final outcome = translated + ? await session.executeCommand( + job.sequence, + ApplySubtitleTranslation( + source: recognition.source!.toFilePath(), + audioStream: recognition.command.audioStream, + sourceStartMs: recognition.sourceStartMs, + taskId: job.translation!.id, + clipId: clipId, + expectedVersion: expectedVersion, + ), + ) + : await session.executeCommand( + job.sequence, + ApplyTranscription( + taskId: recognition.id, + clipId: clipId, + expectedVersion: expectedVersion, + ), + ); + final ids = (outcome.data['captionIds'] as List).cast(); + final view = session.view(job.sequence); + final handle = ids.isEmpty + ? null + : view.version.kernelVersion.query().elementById( + ElementId(ids.first), + ); + final component = handle == null + ? null + : session.captionComponentFor(job.sequence, handle); + if (component != null) view.setSelection([component]); + return outcome.data['cueCount'] as int; + }, + ); + + Future cancel(SubtitleBackgroundTask job) => + _run(SubtitleActionKind.cancel, () async { + await session.subtitleWorkflows.cancel(job); + return null; + }); + Future retry(SubtitleBackgroundTask job) => + _run(SubtitleActionKind.retry, () async { + await session.subtitleWorkflows.retry(job); + return null; + }); + + Future _run( + SubtitleActionKind kind, + Future Function() action, + ) async { + if (state.isLoading) return; + final lease = ref.keepAlive(); + final release = session.retainViews(); + state = const AsyncLoading(); + try { + final count = await action(); + if (ref.mounted) { + state = AsyncData(SubtitleActionFeedback(kind: kind, cueCount: count)); + } + } catch (error, stack) { + if (ref.mounted) { + state = AsyncError(SubtitleActionException(kind, error), stack); + } + } finally { + release(); + lease.close(); + } + } +} diff --git a/lib/features/media/subtitle_task_actions.freezed.dart b/lib/features/media/subtitle_task_actions.freezed.dart new file mode 100644 index 0000000..549be2b --- /dev/null +++ b/lib/features/media/subtitle_task_actions.freezed.dart @@ -0,0 +1,645 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'subtitle_task_actions.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +T _$identity(T value) => value; + +/// @nodoc +mixin _$SubtitleActionFeedback { + SubtitleActionKind get kind; + int? get cueCount; + + /// Create a copy of SubtitleActionFeedback + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $SubtitleActionFeedbackCopyWith get copyWith => + _$SubtitleActionFeedbackCopyWithImpl( + this as SubtitleActionFeedback, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as SubtitleActionFeedback; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is SubtitleActionFeedback && + (identical(other.kind, _this.kind) || other.kind == _this.kind) && + (identical(other.cueCount, _this.cueCount) || + other.cueCount == _this.cueCount)); + } + + @override + int get hashCode { + final _this = this as SubtitleActionFeedback; + return Object.hash(runtimeType, _this.kind, _this.cueCount); + } + + @override + String toString() { + final _this = this as SubtitleActionFeedback; + return 'SubtitleActionFeedback(kind: ${_this.kind}, cueCount: ${_this.cueCount})'; + } +} + +/// @nodoc +abstract mixin class $SubtitleActionFeedbackCopyWith<$Res> { + factory $SubtitleActionFeedbackCopyWith( + SubtitleActionFeedback value, + $Res Function(SubtitleActionFeedback) _then, + ) = _$SubtitleActionFeedbackCopyWithImpl; + @useResult + $Res call({SubtitleActionKind kind, int? cueCount}); +} + +/// @nodoc +class _$SubtitleActionFeedbackCopyWithImpl<$Res> + implements $SubtitleActionFeedbackCopyWith<$Res> { + _$SubtitleActionFeedbackCopyWithImpl(this._self, this._then); + + final SubtitleActionFeedback _self; + final $Res Function(SubtitleActionFeedback) _then; + + /// Create a copy of SubtitleActionFeedback + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({Object? kind = null, Object? cueCount = freezed}) { + return _then( + SubtitleActionFeedback( + kind: null == kind + ? _self.kind + : kind // ignore: cast_nullable_to_non_nullable + as SubtitleActionKind, + cueCount: freezed == cueCount + ? _self.cueCount + : cueCount // ignore: cast_nullable_to_non_nullable + as int?, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [SubtitleActionFeedback]. +extension SubtitleActionFeedbackPatterns on SubtitleActionFeedback { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_SubtitleActionFeedback value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _SubtitleActionFeedback() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_SubtitleActionFeedback value) $default, + ) { + final _that = this; + switch (_that) { + case _SubtitleActionFeedback(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_SubtitleActionFeedback value)? $default, + ) { + final _that = this; + switch (_that) { + case _SubtitleActionFeedback() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function(SubtitleActionKind kind, int? cueCount)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _SubtitleActionFeedback() when $default != null: + return $default(_that.kind, _that.cueCount); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function(SubtitleActionKind kind, int? cueCount) $default, + ) { + final _that = this; + switch (_that) { + case _SubtitleActionFeedback(): + return $default(_that.kind, _that.cueCount); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function(SubtitleActionKind kind, int? cueCount)? $default, + ) { + final _that = this; + switch (_that) { + case _SubtitleActionFeedback() when $default != null: + return $default(_that.kind, _that.cueCount); + case _: + return null; + } + } +} + +/// @nodoc + +class _SubtitleActionFeedback implements SubtitleActionFeedback { + const _SubtitleActionFeedback({required this.kind, this.cueCount}); + + @override + final SubtitleActionKind kind; + @override + final int? cueCount; + + /// Create a copy of SubtitleActionFeedback + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$SubtitleActionFeedbackCopyWith<_SubtitleActionFeedback> get copyWith => + __$SubtitleActionFeedbackCopyWithImpl<_SubtitleActionFeedback>( + this, + _$identity, + ); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _SubtitleActionFeedback && + (identical(other.kind, kind) || other.kind == kind) && + (identical(other.cueCount, cueCount) || + other.cueCount == cueCount)); + } + + @override + int get hashCode { + return Object.hash(runtimeType, kind, cueCount); + } + + @override + String toString() { + return 'SubtitleActionFeedback(kind: $kind, cueCount: $cueCount)'; + } +} + +/// @nodoc +abstract mixin class _$SubtitleActionFeedbackCopyWith<$Res> + implements $SubtitleActionFeedbackCopyWith<$Res> { + factory _$SubtitleActionFeedbackCopyWith( + _SubtitleActionFeedback value, + $Res Function(_SubtitleActionFeedback) _then, + ) = __$SubtitleActionFeedbackCopyWithImpl; + @override + @useResult + $Res call({SubtitleActionKind kind, int? cueCount}); +} + +/// @nodoc +class __$SubtitleActionFeedbackCopyWithImpl<$Res> + implements _$SubtitleActionFeedbackCopyWith<$Res> { + __$SubtitleActionFeedbackCopyWithImpl(this._self, this._then); + + final _SubtitleActionFeedback _self; + final $Res Function(_SubtitleActionFeedback) _then; + + /// Create a copy of SubtitleActionFeedback + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({Object? kind = null, Object? cueCount = freezed}) { + return _then( + _SubtitleActionFeedback( + kind: null == kind + ? _self.kind + : kind // ignore: cast_nullable_to_non_nullable + as SubtitleActionKind, + cueCount: freezed == cueCount + ? _self.cueCount + : cueCount // ignore: cast_nullable_to_non_nullable + as int?, + ), + ); + } +} + +/// @nodoc +mixin _$SubtitleActionException { + SubtitleActionKind get kind; + Object get cause; + + /// Create a copy of SubtitleActionException + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $SubtitleActionExceptionCopyWith get copyWith => + _$SubtitleActionExceptionCopyWithImpl( + this as SubtitleActionException, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as SubtitleActionException; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is SubtitleActionException && + (identical(other.kind, _this.kind) || other.kind == _this.kind) && + const DeepCollectionEquality().equals(other.cause, _this.cause)); + } + + @override + int get hashCode { + final _this = this as SubtitleActionException; + return Object.hash( + runtimeType, + _this.kind, + const DeepCollectionEquality().hash(_this.cause), + ); + } + + @override + String toString() { + final _this = this as SubtitleActionException; + return 'SubtitleActionException(kind: ${_this.kind}, cause: ${_this.cause})'; + } +} + +/// @nodoc +abstract mixin class $SubtitleActionExceptionCopyWith<$Res> { + factory $SubtitleActionExceptionCopyWith( + SubtitleActionException value, + $Res Function(SubtitleActionException) _then, + ) = _$SubtitleActionExceptionCopyWithImpl; + @useResult + $Res call({SubtitleActionKind kind, Object cause}); +} + +/// @nodoc +class _$SubtitleActionExceptionCopyWithImpl<$Res> + implements $SubtitleActionExceptionCopyWith<$Res> { + _$SubtitleActionExceptionCopyWithImpl(this._self, this._then); + + final SubtitleActionException _self; + final $Res Function(SubtitleActionException) _then; + + /// Create a copy of SubtitleActionException + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({Object? kind = null, Object? cause = null}) { + return _then( + SubtitleActionException( + null == kind + ? _self.kind + : kind // ignore: cast_nullable_to_non_nullable + as SubtitleActionKind, + null == cause ? _self.cause : cause, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [SubtitleActionException]. +extension SubtitleActionExceptionPatterns on SubtitleActionException { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_SubtitleActionException value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _SubtitleActionException() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_SubtitleActionException value) $default, + ) { + final _that = this; + switch (_that) { + case _SubtitleActionException(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_SubtitleActionException value)? $default, + ) { + final _that = this; + switch (_that) { + case _SubtitleActionException() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function(SubtitleActionKind kind, Object cause)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _SubtitleActionException() when $default != null: + return $default(_that.kind, _that.cause); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function(SubtitleActionKind kind, Object cause) $default, + ) { + final _that = this; + switch (_that) { + case _SubtitleActionException(): + return $default(_that.kind, _that.cause); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function(SubtitleActionKind kind, Object cause)? $default, + ) { + final _that = this; + switch (_that) { + case _SubtitleActionException() when $default != null: + return $default(_that.kind, _that.cause); + case _: + return null; + } + } +} + +/// @nodoc + +class _SubtitleActionException implements SubtitleActionException { + const _SubtitleActionException(this.kind, this.cause); + + @override + final SubtitleActionKind kind; + @override + final Object cause; + + /// Create a copy of SubtitleActionException + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$SubtitleActionExceptionCopyWith<_SubtitleActionException> get copyWith => + __$SubtitleActionExceptionCopyWithImpl<_SubtitleActionException>( + this, + _$identity, + ); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _SubtitleActionException && + (identical(other.kind, kind) || other.kind == kind) && + const DeepCollectionEquality().equals(other.cause, cause)); + } + + @override + int get hashCode { + return Object.hash( + runtimeType, + kind, + const DeepCollectionEquality().hash(cause), + ); + } + + @override + String toString() { + return 'SubtitleActionException(kind: $kind, cause: $cause)'; + } +} + +/// @nodoc +abstract mixin class _$SubtitleActionExceptionCopyWith<$Res> + implements $SubtitleActionExceptionCopyWith<$Res> { + factory _$SubtitleActionExceptionCopyWith( + _SubtitleActionException value, + $Res Function(_SubtitleActionException) _then, + ) = __$SubtitleActionExceptionCopyWithImpl; + @override + @useResult + $Res call({SubtitleActionKind kind, Object cause}); +} + +/// @nodoc +class __$SubtitleActionExceptionCopyWithImpl<$Res> + implements _$SubtitleActionExceptionCopyWith<$Res> { + __$SubtitleActionExceptionCopyWithImpl(this._self, this._then); + + final _SubtitleActionException _self; + final $Res Function(_SubtitleActionException) _then; + + /// Create a copy of SubtitleActionException + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({Object? kind = null, Object? cause = null}) { + return _then( + _SubtitleActionException( + null == kind + ? _self.kind + : kind // ignore: cast_nullable_to_non_nullable + as SubtitleActionKind, + null == cause ? _self.cause : cause, + ), + ); + } +} diff --git a/lib/features/media/subtitle_task_actions.g.dart b/lib/features/media/subtitle_task_actions.g.dart new file mode 100644 index 0000000..d986a17 --- /dev/null +++ b/lib/features/media/subtitle_task_actions.g.dart @@ -0,0 +1,138 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'subtitle_task_actions.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning +/// One operation state is shared by the compact card and its details dialog. + +@ProviderFor(SubtitleTaskActions) +final subtitleTaskActionsProvider = SubtitleTaskActionsFamily._(); + +/// One operation state is shared by the compact card and its details dialog. +final class SubtitleTaskActionsProvider + extends + $NotifierProvider< + SubtitleTaskActions, + AsyncValue + > { + /// One operation state is shared by the compact card and its details dialog. + SubtitleTaskActionsProvider._({ + required SubtitleTaskActionsFamily super.from, + required (EditorTimelineSession, String) super.argument, + }) : super( + retry: null, + name: r'subtitleTaskActionsProvider', + isAutoDispose: true, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$subtitleTaskActionsHash(); + + @override + String toString() { + return r'subtitleTaskActionsProvider' + '' + '$argument'; + } + + @$internal + @override + SubtitleTaskActions create() => SubtitleTaskActions(); + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(AsyncValue value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider>( + value, + ), + ); + } + + @override + bool operator ==(Object other) { + return other is SubtitleTaskActionsProvider && other.argument == argument; + } + + @override + int get hashCode { + return argument.hashCode; + } +} + +String _$subtitleTaskActionsHash() => + r'6308d7270d9a363b70bb03ae8dbbbbc83d2a71b7'; + +/// One operation state is shared by the compact card and its details dialog. + +final class SubtitleTaskActionsFamily extends $Family + with + $ClassFamilyOverride< + SubtitleTaskActions, + AsyncValue, + AsyncValue, + AsyncValue, + (EditorTimelineSession, String) + > { + SubtitleTaskActionsFamily._() + : super( + retry: null, + name: r'subtitleTaskActionsProvider', + dependencies: null, + $allTransitiveDependencies: null, + isAutoDispose: true, + ); + + /// One operation state is shared by the compact card and its details dialog. + + SubtitleTaskActionsProvider call( + EditorTimelineSession session, + String jobId, + ) => SubtitleTaskActionsProvider._(argument: (session, jobId), from: this); + + @override + String toString() => r'subtitleTaskActionsProvider'; +} + +/// One operation state is shared by the compact card and its details dialog. + +abstract class _$SubtitleTaskActions + extends $Notifier> { + late final _$args = ref.$arg as (EditorTimelineSession, String); + EditorTimelineSession get session => _$args.$1; + String get jobId => _$args.$2; + + AsyncValue build( + EditorTimelineSession session, + String jobId, + ); + @$mustCallSuper + @override + WhenComplete runBuild() { + final ref = + this.ref + as $Ref< + AsyncValue, + AsyncValue + >; + final element = + ref.element + as $ClassProviderElement< + AnyNotifier< + AsyncValue, + AsyncValue + >, + AsyncValue, + Object?, + Object? + >; + return element.handleCreate(ref, () => build(_$args.$1, _$args.$2)); + } +} diff --git a/lib/features/media/transcription_dialog.dart b/lib/features/media/transcription_dialog.dart new file mode 100644 index 0000000..dcbdede --- /dev/null +++ b/lib/features/media/transcription_dialog.dart @@ -0,0 +1,353 @@ +import 'package:cutdex/l10n/l10n.dart'; + +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/runtime/processing_contracts.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../integrations/runtime/processing_resource_repository.dart'; + +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex_ui/widgets.dart'; + +import '../../shared/widgets/confirm_resource_download_cancel.dart'; +import '../../shared/widgets/processing_resource_download_dialog.dart'; +import '../../workspace/timeline_session.dart'; + +import 'processing_targets.dart'; +import 'subtitle_download.dart'; +export 'processing_targets.dart'; + +class TranscriptionDialog extends ConsumerStatefulWidget { + const TranscriptionDialog({ + super.key, + required this.session, + this.asset, + this.target, + }) : assert(asset == null || target == null); + const TranscriptionDialog.forCurrentTask({ + super.key, + required this.session, + this.asset, + this.target, + }) : assert(asset == null || target == null); + final EditorTimelineSession session; + final AssetDocument? asset; + final TranscriptionClipTarget? target; + @override + ConsumerState createState() => + _TranscriptionDialogState(); +} + +class _TranscriptionDialogState extends ConsumerState { + String _translationSource = 'auto'; + String _translationTarget = 'none'; + bool _closing = false; + late final VoidCallback _release; + SubtitleStartProvider get _startProvider => + subtitleStartProvider(widget.session); + SubtitleDownloadState get _download { + final global = ref.read(subtitleDownloadProvider); + final local = ref.read(_startProvider); + if (identical(global.request?.session, widget.session) && global.running) { + return global; + } + return local is SubtitleIdle ? global : local; + } + + bool get _ownsDownload => + identical(_download.request?.session, widget.session); + bool get _installingResource => + _ownsDownload && _download is SubtitleDownloading; + bool get _picking => _ownsDownload && _download is SubtitleStarting; + bool get _resourcePaused => _ownsDownload + ? switch (_download) { + SubtitleDownloading(:final paused) => paused, + _ => false, + } + : false; + double? get _resourceProgress => _ownsDownload + ? switch (_download) { + SubtitleDownloading(:final progress) => progress, + _ => null, + } + : null; + ProcessingCapability get _resourceStage => _ownsDownload + ? switch (_download) { + SubtitleDownloading(:final stage) => stage, + _ => ProcessingCapability.transcription, + } + : ProcessingCapability.transcription; + ProcessingResourceRepository? get _resourceRepository => _ownsDownload + ? switch (_download) { + SubtitleDownloading(:final repository) => repository, + _ => null, + } + : null; + TranscriptionClipTarget? get _target => + _installingResource ? _download.request?.target : widget.target; + AssetDocument? get _asset => + _installingResource ? _download.request?.asset : widget.asset; + String? get _mediaId => _target?.mediaId ?? _asset?.id; + String? get _error => !_ownsDownload + ? null + : switch (_download) { + SubtitleFailed(:final failure) => switch (failure) { + SubtitleStartFailure.start => context.l10n.startTranscriptionFailed, + SubtitleStartFailure.download => + context.l10n.processingResourceDownloadFailed, + SubtitleStartFailure.engine => + context.l10n.subtitleEngineUnavailable, + }, + _ => null, + }; + + @override + void initState() { + super.initState(); + _release = widget.session.retainViews(); + if (_ownsDownload && _download.running) { + _translationSource = _download.request!.language; + _translationTarget = _download.request!.targetLanguage; + } + } + + @override + void dispose() { + _release(); + super.dispose(); + } + + void _dismissDialog() { + if (!mounted) return; + final route = ModalRoute.of(context); + if (route == null) return; + final navigator = Navigator.of(context); + if (route.isCurrent) { + navigator.pop(); + } else { + navigator.removeRoute(route); + } + } + + SubtitleRequest _request() => SubtitleRequest( + session: widget.session, + sequence: _target?.sequence ?? widget.session.activeSequenceId, + target: _target, + asset: _asset, + language: _translationSource, + targetLanguage: _translationTarget, + ); + Future _start() => ref.read(_startProvider.notifier).start(_request()); + Future _downloadResourceAndStart() { + ref.read(_startProvider.notifier).reset(); + return ref + .read(subtitleDownloadProvider.notifier) + .start(_request(), download: true); + } + + void _toggleResourceDownload() => + ref.read(subtitleDownloadProvider.notifier).togglePause(); + void _cancelResourceDownload() => + ref.read(subtitleDownloadProvider.notifier).cancel(); + + String _translationLanguageLabel(String code) => + context.l10n.subtitleLanguageName(code); + + Widget _translationLanguageMenu({ + required String label, + required String value, + required String other, + required ValueChanged onChanged, + bool source = false, + bool enabled = true, + }) => AppField( + label: label, + child: AppSelect( + emptyLabel: context.l10n.noMatchingOptions, + label: label, + value: value, + searchable: true, + searchHint: context.l10n.searchOptions(label), + onChanged: enabled ? onChanged : null, + options: [ + if (source) ...[ + AppSelectOption('auto', context.l10n.autoDetect), + ] else + AppSelectOption('none', context.l10n.noTranslation), + for (final code in [ + 'zh', + 'en', + 'ja', + 'ko', + if (source) 'yue', + ...m2m100LanguageNames.keys.where( + (code) => !const {'zh', 'en', 'ja', 'ko'}.contains(code), + ), + ]) + AppSelectOption( + code, + _translationLanguageLabel(code), + enabled: code != other, + searchTerms: [ + code, + ?subtitleNativeLanguageNames[code], + ?m2m100LanguageNames[code], + ], + ), + ], + ), + ); + + Widget _buildModelDownloadDialog() { + final packages = + _resourceRepository?.catalog ?? defaultProcessingResourceCatalog; + final service = widget.session.transcriptions; + final downloadBytes = packages + .where( + (package) => + ProcessingResourceRepository.subtitleCapabilities.contains( + package.capability, + ) && + !(package.capability == ProcessingCapability.transcription && + service?.recognitionAvailable == true) && + !(package.capability == ProcessingCapability.translation && + service?.translationAvailable == true), + ) + .fold(0, (total, package) => total + package.bytes); + final totalBytes = packages + .where( + (package) => ProcessingResourceRepository.subtitleCapabilities + .contains(package.capability), + ) + .fold(0, (total, package) => total + package.bytes); + final progressTotal = _resourceRepository?.subtitleTotalBytes ?? totalBytes; + final downloadedBytes = + _resourceRepository?.subtitleDownloadedBytes ?? + ((_resourceProgress ?? 0) * progressTotal).round(); + return ProcessingResourceDownloadDialog( + title: context.l10n.subtitleResourceDownloadTask, + description: context.l10n.subtitleResourcesRequired, + resourceName: _resourceStage == ProcessingCapability.transcription + ? context.l10n.speechResourceStage + : context.l10n.translationResourceStage, + downloadSize: context.l10n.subtitleResourcesDownloadSize( + formatResourceBytes(downloadBytes), + ), + downloading: _installingResource, + paused: _resourcePaused, + downloadedBytes: downloadedBytes, + totalBytes: progressTotal, + bytesPerSecond: _resourceRepository?.subtitleDownloadBytesPerSecond ?? 0, + error: _error, + downloadButtonKey: const Key('download-transcription-resource'), + pauseButtonKey: const Key('download-transcription-resource'), + backgroundButtonKey: const Key('background-transcription-resource'), + onCancel: () async { + if (_installingResource && + !await confirmResourceDownloadCancellation(context)) { + return; + } + if (!mounted) return; + _cancelResourceDownload(); + _dismissDialog(); + }, + onDownload: _downloadResourceAndStart, + onTogglePause: _toggleResourceDownload, + onBackground: _dismissDialog, + ); + } + + @override + Widget build(BuildContext context) { + ref.watch(subtitleDownloadProvider); + ref.watch(_startProvider); + void handleResult(SubtitleDownloadState next) { + if (_closing || !identical(next.request?.session, widget.session)) return; + if (next is SubtitleStarted || next is SubtitleCancelled) { + _closing = true; + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted) return; + final messenger = ScaffoldMessenger.maybeOf(context); + final message = context.l10n.subtitleTaskStarted; + _dismissDialog(); + if (next is SubtitleStarted) { + messenger?.showSnackBar(SnackBar(content: Text(message))); + } + }); + } + } + + ref.listen(subtitleDownloadProvider, (_, next) => handleResult(next)); + ref.listen(_startProvider, (_, next) => handleResult(next)); + return ListenableBuilder( + listenable: widget.session, + builder: (context, _) { + final service = widget.session.transcriptions; + if (service?.recognitionAvailable != true || + service?.translationAvailable != true || + _installingResource) { + return _buildModelDownloadDialog(); + } + final busy = + (service?.tasks.any((task) => !task.terminal) ?? false) || + (service?.translationTasks.any((task) => !task.terminal) ?? false); + return AppDialog( + title: _target == null + ? context.l10n.transcribe + : context.l10n.generateCaptions, + withShadow: true, + width: 560, + actions: [ + if (_mediaId != null && service != null) + FilledButton( + onPressed: busy || _picking || !widget.session.acceptsEdits + ? null + : _start, + child: Text(context.l10n.generateCaptions), + ), + ], + child: SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + _translationLanguageMenu( + label: context.l10n.sourceLanguage, + value: _translationSource, + other: _translationTarget, + source: true, + enabled: !busy && !_picking, + onChanged: (value) => + setState(() => _translationSource = value), + ), + const SizedBox(height: AppSpacing.compact), + _translationLanguageMenu( + label: context.l10n.translationLanguage, + value: _translationTarget, + other: _translationSource, + enabled: + service?.translationAvailable == true && + !busy && + !_picking, + onChanged: (value) => + setState(() => _translationTarget = value), + ), + if (service?.translationAvailable != true) + Padding( + padding: const EdgeInsets.only(top: AppSpacing.small), + child: Text(context.l10n.translationNotConfigured), + ), + if (_error != null) + Padding( + padding: const EdgeInsets.only(top: AppSpacing.compact), + child: Text(_error!), + ), + ], + ), + ), + ); + }, + ); + } +} diff --git a/lib/features/media/unavailable_media_placeholder.dart b/lib/features/media/unavailable_media_placeholder.dart new file mode 100644 index 0000000..4db98b2 --- /dev/null +++ b/lib/features/media/unavailable_media_placeholder.dart @@ -0,0 +1,58 @@ +import 'package:cutdex/l10n/l10n.dart'; +import 'package:flutter/material.dart'; + +import 'package:cutdex_ui/theme.dart'; + +import '../../workspace/media_availability.dart'; + +class UnavailableMediaPlaceholder extends StatelessWidget { + const UnavailableMediaPlaceholder({ + super.key, + required this.availability, + this.showLabel = true, + this.isPreview = false, + }); + final MediaAvailability availability; + final bool showLabel; + final bool isPreview; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final label = availability == MediaAvailability.missing + ? context.l10n.mediaMissing + : context.l10n.mediaUnavailable; + // Project covers share the canvas background, including missing media. + return ColoredBox( + color: isPreview + ? Colors.transparent + : AppSurfaces.of(context).previewBackground, + child: Center( + child: FittedBox( + fit: BoxFit.scaleDown, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.broken_image_outlined, + size: isPreview ? 32 : 24, + color: theme.colorScheme.error, + ), + if (showLabel) ...[ + const SizedBox(height: AppSpacing.gap), + Text( + label, + style: + (isPreview + ? theme.textTheme.bodyMedium + : theme.textTheme.bodySmall) + ?.copyWith(color: theme.colorScheme.error), + ), + ], + ], + ), + ), + ), + ); + } +} diff --git a/lib/features/media/visual_asset_tile.dart b/lib/features/media/visual_asset_tile.dart new file mode 100644 index 0000000..39cac85 --- /dev/null +++ b/lib/features/media/visual_asset_tile.dart @@ -0,0 +1,53 @@ +import 'package:cutdex_sdk/project.dart'; +import 'package:flutter/material.dart'; + +import 'media_asset_cover.dart'; + +import 'package:cutdex_ui/theme.dart'; + +class VisualAssetTile extends StatelessWidget { + const VisualAssetTile({super.key, required this.asset, this.showName = true}); + final AssetDocument asset; + final bool showName; + + @override + Widget build(BuildContext context) { + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + AspectRatio( + key: ValueKey('visual-cover-${asset.id}'), + aspectRatio: 16 / 9, + child: ColoredBox( + color: AppSurfaces.of(context).previewBackground, + child: MediaAssetCover( + asset: asset, + fallback: Center( + child: Icon( + asset.metadata['kind'] == 'image' + ? Icons.image_outlined + : Icons.movie_outlined, + size: AppIconSize.emptyState, + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + ), + ), + ), + if (showName) ...[ + const SizedBox(height: AppSpacing.small), + Tooltip( + message: asset.name, + child: Text( + asset.name, + key: ValueKey('visual-name-${asset.id}'), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: Theme.of(context).textTheme.bodySmall, + ), + ), + ], + ], + ); + } +} diff --git a/lib/features/preview/fullscreen_playback_bar.dart b/lib/features/preview/fullscreen_playback_bar.dart new file mode 100644 index 0000000..6dd39f8 --- /dev/null +++ b/lib/features/preview/fullscreen_playback_bar.dart @@ -0,0 +1,239 @@ +import 'dart:async'; + +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter/material.dart'; + +import '../../l10n/l10n.dart'; + +import 'package:cutdex_ui/theme.dart'; + +class FullscreenPlaybackBar extends StatefulWidget { + const FullscreenPlaybackBar({ + super.key, + required this.positionTick, + required this.durationTick, + required this.frameTick, + required this.playing, + required this.onPlayPause, + required this.onSeek, + required this.onExit, + required this.onScrubStart, + required this.onScrubUpdate, + required this.onScrubEnd, + }); + + final int positionTick; + final int durationTick; + final int frameTick; + final bool playing; + final VoidCallback? onPlayPause; + final ValueChanged? onSeek; + final VoidCallback? onExit; + final VoidCallback? onScrubStart; + final ValueChanged? onScrubUpdate; + final ValueChanged? onScrubEnd; + + @override + State createState() => _FullscreenPlaybackBarState(); +} + +class _FullscreenPlaybackBarState extends State { + double? _dragPosition; + + int get _position => (_dragPosition?.round() ?? widget.positionTick).clamp( + 0, + widget.durationTick, + ); + + void _step(int direction) { + final tick = (_position ~/ widget.frameTick + direction) * widget.frameTick; + widget.onSeek?.call(tick.clamp(0, widget.durationTick)); + } + + @override + void dispose() { + if (_dragPosition case final value?) { + final end = widget.onScrubEnd; + scheduleMicrotask(() => end?.call(value.round())); + } + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final enabled = widget.onSeek != null && widget.durationTick > 0; + final colors = Theme.of(context).colorScheme; + return SizedBox( + key: const Key('fullscreen-playback-bar'), + height: 76, + child: Padding( + padding: const EdgeInsets.fromLTRB( + AppSpacing.compact, + AppSpacing.tiny, + AppSpacing.compact, + AppSpacing.small, + ), + child: Column( + children: [ + SizedBox( + height: 36, + child: Stack( + alignment: Alignment.center, + children: [ + Align( + alignment: Alignment.centerLeft, + child: _button( + context, + Icons.first_page, + context.l10n.previewGoToStart, + enabled ? () => widget.onSeek!(0) : null, + ), + ), + Row( + mainAxisSize: MainAxisSize.min, + children: [ + _button( + context, + Icons.skip_previous, + context.l10n.previewPreviousFrame, + enabled && _position > 0 ? () => _step(-1) : null, + ), + _button( + context, + widget.playing ? Icons.pause : Icons.play_arrow, + widget.playing ? context.l10n.pause : context.l10n.play, + widget.onPlayPause, + size: 32, + ), + _button( + context, + Icons.skip_next, + context.l10n.previewNextFrame, + enabled && _position < widget.durationTick + ? () => _step(1) + : null, + ), + ], + ), + Align( + alignment: Alignment.centerRight, + child: _button( + context, + Icons.fullscreen_exit, + context.l10n.exitPreviewFullscreen, + widget.onExit, + key: const Key('preview-fullscreen'), + ), + ), + ], + ), + ), + Expanded( + child: Row( + children: [ + _timeLabel(context, _time(_position)), + Expanded( + child: SliderTheme( + data: SliderTheme.of(context).copyWith( + trackHeight: 4, + activeTrackColor: colors.outline, + inactiveTrackColor: colors.surfaceContainerHighest, + thumbColor: colors.onSurface, + overlayColor: colors.onSurface.withValues(alpha: .12), + thumbShape: const RoundSliderThumbShape( + enabledThumbRadius: 5, + disabledThumbRadius: 5, + elevation: 0, + pressedElevation: 0, + ), + overlayShape: const RoundSliderOverlayShape( + overlayRadius: 10, + ), + trackShape: const RoundedRectSliderTrackShape(), + ), + child: Slider( + key: const Key('fullscreen-progress'), + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.small, + ), + value: _position.toDouble(), + max: widget.durationTick > 0 + ? widget.durationTick.toDouble() + : 1, + onChangeStart: enabled + ? (value) { + setState(() => _dragPosition = value); + widget.onScrubStart?.call(); + } + : null, + onChanged: enabled + ? (value) { + setState(() => _dragPosition = value); + widget.onScrubUpdate?.call(value.round()); + } + : null, + onChangeEnd: enabled + ? (value) { + setState(() => _dragPosition = null); + widget.onScrubEnd?.call(value.round()); + } + : null, + ), + ), + ), + _timeLabel( + context, + '-${_time(widget.durationTick - _position)}', + ), + ], + ), + ), + ], + ), + ), + ); + } + + Widget _button( + BuildContext context, + IconData icon, + String tooltip, + VoidCallback? onPressed, { + double size = 20, + Key? key, + }) { + final colors = Theme.of(context).colorScheme; + return IconButton( + key: key, + tooltip: tooltip, + onPressed: onPressed, + padding: EdgeInsets.zero, + constraints: const BoxConstraints.tightFor(width: 36, height: 36), + visualDensity: VisualDensity.compact, + color: colors.onSurface, + disabledColor: colors.onSurface.withValues(alpha: .38), + icon: Icon(icon, size: size), + ); + } + + Widget _timeLabel(BuildContext context, String value) => SizedBox( + width: 62, + child: Text( + value, + textAlign: TextAlign.center, + maxLines: 1, + style: Theme.of(context).textTheme.bodyMedium?.copyWith( + color: Theme.of(context).colorScheme.onSurface, + fontFeatures: [const FontFeature.tabularFigures()], + ), + ), + ); + + String _time(int tick) { + final seconds = tick ~/ TimelineClock.ticksPerSecond; + final minutes = seconds ~/ 60; + final tail = '${seconds % 60}'.padLeft(2, '0'); + if (minutes < 60) return '${minutes.toString().padLeft(2, '0')}:$tail'; + return '${minutes ~/ 60}:${(minutes % 60).toString().padLeft(2, '0')}:$tail'; + } +} diff --git a/lib/features/preview/preview_fullscreen.dart b/lib/features/preview/preview_fullscreen.dart new file mode 100644 index 0000000..9634467 --- /dev/null +++ b/lib/features/preview/preview_fullscreen.dart @@ -0,0 +1,167 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex_native/cutdex_native.dart'; + +/// Moves the existing preview into the root overlay, retaining its native view. +class PreviewFullscreenHost extends StatefulWidget { + const PreviewFullscreenHost({super.key, required this.child}); + final Widget child; + + @override + State createState() => _PreviewFullscreenHostState(); +} + +class _PreviewFullscreenHostState extends State { + late final _nativeSession = NativeFullscreenSession( + onExit: () { + if (!mounted) return; + _overlay.hide(); + setState(() => _fullscreen = false); + }, + ); + final _overlay = OverlayPortalController(); + final _contentKey = GlobalKey(); + bool _fullscreen = false; + bool _busy = false; + bool get _native => !kIsWeb && defaultTargetPlatform == TargetPlatform.macOS; + + Future _toggle() async { + if (_busy) return; + final entering = !_fullscreen; + setState(() { + _busy = true; + _fullscreen = entering; + }); + if (entering) { + _overlay.show(); + if (_native) { + _nativeSession.attach(); + } + } else { + _overlay.hide(); + } + try { + if (_native) await _nativeSession.setFullscreen(entering); + } catch (error) { + if (mounted) { + _overlay.hide(); + setState(() => _fullscreen = false); + debugPrint('Could not change preview fullscreen: $error'); + } + } finally { + if (mounted) setState(() => _busy = false); + } + } + + @override + void dispose() { + _nativeSession.dispose(exitFullscreen: _native && _fullscreen); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final fullscreenTheme = AppTheme.previewFullscreenTheme; + final previewBackground = fullscreenTheme + .extension()! + .previewBackground; + final content = PreviewFullscreenScope( + key: _contentKey, + fullscreen: _fullscreen, + toggle: _busy ? null : _toggle, + child: widget.child, + ); + return OverlayPortal( + overlayLocation: OverlayChildLocation.rootOverlay, + controller: _overlay, + overlayChildBuilder: (context) => Positioned.fill( + child: Theme( + data: fullscreenTheme, + child: Material( + color: previewBackground, + child: CallbackShortcuts( + bindings: { + const SingleActivator(LogicalKeyboardKey.escape): () { + if (_fullscreen && !_busy) unawaited(_toggle()); + }, + }, + child: Focus(autofocus: true, child: content), + ), + ), + ), + ), + child: _fullscreen ? const SizedBox.expand() : content, + ); + } +} + +class PreviewFullscreenScope extends InheritedWidget { + const PreviewFullscreenScope({ + super.key, + required this.fullscreen, + required this.toggle, + required super.child, + }); + final bool fullscreen; + final VoidCallback? toggle; + + static PreviewFullscreenScope? of(BuildContext context) => + context.dependOnInheritedWidgetOfExactType(); + + @override + bool updateShouldNotify(PreviewFullscreenScope oldWidget) => + fullscreen != oldWidget.fullscreen || toggle != oldWidget.toggle; +} + +/// Keeps the canvas mounted while the toolbar floats over fullscreen playback. +class PreviewFullscreenLayout extends StatelessWidget { + const PreviewFullscreenLayout({ + super.key, + required this.canvas, + required this.toolbar, + }); + final Widget canvas; + final Widget toolbar; + + @override + Widget build(BuildContext context) { + final fullscreen = PreviewFullscreenScope.of(context)?.fullscreen == true; + return Stack( + fit: StackFit.expand, + children: [ + Positioned.fill( + bottom: fullscreen ? 0 : AppControlSize.panelHeader, + child: canvas, + ), + Align( + alignment: Alignment.bottomCenter, + child: Container( + margin: fullscreen + ? const EdgeInsets.only( + left: AppSpacing.extraLarge, + right: AppSpacing.extraLarge, + bottom: AppSpacing.emptyState, + ) + : EdgeInsets.zero, + constraints: BoxConstraints( + maxWidth: fullscreen ? 560 : double.infinity, + ), + decoration: fullscreen + ? BoxDecoration( + color: Theme.of(context).colorScheme.surfaceContainer + .withValues(alpha: .93), + borderRadius: BorderRadius.circular(AppRadius.large), + ) + : null, + child: toolbar, + ), + ), + ], + ); + } +} diff --git a/lib/features/preview/preview_messages.dart b/lib/features/preview/preview_messages.dart new file mode 100644 index 0000000..3c95f1e --- /dev/null +++ b/lib/features/preview/preview_messages.dart @@ -0,0 +1,34 @@ +import 'package:cutdex/l10n/l10n.dart'; + +import '../../errors/app_failure.dart'; + +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/runtime.dart'; + +String previewErrorMessage(Object e, AppLocalizations l10n) => switch (e) { + AppException(:final failure) => l10n.failureMessage(failure), + EditorMediaException(code: EditorMediaError.invalidTrack) => + l10n.previewInvalidTrack, + EditorMediaException(code: EditorMediaError.unsupportedColorInterpretation) => + l10n.colorBackendUnsupported, + ExecutionException(code: ExecutionErrorCode.missingMedia) => + l10n.previewMissingBinding, + ExecutionException() => l10n.previewUnsupportedEdits, + RuntimeException(code: 'unsupported') => l10n.previewUnsupportedConfiguration, + RuntimeException(code: 'invalidArgument', :final message) + when message.contains('HDR to SDR requires explicit tone mapping') => + l10n.previewHdrUnsupported, + RuntimeException(code: 'invalidArgument', :final message) + when message.contains('Audio source interval exceeds track') => + l10n.previewAudioOutOfRange, + RuntimeException(code: 'invalidArgument', :final message) => + l10n.previewParameterError(message), + RuntimeException(code: 'resourceMissing') => l10n.previewResourceMissing, + RuntimeException(code: 'playback/failed', :final details) + when details['nativeDomain'] == 'AVFoundationErrorDomain' && + details['nativeCode'] == '-11841' => + l10n.previewInvalidComposition, + Error() => l10n.previewInvalidData, + String message => message, + _ => l10n.previewFailed, +}; diff --git a/lib/features/preview/preview_panel.dart b/lib/features/preview/preview_panel.dart new file mode 100644 index 0000000..e41ad62 --- /dev/null +++ b/lib/features/preview/preview_panel.dart @@ -0,0 +1,732 @@ +import '../../diagnostics/app_diagnostics.dart'; + +import 'dart:async'; + +import 'package:cutdex/features/properties/canvas_presets.dart'; +import 'package:cutdex/l10n/l10n.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/preview.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex_ui/widgets.dart'; + +import '../../workspace/media_availability.dart'; +import '../../workspace/preview_controller_registry.dart'; +import '../../workspace/preview_target.dart'; +import '../../workspace/timeline_provider.dart'; +import '../../workspace/timeline_session.dart'; +import '../media/audio_asset_tile.dart'; +import '../media/unavailable_media_placeholder.dart'; +import 'fullscreen_playback_bar.dart'; +import 'preview_fullscreen.dart'; +import 'preview_messages.dart'; + +export '../../workspace/preview_target.dart' show runtimeConnectionProvider; + +part 'preview_panel.g.dart'; + +/// The editor failed before a native preview session could be created. +final class EditorSessionStartupException implements Exception { + const EditorSessionStartupException(this.cause); + final Object cause; + @override + String toString() => 'Editor session startup failed: $cause'; +} + +@riverpod +FutureOr> editorPreview( + Ref ref, + String projectId, + String timelineId, +) { + final ids = (projectId, timelineId); + + final timelineState = ref.watch( + editorTimelineProvider(projectId, timelineId), + ); + if (timelineState case AsyncData(:final value)) { + return _preparePreview(ref, ids, value); + } + if (timelineState case AsyncError(:final error, :final stackTrace)) { + AppDiagnostics.failure( + 'preview', + 'editorStartup', + error, + stackTrace, + context: {'projectId': projectId, 'timelineId': timelineId}, + ); + Error.throwWithStackTrace(EditorSessionStartupException(error), stackTrace); + } + return _preparePreviewAfterTimeline(ref, ids); +} + +Future _preparePreviewAfterTimeline( + Ref ref, + (String, String) ids, +) async { + try { + final timeline = await ref.read( + editorTimelineProvider(ids.$1, ids.$2).future, + ); + return await _preparePreview(ref, ids, timeline); + } catch (error, stack) { + if (error is EditorSessionStartupException) rethrow; + AppDiagnostics.failure( + 'preview', + 'editorStartup', + error, + stack, + context: {'projectId': ids.$1, 'timelineId': ids.$2}, + ); + Error.throwWithStackTrace(EditorSessionStartupException(error), stack); + } +} + +FutureOr _preparePreview( + Ref ref, + (String, String) ids, + EditorTimelineSession timeline, +) { + final sequence = timeline.activeSequenceId; + if (sequence == null || timeline.sequenceDurationTicks(sequence) == 0) { + void startWhenContentExists() { + final active = timeline.activeSequenceId; + if (active != null && timeline.sequenceDurationTicks(active) > 0) { + unawaited( + ref + .read(previewControllerRegistryProvider) + .invalidate(ids) + .catchError((Object _) {}), + ); + ref.invalidateSelf(); + } + } + + timeline.addListener(startWhenContentExists); + ref.onDispose(() => timeline.removeListener(startWhenContentExists)); + return null; + } + try { + if (!ref.mounted) throw StateError('Editor closed'); + final result = ref + .read(previewControllerRegistryProvider) + .prepare(ids, timeline); + if (result case Future future) { + return future.catchError((Object error, StackTrace stack) { + AppDiagnostics.failure( + 'preview', + 'nativeStartup', + error, + stack, + context: {'projectId': ids.$1, 'timelineId': ids.$2}, + ); + Error.throwWithStackTrace(error, stack); + }); + } + return result; + } catch (error, stack) { + AppDiagnostics.failure( + 'preview', + 'nativeStartup', + error, + stack, + context: {'projectId': ids.$1, 'timelineId': ids.$2}, + ); + rethrow; + } +} + +class EditorPreviewPanel extends StatelessWidget { + const EditorPreviewPanel({ + super.key, + required this.projectId, + required this.timelineId, + }); + final String projectId; + final String timelineId; + + @override + Widget build(BuildContext context) => PreviewFullscreenHost( + child: _EditorPreviewContent(projectId: projectId, timelineId: timelineId), + ); +} + +class _EditorPreviewContent extends ConsumerWidget { + const _EditorPreviewContent({ + required this.projectId, + required this.timelineId, + }); + final String projectId; + final String timelineId; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final provider = editorPreviewProvider(projectId, timelineId); + final state = ref.watch(provider); + final controller = state.asData?.value; + Widget panel() { + final activeController = controller; + final showCanvas = + state.hasError || + (activeController != null && + (activeController.durationTick > 0 || + activeController.error != null)); + final overlayBuilder = + activeController != null && + PreviewFullscreenScope.of(context)?.fullscreen != true && + activeController.session != null && + activeController.error == null + ? (Rect rect) => ListenableBuilder( + listenable: activeController.positionChanges, + builder: (context, _) => Theme( + data: AppTheme.previewCanvasTheme, + child: + activeController.maskEditingElement != null || + activeController.obscureEditingElement != null + ? MaskInteractionOverlay( + controller: activeController, + canvasRect: rect, + obscure: activeController.obscureEditingElement != null, + ) + : PreviewInteractionOverlay( + onError: (_) => ScaffoldMessenger.maybeOf(context) + ?.showSnackBar( + SnackBar( + content: Text( + context.l10n.canvasTransformFailed, + ), + ), + ), + controller: activeController, + canvasRect: rect, + ), + ), + ) + : null; + return WorkspacePanel( + headerHeight: 0, + showHeaderDivider: false, + child: PreviewFullscreenLayout( + canvas: showCanvas + ? Padding( + padding: + PreviewFullscreenScope.of(context)?.fullscreen == true + ? EdgeInsets.zero + : AppSpacing.panelSection, + child: PreviewCanvas( + alignment: Alignment.center, + horizontalPadding: 0, + backgroundColor: AppSurfaces.of(context).previewBackground, + overlayBuilder: overlayBuilder, + aspectRatio: + (activeController?.canvas ?? ProjectCanvas.widescreen) + .aspectRatio, + child: Theme( + data: AppTheme.previewCanvasTheme, + child: Builder( + builder: (context) => state.when( + loading: () => const DelayedLoadingIndicator( + child: Center(child: CircularProgressIndicator()), + ), + error: (error, _) => Center( + child: SingleChildScrollView( + primary: false, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + error is EditorSessionStartupException + ? context.l10n.editorSessionStartFailed + : error is RuntimeException && + error.code == 'unsupported' + ? context.l10n.nativePreviewUnsupported + : context.l10n.previewStartFailed, + textAlign: TextAlign.center, + ), + TextButton( + onPressed: () { + if (error + is EditorSessionStartupException) { + ref.invalidate( + editorTimelineProvider( + projectId, + timelineId, + ), + ); + } else { + unawaited( + ref + .read( + previewControllerRegistryProvider, + ) + .invalidate(( + projectId, + timelineId, + )), + ); + ref.invalidate(provider); + } + }, + child: Text(context.l10n.retry), + ), + ], + ), + ), + ), + data: (preview) { + if (preview == null) { + return const SizedBox.expand( + key: Key('empty-preview-area'), + ); + } + return Stack( + fit: StackFit.expand, + children: [ + if (preview.session case final session?) + RuntimePreview(session: session), + ListenableBuilder( + listenable: preview.positionChanges, + builder: (context, _) { + final unavailable = + preview.unavailableAtPlayhead; + if (preview.error != null || + unavailable.isEmpty) { + return const SizedBox.shrink(); + } + return IgnorePointer( + child: Align( + alignment: Alignment.bottomCenter, + child: Padding( + padding: const EdgeInsets.all( + AppSpacing.medium, + ), + child: Text( + context.l10n.mediaOffline( + unavailable.join(', '), + ), + maxLines: 2, + overflow: TextOverflow.ellipsis, + textAlign: TextAlign.center, + ), + ), + ), + ); + }, + ), + if (preview.error != null || + preview.durationTick == 0) + ColoredBox( + color: AppSurfaces.of(context) + .previewBackground, + child: Center( + child: Padding( + padding: const EdgeInsets.all( + AppSpacing.medium, + ), + child: Text( + preview.error == null + ? context.l10n.noPreviewContent + : previewErrorMessage( + preview.error!, + context.l10n, + ), + textAlign: TextAlign.center, + ), + ), + ), + ), + ], + ); + }, + ), + ), + ), + ), + ) + : const SizedBox.expand(key: Key('empty-preview-area')), + toolbar: _PreviewToolbar(controller: controller), + ), + ); + } + + final target = ref.watch(previewTargetProvider(projectId, timelineId)); + final navigation = ref.watch( + previewNavigationProvider(projectId, timelineId), + ); + return CallbackShortcuts( + bindings: PreviewFullscreenScope.of(context)?.fullscreen == true + ? { + const SingleActivator(LogicalKeyboardKey.space): () => + target.togglePlayback?.call(), + } + : const {}, + child: switch (navigation) { + SourcePreviewTarget(:final asset, :final controller) + when controller != null => + _SourcePreviewPanel( + key: ValueKey(asset.id), + asset: asset, + projectId: projectId, + source: controller, + ), + _ => Builder( + builder: (context) { + target.togglePlayback = controller == null + ? null + : () => unawaited(controller.togglePlayback()); + return controller == null + ? panel() + : ListenableBuilder( + listenable: controller, + builder: (_, _) => panel(), + ); + }, + ), + }, + ); + } +} + +class _SourcePreviewPanel extends ConsumerWidget { + const _SourcePreviewPanel({ + super.key, + required this.asset, + required this.projectId, + required this.source, + }); + final AssetDocument asset; + final String projectId; + final SourcePreviewController source; + @override + Widget build(BuildContext context, WidgetRef ref) { + final availability = ref + .watch(mediaAvailabilityProvider(projectId, asset)) + .asData + ?.value; + return ListenableBuilder( + listenable: source, + builder: (context, _) { + // The availability probe can finish while a newly dropped file is + // still switching security-scoped leases. Once the runtime has opened + // the source, that live session is stronger evidence than the stale + // probe result and must not be covered by an unavailable placeholder. + final unavailable = + availability != null && + availability != MediaAvailability.available && + source.session == null && + source.image == null; + return CallbackShortcuts( + bindings: { + const SingleActivator(LogicalKeyboardKey.space): + source.togglePlayback, + }, + child: Focus( + autofocus: true, + child: WorkspacePanel( + title: asset.name, + showHeaderDivider: false, + headerHeight: + PreviewFullscreenScope.of(context)?.fullscreen == true + ? 0 + : AppControlSize.panelHeader, + child: PreviewFullscreenLayout( + canvas: Padding( + padding: + PreviewFullscreenScope.of(context)?.fullscreen == true + ? EdgeInsets.zero + : AppSpacing.panelSection, + child: PreviewCanvas( + alignment: Alignment.center, + horizontalPadding: 0, + backgroundColor: AppSurfaces.of(context).previewBackground, + aspectRatio: source.aspectRatio, + child: unavailable + ? UnavailableMediaPlaceholder( + availability: availability, + isPreview: true, + ) + : Theme( + data: AppTheme.previewCanvasTheme, + child: Builder( + builder: (context) { + if (source.error case final error?) { + return Center( + child: Padding( + padding: const EdgeInsets.all( + AppSpacing.medium, + ), + child: Text( + previewErrorMessage( + error, + context.l10n, + ), + textAlign: TextAlign.center, + ), + ), + ); + } + if (source.busy && + source.session == null && + source.image == null) { + return DelayedLoadingIndicator( + key: ValueKey(source), + child: const Center( + child: CircularProgressIndicator(), + ), + ); + } + if (source.image case final bytes?) { + return Image.memory( + bytes, + fit: BoxFit.contain, + ); + } + if (source.session case final session?) { + return Stack( + fit: StackFit.expand, + children: [ + RuntimePreview(session: session), + if (source.audioOnly) + IgnorePointer( + child: AudioAssetTile( + asset: asset, + showName: false, + ), + ), + ], + ); + } + return const SizedBox.shrink(); + }, + ), + ), + ), + ), + toolbar: _PreviewToolbar(controller: null, source: source), + ), + ), + ), + ); + }, + ); + } +} + +class _PreviewToolbar extends StatelessWidget { + const _PreviewToolbar({required this.controller, this.source}); + + final PreviewController? controller; + final SourcePreviewController? source; + + @override + Widget build(BuildContext context) { + final listenable = source == null && controller != null + ? Listenable.merge([controller!, controller!.positionChanges]) + : source; + if (listenable != null) { + return ListenableBuilder( + listenable: listenable, + builder: (context, _) => _build(context), + ); + } + return _build(context); + } + + Widget _build(BuildContext context) { + final preview = controller; + final playing = source?.playing ?? preview?.playing ?? false; + final frameDuration = + source?.frameDuration ?? + preview?.frameDuration ?? + TimelineFormat.fps30.frameDuration; + if (PreviewFullscreenScope.of(context) case final fullscreen? + when fullscreen.fullscreen) { + final duration = source?.durationTick ?? preview?.durationTick ?? 0; + final frameTick = TimelineClock.standard.toTicks(frameDuration); + final canPlay = source?.canPlay ?? preview?.canPlay ?? false; + Future seek(int requested) async { + final lastTick = duration > 0 + ? ((duration - 1) ~/ frameTick) * frameTick + : 0; + final tick = requested.clamp(0, lastTick); + try { + final time = CommandTime(tick, TimelineClock.ticksPerSecond); + if (source case final source?) { + await source.control(SourcePreviewAction.seek, at: time); + } else if (preview?.activeSequence() case final sequence?) { + await preview!.controlPreview( + sequence, + PreviewAction.seek, + at: time, + ); + } + } catch (error) { + if (context.mounted) { + ScaffoldMessenger.maybeOf(context)?.showSnackBar( + SnackBar(content: Text(previewErrorMessage(error, context.l10n))), + ); + } + } + } + + final sequence = preview?.activeSequence(); + final view = sequence == null ? null : preview!.viewForSequence(sequence); + void updateScrub(int tick) { + if (source case final source?) { + source.updateScrubbing(tick); + } else { + view?.seekTo(tick.clamp(0, duration)); + } + } + + return FullscreenPlaybackBar( + positionTick: source?.positionTick ?? preview?.positionTick ?? 0, + durationTick: duration, + frameTick: frameTick, + playing: playing, + onPlayPause: canPlay + ? (source?.togglePlayback ?? preview?.togglePlayback) + : null, + onSeek: canPlay && duration > 0 + ? (tick) => unawaited(seek(tick)) + : null, + onExit: fullscreen.toggle, + onScrubStart: source?.beginScrubbing ?? view?.beginScrubbing, + onScrubUpdate: updateScrub, + onScrubEnd: (tick) { + updateScrub(tick); + if (source case final source?) { + source.endScrubbing(); + } else { + view?.endScrubbing(); + } + }, + ); + } + return SizedBox( + key: const Key('preview-toolbar'), + height: AppControlSize.panelHeader, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: AppSpacing.compact), + child: Row( + children: [ + Expanded( + child: Text.rich( + TextSpan( + children: [ + TextSpan( + text: _time( + source?.positionTick ?? preview?.positionTick ?? 0, + frameDuration, + ), + style: TextStyle( + color: Theme.of(context).colorScheme.onSurface, + ), + ), + TextSpan( + text: + ' / ${_time(source?.durationTick ?? preview?.durationTick ?? 0, frameDuration)}', + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + ], + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: Theme.of(context).textTheme.bodySmall?.copyWith( + fontFeatures: [const FontFeature.tabularFigures()], + ), + ), + ), + IconButton( + tooltip: playing ? context.l10n.pause : context.l10n.play, + onPressed: source != null + ? (source!.canPlay ? source!.togglePlayback : null) + : preview != null && preview.canPlay + ? preview.togglePlayback + : null, + icon: Icon(playing ? Icons.pause : Icons.play_arrow), + ), + Expanded( + child: Align( + alignment: Alignment.centerRight, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (preview != null && + (preview.error != null || + preview.hasUnavailableMedia)) ...[ + IconButton( + tooltip: context.l10n.retryPreview, + onPressed: preview.busy ? null : preview.retry, + icon: const Icon(Icons.refresh), + ), + const SizedBox(width: AppSpacing.gap), + ], + if (source == null && + PreviewFullscreenScope.of(context)?.fullscreen != true) + Flexible( + child: AppSelect( + emptyLabel: context.l10n.noMatchingOptions, + label: context.l10n.canvasRatio, + outlined: false, + value: preview?.canvas ?? ProjectCanvas.widescreen, + onChanged: preview?.setCanvas, + options: [ + for (final entry + in ProjectCanvasPresets.values.entries) + AppSelectOption(entry.value, entry.key), + ], + ), + ), + if (PreviewFullscreenScope.of(context) + case final fullscreen?) + IconButton( + key: const Key('preview-fullscreen'), + tooltip: fullscreen.fullscreen + ? context.l10n.exitPreviewFullscreen + : context.l10n.previewFullscreen, + onPressed: + fullscreen.fullscreen || + source?.session != null || + source?.image != null || + preview?.session != null + ? fullscreen.toggle + : null, + icon: Icon( + fullscreen.fullscreen + ? Icons.fullscreen_exit + : Icons.fullscreen, + ), + ), + ], + ), + ), + ), + ], + ), + ), + ); + } + + String _time(int tick, RationalTime frameDuration) { + final frameTicks = TimelineClock.standard.toTicks(frameDuration); + final fps = (frameDuration.denominator / frameDuration.numerator).round(); + final frames = (tick < 0 ? 0 : tick) ~/ frameTicks; + final seconds = frames ~/ fps; + return [ + seconds ~/ 3600, + seconds ~/ 60 % 60, + seconds % 60, + frames % fps, + ].map((value) => value.toString().padLeft(2, '0')).join(':'); + } +} diff --git a/lib/features/preview/preview_panel.g.dart b/lib/features/preview/preview_panel.g.dart new file mode 100644 index 0000000..7272d68 --- /dev/null +++ b/lib/features/preview/preview_panel.g.dart @@ -0,0 +1,91 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'preview_panel.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(editorPreview) +final editorPreviewProvider = EditorPreviewFamily._(); + +final class EditorPreviewProvider + extends + $FunctionalProvider< + AsyncValue?>, + Raw?, + FutureOr?> + > + with + $FutureModifier?>, + $FutureProvider?> { + EditorPreviewProvider._({ + required EditorPreviewFamily super.from, + required (String, String) super.argument, + }) : super( + retry: null, + name: r'editorPreviewProvider', + isAutoDispose: true, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$editorPreviewHash(); + + @override + String toString() { + return r'editorPreviewProvider' + '' + '$argument'; + } + + @$internal + @override + $FutureProviderElement?> $createElement( + $ProviderPointer pointer, + ) => $FutureProviderElement(pointer); + + @override + FutureOr?> create(Ref ref) { + final argument = this.argument as (String, String); + return editorPreview(ref, argument.$1, argument.$2); + } + + @override + bool operator ==(Object other) { + return other is EditorPreviewProvider && other.argument == argument; + } + + @override + int get hashCode { + return argument.hashCode; + } +} + +String _$editorPreviewHash() => r'f612b965e1573a819af0e77f910a66021e937bfe'; + +final class EditorPreviewFamily extends $Family + with + $FunctionalFamilyOverride< + FutureOr?>, + (String, String) + > { + EditorPreviewFamily._() + : super( + retry: null, + name: r'editorPreviewProvider', + dependencies: null, + $allTransitiveDependencies: null, + isAutoDispose: true, + ); + + EditorPreviewProvider call(String projectId, String timelineId) => + EditorPreviewProvider._(argument: (projectId, timelineId), from: this); + + @override + String toString() => r'editorPreviewProvider'; +} diff --git a/lib/features/projects/conversation_sidebar.dart b/lib/features/projects/conversation_sidebar.dart new file mode 100644 index 0000000..f01b697 --- /dev/null +++ b/lib/features/projects/conversation_sidebar.dart @@ -0,0 +1,282 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; +import 'package:uuid/uuid.dart'; + +import '../../integrations/agent/conversation_repository.dart'; +import '../../workspace/project_state.dart'; +import '../../workspace/projects.dart'; +import '../assistant/agent_conversation_service.dart'; +import '../assistant/agent_composer_store.dart'; + +part 'conversation_sidebar.g.dart'; +part 'conversation_sidebar.freezed.dart'; + +@freezed +abstract class ConversationSnapshot with _$ConversationSnapshot { + const factory ConversationSnapshot({ + String? projectId, + @Default({}) Map> groups, + @Default([]) List trashed, + String? selectedId, + @Default(false) bool reloadFailed, + }) = _ConversationSnapshot; +} + +@freezed +abstract class ConversationWorkspaceKey with _$ConversationWorkspaceKey { + const factory ConversationWorkspaceKey({ + String? projectId, + required List projectIds, + }) = _ConversationWorkspaceKey; +} + +@freezed +abstract class ConversationSelectionState with _$ConversationSelectionState { + const factory ConversationSelectionState({ + String? selectedId, + required String draftKey, + @Default(false) bool initialized, + }) = _ConversationSelectionState; +} + +@Riverpod(keepAlive: true) +Future savedConversationSelection(Ref ref, String? projectId) async { + if (projectId == null) return null; + ref.watch(projectsProvider.select((value) => value.value?.activeProject?.id)); + final repository = await ref.watch(conversationRepositoryProvider.future); + return repository.selected(projectId); +} + +/// Keeps a draft or explicit selection stable while the list refreshes. +@Riverpod(keepAlive: true) +class ConversationSelection extends _$ConversationSelection { + String? _draftKey; + @override + ConversationSelectionState build(String? projectId) { + final composers = ref.read(agentComposerStoreProvider); + ref.onDispose(() { + if (_draftKey case final key?) composers.removeDraft(projectId, key); + }); + ref.watch( + projectsProvider.select((value) => value.value?.activeProject?.id), + ); + final saved = savedConversationSelectionProvider(projectId); + ref.listen(saved, (_, next) { + if (!state.initialized && + next.hasValue && + !next.isLoading && + !next.hasError) { + state = state.copyWith(selectedId: next.value, initialized: true); + } + }); + final selected = ref.read(saved); + final initialized = + selected.hasValue && !selected.isLoading && !selected.hasError; + _draftKey = const Uuid().v4(); + return ConversationSelectionState( + draftKey: _draftKey!, + selectedId: initialized ? selected.value : null, + initialized: initialized, + ); + } + + void newConversation() { + ref.read(agentComposerStoreProvider).removeDraft(projectId, state.draftKey); + _draftKey = const Uuid().v4(); + state = ConversationSelectionState(draftKey: _draftKey!, initialized: true); + } + + void select(String id) => + state = state.copyWith(selectedId: id, initialized: true); +} + +@Riverpod(keepAlive: true) +class ConversationSidebar extends _$ConversationSidebar { + int _revision = 0; + + @override + Future build() async { + await ref.watch( + projectsProvider.selectAsync( + (workspace) => ConversationWorkspaceKey( + projectId: workspace.activeProject?.id, + projectIds: [for (final project in workspace.recent) project.id], + ), + ), + ); + _revision++; + final workspace = ref.read(projectsProvider).requireValue; + return _load(workspace); + } + + Future _load(ProjectState workspace) async { + final projectId = workspace.activeProject?.id; + if (projectId == null && workspace.recent.isEmpty) { + return const ConversationSnapshot(); + } + final repository = await ref.read(conversationRepositoryProvider.future); + final lists = await Future.wait([ + for (final project in workspace.recent) repository.list(project.id), + ]); + return ConversationSnapshot( + projectId: projectId, + groups: { + for (var index = 0; index < workspace.recent.length; index++) + workspace.recent[index].id: List.unmodifiable(lists[index]), + }, + trashed: projectId == null + ? const [] + : List.unmodifiable(await repository.list(projectId, trash: true)), + selectedId: await ref.read( + savedConversationSelectionProvider(projectId).future, + ), + ); + } + + Future reload() async { + final revision = ++_revision; + final workspace = ref.read(projectsProvider).requireValue; + try { + final next = await _load(workspace); + if (!ref.mounted || + revision != _revision || + ref.read(projectsProvider).value?.activeProject?.id != + next.projectId) { + return; + } + state = AsyncData(next); + } catch (error, stack) { + if (ref.mounted && revision == _revision) { + state = state.value == null + ? AsyncError(error, stack) + : AsyncData(state.requireValue.copyWith(reloadFailed: true)); + } + } + } + + void newConversation() => ref + .read( + conversationSelectionProvider( + ref.read(projectsProvider).value?.activeProject?.id, + ).notifier, + ) + .newConversation(); + + Future rememberSelection(ConversationMetadata item) async { + final repository = await ref.read(conversationRepositoryProvider.future); + await repository.select(item.projectId, item.id); + if (ref.mounted) { + ref.invalidate(savedConversationSelectionProvider(item.projectId)); + } + } + + void activate(ConversationMetadata item) => ref + .read(conversationSelectionProvider(item.projectId).notifier) + .select(item.id); + + Future updateListing( + ConversationMetadata item, { + String? selectIfDraftKey, + }) async { + if (ref.read(projectsProvider).value?.activeProject?.id != item.projectId) { + return; + } + final current = state.value ?? await future; + if (!ref.mounted) return; + _revision++; + if (ref.read(projectsProvider).value?.activeProject?.id != item.projectId) { + return; + } + final selection = ref.read(conversationSelectionProvider(item.projectId)); + final selectCreated = + selectIfDraftKey != null && + selection.selectedId == null && + selection.draftKey == selectIfDraftKey; + state = AsyncData( + current.copyWith( + groups: { + ...current.groups, + item.projectId: [ + item, + ...?current.groups[item.projectId]?.where( + (existing) => existing.id != item.id, + ), + ], + }, + ), + ); + if (selectCreated) { + ref + .read(agentComposerStoreProvider) + .promoteDraft(item.projectId, selectIfDraftKey, item.id); + activate(item); + await rememberSelection(item); + } + } + + Future rename(ConversationMetadata item, String title) => + updateMetadata(item.copyWith(title: title)); + Future updateMetadata(ConversationMetadata item) async { + final repository = await ref.read(conversationRepositoryProvider.future); + await repository.update(item); + if (ref.mounted) await reload(); + } + + Future trash(ConversationMetadata item) async { + await ref + .read(agentConversationRegistryProvider) + .cancel(item.projectId, item.id); + final repository = await ref.read(conversationRepositoryProvider.future); + await repository.trash(item.projectId, item.id); + if (!ref.mounted) return; + _forgetRemovedSelection(item); + await reload(); + } + + Future restore(ConversationMetadata item) async { + final repository = await ref.read(conversationRepositoryProvider.future); + await repository.restore(item.projectId, item.id); + if (ref.mounted) { + ref.invalidate(savedConversationSelectionProvider(item.projectId)); + await reload(); + } + } + + Future delete(ConversationMetadata item) async { + await ref + .read(agentConversationRegistryProvider) + .cancel(item.projectId, item.id); + final repository = await ref.read(conversationRepositoryProvider.future); + await repository.deletePermanently(item.projectId, item.id); + if (!ref.mounted) return; + _forgetRemovedSelection(item); + ref + .read(agentComposerStoreProvider) + .removeConversation(item.projectId, item.id); + await reload(); + } + + void _forgetRemovedSelection(ConversationMetadata item) { + ref.invalidate(savedConversationSelectionProvider(item.projectId)); + if (ref.read(projectsProvider).value?.activeProject?.id == item.projectId && + ref.read(conversationSelectionProvider(item.projectId)).selectedId == + item.id) { + newConversation(); + } + } + + Future emptyTrash() async { + final items = state.value?.trashed ?? const []; + final repository = await ref.read(conversationRepositoryProvider.future); + for (final item in items) { + await repository.deletePermanently(item.projectId, item.id); + if (!ref.mounted) return; + _forgetRemovedSelection(item); + ref + .read(agentComposerStoreProvider) + .removeConversation(item.projectId, item.id); + } + if (ref.mounted) await reload(); + } +} diff --git a/lib/features/projects/conversation_sidebar.freezed.dart b/lib/features/projects/conversation_sidebar.freezed.dart new file mode 100644 index 0000000..2ff692d --- /dev/null +++ b/lib/features/projects/conversation_sidebar.freezed.dart @@ -0,0 +1,1168 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'conversation_sidebar.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +T _$identity(T value) => value; + +/// @nodoc +mixin _$ConversationSnapshot { + String? get projectId; + Map> get groups; + List get trashed; + String? get selectedId; + bool get reloadFailed; + + /// Create a copy of ConversationSnapshot + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $ConversationSnapshotCopyWith get copyWith => + _$ConversationSnapshotCopyWithImpl( + this as ConversationSnapshot, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as ConversationSnapshot; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is ConversationSnapshot && + (identical(other.projectId, _this.projectId) || + other.projectId == _this.projectId) && + const DeepCollectionEquality().equals(other.groups, _this.groups) && + const DeepCollectionEquality().equals( + other.trashed, + _this.trashed, + ) && + (identical(other.selectedId, _this.selectedId) || + other.selectedId == _this.selectedId) && + (identical(other.reloadFailed, _this.reloadFailed) || + other.reloadFailed == _this.reloadFailed)); + } + + @override + int get hashCode { + final _this = this as ConversationSnapshot; + return Object.hash( + runtimeType, + _this.projectId, + const DeepCollectionEquality().hash(_this.groups), + const DeepCollectionEquality().hash(_this.trashed), + _this.selectedId, + _this.reloadFailed, + ); + } + + @override + String toString() { + final _this = this as ConversationSnapshot; + return 'ConversationSnapshot(projectId: ${_this.projectId}, groups: ${_this.groups}, trashed: ${_this.trashed}, selectedId: ${_this.selectedId}, reloadFailed: ${_this.reloadFailed})'; + } +} + +/// @nodoc +abstract mixin class $ConversationSnapshotCopyWith<$Res> { + factory $ConversationSnapshotCopyWith( + ConversationSnapshot value, + $Res Function(ConversationSnapshot) _then, + ) = _$ConversationSnapshotCopyWithImpl; + @useResult + $Res call({ + String? projectId, + Map> groups, + List trashed, + String? selectedId, + bool reloadFailed, + }); +} + +/// @nodoc +class _$ConversationSnapshotCopyWithImpl<$Res> + implements $ConversationSnapshotCopyWith<$Res> { + _$ConversationSnapshotCopyWithImpl(this._self, this._then); + + final ConversationSnapshot _self; + final $Res Function(ConversationSnapshot) _then; + + /// Create a copy of ConversationSnapshot + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? projectId = freezed, + Object? groups = null, + Object? trashed = null, + Object? selectedId = freezed, + Object? reloadFailed = null, + }) { + return _then( + ConversationSnapshot( + projectId: freezed == projectId + ? _self.projectId + : projectId // ignore: cast_nullable_to_non_nullable + as String?, + groups: null == groups + ? _self.groups + : groups // ignore: cast_nullable_to_non_nullable + as Map>, + trashed: null == trashed + ? _self.trashed + : trashed // ignore: cast_nullable_to_non_nullable + as List, + selectedId: freezed == selectedId + ? _self.selectedId + : selectedId // ignore: cast_nullable_to_non_nullable + as String?, + reloadFailed: null == reloadFailed + ? _self.reloadFailed + : reloadFailed // ignore: cast_nullable_to_non_nullable + as bool, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [ConversationSnapshot]. +extension ConversationSnapshotPatterns on ConversationSnapshot { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_ConversationSnapshot value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ConversationSnapshot() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_ConversationSnapshot value) $default, + ) { + final _that = this; + switch (_that) { + case _ConversationSnapshot(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_ConversationSnapshot value)? $default, + ) { + final _that = this; + switch (_that) { + case _ConversationSnapshot() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + String? projectId, + Map> groups, + List trashed, + String? selectedId, + bool reloadFailed, + )? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ConversationSnapshot() when $default != null: + return $default( + _that.projectId, + _that.groups, + _that.trashed, + _that.selectedId, + _that.reloadFailed, + ); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function( + String? projectId, + Map> groups, + List trashed, + String? selectedId, + bool reloadFailed, + ) + $default, + ) { + final _that = this; + switch (_that) { + case _ConversationSnapshot(): + return $default( + _that.projectId, + _that.groups, + _that.trashed, + _that.selectedId, + _that.reloadFailed, + ); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + String? projectId, + Map> groups, + List trashed, + String? selectedId, + bool reloadFailed, + )? + $default, + ) { + final _that = this; + switch (_that) { + case _ConversationSnapshot() when $default != null: + return $default( + _that.projectId, + _that.groups, + _that.trashed, + _that.selectedId, + _that.reloadFailed, + ); + case _: + return null; + } + } +} + +/// @nodoc + +class _ConversationSnapshot implements ConversationSnapshot { + const _ConversationSnapshot({ + this.projectId, + Map> groups = const {}, + List trashed = const [], + this.selectedId, + this.reloadFailed = false, + }) : _groups = groups, + _trashed = trashed; + + @override + final String? projectId; + final Map> _groups; + @override + @JsonKey() + Map> get groups { + if (_groups is EqualUnmodifiableMapView) return _groups; + // ignore: implicit_dynamic_type + return EqualUnmodifiableMapView(_groups); + } + + final List _trashed; + @override + @JsonKey() + List get trashed { + if (_trashed is EqualUnmodifiableListView) return _trashed; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_trashed); + } + + @override + final String? selectedId; + @override + @JsonKey() + final bool reloadFailed; + + /// Create a copy of ConversationSnapshot + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$ConversationSnapshotCopyWith<_ConversationSnapshot> get copyWith => + __$ConversationSnapshotCopyWithImpl<_ConversationSnapshot>( + this, + _$identity, + ); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _ConversationSnapshot && + (identical(other.projectId, projectId) || + other.projectId == projectId) && + const DeepCollectionEquality().equals(other.groups, _groups) && + const DeepCollectionEquality().equals(other.trashed, _trashed) && + (identical(other.selectedId, selectedId) || + other.selectedId == selectedId) && + (identical(other.reloadFailed, reloadFailed) || + other.reloadFailed == reloadFailed)); + } + + @override + int get hashCode { + return Object.hash( + runtimeType, + projectId, + const DeepCollectionEquality().hash(_groups), + const DeepCollectionEquality().hash(_trashed), + selectedId, + reloadFailed, + ); + } + + @override + String toString() { + return 'ConversationSnapshot(projectId: $projectId, groups: $groups, trashed: $trashed, selectedId: $selectedId, reloadFailed: $reloadFailed)'; + } +} + +/// @nodoc +abstract mixin class _$ConversationSnapshotCopyWith<$Res> + implements $ConversationSnapshotCopyWith<$Res> { + factory _$ConversationSnapshotCopyWith( + _ConversationSnapshot value, + $Res Function(_ConversationSnapshot) _then, + ) = __$ConversationSnapshotCopyWithImpl; + @override + @useResult + $Res call({ + String? projectId, + Map> groups, + List trashed, + String? selectedId, + bool reloadFailed, + }); +} + +/// @nodoc +class __$ConversationSnapshotCopyWithImpl<$Res> + implements _$ConversationSnapshotCopyWith<$Res> { + __$ConversationSnapshotCopyWithImpl(this._self, this._then); + + final _ConversationSnapshot _self; + final $Res Function(_ConversationSnapshot) _then; + + /// Create a copy of ConversationSnapshot + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? projectId = freezed, + Object? groups = null, + Object? trashed = null, + Object? selectedId = freezed, + Object? reloadFailed = null, + }) { + return _then( + _ConversationSnapshot( + projectId: freezed == projectId + ? _self.projectId + : projectId // ignore: cast_nullable_to_non_nullable + as String?, + groups: null == groups + ? _self._groups + : groups // ignore: cast_nullable_to_non_nullable + as Map>, + trashed: null == trashed + ? _self._trashed + : trashed // ignore: cast_nullable_to_non_nullable + as List, + selectedId: freezed == selectedId + ? _self.selectedId + : selectedId // ignore: cast_nullable_to_non_nullable + as String?, + reloadFailed: null == reloadFailed + ? _self.reloadFailed + : reloadFailed // ignore: cast_nullable_to_non_nullable + as bool, + ), + ); + } +} + +/// @nodoc +mixin _$ConversationWorkspaceKey { + String? get projectId; + List get projectIds; + + /// Create a copy of ConversationWorkspaceKey + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $ConversationWorkspaceKeyCopyWith get copyWith => + _$ConversationWorkspaceKeyCopyWithImpl( + this as ConversationWorkspaceKey, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as ConversationWorkspaceKey; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is ConversationWorkspaceKey && + (identical(other.projectId, _this.projectId) || + other.projectId == _this.projectId) && + const DeepCollectionEquality().equals( + other.projectIds, + _this.projectIds, + )); + } + + @override + int get hashCode { + final _this = this as ConversationWorkspaceKey; + return Object.hash( + runtimeType, + _this.projectId, + const DeepCollectionEquality().hash(_this.projectIds), + ); + } + + @override + String toString() { + final _this = this as ConversationWorkspaceKey; + return 'ConversationWorkspaceKey(projectId: ${_this.projectId}, projectIds: ${_this.projectIds})'; + } +} + +/// @nodoc +abstract mixin class $ConversationWorkspaceKeyCopyWith<$Res> { + factory $ConversationWorkspaceKeyCopyWith( + ConversationWorkspaceKey value, + $Res Function(ConversationWorkspaceKey) _then, + ) = _$ConversationWorkspaceKeyCopyWithImpl; + @useResult + $Res call({String? projectId, List projectIds}); +} + +/// @nodoc +class _$ConversationWorkspaceKeyCopyWithImpl<$Res> + implements $ConversationWorkspaceKeyCopyWith<$Res> { + _$ConversationWorkspaceKeyCopyWithImpl(this._self, this._then); + + final ConversationWorkspaceKey _self; + final $Res Function(ConversationWorkspaceKey) _then; + + /// Create a copy of ConversationWorkspaceKey + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({Object? projectId = freezed, Object? projectIds = null}) { + return _then( + ConversationWorkspaceKey( + projectId: freezed == projectId + ? _self.projectId + : projectId // ignore: cast_nullable_to_non_nullable + as String?, + projectIds: null == projectIds + ? _self.projectIds + : projectIds // ignore: cast_nullable_to_non_nullable + as List, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [ConversationWorkspaceKey]. +extension ConversationWorkspaceKeyPatterns on ConversationWorkspaceKey { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_ConversationWorkspaceKey value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ConversationWorkspaceKey() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_ConversationWorkspaceKey value) $default, + ) { + final _that = this; + switch (_that) { + case _ConversationWorkspaceKey(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_ConversationWorkspaceKey value)? $default, + ) { + final _that = this; + switch (_that) { + case _ConversationWorkspaceKey() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function(String? projectId, List projectIds)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ConversationWorkspaceKey() when $default != null: + return $default(_that.projectId, _that.projectIds); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function(String? projectId, List projectIds) $default, + ) { + final _that = this; + switch (_that) { + case _ConversationWorkspaceKey(): + return $default(_that.projectId, _that.projectIds); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function(String? projectId, List projectIds)? $default, + ) { + final _that = this; + switch (_that) { + case _ConversationWorkspaceKey() when $default != null: + return $default(_that.projectId, _that.projectIds); + case _: + return null; + } + } +} + +/// @nodoc + +class _ConversationWorkspaceKey implements ConversationWorkspaceKey { + const _ConversationWorkspaceKey({ + this.projectId, + required List projectIds, + }) : _projectIds = projectIds; + + @override + final String? projectId; + final List _projectIds; + @override + List get projectIds { + if (_projectIds is EqualUnmodifiableListView) return _projectIds; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_projectIds); + } + + /// Create a copy of ConversationWorkspaceKey + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$ConversationWorkspaceKeyCopyWith<_ConversationWorkspaceKey> get copyWith => + __$ConversationWorkspaceKeyCopyWithImpl<_ConversationWorkspaceKey>( + this, + _$identity, + ); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _ConversationWorkspaceKey && + (identical(other.projectId, projectId) || + other.projectId == projectId) && + const DeepCollectionEquality().equals( + other.projectIds, + _projectIds, + )); + } + + @override + int get hashCode { + return Object.hash( + runtimeType, + projectId, + const DeepCollectionEquality().hash(_projectIds), + ); + } + + @override + String toString() { + return 'ConversationWorkspaceKey(projectId: $projectId, projectIds: $projectIds)'; + } +} + +/// @nodoc +abstract mixin class _$ConversationWorkspaceKeyCopyWith<$Res> + implements $ConversationWorkspaceKeyCopyWith<$Res> { + factory _$ConversationWorkspaceKeyCopyWith( + _ConversationWorkspaceKey value, + $Res Function(_ConversationWorkspaceKey) _then, + ) = __$ConversationWorkspaceKeyCopyWithImpl; + @override + @useResult + $Res call({String? projectId, List projectIds}); +} + +/// @nodoc +class __$ConversationWorkspaceKeyCopyWithImpl<$Res> + implements _$ConversationWorkspaceKeyCopyWith<$Res> { + __$ConversationWorkspaceKeyCopyWithImpl(this._self, this._then); + + final _ConversationWorkspaceKey _self; + final $Res Function(_ConversationWorkspaceKey) _then; + + /// Create a copy of ConversationWorkspaceKey + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({Object? projectId = freezed, Object? projectIds = null}) { + return _then( + _ConversationWorkspaceKey( + projectId: freezed == projectId + ? _self.projectId + : projectId // ignore: cast_nullable_to_non_nullable + as String?, + projectIds: null == projectIds + ? _self._projectIds + : projectIds // ignore: cast_nullable_to_non_nullable + as List, + ), + ); + } +} + +/// @nodoc +mixin _$ConversationSelectionState { + String? get selectedId; + String get draftKey; + bool get initialized; + + /// Create a copy of ConversationSelectionState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $ConversationSelectionStateCopyWith + get copyWith => + _$ConversationSelectionStateCopyWithImpl( + this as ConversationSelectionState, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as ConversationSelectionState; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is ConversationSelectionState && + (identical(other.selectedId, _this.selectedId) || + other.selectedId == _this.selectedId) && + (identical(other.draftKey, _this.draftKey) || + other.draftKey == _this.draftKey) && + (identical(other.initialized, _this.initialized) || + other.initialized == _this.initialized)); + } + + @override + int get hashCode { + final _this = this as ConversationSelectionState; + return Object.hash( + runtimeType, + _this.selectedId, + _this.draftKey, + _this.initialized, + ); + } + + @override + String toString() { + final _this = this as ConversationSelectionState; + return 'ConversationSelectionState(selectedId: ${_this.selectedId}, draftKey: ${_this.draftKey}, initialized: ${_this.initialized})'; + } +} + +/// @nodoc +abstract mixin class $ConversationSelectionStateCopyWith<$Res> { + factory $ConversationSelectionStateCopyWith( + ConversationSelectionState value, + $Res Function(ConversationSelectionState) _then, + ) = _$ConversationSelectionStateCopyWithImpl; + @useResult + $Res call({String? selectedId, String draftKey, bool initialized}); +} + +/// @nodoc +class _$ConversationSelectionStateCopyWithImpl<$Res> + implements $ConversationSelectionStateCopyWith<$Res> { + _$ConversationSelectionStateCopyWithImpl(this._self, this._then); + + final ConversationSelectionState _self; + final $Res Function(ConversationSelectionState) _then; + + /// Create a copy of ConversationSelectionState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? selectedId = freezed, + Object? draftKey = null, + Object? initialized = null, + }) { + return _then( + ConversationSelectionState( + selectedId: freezed == selectedId + ? _self.selectedId + : selectedId // ignore: cast_nullable_to_non_nullable + as String?, + draftKey: null == draftKey + ? _self.draftKey + : draftKey // ignore: cast_nullable_to_non_nullable + as String, + initialized: null == initialized + ? _self.initialized + : initialized // ignore: cast_nullable_to_non_nullable + as bool, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [ConversationSelectionState]. +extension ConversationSelectionStatePatterns on ConversationSelectionState { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_ConversationSelectionState value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ConversationSelectionState() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_ConversationSelectionState value) $default, + ) { + final _that = this; + switch (_that) { + case _ConversationSelectionState(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_ConversationSelectionState value)? $default, + ) { + final _that = this; + switch (_that) { + case _ConversationSelectionState() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function(String? selectedId, String draftKey, bool initialized)? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ConversationSelectionState() when $default != null: + return $default(_that.selectedId, _that.draftKey, _that.initialized); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function(String? selectedId, String draftKey, bool initialized) + $default, + ) { + final _that = this; + switch (_that) { + case _ConversationSelectionState(): + return $default(_that.selectedId, _that.draftKey, _that.initialized); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function(String? selectedId, String draftKey, bool initialized)? + $default, + ) { + final _that = this; + switch (_that) { + case _ConversationSelectionState() when $default != null: + return $default(_that.selectedId, _that.draftKey, _that.initialized); + case _: + return null; + } + } +} + +/// @nodoc + +class _ConversationSelectionState implements ConversationSelectionState { + const _ConversationSelectionState({ + this.selectedId, + required this.draftKey, + this.initialized = false, + }); + + @override + final String? selectedId; + @override + final String draftKey; + @override + @JsonKey() + final bool initialized; + + /// Create a copy of ConversationSelectionState + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$ConversationSelectionStateCopyWith<_ConversationSelectionState> + get copyWith => + __$ConversationSelectionStateCopyWithImpl<_ConversationSelectionState>( + this, + _$identity, + ); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _ConversationSelectionState && + (identical(other.selectedId, selectedId) || + other.selectedId == selectedId) && + (identical(other.draftKey, draftKey) || + other.draftKey == draftKey) && + (identical(other.initialized, initialized) || + other.initialized == initialized)); + } + + @override + int get hashCode { + return Object.hash(runtimeType, selectedId, draftKey, initialized); + } + + @override + String toString() { + return 'ConversationSelectionState(selectedId: $selectedId, draftKey: $draftKey, initialized: $initialized)'; + } +} + +/// @nodoc +abstract mixin class _$ConversationSelectionStateCopyWith<$Res> + implements $ConversationSelectionStateCopyWith<$Res> { + factory _$ConversationSelectionStateCopyWith( + _ConversationSelectionState value, + $Res Function(_ConversationSelectionState) _then, + ) = __$ConversationSelectionStateCopyWithImpl; + @override + @useResult + $Res call({String? selectedId, String draftKey, bool initialized}); +} + +/// @nodoc +class __$ConversationSelectionStateCopyWithImpl<$Res> + implements _$ConversationSelectionStateCopyWith<$Res> { + __$ConversationSelectionStateCopyWithImpl(this._self, this._then); + + final _ConversationSelectionState _self; + final $Res Function(_ConversationSelectionState) _then; + + /// Create a copy of ConversationSelectionState + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? selectedId = freezed, + Object? draftKey = null, + Object? initialized = null, + }) { + return _then( + _ConversationSelectionState( + selectedId: freezed == selectedId + ? _self.selectedId + : selectedId // ignore: cast_nullable_to_non_nullable + as String?, + draftKey: null == draftKey + ? _self.draftKey + : draftKey // ignore: cast_nullable_to_non_nullable + as String, + initialized: null == initialized + ? _self.initialized + : initialized // ignore: cast_nullable_to_non_nullable + as bool, + ), + ); + } +} diff --git a/lib/features/projects/conversation_sidebar.g.dart b/lib/features/projects/conversation_sidebar.g.dart new file mode 100644 index 0000000..639d752 --- /dev/null +++ b/lib/features/projects/conversation_sidebar.g.dart @@ -0,0 +1,247 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'conversation_sidebar.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(savedConversationSelection) +final savedConversationSelectionProvider = SavedConversationSelectionFamily._(); + +final class SavedConversationSelectionProvider + extends $FunctionalProvider, String?, FutureOr> + with $FutureModifier, $FutureProvider { + SavedConversationSelectionProvider._({ + required SavedConversationSelectionFamily super.from, + required String? super.argument, + }) : super( + retry: null, + name: r'savedConversationSelectionProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$savedConversationSelectionHash(); + + @override + String toString() { + return r'savedConversationSelectionProvider' + '' + '($argument)'; + } + + @$internal + @override + $FutureProviderElement $createElement($ProviderPointer pointer) => + $FutureProviderElement(pointer); + + @override + FutureOr create(Ref ref) { + final argument = this.argument as String?; + return savedConversationSelection(ref, argument); + } + + @override + bool operator ==(Object other) { + return other is SavedConversationSelectionProvider && + other.argument == argument; + } + + @override + int get hashCode { + return argument.hashCode; + } +} + +String _$savedConversationSelectionHash() => + r'849182ed07f7227ba041f611ccdb3cbb1423f95e'; + +final class SavedConversationSelectionFamily extends $Family + with $FunctionalFamilyOverride, String?> { + SavedConversationSelectionFamily._() + : super( + retry: null, + name: r'savedConversationSelectionProvider', + dependencies: null, + $allTransitiveDependencies: null, + isAutoDispose: false, + ); + + SavedConversationSelectionProvider call(String? projectId) => + SavedConversationSelectionProvider._(argument: projectId, from: this); + + @override + String toString() => r'savedConversationSelectionProvider'; +} + +/// Keeps a draft or explicit selection stable while the list refreshes. + +@ProviderFor(ConversationSelection) +final conversationSelectionProvider = ConversationSelectionFamily._(); + +/// Keeps a draft or explicit selection stable while the list refreshes. +final class ConversationSelectionProvider + extends + $NotifierProvider { + /// Keeps a draft or explicit selection stable while the list refreshes. + ConversationSelectionProvider._({ + required ConversationSelectionFamily super.from, + required String? super.argument, + }) : super( + retry: null, + name: r'conversationSelectionProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$conversationSelectionHash(); + + @override + String toString() { + return r'conversationSelectionProvider' + '' + '($argument)'; + } + + @$internal + @override + ConversationSelection create() => ConversationSelection(); + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(ConversationSelectionState value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } + + @override + bool operator ==(Object other) { + return other is ConversationSelectionProvider && other.argument == argument; + } + + @override + int get hashCode { + return argument.hashCode; + } +} + +String _$conversationSelectionHash() => + r'eef3c6c95f86b017e73d3244adccc257f717699b'; + +/// Keeps a draft or explicit selection stable while the list refreshes. + +final class ConversationSelectionFamily extends $Family + with + $ClassFamilyOverride< + ConversationSelection, + ConversationSelectionState, + ConversationSelectionState, + ConversationSelectionState, + String? + > { + ConversationSelectionFamily._() + : super( + retry: null, + name: r'conversationSelectionProvider', + dependencies: null, + $allTransitiveDependencies: null, + isAutoDispose: false, + ); + + /// Keeps a draft or explicit selection stable while the list refreshes. + + ConversationSelectionProvider call(String? projectId) => + ConversationSelectionProvider._(argument: projectId, from: this); + + @override + String toString() => r'conversationSelectionProvider'; +} + +/// Keeps a draft or explicit selection stable while the list refreshes. + +abstract class _$ConversationSelection + extends $Notifier { + late final _$args = ref.$arg as String?; + String? get projectId => _$args; + + ConversationSelectionState build(String? projectId); + @$mustCallSuper + @override + WhenComplete runBuild() { + final ref = + this.ref + as $Ref; + final element = + ref.element + as $ClassProviderElement< + AnyNotifier< + ConversationSelectionState, + ConversationSelectionState + >, + ConversationSelectionState, + Object?, + Object? + >; + return element.handleCreate(ref, () => build(_$args)); + } +} + +@ProviderFor(ConversationSidebar) +final conversationSidebarProvider = ConversationSidebarProvider._(); + +final class ConversationSidebarProvider + extends $AsyncNotifierProvider { + ConversationSidebarProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'conversationSidebarProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$conversationSidebarHash(); + + @$internal + @override + ConversationSidebar create() => ConversationSidebar(); +} + +String _$conversationSidebarHash() => + r'13122a844ce87622c8d4919042e4dbefc69b790f'; + +abstract class _$ConversationSidebar + extends $AsyncNotifier { + FutureOr build(); + @$mustCallSuper + @override + WhenComplete runBuild() { + final ref = + this.ref + as $Ref, ConversationSnapshot>; + final element = + ref.element + as $ClassProviderElement< + AnyNotifier< + AsyncValue, + ConversationSnapshot + >, + AsyncValue, + Object?, + Object? + >; + return element.handleCreate(ref, build); + } +} diff --git a/lib/features/projects/editor_loading_region.dart b/lib/features/projects/editor_loading_region.dart new file mode 100644 index 0000000..823feef --- /dev/null +++ b/lib/features/projects/editor_loading_region.dart @@ -0,0 +1,116 @@ +import 'package:cutdex_native/cutdex_native.dart'; +import 'package:flutter/material.dart'; + +import '../../l10n/l10n.dart'; +import '../../workspace/project_state.dart'; + +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex_ui/widgets.dart'; + +class EmptyEditor extends StatelessWidget { + const EmptyEditor({ + super.key, + required this.state, + required this.headerLeading, + required this.showProjectName, + }); + + final ProjectState state; + final Widget headerLeading; + final bool showProjectName; + + @override + Widget build(BuildContext context) => Column( + children: [ + SizedBox( + height: AppControlSize.panelHeader, + child: WindowHeaderPadding( + child: Row( + children: [ + headerLeading, + if (showProjectName) + Expanded( + child: Text( + state.activeProject?.name ?? '', + key: const Key('workspace-project-title'), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: Theme.of(context).textTheme.titleSmall, + ), + ), + ], + ), + ), + ), + Expanded( + child: Center( + child: SingleChildScrollView( + padding: const EdgeInsets.all(AppSpacing.page), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.movie_outlined, + size: AppIconSize.project, + color: Theme.of(context).colorScheme.primary, + ), + const SizedBox(height: AppSpacing.medium), + Text( + state.activeProject == null + ? context.l10n.projectsEmpty + : context.l10n.projectNoTimelines, + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.headlineMedium, + ), + if (state.activeProject != null) ...[ + const SizedBox(height: AppSpacing.small), + Text( + context.l10n.createTimelineHint, + textAlign: TextAlign.center, + ), + ], + ], + ), + ), + ), + ), + ], + ); +} + +class ProjectLoadingRegion extends StatelessWidget { + const ProjectLoadingRegion({ + super.key, + required this.loading, + required this.child, + }); + + final bool loading; + final Widget child; + + @override + Widget build(BuildContext context) => Stack( + fit: StackFit.expand, + children: [ + ExcludeFocus( + excluding: loading, + child: IgnorePointer(ignoring: loading, child: child), + ), + if (loading) + DelayedLoadingIndicator( + child: Positioned.fill( + child: ColoredBox( + key: const Key('editor-project-loading'), + color: Theme.of(context).colorScheme.surface, + child: const Center( + child: SizedBox.square( + dimension: 20, + child: CircularProgressIndicator(strokeWidth: 2), + ), + ), + ), + ), + ), + ], + ); +} diff --git a/lib/features/projects/project_sidebar.dart b/lib/features/projects/project_sidebar.dart new file mode 100644 index 0000000..9cfdf64 --- /dev/null +++ b/lib/features/projects/project_sidebar.dart @@ -0,0 +1,1275 @@ +import '../../integrations/platform/device_experience.dart'; +import 'touch_project_navigation.dart'; + +import 'package:cutdex_ui/theme.dart'; + +import 'dart:async'; + +import 'package:cutdex/l10n/l10n.dart'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../integrations/platform/editor_window_chrome.dart'; + +import 'package:cutdex_native/cutdex_native.dart'; + +import '../../shared/layout/workspace_layout_metrics.dart'; + +import 'package:cutdex_ui/widgets.dart'; + +import '../../workspace/projects.dart'; +import '../../workspace/workspace_mode.dart'; + +import '../../workspace/project_state.dart'; + +import '../../integrations/agent/conversation_repository.dart' + show ConversationMetadata; +import '../../integrations/agent/agent_settings.dart'; +import '../../integrations/agent/agent_models.dart'; + +import 'widgets/name_dialog.dart'; +import 'conversation_sidebar.dart'; + +typedef ProjectRenamer = Future Function(RecentProject project); + +class ProjectSidebar extends ConsumerStatefulWidget { + const ProjectSidebar({ + super.key, + required this.agent, + this.navigationOnly = false, + this.experience = DeviceExperience.desktop, + this.onNavigationComplete, + required this.mode, + required this.onModeChanged, + required this.navigationWidth, + required this.navigationCollapsed, + required this.agentHeaderLeading, + required this.editorHidden, + required this.onExpandEditor, + required this.state, + required this.selectedProjectId, + required this.integratedTitlebar, + required this.onCreateProject, + required this.onSelectProject, + required this.onRenameProject, + required this.headerControls, + }); + + final Widget agent; + final bool navigationOnly; + final DeviceExperience experience; + final VoidCallback? onNavigationComplete; + final ProjectState state; + final String? selectedProjectId; + final WorkspaceMode mode; + final ValueChanged onModeChanged; + final double navigationWidth; + final bool navigationCollapsed; + final Widget agentHeaderLeading; + final bool editorHidden; + final VoidCallback? onExpandEditor; + final bool integratedTitlebar; + final VoidCallback? onCreateProject; + final ValueChanged? onSelectProject; + final ProjectRenamer onRenameProject; + final Widget headerControls; + + @override + ConsumerState createState() => _ProjectSidebarState(); +} + +class _ProjectSidebarState extends ConsumerState { + bool get _touch => widget.experience != DeviceExperience.desktop; + bool _projectHeaderHovered = false; + String? _hoveredProjectId; + final _cutProjectsMenu = MenuController(); + final Set _expandedConversationProjects = {}; + final Set _collapsedProjects = {}; + bool _showTrash = false; + + ConversationSidebar get _conversations => + ref.read(conversationSidebarProvider.notifier); + ConversationSnapshot get _snapshot { + final snapshot = ref.read(conversationSidebarProvider).value; + return snapshot?.projectId == widget.state.activeProject?.id + ? snapshot ?? const ConversationSnapshot() + : const ConversationSnapshot(); + } + + Map> get _conversationsByProject => + _snapshot.groups; + List get _trashed => _snapshot.trashed; + String? get _selectedConversationId => ref + .read(conversationSelectionProvider(widget.state.activeProject?.id)) + .selectedId; + String? get _conversationError => + (ref.read(conversationSidebarProvider).hasError || _snapshot.reloadFailed) + ? context.l10n.agentSessionRestoreFailed + : null; + + void _finishNavigation() { + final scaffold = Scaffold.maybeOf(context); + if (scaffold?.isDrawerOpen ?? false) { + scaffold!.closeDrawer(); + } else { + widget.onNavigationComplete?.call(); + } + } + + void _selectProjectFromNavigation(RecentProject project) { + widget.onSelectProject?.call(project); + if (widget.navigationOnly) _finishNavigation(); + } + + void _newConversation() => _conversations.newConversation(); + + Future _newConversationForProject(RecentProject project) async { + _cutProjectsMenu.close(); + if (ref.read(projectsProvider).value?.projectBusy == true || + !project.availability.canOpen) { + return; + } + if (widget.state.activeProject?.id != project.id) { + final opened = await ref + .read(projectsProvider.notifier) + .open(project.path, expectedId: project.id); + if (!opened || !mounted) return; + } + _newConversation(); + widget.onModeChanged(WorkspaceMode.agent); + _finishNavigation(); + } + + Future _selectConversation(ConversationMetadata item) async { + _cutProjectsMenu.close(); + if (ref.read(projectsProvider).value?.projectBusy == true) return; + await _conversations.rememberSelection(item); + final currentProject = widget.state.activeProject?.id; + if (currentProject != item.projectId) { + final project = widget.state.recent + .where((entry) => entry.id == item.projectId) + .firstOrNull; + if (project == null || !project.availability.canOpen) return; + var opened = await ref + .read(projectsProvider.notifier) + .open( + project.path, + expectedId: project.id, + timelineId: item.timelineId, + ); + if (!opened) { + opened = await ref + .read(projectsProvider.notifier) + .open(project.path, expectedId: project.id); + } + if (!opened) return; + } else if (widget.state.timeline?.id != item.timelineId && + widget.state.timelines.any( + (timeline) => timeline.id == item.timelineId, + )) { + await ref + .read(projectsProvider.notifier) + .openTimeline(item.projectId, item.timelineId); + } + if (!mounted || widget.state.activeProject?.id != item.projectId) return; + _conversations.activate(item); + widget.onModeChanged(WorkspaceMode.agent); + _finishNavigation(); + } + + Future _renameConversation(ConversationMetadata item) async { + final name = await askName( + context, + title: context.l10n.renameConversationTitle, + label: context.l10n.name, + description: context.l10n.renameConversationDescription, + initialValue: item.title, + submitLabel: context.l10n.save, + ); + if (name == null || !mounted) return; + await _conversations.rename(item, name); + } + + Future _trashConversation(ConversationMetadata item) => + _conversations.trash(item); + Future _restoreConversation(ConversationMetadata item) => + _conversations.restore(item); + + Future _relinkProvider(ConversationMetadata item) async { + final settings = await ref.read(agentSettingsProvider.future); + if (!mounted) return; + final candidates = settings.providers.where( + (provider) => + provider.enabled && + AgentApiType.values.any((type) => type.name == provider.apiType) && + provider.models.any((model) => model.id == item.modelId), + ); + final selected = await showAppDialog( + context: context, + builder: (dialogContext) => AppDialog( + title: context.l10n.agentRelinkProvider, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + if (candidates.isEmpty) Text(context.l10n.agentProviderRequired), + for (final provider in candidates) + AppDialogOption( + label: provider.name, + onPressed: () => Navigator.pop(dialogContext, provider.id), + ), + ], + ), + ), + ); + if (selected == null) return; + await _conversations.updateMetadata(item.copyWith(providerId: selected)); + } + + Future _removeProject(RecentProject project) async { + final index = widget.state.recent.indexWhere( + (item) => item.id == project.id, + ); + final removed = await ref + .read(projectsProvider.notifier) + .removeRecentProject(project.id); + if (!removed || !mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(context.l10n.projectRemoved), + action: SnackBarAction( + label: context.l10n.undo, + onPressed: () => ref + .read(projectsProvider.notifier) + .restoreRecentProject(project, index), + ), + ), + ); + } + + Future _deleteForever(ConversationMetadata item) async { + if (!await _confirmDelete(item: item) || !mounted) return; + try { + await _conversations.delete(item); + } catch (_) { + if (mounted) { + ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text(context.l10n.operationFailed))); + } + } + } + + Future _emptyTrash() async { + if (!await _confirmDelete() || !mounted) return; + await _conversations.emptyTrash(); + } + + Future _confirmDelete({ConversationMetadata? item}) async => + await showAppDialog( + context: context, + builder: (dialogContext) => AppDialog( + title: context.l10n.agentDeleteForever, + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogContext, false), + child: Text(context.l10n.cancel), + ), + FilledButton( + style: FilledButton.styleFrom( + backgroundColor: Theme.of(context).colorScheme.error, + foregroundColor: Theme.of(context).colorScheme.onError, + ), + onPressed: () => Navigator.pop(dialogContext, true), + child: Text(context.l10n.agentDeleteForever), + ), + ], + child: Text( + item == null + ? context.l10n.agentEmptyTrashConfirmation + : context.l10n.agentDeleteConfirmation(item.title), + ), + ), + ) == + true; + + Widget _conversationRow(ConversationMetadata item) { + final selected = + widget.state.activeProject?.id == item.projectId && + _selectedConversationId == item.id; + List actions(BuildContext context) => [ + AppMenuItem( + label: context.l10n.rename, + onPressed: () => _renameConversation(item), + ), + AppMenuItem( + label: context.l10n.agentMoveToTrash, + onPressed: () => _trashConversation(item), + ), + AppMenuItem( + label: context.l10n.agentRelinkProvider, + onPressed: () => _relinkProvider(item), + ), + const AppMenuSeparator(), + AppMenuItem( + label: '${context.l10n.agentDeleteForever}…', + destructive: true, + onPressed: () => _deleteForever(item), + ), + ]; + if (_touch) { + return TouchConversationTile( + id: item.id, + title: item.title, + selected: selected, + onSelect: () => _selectConversation(item), + actions: actions, + ); + } + return Padding( + padding: AppSidebarMetrics.rowPadding, + child: AppContextMenu( + itemsBuilder: actions, + child: Material( + color: selected + ? AppSidebarColors.of(context).hover + : Colors.transparent, + borderRadius: BorderRadius.circular(AppSidebarMetrics.radius), + child: InkWell( + key: ValueKey('sidebar-conversation-${item.id}'), + hoverColor: selected + ? Colors.transparent + : AppSidebarColors.of(context).hover, + splashColor: Colors.transparent, + highlightColor: Colors.transparent, + borderRadius: BorderRadius.circular(AppSidebarMetrics.radius), + onTap: () => _selectConversation(item), + child: SizedBox( + height: AppSidebarMetrics.rowHeight, + child: Align( + alignment: AlignmentDirectional.centerStart, + child: Padding( + padding: const EdgeInsetsDirectional.only( + start: AppSidebarMetrics.textInset, + end: AppSidebarMetrics.cellPadding, + ), + child: Text( + item.title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: AppSidebarTypography.style( + context, + fontSize: AppSidebarMetrics.conversationFontSize, + height: AppSidebarMetrics.conversationLineHeight, + ), + ), + ), + ), + ), + ), + ), + ), + ); + } + + Widget _projectGroup(RecentProject project) { + final conversations = _conversationsByProject[project.id] ?? const []; + final expanded = _expandedConversationProjects.contains(project.id); + final collapsed = _collapsedProjects.contains(project.id); + final visible = collapsed + ? const [] + : expanded + ? conversations + : conversations.take(5); + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + MouseRegion( + onEnter: (_) => setState(() => _hoveredProjectId = project.id), + onExit: (_) { + if (_hoveredProjectId == project.id) { + setState(() => _hoveredProjectId = null); + } + }, + child: _touch + ? TouchProjectTile( + project: project, + selected: widget.selectedProjectId == project.id, + expanded: !collapsed, + availabilityLabel: _availabilityLabel( + context, + project.availability, + ), + onSelect: () => _selectProjectFromNavigation(project), + onToggle: () => setState(() { + if (collapsed) { + _collapsedProjects.remove(project.id); + } else { + _collapsedProjects.add(project.id); + } + }), + onNewConversation: + widget.state.projectBusy || !project.availability.canOpen + ? null + : () => _newConversationForProject(project), + onRename: project.availability.canOpen + ? () => widget.onRenameProject(project) + : null, + onRemove: widget.state.projectBusy + ? null + : () => _removeProject(project), + ) + : Padding( + padding: AppSidebarMetrics.rowPadding, + child: _ProjectTile( + project: project, + active: widget.selectedProjectId == project.id, + availabilityLabel: _availabilityLabel( + context, + project.availability, + ), + onSelect: () { + _cutProjectsMenu.close(); + _selectProjectFromNavigation(project); + }, + onRename: () => widget.onRenameProject(project), + onRemove: widget.state.projectBusy + ? null + : () => _removeProject(project), + expanded: !collapsed, + onToggleExpanded: () => setState(() { + if (collapsed) { + _collapsedProjects.remove(project.id); + } else { + _collapsedProjects.add(project.id); + } + }), + sidebarStyle: true, + hovered: _hoveredProjectId == project.id, + onNewConversation: () => + _newConversationForProject(project), + ), + ), + ), + for (final item in visible) ...[ + const SizedBox(height: AppSidebarMetrics.rowGap), + _conversationRow(item), + ], + if (!collapsed && + _conversationsByProject.containsKey(project.id) && + conversations.isEmpty) + Padding( + key: ValueKey('sidebar-project-empty-${project.id}'), + padding: const EdgeInsetsDirectional.fromSTEB( + AppSidebarMetrics.outerPadding + AppSidebarMetrics.textInset, + 4, + AppSidebarMetrics.outerPadding + AppSidebarMetrics.cellPadding, + 4, + ), + child: Text( + context.l10n.agentNoConversations, + style: AppSidebarTypography.style( + context, + fontSize: AppSidebarMetrics.hintFontSize, + height: AppSidebarMetrics.lineHeight, + color: AppSidebarColors.of(context).tertiary, + ), + ), + ), + if (!collapsed && conversations.length > 5) + Padding( + padding: const EdgeInsetsDirectional.only( + start: + AppSidebarMetrics.outerPadding + + AppSidebarMetrics.textInset - + AppSidebarMetrics.cellPadding, + ), + child: Align( + alignment: AlignmentDirectional.centerStart, + child: TextButton( + style: TextButton.styleFrom( + minimumSize: const Size(0, AppSidebarMetrics.rowHeight), + padding: const EdgeInsets.symmetric( + horizontal: AppSidebarMetrics.cellPadding, + ), + ), + onPressed: () => setState(() { + if (expanded) { + _expandedConversationProjects.remove(project.id); + } else { + _expandedConversationProjects.add(project.id); + } + }), + child: Text( + expanded + ? context.l10n.showFewerConversations + : context.l10n.showMoreConversations, + style: Theme.of(context).textTheme.bodySmall + ?.copyWith(color: AppSidebarColors.of(context).secondary), + ), + ), + ), + ), + ], + ); + } + + @override + Widget build(BuildContext context) { + ref.watch(conversationSidebarProvider); + ref.watch(conversationSelectionProvider(widget.state.activeProject?.id)); + final compact = MediaQuery.sizeOf(context).height < 520; + final headerHeight = widget.navigationOnly + ? 48.0 + : widget.integratedTitlebar + ? AppControlSize.panelHeader + : AppControlSize.headerButton; + final modeTop = headerHeight; + final modeHeader = SizedBox( + height: + modeTop + AppSidebarMetrics.modeHeight + AppSidebarMetrics.sectionGap, + child: Stack( + children: [ + Positioned( + top: 0, + left: 0, + right: 0, + height: headerHeight, + child: SizedBox( + key: const Key('projects-window-header'), + child: WindowHeaderPadding( + child: Row( + children: [ + if (widget.integratedTitlebar) + SizedBox( + key: const Key('native-window-controls-space'), + width: EditorWindowChrome.leadingWidth, + height: AppControlSize.panelHeader, + ) + else + const SizedBox(width: AppSpacing.small), + widget.headerControls, + ], + ), + ), + ), + ), + Positioned( + top: modeTop, + left: AppSidebarMetrics.outerPadding, + right: AppSidebarMetrics.outerPadding, + height: AppSidebarMetrics.modeHeight, + child: Align( + alignment: AlignmentDirectional.topStart, + child: AppPopover( + width: AppMenuMetrics.modeMenuWidth, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (final mode in WorkspaceMode.values) + AppMenuItem( + key: ValueKey('sidebar-mode-${mode.name}'), + label: mode == WorkspaceMode.agent + ? context.l10n.workspaceAgent + : context.l10n.workspaceCut, + selected: widget.mode == mode, + description: mode == WorkspaceMode.agent + ? context.l10n.agentLayoutDescription + : context.l10n.editingLayoutDescription, + onPressed: () { + widget.onModeChanged(mode); + if (widget.navigationOnly) _finishNavigation(); + }, + ), + ], + ), + builder: (context, toggle) => TextButton( + key: const Key('sidebar-mode-trigger'), + onPressed: toggle, + style: ButtonStyle( + foregroundColor: sidebarActionButtonStyle(context) + .foregroundColor, + padding: const WidgetStatePropertyAll( + EdgeInsets.symmetric(horizontal: 8), + ), + minimumSize: const WidgetStatePropertyAll( + Size(0, AppSidebarMetrics.modeHeight), + ), + alignment: AlignmentDirectional.centerStart, + backgroundColor: WidgetStateProperty.resolveWith( + (states) => + states.contains(WidgetState.hovered) || + states.contains(WidgetState.focused) || + states.contains(WidgetState.pressed) + ? AppSidebarColors.of(context).hover + : Colors.transparent, + ), + overlayColor: const WidgetStatePropertyAll( + Colors.transparent, + ), + shape: WidgetStatePropertyAll( + RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), + ), + ), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Flexible( + child: Text( + widget.mode == WorkspaceMode.agent + ? context.l10n.workspaceAgent + : context.l10n.workspaceCut, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: AppSidebarTypography.style( + context, + fontSize: AppSidebarMetrics.titleFontSize, + height: AppSidebarMetrics.titleLineHeight, + weight: FontWeight.w600, + ), + ), + ), + const SizedBox(width: AppSpacing.small), + const Icon( + Icons.keyboard_arrow_down, + size: AppSidebarMetrics.iconSize, + ), + ], + ), + ), + ), + ), + ), + ], + ), + ); + final projectList = SingleChildScrollView( + key: const Key('sidebar-projects-conversations'), + primary: false, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (widget.mode == WorkspaceMode.agent || widget.navigationOnly) + MouseRegion( + onEnter: (_) => setState(() => _projectHeaderHovered = true), + onExit: (_) => setState(() => _projectHeaderHovered = false), + child: Padding( + padding: const EdgeInsets.fromLTRB( + AppSidebarMetrics.outerPadding, + 0, + AppSidebarMetrics.outerPadding, + AppSidebarMetrics.sectionGap, + ), + child: _touch + ? TouchProjectsHeader(onCreate: widget.onCreateProject) + : _ProjectsHeader( + onCreateProject: widget.onCreateProject, + hovered: _projectHeaderHovered, + ), + ), + ), + if (widget.state.recent.isEmpty) + Padding( + padding: const EdgeInsets.symmetric( + horizontal: + AppSidebarMetrics.outerPadding + + AppSidebarMetrics.cellPadding, + vertical: AppSpacing.small, + ), + child: Text( + context.l10n.projectsNone, + style: AppSidebarTypography.style( + context, + fontSize: AppSidebarMetrics.hintFontSize, + height: AppSidebarMetrics.lineHeight, + color: AppSidebarColors.of(context).tertiary, + ), + ), + ), + for (var index = 0; index < widget.state.recent.length; index++) ...[ + if (index > 0) const SizedBox(height: AppSidebarMetrics.projectGap), + _projectGroup(widget.state.recent[index]), + ], + if (_conversationError != null) + Padding( + padding: const EdgeInsets.all(AppSpacing.small), + child: Text( + _conversationError!, + style: Theme.of(context).textTheme.bodySmall, + ), + ), + if (widget.state.activeProject != null && + (_trashed.isNotEmpty || _showTrash)) + ExpansionTile( + title: Text( + context.l10n.agentTrash, + style: AppSidebarTypography.style( + context, + color: AppSidebarColors.of(context).tertiary, + weight: FontWeight.w500, + ), + ), + initiallyExpanded: _showTrash, + onExpansionChanged: (value) => setState(() => _showTrash = value), + trailing: _trashed.isEmpty + ? null + : TextButton( + onPressed: _emptyTrash, + child: Text(context.l10n.agentEmptyTrash), + ), + children: [ + ListView.builder( + primary: false, + shrinkWrap: true, + itemCount: _trashed.length, + itemBuilder: (context, index) { + final item = _trashed[index]; + return ListTile( + dense: true, + title: Text( + item.title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: AppSidebarTypography.style( + context, + fontSize: AppSidebarMetrics.fontSize, + height: AppSidebarMetrics.lineHeight, + color: AppSidebarColors.of(context).secondary, + ), + ), + trailing: PopupMenuButton( + tooltip: context.l10n.agentConversationActions, + onSelected: (value) { + if (value == 'restore') { + _restoreConversation(item); + } + if (value == 'delete') _deleteForever(item); + }, + itemBuilder: (context) => [ + PopupMenuItem( + height: AppMenuMetrics.rowHeight, + value: 'restore', + child: Text(context.l10n.agentRestore), + ), + PopupMenuItem( + height: AppMenuMetrics.rowHeight, + value: 'delete', + child: Text(context.l10n.agentDeleteForever), + ), + ], + ), + ); + }, + ), + ], + ), + ], + ), + ); + final chatPanel = widget.agent; + if (widget.navigationOnly) { + return Material( + color: Theme.of(context).colorScheme.surfaceContainerLow, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + modeHeader, + Expanded(child: projectList), + ], + ), + ); + } + final content = widget.mode == WorkspaceMode.agent + ? Row( + key: const Key('agent-mode-layout'), + children: [ + if (!widget.navigationCollapsed) + SizedBox( + width: widget.navigationWidth, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + modeHeader, + Expanded(child: projectList), + ], + ), + ), + if (!widget.navigationCollapsed) + VerticalDivider( + key: const Key('sidebar-chat-divider'), + width: 1, + thickness: 1, + color: AppTheme.sidebarDividerColor(context), + ), + Expanded( + child: Material( + key: const Key('agent-panel-surface'), + color: Theme.of(context).colorScheme.surface, + child: WindowHeaderPane( + offset: Offset( + widget.navigationCollapsed + ? 0 + : widget.navigationWidth + 1, + 0, + ), + child: Column( + children: [ + SizedBox( + key: const Key('agent-content-header'), + height: AppControlSize.panelHeader, + child: WindowHeaderPadding( + child: LayoutBuilder( + builder: (context, constraints) { + final header = Row( + children: [ + widget.agentHeaderLeading, + Expanded( + child: Text( + widget.state.activeProject?.name ?? '', + key: const Key( + 'workspace-project-title', + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: Theme.of(context) + .textTheme + .titleSmall, + ), + ), + if (widget.editorHidden) + HeaderControlRegion( + child: Padding( + padding: + const EdgeInsetsDirectional.only( + end: AppSpacing.small, + ), + child: SizedBox.square( + dimension: + AppControlSize.headerButton, + child: IconButton( + key: const Key( + 'expand-editor-button', + ), + tooltip: + context.l10n.expandEditor, + onPressed: widget.onExpandEditor, + padding: EdgeInsets.zero, + icon: const Icon( + Icons.vertical_split_outlined, + size: AppIconSize.header, + ), + ), + ), + ), + ), + ], + ); + if (constraints.maxWidth >= + WorkspaceLayoutMetrics + .contentMinimumWidth) { + return header; + } + return SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: SizedBox( + width: WorkspaceLayoutMetrics + .contentMinimumWidth, + child: header, + ), + ); + }, + ), + ), + ), + Expanded(child: chatPanel), + ], + ), + ), + ), + ), + ], + ) + : Column( + key: const Key('cut-mode-layout'), + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + modeHeader, + MouseRegion( + onEnter: (_) => setState(() => _projectHeaderHovered = true), + onExit: (_) => setState(() => _projectHeaderHovered = false), + child: Padding( + padding: const EdgeInsets.fromLTRB( + AppSidebarMetrics.outerPadding, + 4, + AppSidebarMetrics.outerPadding, + 0, + ), + child: MenuAnchor( + controller: _cutProjectsMenu, + consumeOutsideTap: false, + alignmentOffset: const Offset(0, 4), + style: AppMenuStyle.panel(context, minWidth: 300), + menuChildren: [ + SizedBox( + width: 320, + height: (MediaQuery.sizeOf(context).height - 180).clamp( + 160.0, + 440.0, + ), + child: projectList, + ), + ], + builder: (context, controller, _) => _ProjectsHeader( + hovered: _projectHeaderHovered, + onPressed: () => controller.isOpen + ? controller.close() + : controller.open(), + onCreateProject: widget.onCreateProject == null + ? null + : () { + controller.close(); + widget.onCreateProject!(); + }, + ), + ), + ), + ), + Expanded(child: chatPanel), + ], + ); + return Material( + color: Theme.of(context).colorScheme.surfaceContainerLow, + child: compact + ? LayoutBuilder( + builder: (context, constraints) => SingleChildScrollView( + child: SizedBox( + height: constraints.maxHeight < 650 + ? 650 + : constraints.maxHeight, + child: content, + ), + ), + ) + : content, + ); + } +} + +class _ProjectsHeader extends StatelessWidget { + const _ProjectsHeader({ + required this.onCreateProject, + required this.hovered, + this.onPressed, + }); + + final VoidCallback? onCreateProject; + final bool hovered; + final VoidCallback? onPressed; + + @override + Widget build(BuildContext context) => Row( + children: [ + Expanded( + child: SizedBox( + key: const Key('projects-heading'), + height: AppSidebarMetrics.sectionHeight, + child: Material( + color: Colors.transparent, + child: InkWell( + key: onPressed == null ? null : const Key('cut-projects-trigger'), + onTap: onPressed, + hoverColor: AppSidebarColors.of(context).hover, + focusColor: AppSidebarColors.of(context).hover, + highlightColor: Colors.transparent, + splashColor: Colors.transparent, + borderRadius: BorderRadius.circular(AppSidebarMetrics.radius), + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.small, + ), + child: Row( + children: [ + Flexible( + child: Text( + context.l10n.projects, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: AppSidebarTypography.style( + context, + fontSize: AppSidebarMetrics.sectionFontSize, + weight: FontWeight.w500, + color: AppSidebarColors.of(context).section, + ), + ), + ), + if (onPressed != null) ...[ + const SizedBox(width: AppSpacing.tiny), + Icon( + Icons.keyboard_arrow_down, + size: AppSidebarMetrics.iconSize, + color: AppSidebarColors.of(context).secondary, + ), + ], + ], + ), + ), + ), + ), + ), + ), + const SizedBox(width: AppSpacing.tiny), + AnimatedOpacity( + opacity: hovered ? 1 : 0, + duration: const Duration(milliseconds: 120), + child: SizedBox.square( + key: const Key('projects-more'), + dimension: AppSidebarMetrics.actionSize, + child: Center( + child: Icon( + Icons.more_horiz, + size: AppSidebarMetrics.iconSize, + color: AppSidebarColors.of(context).tertiary, + ), + ), + ), + ), + IgnorePointer( + ignoring: !hovered, + child: AnimatedOpacity( + opacity: hovered ? 1 : 0, + duration: const Duration(milliseconds: 120), + child: SizedBox.square( + dimension: AppSidebarMetrics.actionSize, + child: IconButton( + key: const Key('create-project'), + style: sidebarActionButtonStyle(context), + tooltip: context.l10n.newProject, + onPressed: onCreateProject, + padding: EdgeInsets.zero, + icon: const Icon(Icons.add, size: AppSidebarMetrics.iconSize), + ), + ), + ), + ), + ], + ); +} + +Color _sidebarItemHighlightColor(BuildContext context) => + Theme.of(context).colorScheme.secondaryContainer; + +ButtonStyle sidebarActionButtonStyle(BuildContext context) => + AppTheme.iconButtonStyle(context); + +String _availabilityLabel( + BuildContext context, + ProjectAvailability availability, +) => switch (availability) { + ProjectAvailability.available => '', + ProjectAvailability.missing || + ProjectAvailability.volumeOffline || + ProjectAvailability.invalid || + ProjectAvailability.unavailable => context.l10n.projectAccessFailed, +}; + +class _ProjectTile extends StatelessWidget { + const _ProjectTile({ + required this.project, + required this.active, + required this.availabilityLabel, + required this.onSelect, + required this.onRename, + this.sidebarStyle = false, + this.hovered = false, + this.onNewConversation, + this.onRemove, + this.onToggleExpanded, + this.expanded = true, + }); + + final RecentProject project; + final bool active; + final String availabilityLabel; + final VoidCallback onSelect; + final VoidCallback onRename; + final bool sidebarStyle; + final bool hovered; + final VoidCallback? onNewConversation; + final VoidCallback? onRemove; + final VoidCallback? onToggleExpanded; + final bool expanded; + + List _menuItems(BuildContext context) => [ + AppMenuItem( + label: context.l10n.rename, + icon: Icons.drive_file_rename_outline, + onPressed: project.availability.canOpen ? onRename : null, + ), + if (sidebarStyle) ...[ + const AppMenuSeparator(), + AppMenuItem( + label: context.l10n.removeProjectFromSidebar, + onPressed: onRemove, + ), + ], + ]; + + @override + Widget build(BuildContext context) => AppContextMenu( + itemsBuilder: _menuItems, + child: ListTile( + key: ValueKey( + '${sidebarStyle ? 'sidebar-project' : 'open-project'}-${project.id}', + ), + minTileHeight: sidebarStyle + ? AppSidebarMetrics.rowHeight + : project.availability.canOpen + ? 36 + : 48, + minVerticalPadding: 0, + contentPadding: EdgeInsets.symmetric( + horizontal: sidebarStyle ? 0 : AppSpacing.small, + ), + horizontalTitleGap: sidebarStyle + ? AppSidebarMetrics.iconGap + : AppSpacing.small, + minLeadingWidth: sidebarStyle ? AppSidebarMetrics.iconSlotWidth : null, + visualDensity: VisualDensity.standard, + titleAlignment: ListTileTitleAlignment.center, + selected: active, + selectedTileColor: sidebarStyle + ? Colors.transparent + : _sidebarItemHighlightColor(context), + textColor: project.availability.canOpen + ? null + : Theme.of(context).disabledColor, + iconColor: project.availability.canOpen + ? null + : Theme.of(context).disabledColor, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(AppRadius.extraLarge), + ), + hoverColor: sidebarStyle + ? AppSidebarColors.of(context).hover + : _sidebarItemHighlightColor(context), + focusColor: sidebarStyle ? AppSidebarColors.of(context).hover : null, + splashColor: Colors.transparent, + leading: sidebarStyle + ? SizedBox( + width: AppSidebarMetrics.iconSlotWidth, + height: AppSidebarMetrics.rowHeight, + child: IconButton( + key: ValueKey('sidebar-project-toggle-${project.id}'), + tooltip: expanded + ? context.l10n.collapseProject + : context.l10n.expandProject, + padding: EdgeInsets.zero, + style: sidebarActionButtonStyle(context), + onPressed: onToggleExpanded, + icon: Icon( + !project.availability.canOpen + ? Icons.folder_off_outlined + : hovered + ? (expanded + ? Icons.keyboard_arrow_down + : Icons.chevron_right) + : (expanded + ? Icons.folder_open_outlined + : Icons.folder_outlined), + size: AppSidebarMetrics.iconSize, + ), + ), + ) + : Icon( + project.availability.canOpen + ? Icons.folder_outlined + : Icons.folder_off_outlined, + size: 18, + ), + title: Text( + project.name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: sidebarStyle + ? AppSidebarTypography.style( + context, + color: project.availability.canOpen + ? AppSidebarColors.of(context).primary + : AppSidebarColors.of(context).disabled, + ) + : Theme.of(context).textTheme.bodyMedium?.copyWith( + color: project.availability.canOpen + ? null + : Theme.of(context).disabledColor, + ), + ), + subtitle: project.availability.canOpen + ? null + : Text( + availabilityLabel, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: sidebarStyle + ? AppSidebarTypography.style( + context, + fontSize: AppSidebarMetrics.hintFontSize, + height: AppSidebarMetrics.lineHeight, + color: AppSidebarColors.of(context).tertiary, + ) + : null, + ), + trailing: sidebarStyle + ? IgnorePointer( + ignoring: !hovered, + child: AnimatedOpacity( + opacity: hovered ? 1 : 0, + duration: const Duration(milliseconds: 120), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + SizedBox.square( + dimension: AppSidebarMetrics.actionSize, + child: AppPopover( + width: 160, + child: Column( + mainAxisSize: MainAxisSize.min, + children: _menuItems(context), + ), + builder: (context, toggle) => IconButton( + key: ValueKey('sidebar-project-more-${project.id}'), + onPressed: toggle, + style: sidebarActionButtonStyle(context), + padding: EdgeInsets.zero, + icon: const Icon( + Icons.more_horiz, + size: AppSidebarMetrics.iconSize, + ), + ), + ), + ), + const SizedBox(width: 4), + SizedBox.square( + dimension: AppSidebarMetrics.actionSize, + child: IconButton( + key: ValueKey('new-agent-conversation-${project.id}'), + tooltip: context.l10n.agentNewConversation, + onPressed: onNewConversation, + style: sidebarActionButtonStyle(context), + padding: EdgeInsets.zero, + icon: const Icon( + Icons.edit_square, + size: AppSidebarMetrics.iconSize, + ), + ), + ), + ], + ), + ), + ) + : null, + onTap: onSelect, + ), + ); +} diff --git a/lib/features/projects/projects_page.dart b/lib/features/projects/projects_page.dart new file mode 100644 index 0000000..54c98af --- /dev/null +++ b/lib/features/projects/projects_page.dart @@ -0,0 +1,664 @@ +import 'package:cutdex/errors/app_failure.dart'; + +import 'dart:async'; + +import 'package:cutdex/l10n/l10n.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../app/adaptive/desktop_workspace_controller.dart'; +import '../../app/adaptive/workspace_layout_policy.dart'; +import '../../app/shells/phone_workspace_shell.dart'; +import '../../app/shells/desktop_workspace_shell.dart'; +import '../../app/shells/tablet_workspace_shell.dart'; +import '../../integrations/platform/device_experience.dart'; +import '../../integrations/platform/editor_window_chrome.dart'; +import '../../integrations/platform/file_picker.dart'; + +import 'package:cutdex_native/cutdex_native.dart'; + +import '../../persistence/app_settings_repositories.dart'; + +import 'package:cutdex_ui/theme.dart'; + +import '../../workspace/project_state.dart'; +import '../../workspace/projects.dart'; +import '../../workspace/view_settings.dart'; +import '../../workspace/workspace_mode.dart'; +import '../../workspace/workspace_navigation.dart'; +import '../../workspace/workspace_session_scope.dart'; +import '../assistant/workspace_agent_surface.dart'; +import '../editor/background_tasks_button.dart'; +import '../editor/editor_page.dart'; +import '../settings/settings_dialog.dart'; +import 'editor_loading_region.dart'; +import 'project_sidebar.dart'; +import 'widgets/name_dialog.dart'; + +/// The single application surface: project navigation beside the editor. + +class EditingPage extends ConsumerStatefulWidget { + const EditingPage({super.key}); + + @override + ConsumerState createState() => _EditingPageState(); +} + +class _EditingPageState extends ConsumerState { + final _desktopSplits = DesktopWorkspaceController(); + final _editorKey = GlobalKey(); + final _agentKey = GlobalKey(); + final _navigationKey = GlobalKey(); + final _drawerNavigationKey = GlobalKey(); + final _desktopScaffoldKey = GlobalKey(); + WorkspaceViewSettingsData get _viewSettings => + ref.read(workspaceViewSettingsProvider).value ?? + const WorkspaceViewSettingsData(); + WorkspaceViewSettings get _viewController => + ref.read(workspaceViewSettingsProvider.notifier); + WorkspaceMode get _mode => _viewSettings.mode; + set _mode(WorkspaceMode value) => _viewController.setMode(value); + bool get _sidebarCollapsed => _viewSettings.sidebarCollapsed; + set _sidebarCollapsed(bool value) => + _viewController.setSidebarCollapsed(value); + double? get _sidebarWidthOverride => _viewSettings.sidebarWidth; + set _sidebarWidthOverride(double? value) => + _viewController.setSidebarWidth(value); + bool get _startupReady => ref.read(workspaceNavigationProvider).ready; + bool get _switchingProject => + ref.read(workspaceNavigationProvider).switchingProject; + String? get _selectedProjectId => + ref.read(workspaceNavigationProvider).selectedProjectId; + + void _saveViewState({String? activeProjectId}) { + if (!_startupReady) return; + final current = ref.read(projectsProvider).value; + unawaited( + _viewController.save( + activeProjectId: activeProjectId ?? current?.activeProject?.id, + ), + ); + } + + Future _selectProject( + BuildContext context, + WidgetRef ref, { + required bool create, + }) async { + if (ref.read(projectsProvider).value?.projectBusy == true) return; + try { + if (create) { + final name = await askName( + context, + title: context.l10n.newProject, + label: context.l10n.projectName, + ); + if (name == null || !context.mounted) return; + final created = await ref + .read(projectsProvider.notifier) + .createProject( + name, + initialTimelineName: context.l10n.defaultTimelineName(1), + ); + if (!created && context.mounted) { + final error = ref.read(projectsProvider).value?.error; + if (error?.requiresProjectLocation == true) { + await showSettingsDialog(context); + } + } + return; + } + final directory = await ref + .read(filePickerProvider) + .pickDirectory(confirmButtonText: context.l10n.openProject); + if (directory == null || !context.mounted) return; + await ref.read(projectsProvider.notifier).open(directory); + } catch (_) { + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(context.l10n.selectDirectoryFailed)), + ); + } + } + } + + Future _openProject(WidgetRef ref, RecentProject project) => + ref.read(workspaceNavigationProvider.notifier).openProject(project); + + Future _renameProject( + BuildContext context, + WidgetRef ref, + RecentProject project, + ) async { + if (ref.read(projectsProvider).value?.projectBusy == true) return false; + final name = await askName( + context, + title: context.l10n.rename, + label: context.l10n.projectName, + initialValue: project.name, + submitLabel: context.l10n.rename, + ); + if (name == null || !context.mounted || name == project.name) return false; + return ref.read(projectsProvider.notifier).renameProject(project, name); + } + + Future _relocateProject( + BuildContext context, + WidgetRef ref, + RecentProject project, + ) async { + if (ref.read(projectsProvider).value?.projectBusy == true) return; + final directory = await ref + .read(filePickerProvider) + .pickDirectory(confirmButtonText: context.l10n.openProject); + if (directory == null || !context.mounted) return; + await ref + .read(projectsProvider.notifier) + .open(directory, expectedId: project.id); + } + + @override + void dispose() { + _desktopSplits.dispose(); + super.dispose(); + } + + void _setMode(WorkspaceMode mode) { + _mode = mode; + _saveViewState(); + } + + @override + Widget build(BuildContext context) { + ref.watch(workspaceViewSettingsProvider); + ref.watch(workspaceNavigationProvider); + final experience = ref.watch(deviceExperienceProvider); + final desktop = experience == DeviceExperience.desktop; + final projects = ref.watch(projectsProvider); + final state = projects.value ?? const ProjectState(); + return EditorWindowChrome( + headerHeight: desktop ? AppControlSize.panelHeader : 48, + builder: (context, integrated) => Scaffold( + body: SafeArea( + top: !integrated, + child: AnimatedSwitcher( + duration: const Duration(milliseconds: 320), + child: !_startupReady + ? const _StartupLoading(key: ValueKey('startup-loading')) + : WorkspaceSessionScope( + key: const ValueKey('workspace-content'), + state: state, + child: Stack( + children: [ + LayoutBuilder( + builder: (context, constraints) { + final navigationHiddenBySpace = + desktop && + !WorkspaceLayoutPolicy.desktopNavigationFits( + constraints.maxWidth, + ); + final navigationCollapsed = + _sidebarCollapsed || navigationHiddenBySpace; + Widget controls({ + bool navigationToggle = true, + }) => HeaderControlRegion( + child: Row( + mainAxisSize: MainAxisSize.min, + spacing: AppSpacing.tiny, + children: [ + if (navigationToggle) + SizedBox.square( + dimension: AppControlSize.headerButton, + child: IconButton( + key: const Key( + 'project-sidebar-toggle', + ), + tooltip: navigationCollapsed + ? context.l10n.expandSidebar + : context.l10n.collapseSidebar, + onPressed: () { + if (navigationHiddenBySpace) { + _desktopScaffoldKey.currentState + ?.openDrawer(); + } else { + _sidebarCollapsed = + !_sidebarCollapsed; + _saveViewState(); + } + }, + style: sidebarActionButtonStyle( + context, + ), + icon: const Icon( + Icons.view_sidebar_outlined, + size: AppIconSize.header, + ), + ), + ), + if (desktop && + navigationCollapsed && + navigationToggle) + PopupMenuButton( + key: const Key('desktop-workspace-mode'), + initialValue: _mode, + onSelected: _setMode, + itemBuilder: (context) => [ + for (final mode in WorkspaceMode.values) + PopupMenuItem( + key: ValueKey( + 'desktop-mode-${mode.name}', + ), + value: mode, + child: Text( + mode == WorkspaceMode.agent + ? context.l10n.workspaceAgent + : context.l10n.workspaceCut, + ), + ), + ], + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: 6, + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + _mode == WorkspaceMode.agent + ? context.l10n.workspaceAgent + : context.l10n.workspaceCut, + ), + const Icon( + Icons.keyboard_arrow_down, + size: 16, + ), + ], + ), + ), + ), + SizedBox.square( + dimension: desktop + ? AppControlSize.headerButton + : 48, + child: IconButton( + key: const Key('project-settings-button'), + tooltip: context.l10n.settings, + onPressed: () => + showSettingsDialog(context), + style: sidebarActionButtonStyle(context), + icon: const Icon( + Icons.settings_outlined, + size: AppIconSize.header, + ), + ), + ), + SizedBox.square( + dimension: desktop + ? AppControlSize.headerButton + : 48, + child: const BackgroundTasksButton(), + ), + ], + ), + ); + Widget leading() => Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (navigationCollapsed && integrated) + SizedBox( + width: EditorWindowChrome.leadingWidth, + ), + if (navigationCollapsed) controls(), + const SizedBox(width: AppSpacing.compact), + ], + ); + void selectProject(RecentProject project) { + if (project.availability.canOpen) { + _openProject(ref, project); + } else { + _relocateProject(context, ref, project); + } + } + + final agent = WorkspaceAgentSurface( + key: _agentKey, + state: state, + onSelectProject: (project) => + project.availability.canOpen + ? _openProject(ref, project) + : _relocateProject(context, ref, project), + onCreateProject: () => + _selectProject(context, ref, create: true), + ); + Widget navigation({ + DesktopWorkspaceGeometry? geometry, + VoidCallback? expandEditor, + bool drawer = false, + }) => ProjectSidebar( + experience: experience, + key: drawer + ? _drawerNavigationKey + : _navigationKey, + agent: desktop && !drawer + ? agent + : const SizedBox.shrink(), + navigationOnly: !desktop || drawer, + onNavigationComplete: desktop && !drawer + ? null + : () => Navigator.of(context).maybePop(), + editorHidden: geometry?.editorHidden ?? false, + onExpandEditor: expandEditor, + agentHeaderLeading: desktop + ? leading() + : const SizedBox.shrink(), + navigationCollapsed: + desktop && !drawer && navigationCollapsed, + mode: _mode, + onModeChanged: _setMode, + navigationWidth: geometry?.sidebarWidth ?? 320, + state: state, + selectedProjectId: + _selectedProjectId ?? state.activeProject?.id, + integratedTitlebar: integrated, + onCreateProject: () => + _selectProject(context, ref, create: true), + onSelectProject: selectProject, + onRenameProject: (project) => + _renameProject(context, ref, project), + headerControls: desktop && !drawer + ? controls() + : HeaderControlRegion( + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Builder( + builder: (context) => IconButton( + tooltip: MaterialLocalizations.of( + context, + ).closeButtonTooltip, + onPressed: () => + Scaffold.of(context) + .closeDrawer(), + icon: const Icon(Icons.close), + ), + ), + ], + ), + ), + ); + final editor = ProjectLoadingRegion( + loading: _switchingProject, + child: + state.activeProject != null && + state.timeline != null + ? EditorWorkspace( + key: _editorKey, + experience: experience, + projectId: state.activeProject!.id, + timelineId: state.timeline!.id, + projectName: state.activeProject!.name, + showProjectName: + desktop && _mode == WorkspaceMode.cut, + integratedTitlebar: desktop && integrated, + headerLeading: + desktop && _mode == WorkspaceMode.cut + ? leading() + : const SizedBox( + width: AppSpacing.compact, + ), + ) + : EmptyEditor( + state: state, + showProjectName: + desktop && _mode == WorkspaceMode.cut, + headerLeading: + desktop && _mode == WorkspaceMode.cut + ? leading() + : const SizedBox( + width: AppSpacing.compact, + ), + ), + ); + return switch (experience) { + DeviceExperience.desktop => DesktopWorkspaceShell( + controller: _desktopSplits, + scaffoldKey: _desktopScaffoldKey, + navigationDrawer: navigation(drawer: true), + mode: _mode, + sidebarCollapsed: navigationCollapsed, + sidebarWidth: _sidebarWidthOverride, + onSidebarCollapsedChanged: (value) { + _sidebarCollapsed = value; + _saveViewState(); + }, + onSidebarWidthChanged: (value) { + _sidebarWidthOverride = value; + _saveViewState(); + }, + sidebarBuilder: (geometry, expand) => + navigation( + geometry: geometry, + expandEditor: expand, + ), + editor: editor, + ), + DeviceExperience.tablet => TabletWorkspaceShell( + mode: _mode, + onModeChanged: _setMode, + navigation: navigation(), + headerActions: controls( + navigationToggle: false, + ), + title: state.activeProject?.name ?? 'Cutdex', + integratedTitlebar: integrated, + agent: agent, + editor: editor, + ), + DeviceExperience.phone => PhoneWorkspaceShell( + mode: _mode, + onModeChanged: _setMode, + navigation: navigation(), + headerActions: controls( + navigationToggle: false, + ), + title: state.activeProject?.name ?? 'Cutdex', + integratedTitlebar: integrated, + agent: agent, + editor: editor, + ), + }; + }, + ), + PositionedDirectional( + top: AppSpacing.compact, + end: AppSpacing.compact, + child: _SonnerErrorToast( + message: projects.hasError + ? const AppFailure( + AppErrorCode.loadProjectsFailed, + ) + : state.error, + ), + ), + ], + ), + ), + ), + ), + ), + ); + } +} + +class _StartupLoading extends StatefulWidget { + const _StartupLoading({super.key}); + + @override + State<_StartupLoading> createState() => _StartupLoadingState(); +} + +class _StartupLoadingState extends State<_StartupLoading> + with SingleTickerProviderStateMixin { + late final AnimationController _pulse = AnimationController( + vsync: this, + duration: const Duration(milliseconds: 1800), + )..repeat(reverse: true); + + late final Animation _opacity = Tween( + begin: 0.5, + end: 1, + ).animate(CurvedAnimation(parent: _pulse, curve: Curves.easeInOut)); + + @override + void dispose() { + _pulse.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => Center( + child: Semantics( + liveRegion: true, + child: FadeTransition( + opacity: _opacity, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + 'CUTDEX', + style: Theme.of(context).textTheme.titleMedium + ?.copyWith(fontWeight: FontWeight.w600, letterSpacing: 3), + ), + const SizedBox(height: AppSpacing.medium), + Text( + context.l10n.openingWorkspace, + style: Theme.of(context).textTheme.bodyMedium?.copyWith( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + ], + ), + ), + ), + ); +} + +class _SonnerErrorToast extends StatefulWidget { + const _SonnerErrorToast({required this.message}); + + final AppFailure? message; + + @override + State<_SonnerErrorToast> createState() => _SonnerErrorToastState(); +} + +class _SonnerErrorToastState extends State<_SonnerErrorToast> { + static const _displayDuration = Duration(seconds: 6); + + Timer? _timer; + AppFailure? _displayedMessage; + bool _visible = false; + + @override + void initState() { + super.initState(); + _show(widget.message); + } + + @override + void didUpdateWidget(covariant _SonnerErrorToast oldWidget) { + super.didUpdateWidget(oldWidget); + if (widget.message != null && + (oldWidget.message == null || widget.message != oldWidget.message)) { + _show(widget.message); + } + } + + void _show(AppFailure? message) { + if (message == null) return; + _timer?.cancel(); + _displayedMessage = message; + _visible = true; + _timer = Timer(_displayDuration, _hide); + } + + void _hide() { + if (mounted) setState(() => _visible = false); + } + + @override + void dispose() { + _timer?.cancel(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final message = _displayedMessage; + if (message == null) return const SizedBox.shrink(); + final theme = Theme.of(context); + return IgnorePointer( + ignoring: !_visible, + child: AnimatedSlide( + offset: _visible ? Offset.zero : const Offset(0.08, 0), + duration: const Duration(milliseconds: 180), + curve: Curves.easeOutCubic, + child: AnimatedOpacity( + opacity: _visible ? 1 : 0, + duration: const Duration(milliseconds: 160), + child: Semantics( + liveRegion: true, + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 360), + child: DecoratedBox( + decoration: BoxDecoration( + color: theme.colorScheme.surfaceContainerHigh, + border: Border.all(color: theme.colorScheme.outlineVariant), + borderRadius: BorderRadius.circular(AppRadius.large), + boxShadow: [ + BoxShadow( + color: theme.colorScheme.shadow.withValues(alpha: .25), + blurRadius: 16, + offset: const Offset(0, 6), + ), + ], + ), + child: Padding( + padding: const EdgeInsetsDirectional.only( + start: AppSpacing.compact, + top: AppSpacing.small, + bottom: AppSpacing.small, + end: AppSpacing.tiny, + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.error_outline, + size: AppIconSize.small, + color: theme.colorScheme.error, + ), + const SizedBox(width: AppSpacing.small), + Flexible( + child: Text( + context.l10n.failureMessage(message), + style: theme.textTheme.bodyMedium, + ), + ), + IconButton( + tooltip: MaterialLocalizations.of(context) + .closeButtonTooltip, + onPressed: _hide, + icon: const Icon(Icons.close, size: AppIconSize.small), + ), + ], + ), + ), + ), + ), + ), + ), + ), + ); + } +} diff --git a/lib/features/projects/touch_project_navigation.dart b/lib/features/projects/touch_project_navigation.dart new file mode 100644 index 0000000..5b0dec0 --- /dev/null +++ b/lib/features/projects/touch_project_navigation.dart @@ -0,0 +1,137 @@ +import 'package:flutter/material.dart'; + +import '../../l10n/l10n.dart'; + +import 'package:cutdex_ui/widgets.dart'; + +import '../../workspace/project_state.dart'; + +class TouchProjectsHeader extends StatelessWidget { + const TouchProjectsHeader({super.key, required this.onCreate}); + final VoidCallback? onCreate; + + @override + Widget build(BuildContext context) => Row( + children: [ + Expanded(child: Text(context.l10n.projects)), + SizedBox.square( + dimension: 48, + child: IconButton( + key: const Key('create-project'), + tooltip: context.l10n.newProject, + onPressed: onCreate, + icon: const Icon(Icons.add), + ), + ), + ], + ); +} + +/// Touch navigation keeps its actions visible and uses finger-sized targets. +class TouchProjectTile extends StatelessWidget { + const TouchProjectTile({ + super.key, + required this.project, + required this.selected, + required this.expanded, + required this.availabilityLabel, + required this.onSelect, + required this.onToggle, + required this.onNewConversation, + required this.onRename, + required this.onRemove, + }); + final RecentProject project; + final bool selected; + final bool expanded; + final String availabilityLabel; + final VoidCallback onSelect; + final VoidCallback onToggle; + final VoidCallback? onNewConversation; + final VoidCallback? onRename; + final VoidCallback? onRemove; + + @override + Widget build(BuildContext context) => ListTile( + key: ValueKey('sidebar-project-${project.id}'), + contentPadding: EdgeInsets.zero, + minTileHeight: 56, + selected: selected, + leading: IconButton( + key: ValueKey('sidebar-project-toggle-${project.id}'), + constraints: const BoxConstraints.tightFor(width: 48, height: 48), + tooltip: expanded + ? context.l10n.collapseProject + : context.l10n.expandProject, + onPressed: onToggle, + icon: Icon(expanded ? Icons.expand_more : Icons.chevron_right), + ), + title: Text(project.name, maxLines: 1, overflow: TextOverflow.ellipsis), + subtitle: project.availability.canOpen ? null : Text(availabilityLabel), + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: [ + IconButton( + key: ValueKey('new-agent-conversation-${project.id}'), + constraints: const BoxConstraints.tightFor(width: 48, height: 48), + tooltip: context.l10n.agentNewConversation, + onPressed: onNewConversation, + icon: const Icon(Icons.edit_square), + ), + AppPopover( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + AppMenuItem(label: context.l10n.rename, onPressed: onRename), + AppMenuItem( + label: context.l10n.removeProjectFromSidebar, + onPressed: onRemove, + ), + ], + ), + builder: (context, toggle) => IconButton( + key: ValueKey('sidebar-project-more-${project.id}'), + constraints: const BoxConstraints.tightFor(width: 48, height: 48), + onPressed: toggle, + icon: const Icon(Icons.more_horiz), + ), + ), + ], + ), + onTap: onSelect, + ); +} + +class TouchConversationTile extends StatelessWidget { + const TouchConversationTile({ + super.key, + required this.id, + required this.title, + required this.selected, + required this.onSelect, + required this.actions, + }); + final String id; + final String title; + final bool selected; + final VoidCallback onSelect; + final List Function(BuildContext) actions; + + @override + Widget build(BuildContext context) => ListTile( + key: ValueKey('sidebar-conversation-$id'), + minTileHeight: 48, + selected: selected, + title: Text(title, maxLines: 1, overflow: TextOverflow.ellipsis), + onTap: onSelect, + trailing: AppPopover( + child: Column(mainAxisSize: MainAxisSize.min, children: actions(context)), + builder: (context, toggle) => IconButton( + key: ValueKey('sidebar-conversation-more-$id'), + constraints: const BoxConstraints.tightFor(width: 48, height: 48), + onPressed: toggle, + icon: const Icon(Icons.more_horiz), + ), + ), + ); +} diff --git a/lib/features/projects/widgets/name_dialog.dart b/lib/features/projects/widgets/name_dialog.dart new file mode 100644 index 0000000..03498c2 --- /dev/null +++ b/lib/features/projects/widgets/name_dialog.dart @@ -0,0 +1,103 @@ +import 'package:cutdex/l10n/l10n.dart'; +import 'package:flutter/material.dart'; + +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex_ui/widgets.dart'; + +Future askName( + BuildContext context, { + required String title, + required String label, + String? description, + String initialValue = '', + String? submitLabel, +}) => showAppDialog( + context: context, + builder: (_) => _NameDialog( + title: title, + label: label, + description: description, + initialValue: initialValue, + submitLabel: submitLabel, + ), +); + +class _NameDialog extends StatefulWidget { + const _NameDialog({ + required this.title, + required this.label, + this.description, + required this.initialValue, + this.submitLabel, + }); + final String title; + final String label; + final String? description; + final String initialValue; + final String? submitLabel; + @override + State<_NameDialog> createState() => _NameDialogState(); +} + +class _NameDialogState extends State<_NameDialog> { + late final _controller = TextEditingController(text: widget.initialValue) + ..selection = TextSelection( + baseOffset: 0, + extentOffset: widget.initialValue.length, + ); + final _form = GlobalKey(); + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + void _submit() { + if (_form.currentState!.validate()) { + Navigator.pop(context, _controller.text.trim()); + } + } + + @override + Widget build(BuildContext context) => AppDialog( + title: widget.title, + description: widget.description, + width: 420, + actions: [ + TextButton( + onPressed: () => Navigator.pop(context), + child: Text(context.l10n.cancel), + ), + FilledButton( + onPressed: _submit, + child: Text(widget.submitLabel ?? context.l10n.create), + ), + ], + child: Builder( + builder: (dialogContext) => Form( + key: _form, + child: TextFormField( + controller: _controller, + style: AppTheme.inputTextStyle(dialogContext), + cursorHeight: AppTheme.inputCursorHeight(dialogContext), + autofocus: true, + maxLength: 80, + buildCounter: ( + _, { + required currentLength, + required isFocused, + maxLength, + }) => null, + decoration: InputDecoration(hintText: widget.label), + validator: (value) => value == null || value.trim().isEmpty + ? context.l10n.enterName + : RegExp(r'[/\\\x00-\x1F]').hasMatch(value) || + ['.', '..'].contains(value.trim()) + ? context.l10n.invalidName + : null, + onFieldSubmitted: (_) => _submit(), + ), + ), + ), + ); +} diff --git a/lib/features/properties/animation_labels.dart b/lib/features/properties/animation_labels.dart new file mode 100644 index 0000000..6354276 --- /dev/null +++ b/lib/features/properties/animation_labels.dart @@ -0,0 +1,26 @@ +import 'package:flutter/widgets.dart'; +import 'package:cutdex/l10n/l10n.dart'; +import 'package:cutdex_sdk/editor.dart'; + +extension TransformChannelLabel on TransformChannel { + String label(BuildContext context) => switch (this) { + TransformChannel.position => context.l10n.position, + TransformChannel.rotation => context.l10n.rotation, + TransformChannel.scale => context.l10n.scale, + }; +} + +Map> localizedMaskChannels(BuildContext context) => { + context.l10n.position: ['center.x', 'center.y'], + context.l10n.size: ['width', 'height'], + context.l10n.rotation: ['rotation'], + context.l10n.feather: ['feather'], +}; + +// Stable channel identifiers are independent of the interface language. +const maskChannels = { + 'position': ['center.x', 'center.y'], + 'size': ['width', 'height'], + 'rotation': ['rotation'], + 'feather': ['feather'], +}; diff --git a/lib/features/properties/audio_gain_scale.dart b/lib/features/properties/audio_gain_scale.dart new file mode 100644 index 0000000..91ec58a --- /dev/null +++ b/lib/features/properties/audio_gain_scale.dart @@ -0,0 +1,27 @@ +/// Slider travel is a presentation choice, independent of authored gain. +abstract final class AudioGainScale { + static const decimalPlaces = 1; + static double quantizeDb(double db) => double.parse(formatDb(db)); + static String formatDb(double db) { + final text = db.toStringAsFixed(decimalPlaces); + return text == '-0.0' ? '0.0' : text; + } + + // Reserve 70% of travel for -24...+6 dB. Zero is a separate mute endpoint. + static double dbAt(double position) { + if (!position.isFinite) throw ArgumentError.value(position); + final p = position.clamp(0.0, 1.0); + if (p <= .01) return -90; + if (p <= .2) return -90 + (p - .01) / .19 * 66; + if (p <= .9) return -24 + (p - .2) / .7 * 30; + return 6 + (p - .9) / .1 * 6; + } + + static double positionAt(double db) { + if (!db.isFinite) throw ArgumentError.value(db); + final value = db.clamp(-90.0, 12.0); + if (value <= -24) return .01 + (value + 90) / 66 * .19; + if (value <= 6) return .2 + (value + 24) / 30 * .7; + return .9 + (value - 6) / 6 * .1; + } +} diff --git a/lib/features/properties/audio_properties.dart b/lib/features/properties/audio_properties.dart new file mode 100644 index 0000000..aee5489 --- /dev/null +++ b/lib/features/properties/audio_properties.dart @@ -0,0 +1,362 @@ +import 'package:cutdex/l10n/l10n.dart'; +import 'package:cutdex/features/properties/audio_gain_scale.dart'; +import 'package:cutdex_sdk/timeline/engine.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter/material.dart'; + +import 'package:cutdex_ui/widgets.dart'; +import 'package:cutdex_ui/theme.dart'; + +import '../../workspace/timeline_session.dart'; + +import 'package:cutdex_sdk/editor.dart'; + +export 'package:cutdex_sdk/editor.dart' show ClipAudioGain; + +class AudioProperties extends StatefulWidget { + const AudioProperties({ + super.key, + required this.session, + required this.sequence, + required this.clip, + required this.hasAudio, + }); + final EditorTimelineSession session; + final SequenceId sequence; + final ElementRecord clip; + final bool hasAudio; + + @override + State createState() => _AudioPropertiesState(); +} + +class _AudioPropertiesState extends State { + final _text = TextEditingController(); + final _focus = FocusNode(); + ClipAudioGain? _timeline; + Object? _editVersion; + int? _editTick; + String? _error; + bool _dirty = false; + + @override + void initState() { + super.initState(); + _focus.addListener(_focusChanged); + } + + void _focusChanged() { + if (_focus.hasFocus) { + _beginEdit(); + } else if (_dirty) { + _submit(_text.text); + } + } + + @override + void dispose() { + widget.session.clearAudioGainPreview(widget.clip.id); + _focus.removeListener(_focusChanged); + _focus.dispose(); + _text.dispose(); + super.dispose(); + } + + void _beginEdit() { + final view = widget.session.view(widget.sequence); + _editVersion = view.version.kernelVersion; + _editTick = view.playheadTick; + } + + bool get _editValid { + final view = widget.session.view(widget.sequence); + return widget.session.activeSequenceId == widget.sequence && + (_editVersion == null || + identical(_editVersion, view.version.kernelVersion)) && + (_editTick == null || _editTick == view.playheadTick); + } + + bool _commit(ClipAudioGain value) { + widget.session.clearAudioGainPreview(widget.clip.id); + final view = widget.session.view(widget.sequence); + final query = view.version.kernelVersion.query(); + final handle = query.elementById(widget.clip.id); + if (handle == null || !_editValid) { + setState(() { + _timeline = null; + _dirty = false; + _error = null; + }); + return false; + } + try { + widget.session.commands.setAudio( + sequence: widget.sequence, + clip: widget.clip.id, + tick: _editTick ?? view.playheadTick, + db: value.db, + muted: value.muted, + ); + setState(() { + _timeline = null; + _dirty = false; + _editVersion = null; + _editTick = null; + _error = null; + }); + return true; + } catch (_) { + setState(() => _error = context.l10n.updateVolumeFailed); + return false; + } + } + + bool _submit(String text) { + final db = double.tryParse(text.trim()); + if (db == null || !db.isFinite || db < -90 || db > 12) { + setState(() => _error = context.l10n.invalidGain); + return false; + } + return _commit(ClipAudioGain(AudioGainScale.quantizeDb(db))); + } + + @override + Widget build(BuildContext context) { + final view = widget.session.view(widget.sequence); + return ListenableBuilder( + listenable: view, + builder: (context, _) { + final query = view.version.kernelVersion.query(); + final handle = query.elementById(widget.clip.id); + final record = handle == null ? widget.clip : query.element(handle); + final localTick = handle == null + ? 0 + : view.playheadTick - query.absoluteStart(handle); + final sourceTick = TimelineSourceClock(record).nearestSourceTick( + localTick.clamp(0, record.duration > 0 ? record.duration - 1 : 0), + ); + final saved = ClipAudioGain.fromRecord(record, sourceTick: sourceTick); + final keyed = + record.parameters?[ClipAudioGain.gainId]?.keyframeAt(sourceTick) != + null; + final value = _editValid ? _timeline ?? saved : saved; + final enabled = widget.hasAudio && handle != null; + if (!_dirty) { + final text = value.muted ? '-∞' : AudioGainScale.formatDb(value.db); + if (_text.text != text) _text.text = text; + } + if (ClipAudioGain.isDetached(record)) { + return Padding( + padding: AppSpacing.panelSection, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + context.l10n.audioDetached, + style: AppTheme.propertySectionTitleStyle(context), + ), + const SizedBox(height: AppSpacing.small), + OutlinedButton.icon( + key: const Key('audio-restore'), + icon: const Icon(Icons.volume_up_outlined), + label: Text(context.l10n.restoreAudio), + onPressed: !enabled || !widget.session.acceptsEdits + ? null + : () { + try { + widget.session.commands.setAudio( + sequence: widget.sequence, + clip: record.id, + muted: false, + ); + setState(() { + _timeline = null; + _dirty = false; + _editVersion = null; + _error = null; + }); + } catch (_) { + setState( + () => _error = context.l10n.updateVolumeFailed, + ); + } + }, + ), + if (_error != null) Text(_error!), + ], + ), + ); + } + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: AppSpacing.panelSection, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + Expanded( + child: Text( + widget.hasAudio + ? context.l10n.volume + : context.l10n.unboundAudio, + style: AppTheme.propertySectionTitleStyle(context), + ), + ), + IconButton( + key: const Key('audio-key'), + tooltip: context.l10n.toggleKeyframe( + keyed + ? context.l10n.delete + : context.l10n.addKeyframeAction, + context.l10n.volume, + ), + isSelected: keyed, + icon: Transform.rotate( + angle: 0.7853981633974483, + child: Icon( + keyed ? Icons.square : Icons.crop_square, + size: 12, + ), + ), + onPressed: !enabled + ? null + : () { + if (_dirty && !_submit(_text.text)) return; + _focus.unfocus(); + FocusManager.instance + .applyFocusChangesIfNeeded(); + try { + widget.session.commands.editKeyframeChannel( + sequence: widget.sequence, + clip: widget.clip.id, + tick: view.playheadTick, + parameterIds: [ClipAudioGain.gainId], + ); + } catch (_) { + setState( + () => _error = + context.l10n.updateKeyframesFailed, + ); + } + }, + ), + IconButton( + key: const Key('audio-mute'), + tooltip: value.muted + ? context.l10n.unmute + : context.l10n.mute, + isSelected: value.muted, + icon: Icon( + value.muted ? Icons.volume_off : Icons.volume_up, + ), + onPressed: !enabled + ? null + : () { + _editVersion = null; + _editTick = null; + _commit( + ClipAudioGain(saved.db, muted: !saved.muted), + ); + }, + ), + IconButton( + key: const Key('audio-reset'), + tooltip: context.l10n.resetVolume, + icon: const Icon(Icons.restart_alt), + onPressed: !enabled + ? null + : () { + _editVersion = null; + _editTick = null; + _commit(const ClipAudioGain(0)); + }, + ), + ], + ), + const SizedBox(height: AppSpacing.small), + Row( + children: [ + Expanded( + child: AppSlider( + key: const Key('audio-slider'), + value: value.muted + ? 0 + : AudioGainScale.positionAt(value.db), + semanticFormatterCallback: (p) => p == 0 + ? context.l10n.mute + : '${AudioGainScale.formatDb(AudioGainScale.dbAt(p))} dB', + onChangeStart: !enabled + ? null + : (_) { + _focus.unfocus(); + FocusManager.instance + .applyFocusChangesIfNeeded(); + _beginEdit(); + }, + onChanged: !enabled + ? null + : (p) => setState(() { + if (!_editValid) { + widget.session.clearAudioGainPreview( + widget.clip.id, + ); + _timeline = null; + return; + } + _dirty = false; + _timeline = p == 0 + ? ClipAudioGain(saved.db, muted: true) + : ClipAudioGain( + AudioGainScale.quantizeDb( + AudioGainScale.dbAt(p), + ), + ); + widget.session.previewAudioGain( + widget.sequence, + widget.clip.id, + _timeline!, + ); + }), + onChangeEnd: !enabled + ? null + : (_) => _commit(_timeline ?? saved), + ), + ), + const SizedBox(width: AppSpacing.small), + SizedBox( + width: 84, + child: AppTextField( + key: const Key('audio-db'), + controller: _text, + focusNode: _focus, + label: null, + unit: 'dB', + enabled: enabled, + errorText: _error, + keyboardType: const TextInputType.numberWithOptions( + signed: true, + decimal: true, + ), + onChanged: (_) { + if (!_dirty) { + _beginEdit(); + } + _dirty = true; + }, + onSubmitted: _submit, + ), + ), + ], + ), + ], + ), + ), + ], + ); + }, + ); + } +} diff --git a/lib/features/properties/canvas_presets.dart b/lib/features/properties/canvas_presets.dart new file mode 100644 index 0000000..f1b77e8 --- /dev/null +++ b/lib/features/properties/canvas_presets.dart @@ -0,0 +1,23 @@ +import 'package:flutter/widgets.dart'; +import 'package:cutdex/l10n/l10n.dart'; +import 'package:cutdex_sdk/editor.dart'; + +abstract final class ProjectCanvasPresets { + static const values = { + '16:9': ProjectCanvas.widescreen, + '4:3': ProjectCanvas(1440, 1080), + '1:1': ProjectCanvas(1080, 1080), + '9:16': ProjectCanvas(1080, 1920), + }; +} + +extension ProjectCanvasLabel on ProjectCanvas { + String label(BuildContext context) { + for (final entry in ProjectCanvasPresets.values.entries) { + if ((entry.value.aspectRatio - aspectRatio).abs() < 0.000001) { + return entry.key; + } + } + return context.l10n.custom; + } +} diff --git a/lib/features/properties/caption_properties.dart b/lib/features/properties/caption_properties.dart new file mode 100644 index 0000000..d3da137 --- /dev/null +++ b/lib/features/properties/caption_properties.dart @@ -0,0 +1,797 @@ +import 'package:cutdex/l10n/l10n.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter/material.dart'; + +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex_ui/widgets.dart'; + +import '../../workspace/timeline_session.dart'; +import 'property_number_input.dart'; + +enum _CaptionPropertyCategory { + captions, + text; + + String label(BuildContext context) => switch (this) { + captions => context.l10n.captions, + text => context.l10n.text, + }; +} + +/// Presentation only: validation, publication and history belong to editor. +class CaptionProperties extends StatefulWidget { + const CaptionProperties({ + super.key, + required this.session, + required this.sequence, + required this.clipId, + this.transformProperties, + }); + final EditorTimelineSession session; + final SequenceId sequence; + final String clipId; + final Widget? transformProperties; + + @override + State createState() => _CaptionPropertiesState(); +} + +class _CaptionPropertiesState extends State { + static const _maximumCommandSeconds = 9000000000000.0; + _CaptionPropertyCategory _selected = _CaptionPropertyCategory.text; + final _captionSearch = TextEditingController(); + String _captionQuery = ''; + bool _wrapCaptions = false; + String? _scrubField; + double? _scrubBase; + double? _scrubTimeline; + double _scrubScale = 1; + String? _scrubVersion; + + bool _save(SetCaption command) { + try { + widget.session.setCaption(widget.sequence, command); + return true; + } on CommandRejected catch (error) { + ScaffoldMessenger.maybeOf(context)?.showSnackBar( + SnackBar( + content: Text( + error.code == 'staleVersion' + ? context.l10n.captionEditChanged + : context.l10n.editFailed, + ), + ), + ); + return false; + } + } + + CommandTime _seconds(double value) => + CommandTime((value * 1000).round(), 1000); + + bool _startScrub(String field, double value, double scale) { + if (_scrubField != null) return false; + setState(() { + _scrubField = field; + _scrubBase = value; + _scrubTimeline = value; + _scrubScale = scale; + _scrubVersion = widget.session.version; + }); + return true; + } + + void _updateScrub(double distance, double min, double max) { + final base = _scrubBase; + if (base == null || _scrubVersion != widget.session.version) { + _cancelScrub(); + return; + } + setState(() { + _scrubTimeline = (base + distance * _scrubScale).clamp(min, max); + }); + } + + void _endScrub() { + final field = _scrubField; + final value = _scrubTimeline; + final base = _scrubBase; + final version = _scrubVersion; + _clearScrub(); + if (field == null || value == null || value == base || version == null) { + return; + } + final command = switch (field) { + 'fontSize' => SetCaption( + captionId: widget.clipId, + fontSize: value, + expectedVersion: version, + ), + 'strokeWidth' => SetCaption( + captionId: widget.clipId, + strokeWidth: value, + expectedVersion: version, + ), + 'positionY' => SetCaption( + captionId: widget.clipId, + positionY: value, + expectedVersion: version, + ), + 'start' => SetCaption( + captionId: widget.clipId, + start: _seconds(value), + expectedVersion: version, + ), + 'duration' => SetCaption( + captionId: widget.clipId, + duration: _seconds(value), + expectedVersion: version, + ), + _ => null, + }; + if (command != null) _save(command); + } + + void _clearScrub() { + if (!mounted) return; + setState(() { + _scrubField = null; + _scrubBase = null; + _scrubTimeline = null; + _scrubVersion = null; + }); + } + + void _cancelScrub() => _clearScrub(); + + @override + void didUpdateWidget(covariant CaptionProperties oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.clipId == widget.clipId && + oldWidget.sequence == widget.sequence) { + return; + } + if (oldWidget.sequence != widget.sequence || + oldWidget.session != widget.session) { + _selected = _CaptionPropertyCategory.text; + } + _scrubField = null; + _scrubBase = null; + _scrubTimeline = null; + _scrubVersion = null; + } + + @override + void dispose() { + _captionSearch.dispose(); + super.dispose(); + } + + void _selectCue(String id) { + final query = widget.session.persistence + .timeline(widget.sequence) + .current + .query(); + final cue = query.elementById(ElementId(id)); + if (cue == null) return; + final identity = widget.session.captionComponentFor(widget.sequence, cue); + widget.session.view(widget.sequence).setSelection([identity ?? cue]); + } + + Widget _captionList( + BuildContext context, + List<({String id, String text})> cues, + ) { + final matches = cues.indexed + .where((entry) => entry.$2.text.toLowerCase().contains(_captionQuery)) + .toList(); + return Column( + children: [ + Padding( + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.panelContentHorizontal, + vertical: AppSpacing.small, + ), + child: SizedBox( + height: 28, + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Expanded( + child: TextField( + key: const ValueKey('caption-search'), + controller: _captionSearch, + style: Theme.of(context).textTheme.bodyMedium, + cursorHeight: AppTheme.inputCursorHeight(context), + textAlignVertical: TextAlignVertical.center, + textInputAction: TextInputAction.search, + decoration: InputDecoration( + hintText: context.l10n.searchOptions( + context.l10n.captions, + ), + isDense: true, + constraints: const BoxConstraints.tightFor(height: 28), + contentPadding: const EdgeInsets.symmetric( + horizontal: 8, + vertical: 0, + ), + prefixIcon: const Icon(Icons.search, size: 14), + prefixIconConstraints: const BoxConstraints( + minWidth: 28, + minHeight: 28, + ), + ), + onChanged: (value) => setState( + () => _captionQuery = value.trim().toLowerCase(), + ), + ), + ), + const SizedBox(width: 4), + IconButton( + key: const ValueKey('caption-wrap-toggle'), + tooltip: _wrapCaptions + ? context.l10n.captionSingleLine + : context.l10n.captionWrapLines, + isSelected: _wrapCaptions, + color: _wrapCaptions + ? Theme.of(context).colorScheme.primary + : null, + icon: const Icon(Icons.wrap_text, size: 16), + padding: EdgeInsets.zero, + style: IconButton.styleFrom( + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + visualDensity: VisualDensity.standard, + ), + constraints: const BoxConstraints.tightFor( + width: 28, + height: 28, + ), + onPressed: () => + setState(() => _wrapCaptions = !_wrapCaptions), + ), + ], + ), + ), + ), + Expanded( + child: matches.isEmpty + ? Center( + child: Text( + context.l10n.noMatchingCaptions, + style: Theme.of(context).textTheme.bodySmall, + ), + ) + : ScrollEdgeFadeBuilder( + key: const ValueKey('caption-scroll-fade'), + builder: (controller) => ListView( + key: const ValueKey('caption-scroll-list'), + controller: controller, + padding: EdgeInsets.zero, + physics: const ClampingScrollPhysics(), + children: [ + for (final (index, cue) in matches) + Padding( + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.panelContentHorizontal, + vertical: AppSpacing.hairline, + ), + child: Material( + borderRadius: BorderRadius.circular( + AppRadius.menuItem, + ), + color: cue.id == widget.clipId + ? Theme.of(context).colorScheme.onSurface + .withValues(alpha: .05) + : Colors.transparent, + child: InkWell( + key: ValueKey('caption-list-${cue.id}'), + onTap: () => _selectCue(cue.id), + borderRadius: BorderRadius.circular( + AppRadius.menuItem, + ), + child: ConstrainedBox( + constraints: const BoxConstraints( + minHeight: 28, + ), + child: Padding( + padding: EdgeInsets.zero, + child: Row( + children: [ + SizedBox( + width: + cues.length.toString().length * 8.0, + child: Text( + '${index + 1}', + key: ValueKey( + 'caption-number-${cue.id}', + ), + textAlign: TextAlign.center, + style: Theme.of(context) + .textTheme + .bodySmall, + ), + ), + const SizedBox(width: 6), + Expanded( + child: Text( + cue.text, + key: ValueKey( + 'caption-content-${cue.id}', + ), + style: Theme.of(context) + .textTheme + .bodyMedium, + maxLines: _wrapCaptions ? null : 1, + softWrap: _wrapCaptions, + overflow: _wrapCaptions + ? TextOverflow.visible + : TextOverflow.ellipsis, + ), + ), + const SizedBox(width: 4), + SizedBox( + width: 28, + height: 28, + child: IconButton( + key: ValueKey( + 'caption-action-${cue.id}', + ), + tooltip: context.l10n.select, + padding: EdgeInsets.zero, + constraints: + const BoxConstraints.tightFor( + width: 28, + height: 28, + ), + icon: const Icon( + Icons.chevron_right, + size: 14, + ), + onPressed: () => _selectCue(cue.id), + ), + ), + ], + ), + ), + ), + ), + ), + ), + ], + ), + ), + ), + ], + ); + } + + @override + Widget build(BuildContext context) => ListenableBuilder( + listenable: widget.session, + builder: (context, _) { + final q = widget.session.persistence + .timeline(widget.sequence) + .current + .query(); + final handle = q.elementById(ElementId(widget.clipId)); + if (handle == null) return Text(context.l10n.captionDeleted); + final clip = q.element(handle); + final isRole = clip.containerStoryline != null; + final role = isRole + ? handle + : widget.session.captionRole(widget.sequence); + final child = role == null ? null : q.element(role).containerStoryline; + final cues = <({String id, String text})>[ + if (child != null) + for (final cue in q.storylineElements(child)) + if (q.element(cue).payloadRef case final payload?) + if (widget.session.payloadFor(payload)?.type == 'caption') + ( + id: q.element(cue).id.value, + text: widget.session + .caption(widget.sequence, q.element(cue).id.value) + .text, + ), + ]; + final categories = [ + _CaptionPropertyCategory.captions, + if (!isRole) _CaptionPropertyCategory.text, + ]; + final selected = isRole ? _CaptionPropertyCategory.captions : _selected; + Widget panel(Widget content) => WorkspacePanel( + paintBackground: false, + headerHeight: CompactPanelTabs.height, + headerPadding: EdgeInsets.zero, + showHeaderDivider: false, + controls: CompactPanelTabs<_CaptionPropertyCategory>( + values: categories, + selected: selected, + labelBuilder: (category) => category.label(context), + tabKeyBuilder: (category) => + ValueKey('caption-property-tab-${category.name}'), + onSelected: (category) => setState(() => _selected = category), + ), + child: content, + ); + if (selected == _CaptionPropertyCategory.captions) { + return panel(_captionList(context, cues)); + } + + final caption = widget.session.caption(widget.sequence, widget.clipId); + final version = widget.session.version; + final start = RationalTime.timelineTicks(q.localContext(handle).start) + .seconds; + final duration = RationalTime.timelineTicks(clip.duration).seconds; + double shown(String field, double value) => + _scrubField == field ? _scrubTimeline ?? value : value; + + Widget number({ + required String field, + required String label, + required double value, + required double min, + required double max, + required double scale, + String? unit, + int decimalPlaces = 2, + required SetCaption Function(double, String) command, + }) => PropertyNumberInput( + key: ValueKey('caption-$field'), + label: label, + unit: unit, + decimalPlaces: decimalPlaces, + value: shown(field, value), + enabled: true, + readOnly: _scrubField != null, + scrubbing: _scrubField == field, + editContext: (widget.clipId, version), + submit: (next) async { + if (!next.isFinite || next < min || next > max) return false; + return _save(command(next, version)); + }, + onScrubStart: () => _startScrub(field, value, scale), + onScrubUpdate: (distance) => _updateScrub(distance, min, max), + onScrubEnd: _endScrub, + onScrubCancel: _cancelScrub, + ); + + return panel( + ScrollEdgeFadeBuilder( + key: const ValueKey('caption-detail-scroll-fade'), + builder: (controller) => ListView( + controller: controller, + padding: const EdgeInsets.symmetric(vertical: AppSpacing.small), + children: + [ + Row( + children: [ + Expanded( + child: Text( + context.l10n.textClip, + style: AppTheme.propertySectionTitleStyle( + context, + ), + ), + ), + IconButton( + tooltip: context.l10n.deleteCaption, + icon: const Icon(Icons.delete_outline), + onPressed: () { + try { + widget.session.commands.applyEdit( + widget.sequence, + DeleteClip( + widget.clipId, + expectedVersion: version, + ), + ); + } on CommandRejected { + ScaffoldMessenger.maybeOf( + context, + )?.showSnackBar( + SnackBar( + content: Text(context.l10n.captionChanged), + ), + ); + } + }, + ), + ], + ), + const SizedBox(height: AppSpacing.small), + Text( + context.l10n.content, + style: AppTheme.propertySectionTitleStyle(context), + ), + const SizedBox(height: AppSpacing.small), + _CaptionTextInput( + key: ValueKey(('caption-text', widget.clipId)), + value: caption.text, + maxLines: 3, + onSubmit: (text) => _save( + SetCaption( + captionId: widget.clipId, + text: text, + expectedVersion: version, + ), + ), + ), + const SizedBox(height: AppSpacing.small), + number( + field: 'fontSize', + label: context.l10n.fontSize, + value: caption.fontSize, + min: 1, + max: 1024, + scale: .2, + unit: 'px', + command: (value, expected) => SetCaption( + captionId: widget.clipId, + fontSize: value, + expectedVersion: expected, + ), + ), + const SizedBox(height: AppSpacing.small), + _CaptionColorInput( + key: ValueKey(('caption-color', widget.clipId)), + value: caption.color, + label: context.l10n.color, + onSubmit: (color) => _save( + SetCaption( + captionId: widget.clipId, + color: color, + expectedVersion: version, + ), + ), + ), + const SizedBox(height: AppSpacing.small), + _CaptionColorInput( + key: ValueKey(('caption-strokeColor', widget.clipId)), + value: caption.strokeColor, + label: context.l10n.outlineColor, + onSubmit: (color) => _save( + SetCaption( + captionId: widget.clipId, + strokeColor: color, + expectedVersion: version, + ), + ), + ), + const SizedBox(height: AppSpacing.small), + number( + field: 'strokeWidth', + label: context.l10n.outlineWidth, + value: caption.strokeWidth, + min: 0, + max: caption.fontSize, + scale: .05, + unit: 'px', + command: (value, expected) => SetCaption( + captionId: widget.clipId, + strokeWidth: value, + expectedVersion: expected, + ), + ), + if (widget.transformProperties case final transform?) ...[ + const SizedBox(height: AppSpacing.medium), + const Divider(height: 1), + const SizedBox(height: AppSpacing.medium), + Text( + context.l10n.transform, + style: AppTheme.propertySectionTitleStyle(context), + ), + const SizedBox(height: AppSpacing.small), + transform, + ], + const SizedBox(height: AppSpacing.medium), + Text( + context.l10n.captionBaseline, + style: AppTheme.propertySectionTitleStyle(context), + ), + const SizedBox(height: AppSpacing.small), + number( + field: 'positionY', + label: context.l10n.vertical, + value: caption.positionY, + min: -.5, + max: .5, + scale: .002, + decimalPlaces: 3, + command: (value, expected) => SetCaption( + captionId: widget.clipId, + positionY: value, + expectedVersion: expected, + ), + ), + const SizedBox(height: AppSpacing.medium), + Text( + context.l10n.time, + style: AppTheme.propertySectionTitleStyle(context), + ), + const SizedBox(height: AppSpacing.small), + LayoutBuilder( + builder: (context, constraints) { + Widget startField() => number( + field: 'start', + label: context.l10n.start, + value: start, + min: 0, + max: _maximumCommandSeconds, + scale: .01, + unit: context.l10n.seconds, + decimalPlaces: 3, + command: (value, expected) => SetCaption( + captionId: widget.clipId, + start: _seconds(value), + expectedVersion: expected, + ), + ); + Widget durationField() => number( + field: 'duration', + label: context.l10n.duration, + value: duration, + min: .001, + max: _maximumCommandSeconds, + scale: .01, + unit: context.l10n.seconds, + decimalPlaces: 3, + command: (value, expected) => SetCaption( + captionId: widget.clipId, + duration: _seconds(value), + expectedVersion: expected, + ), + ); + if (constraints.maxWidth < 240) { + return Column( + children: [ + startField(), + const SizedBox(height: AppSpacing.small), + durationField(), + ], + ); + } + return Row( + children: [ + Expanded(child: startField()), + const SizedBox(width: AppSpacing.small), + Expanded(child: durationField()), + ], + ); + }, + ), + ] + .map( + (item) => + item is SizedBox || + identical(item, widget.transformProperties) + ? item + : Padding( + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.panelContentHorizontal, + ), + child: item, + ), + ) + .toList(), + ), + ), + ); + }, + ); +} + +class _CaptionTextInput extends StatefulWidget { + const _CaptionTextInput({ + super.key, + required this.value, + required this.onSubmit, + this.label, + this.maxLines = 1, + }); + final String value; + final String? label; + final int maxLines; + final bool Function(String) onSubmit; + + @override + State<_CaptionTextInput> createState() => _CaptionTextInputState(); +} + +class _CaptionTextInputState extends State<_CaptionTextInput> { + late final _controller = TextEditingController(text: widget.value); + final _focus = FocusNode(); + bool _dirty = false; + String? _error; + + @override + void initState() { + super.initState(); + _focus.addListener(_handleFocus); + } + + void _handleFocus() { + if (!_focus.hasFocus) _submit(); + } + + void _submit() { + if (!_dirty) return; + final accepted = widget.onSubmit(_controller.text); + if (!mounted) return; + setState(() { + _dirty = false; + _error = accepted ? null : context.l10n.notApplied; + if (!accepted) _controller.text = widget.value; + }); + } + + @override + void didUpdateWidget(covariant _CaptionTextInput oldWidget) { + super.didUpdateWidget(oldWidget); + if (!_dirty && _controller.text != widget.value) { + _controller.text = widget.value; + } + } + + @override + void dispose() { + _focus.removeListener(_handleFocus); + _focus.dispose(); + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => AppTextField( + controller: _controller, + focusNode: _focus, + label: widget.label, + minLines: widget.maxLines, + maxLines: widget.maxLines, + textInputAction: TextInputAction.done, + errorText: _error, + onChanged: (_) { + _dirty = true; + if (_error != null) setState(() => _error = null); + }, + onEditingComplete: () {}, + onSubmitted: (_) => _submit(), + onTapOutside: (_) => _focus.unfocus(), + ); +} + +class _CaptionColorInput extends StatelessWidget { + const _CaptionColorInput({ + super.key, + required this.value, + required this.label, + required this.onSubmit, + }); + + final String value; + final String label; + final bool Function(String) onSubmit; + + @override + Widget build(BuildContext context) => Row( + children: [ + Container( + width: 20, + height: 20, + decoration: BoxDecoration( + color: Color(int.parse('FF${value.substring(1)}', radix: 16)), + border: Border.all(color: Theme.of(context).colorScheme.outline), + borderRadius: BorderRadius.circular(AppRadius.extraSmall), + ), + ), + const SizedBox(width: AppSpacing.small), + Expanded( + child: _CaptionTextInput( + value: value, + label: label, + onSubmit: onSubmit, + ), + ), + ], + ); +} diff --git a/lib/features/properties/color_interpretation_properties.dart b/lib/features/properties/color_interpretation_properties.dart new file mode 100644 index 0000000..4c9314d --- /dev/null +++ b/lib/features/properties/color_interpretation_properties.dart @@ -0,0 +1,103 @@ +import 'package:cutdex/l10n/l10n.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex_ui/widgets.dart'; + +import '../../workspace/media_color_interpretation.dart'; +import '../../workspace/timeline_session.dart'; +import '../preview/preview_panel.dart'; + +class ColorInterpretationProperties extends ConsumerWidget { + const ColorInterpretationProperties({ + super.key, + required this.projectId, + required this.timelineId, + required this.session, + required this.assetId, + required this.trackIndex, + }); + + final String projectId; + final String timelineId; + final EditorTimelineSession session; + final String assetId; + final int trackIndex; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final preview = ref + .watch(editorPreviewProvider(projectId, timelineId)) + .asData + ?.value; + Widget contents() { + final selected = session.mediaColorInterpretation(assetId, trackIndex); + final colors = preview?.videoColorSpaces(assetId); + final detected = colors?.elementAtOrNull(trackIndex); + final reported = + colors != null && trackIndex >= 0 && trackIndex < colors.length; + final status = selected != null + ? context.l10n.manualColorSpace(selected.label(context.l10n)) + : detected != null + ? context.l10n.detectedColorSpace(detected.label(context.l10n)) + : reported + ? context.l10n.unknownColorSpace + : context.l10n.colorInfoNotLoaded; + return Padding( + padding: AppSpacing.panelSection, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + spacing: AppSpacing.gap, + children: [ + Row( + children: [ + Expanded( + child: Text( + context.l10n.mediaColorSpace, + style: AppTheme.propertySectionTitleStyle(context), + ), + ), + Flexible( + child: AppSelect( + emptyLabel: context.l10n.noMatchingOptions, + key: const Key('media-color-menu'), + outlined: false, + label: context.l10n.mediaColorInterpretation, + value: selected?.name ?? 'auto', + onChanged: !reported + ? null + : (value) => session.commands.setMediaColor( + assetId, + trackIndex, + value == 'auto' + ? null + : MediaColorSpace.values.byName(value), + ), + options: [ + AppSelectOption('auto', context.l10n.auto), + for (final color in RenderColorSpace.values) + AppSelectOption(color.name, color.label(context.l10n)), + ], + ), + ), + ], + ), + Text( + status, + key: const Key('media-color-status'), + style: Theme.of(context).textTheme.bodySmall, + ), + ], + ), + ); + } + + return ListenableBuilder( + listenable: Listenable.merge([session, ?preview]), + builder: (_, _) => contents(), + ); + } +} diff --git a/lib/features/properties/mask_properties.dart b/lib/features/properties/mask_properties.dart new file mode 100644 index 0000000..190a5f6 --- /dev/null +++ b/lib/features/properties/mask_properties.dart @@ -0,0 +1,579 @@ +import 'dart:async'; + +import 'package:cutdex/l10n/l10n.dart'; + +import 'dart:math' as math; + +import 'package:cutdex/features/properties/animation_labels.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/preview.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex_ui/widgets.dart'; + +import '../preview/preview_panel.dart'; +import 'property_number_input.dart'; + +class MaskProperties extends ConsumerStatefulWidget { + const MaskProperties({ + super.key, + required this.projectId, + required this.timelineId, + required this.element, + }); + final String projectId, timelineId; + final ElementId element; + @override + ConsumerState createState() => _MaskPropertiesState(); +} + +class _MaskPropertiesState extends ConsumerState { + PreviewController? _preview; + ElementId? _boundElement; + String? _error; + int? _gestureGeneration; + String? _scrubField; + ClipMask Function(double)? _scrubChange; + double _scrubValue = 0; + Future? _pendingValueCommit; + @override + void dispose() { + final preview = _preview; + scheduleMicrotask(() => preview?.releaseMaskEditing(this)); + super.dispose(); + } + + bool _apply(PreviewController preview, ClipMask mask) { + try { + preview.applyMask(mask); + setState(() => _error = null); + return true; + } catch (_) { + setState(() => _error = context.l10n.updateMaskFailed); + return false; + } + } + + Future _submitValue( + PreviewController preview, + double value, + double min, + double max, + ClipMask Function(double) change, + ) { + final operation = Future.sync( + () => + value.isFinite && + value >= min && + value <= max && + _apply(preview, change(value)), + ); + _pendingValueCommit = operation; + return operation.whenComplete(() { + if (identical(_pendingValueCommit, operation)) _pendingValueCommit = null; + }); + } + + Future _editKeys(PreviewController preview, List ids) async { + final element = widget.element; + final maskId = preview.selectedMaskId; + final tick = preview.positionTick; + FocusManager.instance.primaryFocus?.unfocus(); + FocusManager.instance.applyFocusChangesIfNeeded(); + final pending = _pendingValueCommit; + if (pending != null && !await pending) return; + if (!mounted || + widget.element != element || + _preview != preview || + preview.maskEditingElement != element || + preview.selectedMaskId != maskId || + preview.positionTick != tick || + _scrubField != null) { + return; + } + try { + preview.toggleMaskKeys(ids); + } catch (_) { + setState(() => _error = context.l10n.updateKeyframesFailed); + } + } + + @override + Widget build(BuildContext context) { + final preview = ref + .watch(editorPreviewProvider(widget.projectId, widget.timelineId)) + .value; + if (preview == null) return const SizedBox.shrink(); + if (_preview != preview || _boundElement != widget.element) { + final previous = _preview; + if (previous != null && previous != preview) { + scheduleMicrotask(() => previous.releaseMaskEditing(this)); + } + _preview = preview; + _boundElement = widget.element; + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted && identical(_preview, preview)) { + preview.setMaskEditing(widget.element, owner: this); + } + }); + } + return ListenableBuilder( + listenable: preview, + builder: (context, _) { + final mask = preview.maskFor(widget.element); + final animation = preview.maskAnimation(widget.element); + final stack = preview.maskStackFor(widget.element); + final layers = + preview.maskStackFor(widget.element)?.layers ?? []; + final selectedId = preview.selectedMaskId; + final initialId = layers.where((e) => e.enabled).firstOrNull?.id; + final enabled = + preview.canPlay && + stack != null && + preview.maskEditingElement == widget.element; + Widget key(String label) { + final ids = localizedMaskChannels(context)[label]!; + return IconButton( + key: ValueKey('mask-key-$label'), + tooltip: context.l10n.keyframeLabel(label), + isSelected: animation?.keyed(ids) == true, + onPressed: enabled && _scrubField == null && animation != null + ? () => _editKeys(preview, ids) + : null, + icon: Transform.rotate( + angle: math.pi / 4, + child: Icon( + animation?.keyed(ids) == true + ? Icons.square + : Icons.crop_square, + size: 12, + color: animation?.keyed(ids) == true + ? Theme.of(context).colorScheme.primary + : null, + ), + ), + ); + } + + Widget field( + String label, + double value, + double min, + double max, + ClipMask Function(double) change, { + String? unit, + bool wrapRotation = false, + }) => PropertyNumberInput( + key: ValueKey((selectedId, label)), + label: label, + unit: unit, + value: value, + enabled: enabled, + readOnly: _scrubField != null, + scrubbing: _scrubField == label, + editContext: ( + widget.element, + selectedId, + stack?.record, + stack?.localTick, + ), + submit: (v) => _submitValue(preview, v, min, max, change), + onScrubStart: () { + if (_scrubField != null) return false; + final preparing = preview.beginMaskEdit(); + final generation = _gestureGeneration = preview.maskEditGeneration; + _scrubChange = change; + _scrubValue = value; + setState(() => _scrubField = label); + unawaited( + preparing + .then((ready) { + if (!ready && generation == preview.maskEditGeneration) { + preview.cancelMaskEdit(); + if (mounted) setState(() => _scrubField = null); + } + }) + .catchError((Object error) { + if (generation == preview.maskEditGeneration) { + preview.cancelMaskEdit(); + if (mounted) { + setState(() { + _scrubField = null; + _error = context.l10n.maskPreviewFailed; + }); + } + } + }), + ); + return true; + }, + onScrubUpdate: (distance) { + if (_gestureGeneration == preview.maskEditGeneration) { + preview.updateMask( + _scrubChange!( + wrapRotation + ? normalizeRotationDegrees(_scrubValue + distance) + : (_scrubValue + distance).clamp(min, max), + ), + ); + } + }, + onScrubEnd: () { + if (_gestureGeneration == preview.maskEditGeneration) { + preview.endMaskEdit(); + } + if (mounted) setState(() => _scrubField = null); + }, + onScrubCancel: () { + if (_gestureGeneration == preview.maskEditGeneration) { + preview.cancelMaskEdit(); + } + if (mounted) setState(() => _scrubField = null); + }, + ); + Widget axes(String label, Widget first, Widget second) => LayoutBuilder( + builder: (context, constraints) => Row( + children: [ + Expanded( + child: constraints.maxWidth < 240 + ? Column( + children: [ + first, + const SizedBox(height: AppSpacing.small), + second, + ], + ) + : Row( + children: [ + Expanded(child: first), + const SizedBox(width: AppSpacing.small), + Expanded(child: second), + ], + ), + ), + const SizedBox(width: AppSpacing.small), + key(label), + ], + ), + ); + Widget singleField(String label, Widget input) => Row( + children: [ + Expanded(child: input), + const SizedBox(width: AppSpacing.small), + key(label), + ], + ); + Widget heading(String label) => Padding( + padding: const EdgeInsets.only(bottom: AppSpacing.small), + child: Text( + label, + style: AppTheme.propertySectionTitleStyle(context), + ), + ); + Widget section(List children) => Padding( + padding: AppSpacing.panelSection, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: children, + ), + ); + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + section([ + Row( + children: [ + Expanded( + child: Text( + context.l10n.mask, + style: AppTheme.propertySectionTitleStyle(context), + ), + ), + IconButton( + tooltip: context.l10n.moveMaskUp, + icon: const Icon(Icons.arrow_upward, size: 18), + onPressed: + enabled && + layers.indexWhere((e) => e.id == selectedId) > 0 + ? () { + final ids = layers.map((e) => e.id).toList(); + final i = ids.indexOf(selectedId!); + ids.insert(i - 1, ids.removeAt(i)); + preview.reorderMasks(ids); + } + : null, + ), + IconButton( + tooltip: context.l10n.moveMaskDown, + icon: const Icon(Icons.arrow_downward, size: 18), + onPressed: + enabled && + selectedId != null && + layers.lastOrNull?.id != selectedId + ? () { + final ids = layers.map((e) => e.id).toList(); + final i = ids.indexOf(selectedId); + ids.insert(i + 1, ids.removeAt(i)); + preview.reorderMasks(ids); + } + : null, + ), + AppDropdownMenu( + enabled: enabled, + items: [ + AppMenuItem( + label: context.l10n.rectangle, + onPressed: () => + preview.addMask(ClipMaskShape.rectangle), + ), + AppMenuItem( + label: context.l10n.ellipse, + onPressed: () => preview.addMask(ClipMaskShape.ellipse), + ), + ], + builder: (context, toggle, focusNode) => IconButton( + focusNode: focusNode, + tooltip: context.l10n.addMask, + icon: const Icon(Icons.add), + onPressed: toggle, + ), + ), + ], + ), + ]), + section([ + AppItemGroup( + children: [ + for (var i = 0; i < layers.length; i++) + AppItem( + key: ValueKey('mask-row-${layers[i].id}'), + selected: layers[i].id == selectedId, + onPressed: () => preview.selectMask(layers[i].id), + leading: IconButton( + tooltip: layers[i].enabled + ? context.l10n.disableMask + : context.l10n.enableMask, + icon: Icon( + layers[i].enabled + ? Icons.visibility_outlined + : Icons.visibility_off_outlined, + size: 18, + ), + onPressed: enabled + ? () => preview.configureMask( + layers[i].id, + enabled: !layers[i].enabled, + ) + : null, + ), + actions: [ + AppDropdownMenu( + enabled: enabled && layers[i].id != initialId, + items: [ + for (final mode in ClipMaskMode.values) + AppMenuItem( + label: [ + context.l10n.add, + context.l10n.intersect, + context.l10n.subtract, + ][mode.index], + selected: layers[i].mode == mode, + onPressed: () => preview.configureMask( + layers[i].id, + mode: mode, + ), + ), + ], + builder: (context, toggle, focusNode) => IconButton( + focusNode: focusNode, + tooltip: layers[i].id == initialId + ? context.l10n.initialRegion + : context.l10n.maskMode( + [ + context.l10n.add, + context.l10n.intersect, + context.l10n.subtract, + ][layers[i].mode.index], + ), + icon: Icon( + layers[i].id == initialId + ? Icons.crop_free + : switch (layers[i].mode) { + ClipMaskMode.add => Icons.add, + ClipMaskMode.intersect => + Icons.filter_center_focus, + ClipMaskMode.subtract => Icons.remove, + }, + size: AppIconSize.standard, + ), + onPressed: toggle, + ), + ), + IconButton( + tooltip: context.l10n.deleteMask, + icon: const Icon(Icons.delete_outline, size: 18), + onPressed: enabled + ? () => preview.removeMask(layers[i].id) + : null, + ), + ], + child: Text( + '${[context.l10n.rectangle, context.l10n.ellipse][layers[i].mask.shape.index]} ${i + 1}', + ), + ), + ], + ), + ]), + if (mask != null && animation != null) ...[ + section([ + Row( + children: [ + Expanded( + child: AppButtonGroup( + expanded: true, + label: context.l10n.mask, + children: [ + for (final entry in [ + ( + ClipMaskShape.rectangle, + Icons.crop_square, + context.l10n.rectangle, + ), + ( + ClipMaskShape.ellipse, + Icons.circle_outlined, + context.l10n.ellipse, + ), + ]) + IconButton( + key: ValueKey('mask-shape-${entry.$1.name}'), + tooltip: entry.$3, + isSelected: mask.shape == entry.$1, + onPressed: enabled + ? () => _apply( + preview, + mask.copyWith(shape: entry.$1), + ) + : null, + icon: Icon(entry.$2), + ), + ], + ), + ), + const SizedBox(width: AppSpacing.small), + IconButton( + tooltip: context.l10n.resetMask, + onPressed: enabled + ? () => _apply(preview, ClipMask(shape: mask.shape)) + : null, + icon: const Icon(Icons.restart_alt), + ), + ], + ), + ]), + section([ + heading(context.l10n.position), + axes( + context.l10n.position, + field( + 'X', + mask.x * 100, + ClipMask.minPosition * 100, + ClipMask.maxPosition * 100, + (v) => mask.copyWith(x: v / 100), + unit: '%', + ), + field( + 'Y', + mask.y * 100, + ClipMask.minPosition * 100, + ClipMask.maxPosition * 100, + (v) => mask.copyWith(y: v / 100), + unit: '%', + ), + ), + ]), + section([ + singleField( + context.l10n.rotation, + field( + context.l10n.rotation, + mask.rotation, + -180, + 180, + (v) => mask.copyWith(rotation: v), + unit: '°', + wrapRotation: true, + ), + ), + ]), + section([ + heading(context.l10n.size), + axes( + context.l10n.size, + field( + 'W', + mask.width * 100, + ClipMask.minExtent * 100, + ClipMask.maxExtent * 100, + (v) => mask.copyWith(width: v / 100), + unit: '%', + ), + field( + 'H', + mask.height * 100, + ClipMask.minExtent * 100, + ClipMask.maxExtent * 100, + (v) => mask.copyWith(height: v / 100), + unit: '%', + ), + ), + ]), + section([ + singleField( + context.l10n.feather, + field( + context.l10n.feather, + mask.feather * 100, + 0, + 100, + (v) => mask.copyWith(feather: v / 100), + unit: '%', + ), + ), + ]), + section([ + Row( + children: [ + Expanded( + child: Text( + context.l10n.invert, + style: AppTheme.propertySectionTitleStyle(context), + ), + ), + AppSwitch( + value: mask.inverted, + onChanged: enabled + ? (v) => _apply(preview, mask.copyWith(inverted: v)) + : null, + ), + ], + ), + ]), + ], + if (_error != null) + section([ + Text( + _error!, + style: TextStyle(color: Theme.of(context).colorScheme.error), + ), + ]), + ], + ); + }, + ); + } +} diff --git a/lib/features/properties/picture_edits.dart b/lib/features/properties/picture_edits.dart new file mode 100644 index 0000000..4502d1e --- /dev/null +++ b/lib/features/properties/picture_edits.dart @@ -0,0 +1,215 @@ +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/preview.dart'; +import 'package:cutdex_sdk/timeline/engine.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import '../../workspace/timeline_session.dart'; + +part 'picture_edits.g.dart'; +part 'picture_edits.freezed.dart'; + +enum PictureEditFailure { keyframes, alignment, invalidTransform, transform } + +@freezed +abstract class PictureEditTarget with _$PictureEditTarget { + const factory PictureEditTarget({ + required TimelineVersion version, + required int tick, + }) = _PictureEditTarget; +} + +@freezed +abstract class PictureEditException + with _$PictureEditException + implements Exception { + const factory PictureEditException(PictureEditFailure failure) = + _PictureEditException; +} + +@riverpod +class PictureEdits extends _$PictureEdits { + Future? _pending; + @override + AsyncValue build( + EditorTimelineSession session, + SequenceId sequence, + ElementId clip, + ) => const AsyncData(null); + + PictureEditTarget _capture() { + final view = session.view(sequence); + return PictureEditTarget( + version: view.version.kernelVersion, + tick: view.playheadTick, + ); + } + + bool _valid( + PictureEditTarget target, + bool Function() isCurrent, + PreviewController? preview, + ) { + if (!ref.mounted || + !isCurrent() || + session.activeSequenceId != sequence || + preview?.transforms.hasPending == true) { + return false; + } + final view = session.view(sequence); + return target.tick == view.playheadTick && + identical(target.version, view.version.kernelVersion); + } + + ClipAnimation? animation() { + final view = session.view(sequence); + final query = view.version.kernelVersion.query(); + final handle = query.elementById(clip); + return handle == null + ? null + : ClipAnimation.at( + query, + handle, + view.playheadTick, + TimelineClock.standard.toTicks( + session.persistence.timeline(sequence).format.frameDuration, + ), + ); + } + + Future commit( + PreviewController? preview, + ClipTransform Function(ClipTransform) change, { + required bool Function() isCurrent, + }) { + if (state.isLoading || preview?.transforms.hasPending == true) { + return Future.value(false); + } + final target = _capture(); + final work = _run(PictureEditFailure.transform, () async { + await preview?.pauseForCanvasInteraction(); + if (!_valid(target, isCurrent, preview)) return false; + final current = animation()?.value; + if (current == null) return false; + final value = change(current); + if (!value.isValid) { + throw const PictureEditException(PictureEditFailure.invalidTransform); + } + if (value.x == current.x && + value.y == current.y && + value.scale == current.scale && + value.scaleY == current.scaleY && + value.rotation == current.rotation) { + return true; + } + session.commands.setTransform( + sequence: sequence, + clip: clip, + tick: target.tick, + change: (_) => value, + ); + return true; + }); + _pending = work; + return work.whenComplete(() { + if (identical(_pending, work)) _pending = null; + }); + } + + Future editKeys( + PreviewController? preview, + TransformChannel channel, { + KeyframeAction? action, + ParameterInterpolation? interpolation, + required bool Function() isCurrent, + }) async { + final pending = _pending; + if (pending != null && !await pending) return; + if (!ref.mounted || + !isCurrent() || + state.isLoading || + preview?.transforms.hasPending == true) { + return; + } + final target = _capture(); + await _run(PictureEditFailure.keyframes, () async { + await preview?.pauseForCanvasInteraction(); + if (!_valid(target, isCurrent, preview)) return false; + session.commands.editKeyframeChannel( + sequence: sequence, + clip: clip, + tick: target.tick, + parameterIds: channel.ids, + action: action, + interpolation: interpolation, + ); + return true; + }); + } + + Future align( + PreviewController preview, + CanvasAlignment alignment, { + required bool Function() isCurrent, + }) async { + if (state.isLoading || preview.transforms.hasPending) return; + final target = _capture(); + final current = animation(); + if (current == null) return; + final command = AlignClip( + clipId: clip.value, + at: CommandTime( + current.start + current.localTick, + TimelineClock.ticksPerSecond, + ), + alignment: alignment, + expectedVersion: session.version, + ); + await _run(PictureEditFailure.alignment, () async { + await preview.pauseForCanvasInteraction(); + await session.alignClip( + sequence, + command, + isCancelled: () => !_valid(target, isCurrent, preview), + ); + return true; + }); + } + + Future _run( + PictureEditFailure failure, + Future Function() action, + ) async { + final lease = ref.keepAlive(); + state = const AsyncLoading(); + try { + final applied = await session.runEditAsync( + switch (failure) { + PictureEditFailure.keyframes => 'editKeyframes', + PictureEditFailure.alignment => 'alignClip', + _ => 'setTransform', + }, + sequence, + action, + context: { + 'clipIds': [clip.value], + 'entryPoint': 'property', + 'playheadTick': session.view(sequence).playheadTick, + }, + ); + if (ref.mounted) state = const AsyncData(null); + return applied; + } catch (error, stack) { + if (ref.mounted) { + state = AsyncError( + error is PictureEditException ? error : PictureEditException(failure), + stack, + ); + } + return false; + } finally { + lease.close(); + } + } +} diff --git a/lib/features/properties/picture_edits.freezed.dart b/lib/features/properties/picture_edits.freezed.dart new file mode 100644 index 0000000..ed0b9de --- /dev/null +++ b/lib/features/properties/picture_edits.freezed.dart @@ -0,0 +1,627 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'picture_edits.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +T _$identity(T value) => value; + +/// @nodoc +mixin _$PictureEditTarget { + TimelineVersion get version; + int get tick; + + /// Create a copy of PictureEditTarget + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $PictureEditTargetCopyWith get copyWith => + _$PictureEditTargetCopyWithImpl( + this as PictureEditTarget, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as PictureEditTarget; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is PictureEditTarget && + (identical(other.version, _this.version) || + other.version == _this.version) && + (identical(other.tick, _this.tick) || other.tick == _this.tick)); + } + + @override + int get hashCode { + final _this = this as PictureEditTarget; + return Object.hash(runtimeType, _this.version, _this.tick); + } + + @override + String toString() { + final _this = this as PictureEditTarget; + return 'PictureEditTarget(version: ${_this.version}, tick: ${_this.tick})'; + } +} + +/// @nodoc +abstract mixin class $PictureEditTargetCopyWith<$Res> { + factory $PictureEditTargetCopyWith( + PictureEditTarget value, + $Res Function(PictureEditTarget) _then, + ) = _$PictureEditTargetCopyWithImpl; + @useResult + $Res call({TimelineVersion version, int tick}); +} + +/// @nodoc +class _$PictureEditTargetCopyWithImpl<$Res> + implements $PictureEditTargetCopyWith<$Res> { + _$PictureEditTargetCopyWithImpl(this._self, this._then); + + final PictureEditTarget _self; + final $Res Function(PictureEditTarget) _then; + + /// Create a copy of PictureEditTarget + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({Object? version = null, Object? tick = null}) { + return _then( + PictureEditTarget( + version: null == version + ? _self.version + : version // ignore: cast_nullable_to_non_nullable + as TimelineVersion, + tick: null == tick + ? _self.tick + : tick // ignore: cast_nullable_to_non_nullable + as int, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [PictureEditTarget]. +extension PictureEditTargetPatterns on PictureEditTarget { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_PictureEditTarget value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _PictureEditTarget() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_PictureEditTarget value) $default, + ) { + final _that = this; + switch (_that) { + case _PictureEditTarget(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_PictureEditTarget value)? $default, + ) { + final _that = this; + switch (_that) { + case _PictureEditTarget() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function(TimelineVersion version, int tick)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _PictureEditTarget() when $default != null: + return $default(_that.version, _that.tick); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function(TimelineVersion version, int tick) $default, + ) { + final _that = this; + switch (_that) { + case _PictureEditTarget(): + return $default(_that.version, _that.tick); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function(TimelineVersion version, int tick)? $default, + ) { + final _that = this; + switch (_that) { + case _PictureEditTarget() when $default != null: + return $default(_that.version, _that.tick); + case _: + return null; + } + } +} + +/// @nodoc + +class _PictureEditTarget implements PictureEditTarget { + const _PictureEditTarget({required this.version, required this.tick}); + + @override + final TimelineVersion version; + @override + final int tick; + + /// Create a copy of PictureEditTarget + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$PictureEditTargetCopyWith<_PictureEditTarget> get copyWith => + __$PictureEditTargetCopyWithImpl<_PictureEditTarget>(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _PictureEditTarget && + (identical(other.version, version) || other.version == version) && + (identical(other.tick, tick) || other.tick == tick)); + } + + @override + int get hashCode { + return Object.hash(runtimeType, version, tick); + } + + @override + String toString() { + return 'PictureEditTarget(version: $version, tick: $tick)'; + } +} + +/// @nodoc +abstract mixin class _$PictureEditTargetCopyWith<$Res> + implements $PictureEditTargetCopyWith<$Res> { + factory _$PictureEditTargetCopyWith( + _PictureEditTarget value, + $Res Function(_PictureEditTarget) _then, + ) = __$PictureEditTargetCopyWithImpl; + @override + @useResult + $Res call({TimelineVersion version, int tick}); +} + +/// @nodoc +class __$PictureEditTargetCopyWithImpl<$Res> + implements _$PictureEditTargetCopyWith<$Res> { + __$PictureEditTargetCopyWithImpl(this._self, this._then); + + final _PictureEditTarget _self; + final $Res Function(_PictureEditTarget) _then; + + /// Create a copy of PictureEditTarget + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({Object? version = null, Object? tick = null}) { + return _then( + _PictureEditTarget( + version: null == version + ? _self.version + : version // ignore: cast_nullable_to_non_nullable + as TimelineVersion, + tick: null == tick + ? _self.tick + : tick // ignore: cast_nullable_to_non_nullable + as int, + ), + ); + } +} + +/// @nodoc +mixin _$PictureEditException { + PictureEditFailure get failure; + + /// Create a copy of PictureEditException + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $PictureEditExceptionCopyWith get copyWith => + _$PictureEditExceptionCopyWithImpl( + this as PictureEditException, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as PictureEditException; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is PictureEditException && + (identical(other.failure, _this.failure) || + other.failure == _this.failure)); + } + + @override + int get hashCode { + final _this = this as PictureEditException; + return Object.hash(runtimeType, _this.failure); + } + + @override + String toString() { + final _this = this as PictureEditException; + return 'PictureEditException(failure: ${_this.failure})'; + } +} + +/// @nodoc +abstract mixin class $PictureEditExceptionCopyWith<$Res> { + factory $PictureEditExceptionCopyWith( + PictureEditException value, + $Res Function(PictureEditException) _then, + ) = _$PictureEditExceptionCopyWithImpl; + @useResult + $Res call({PictureEditFailure failure}); +} + +/// @nodoc +class _$PictureEditExceptionCopyWithImpl<$Res> + implements $PictureEditExceptionCopyWith<$Res> { + _$PictureEditExceptionCopyWithImpl(this._self, this._then); + + final PictureEditException _self; + final $Res Function(PictureEditException) _then; + + /// Create a copy of PictureEditException + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({Object? failure = null}) { + return _then( + PictureEditException( + null == failure + ? _self.failure + : failure // ignore: cast_nullable_to_non_nullable + as PictureEditFailure, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [PictureEditException]. +extension PictureEditExceptionPatterns on PictureEditException { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_PictureEditException value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _PictureEditException() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_PictureEditException value) $default, + ) { + final _that = this; + switch (_that) { + case _PictureEditException(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_PictureEditException value)? $default, + ) { + final _that = this; + switch (_that) { + case _PictureEditException() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function(PictureEditFailure failure)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _PictureEditException() when $default != null: + return $default(_that.failure); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function(PictureEditFailure failure) $default, + ) { + final _that = this; + switch (_that) { + case _PictureEditException(): + return $default(_that.failure); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function(PictureEditFailure failure)? $default, + ) { + final _that = this; + switch (_that) { + case _PictureEditException() when $default != null: + return $default(_that.failure); + case _: + return null; + } + } +} + +/// @nodoc + +class _PictureEditException implements PictureEditException { + const _PictureEditException(this.failure); + + @override + final PictureEditFailure failure; + + /// Create a copy of PictureEditException + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$PictureEditExceptionCopyWith<_PictureEditException> get copyWith => + __$PictureEditExceptionCopyWithImpl<_PictureEditException>( + this, + _$identity, + ); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _PictureEditException && + (identical(other.failure, failure) || other.failure == failure)); + } + + @override + int get hashCode { + return Object.hash(runtimeType, failure); + } + + @override + String toString() { + return 'PictureEditException(failure: $failure)'; + } +} + +/// @nodoc +abstract mixin class _$PictureEditExceptionCopyWith<$Res> + implements $PictureEditExceptionCopyWith<$Res> { + factory _$PictureEditExceptionCopyWith( + _PictureEditException value, + $Res Function(_PictureEditException) _then, + ) = __$PictureEditExceptionCopyWithImpl; + @override + @useResult + $Res call({PictureEditFailure failure}); +} + +/// @nodoc +class __$PictureEditExceptionCopyWithImpl<$Res> + implements _$PictureEditExceptionCopyWith<$Res> { + __$PictureEditExceptionCopyWithImpl(this._self, this._then); + + final _PictureEditException _self; + final $Res Function(_PictureEditException) _then; + + /// Create a copy of PictureEditException + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({Object? failure = null}) { + return _then( + _PictureEditException( + null == failure + ? _self.failure + : failure // ignore: cast_nullable_to_non_nullable + as PictureEditFailure, + ), + ); + } +} diff --git a/lib/features/properties/picture_edits.g.dart b/lib/features/properties/picture_edits.g.dart new file mode 100644 index 0000000..7e9755f --- /dev/null +++ b/lib/features/properties/picture_edits.g.dart @@ -0,0 +1,120 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'picture_edits.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(PictureEdits) +final pictureEditsProvider = PictureEditsFamily._(); + +final class PictureEditsProvider + extends $NotifierProvider> { + PictureEditsProvider._({ + required PictureEditsFamily super.from, + required (EditorTimelineSession, SequenceId, ElementId) super.argument, + }) : super( + retry: null, + name: r'pictureEditsProvider', + isAutoDispose: true, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$pictureEditsHash(); + + @override + String toString() { + return r'pictureEditsProvider' + '' + '$argument'; + } + + @$internal + @override + PictureEdits create() => PictureEdits(); + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(AsyncValue value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider>(value), + ); + } + + @override + bool operator ==(Object other) { + return other is PictureEditsProvider && other.argument == argument; + } + + @override + int get hashCode { + return argument.hashCode; + } +} + +String _$pictureEditsHash() => r'6385f3bd53094d57ed054681d142591e059e8b08'; + +final class PictureEditsFamily extends $Family + with + $ClassFamilyOverride< + PictureEdits, + AsyncValue, + AsyncValue, + AsyncValue, + (EditorTimelineSession, SequenceId, ElementId) + > { + PictureEditsFamily._() + : super( + retry: null, + name: r'pictureEditsProvider', + dependencies: null, + $allTransitiveDependencies: null, + isAutoDispose: true, + ); + + PictureEditsProvider call( + EditorTimelineSession session, + SequenceId sequence, + ElementId clip, + ) => PictureEditsProvider._(argument: (session, sequence, clip), from: this); + + @override + String toString() => r'pictureEditsProvider'; +} + +abstract class _$PictureEdits extends $Notifier> { + late final _$args = + ref.$arg as (EditorTimelineSession, SequenceId, ElementId); + EditorTimelineSession get session => _$args.$1; + SequenceId get sequence => _$args.$2; + ElementId get clip => _$args.$3; + + AsyncValue build( + EditorTimelineSession session, + SequenceId sequence, + ElementId clip, + ); + @$mustCallSuper + @override + WhenComplete runBuild() { + final ref = this.ref as $Ref, AsyncValue>; + final element = + ref.element + as $ClassProviderElement< + AnyNotifier, AsyncValue>, + AsyncValue, + Object?, + Object? + >; + return element.handleCreate( + ref, + () => build(_$args.$1, _$args.$2, _$args.$3), + ); + } +} diff --git a/lib/features/properties/picture_properties.dart b/lib/features/properties/picture_properties.dart new file mode 100644 index 0000000..f9c3284 --- /dev/null +++ b/lib/features/properties/picture_properties.dart @@ -0,0 +1,770 @@ +import 'dart:async'; + +import 'package:cutdex/l10n/l10n.dart'; + +import 'dart:math' as math; + +import 'package:cutdex/features/properties/animation_labels.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/preview.dart'; +import 'package:cutdex_sdk/timeline/engine.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex_ui/widgets.dart'; + +import '../../workspace/timeline_session.dart'; +import '../preview/preview_panel.dart'; +import 'property_number_input.dart'; +import 'picture_edits.dart'; + +class PictureProperties extends ConsumerStatefulWidget { + const PictureProperties({ + super.key, + required this.projectId, + required this.timelineId, + required this.session, + required this.sequence, + required this.clip, + this.animationView = false, + }); + final String projectId; + final String timelineId; + final EditorTimelineSession session; + final SequenceId sequence; + final ElementRecord clip; + final bool animationView; + + @override + ConsumerState createState() => _PicturePropertiesState(); +} + +class _PicturePropertiesState extends ConsumerState { + bool _locked = true; + PictureEditsProvider get _editProvider => + pictureEditsProvider(widget.session, widget.sequence, widget.clip.id); + PictureEdits get _edits => ref.read(_editProvider.notifier); + bool get _saving => ref.read(_editProvider).isLoading; + bool Function() _guard() { + final session = widget.session; + final sequence = widget.sequence; + final clip = widget.clip.id; + return () => + mounted && + _scrubBase == null && + identical(widget.session, session) && + widget.sequence == sequence && + widget.clip.id == clip; + } + + String? get _error => switch (ref.read(_editProvider).error) { + PictureEditException(:final failure) => switch (failure) { + PictureEditFailure.keyframes => context.l10n.updateKeyframesFailed, + PictureEditFailure.alignment => context.l10n.alignClipFailed, + PictureEditFailure.invalidTransform => context.l10n.invalidTransform, + PictureEditFailure.transform => context.l10n.updatePictureFailed, + }, + _ => null, + }; + PreviewTransformEdit? _scrubEdit; + ClipTransform? _scrubBase; + ClipTransform? _scrubTimeline; + TimelineVersion? _scrubVersion; + int? _scrubTick; + String? _scrubField; + ClipTransform Function(ClipTransform, double)? _scrubChange; + + bool _startScrub( + PreviewController? preview, + String field, + ClipTransform Function(ClipTransform, double) change, + ) { + if (_scrubBase != null || + _saving || + preview?.transforms.hasPending == true || + widget.session.activeSequenceId != widget.sequence) { + return false; + } + final base = _current(); + if (base == null) return false; + _scrubBase = base; + _scrubField = field; + _scrubChange = change; + _scrubVersion = widget.session.view(widget.sequence).version.kernelVersion; + _scrubTick = widget.session.view(widget.sequence).playheadTick; + if (preview != null) { + final visual = preview.visualForProperties(widget.clip.id); + if (visual == null || + (_scrubEdit = preview.transforms.begin(visual)) == null) { + _scrubBase = null; + _scrubField = null; + _scrubChange = null; + _scrubVersion = null; + return false; + } + _scrubBase = _scrubEdit!.value; + } + return true; + } + + bool get _scrubValid => + _scrubBase != null && + _scrubEdit?.released != true && + _scrubTick == widget.session.view(widget.sequence).playheadTick && + widget.session.activeSequenceId == widget.sequence && + identical( + _scrubVersion, + widget.session.view(widget.sequence).version.kernelVersion, + ); + + void _updateScrub(double distance) { + if (!_scrubValid) { + _cancelScrub(); + return; + } + final value = _scrubChange!(_scrubBase!, distance); + if (!value.isValid) return; + setState(() => _scrubTimeline = value); + _scrubEdit?.update(value); + } + + void _endScrub(PreviewController? preview) { + final value = _scrubTimeline; + if (!_scrubValid || + value == null || + (value.x == _scrubBase!.x && + value.y == _scrubBase!.y && + value.rotation == _scrubBase!.rotation && + value.scale == _scrubBase!.scale && + value.scaleY == _scrubBase!.scaleY)) { + _cancelScrub(); + return; + } + final edit = _scrubEdit; + _scrubEdit = null; + _scrubBase = null; + _scrubField = null; + _scrubChange = null; + _scrubVersion = null; + setState(() => _scrubTimeline = null); + if (edit != null) { + unawaited(edit.end()); + } else { + unawaited(_commit(preview, (_) => value)); + } + } + + void _cancelScrub() { + final edit = _scrubEdit; + _scrubEdit = null; + _scrubBase = null; + _scrubField = null; + _scrubChange = null; + _scrubVersion = null; + if (mounted) setState(() => _scrubTimeline = null); + edit?.cancel(); + } + + @override + void dispose() { + final edit = _scrubEdit; + _scrubEdit = null; + if (edit != null) scheduleMicrotask(edit.cancel); + super.dispose(); + } + + ClipAnimation? _animation() => _edits.animation(); + ClipTransform? _current() => _animation()?.value; + Future _editKeys( + PreviewController? preview, + TransformChannel channel, { + KeyframeAction? action, + ParameterInterpolation? interpolation, + }) { + FocusManager.instance.primaryFocus?.unfocus(); + FocusManager.instance.applyFocusChangesIfNeeded(); + return _edits.editKeys( + preview, + channel, + action: action, + interpolation: interpolation, + isCurrent: _guard(), + ); + } + + Future _align(PreviewController preview, CanvasAlignment alignment) => + _edits.align(preview, alignment, isCurrent: _guard()); + Future _commit( + PreviewController? preview, + ClipTransform Function(ClipTransform) change, + ) => _edits.commit(preview, change, isCurrent: _guard()); + + @override + Widget build(BuildContext context) { + ref.watch(_editProvider); + final preview = ref + .watch(editorPreviewProvider(widget.projectId, widget.timelineId)) + .asData + ?.value; + Widget contents() { + final animation = _animation(); + final live = preview?.activeSequence() == widget.sequence + ? preview?.transforms.valueFor(widget.clip.id) + : null; + final value = + (_scrubValid ? _scrubTimeline : null) ?? + live ?? + _current() ?? + ClipTransform.fromRecord(widget.clip); + final locked = preview?.aspectRatioLocked ?? _locked; + final canvas = widget.session.canvas; + final enabled = !_saving; + final canvasDragging = + preview?.transforms.hasPending == true && _scrubEdit == null; + Widget keyButton(TransformChannel channel) { + final keyed = animation?.keyed(channel) == true; + final animated = animation?.animated(channel) == true; + return IconButton( + key: ValueKey('picture-key-${channel.name}'), + tooltip: context.l10n.toggleKeyframe( + keyed ? context.l10n.delete : context.l10n.addKeyframeAction, + channel.label(context), + ), + isSelected: keyed, + color: animated ? Theme.of(context).colorScheme.primary : null, + icon: Transform.rotate( + angle: math.pi / 4, + child: Icon(keyed ? Icons.square : Icons.crop_square, size: 12), + ), + onPressed: + enabled && + _scrubBase == null && + !canvasDragging && + animation != null + ? () => _editKeys(preview, channel) + : null, + ); + } + + Widget axes(TransformChannel channel, Widget first, Widget second) => + LayoutBuilder( + builder: (context, constraints) => Row( + children: [ + Expanded( + child: constraints.maxWidth < 240 + ? Column( + children: [ + first, + const SizedBox(height: AppSpacing.small), + second, + ], + ) + : Row( + children: [ + Expanded(child: first), + const SizedBox(width: AppSpacing.small), + Expanded(child: second), + ], + ), + ), + const SizedBox(width: AppSpacing.small), + keyButton(channel), + ], + ), + ); + + Widget keyTools(TransformChannel channel) { + if (animation == null || !animation.animated(channel)) { + return const SizedBox.shrink(); + } + final times = animation.keyTimes(channel); + final tick = animation.playhead; + final previous = times.where((t) => t < tick).lastOrNull; + final next = times.where((t) => t > tick).firstOrNull; + final canEdit = enabled && _scrubBase == null && !canvasDragging; + Future seek(int target) async { + await preview?.pauseForCanvasInteraction(); + if (mounted && widget.session.activeSequenceId == widget.sequence) { + widget.session.view(widget.sequence).seekTo(target); + } + } + + return SizedBox( + height: AppControlSize.standard, + child: Row( + children: [ + Text( + context.l10n.keyframeCount(times.length), + style: Theme.of(context).textTheme.bodySmall, + ), + const Spacer(), + IconButton( + key: ValueKey('picture-key-previous-${channel.name}'), + tooltip: context.l10n.previousKeyframe(channel.label(context)), + onPressed: canEdit && previous != null + ? () => seek(previous) + : null, + icon: const Icon(Icons.chevron_left, size: 16), + ), + IconButton( + key: ValueKey('picture-key-next-${channel.name}'), + tooltip: context.l10n.nextKeyframe(channel.label(context)), + onPressed: canEdit && next != null ? () => seek(next) : null, + icon: const Icon(Icons.chevron_right, size: 16), + ), + AppDropdownMenu( + key: ValueKey('picture-key-menu-${channel.name}'), + enabled: canEdit, + builder: (context, toggle, focus) => IconButton( + tooltip: context.l10n.keyframeSettings( + channel.label(context), + ), + focusNode: focus, + onPressed: toggle, + icon: const Icon(Icons.more_horiz, size: 16), + ), + items: [ + for (final (mode, label) in [ + (ParameterInterpolation.linear, context.l10n.linear), + (ParameterInterpolation.hold, context.l10n.hold), + (ParameterInterpolation.easeIn, context.l10n.easeIn), + (ParameterInterpolation.easeOut, context.l10n.easeOut), + (ParameterInterpolation.easeInOut, context.l10n.easeInOut), + ]) + AppMenuItem( + label: label, + selected: animation.interpolation(channel) == mode, + onPressed: animation.keyed(channel) + ? () => _editKeys( + preview, + channel, + action: KeyframeAction.set, + interpolation: mode, + ) + : null, + ), + const AppMenuSeparator(), + AppMenuItem( + label: context.l10n.removeAllKeyframes, + destructive: true, + onPressed: animation.animated(channel) + ? () => _editKeys( + preview, + channel, + action: KeyframeAction.clear, + ) + : null, + ), + ], + ), + ], + ), + ); + } + + Widget number( + String id, + String? label, + double value, + ClipTransform Function(ClipTransform, double) change, { + String? unit, + double min = double.negativeInfinity, + double max = double.infinity, + bool wrapRotation = false, + }) => PropertyNumberInput( + key: ValueKey(id), + label: label, + unit: unit, + value: value, + enabled: !_saving, + readOnly: _scrubBase != null || preview?.transforms.hasPending == true, + submit: (v) => _commit(preview, (current) => change(current, v)), + onScrubStart: () => _startScrub( + preview, + id, + (base, distance) => change( + base, + wrapRotation + ? normalizeRotationDegrees(value + distance) + : (value + distance).clamp(min, max), + ), + ), + onScrubUpdate: _updateScrub, + onScrubEnd: () => _endScrub(preview), + onScrubCancel: _cancelScrub, + scrubbing: _scrubField == id, + editContext: ( + widget.session.view(widget.sequence).version.kernelVersion, + widget.session.view(widget.sequence).playheadTick, + ), + ); + Widget section(List children) => Padding( + padding: AppSpacing.panelSection, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: children, + ), + ); + final content = Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (widget.animationView && animation != null) ...[ + section([ + _KeyframeTimeline( + animation: animation, + enabled: enabled && !canvasDragging && _scrubBase == null, + onSeek: (tick) async { + await preview?.pauseForCanvasInteraction(); + if (mounted && + widget.session.activeSequenceId == widget.sequence) { + widget.session.view(widget.sequence).seekTo(tick); + } + }, + ), + ]), + ], + if (!widget.animationView) ...[ + section([ + Text( + context.l10n.alignment, + style: AppTheme.propertySectionTitleStyle(context), + ), + const SizedBox(height: AppSpacing.small), + LayoutBuilder( + builder: (context, constraints) => Wrap( + spacing: AppSpacing.small, + runSpacing: AppSpacing.small, + children: [ + for (final group in [ + [ + ( + CanvasAlignment.left, + context.l10n.alignLeft, + Icons.align_horizontal_left, + ), + ( + CanvasAlignment.horizontalCenter, + context.l10n.alignHorizontalCenter, + Icons.align_horizontal_center, + ), + ( + CanvasAlignment.right, + context.l10n.alignRight, + Icons.align_horizontal_right, + ), + ], + [ + ( + CanvasAlignment.top, + context.l10n.alignTop, + Icons.align_vertical_top, + ), + ( + CanvasAlignment.verticalCenter, + context.l10n.alignVerticalCenter, + Icons.align_vertical_center, + ), + ( + CanvasAlignment.bottom, + context.l10n.alignBottom, + Icons.align_vertical_bottom, + ), + ], + ]) + SizedBox( + width: constraints.maxWidth < 200 + ? constraints.maxWidth + : (constraints.maxWidth - AppSpacing.small) / 2, + child: AppButtonGroup( + expanded: true, + label: context.l10n.alignment, + children: [ + for (final (alignment, label, icon) in group) + IconButton( + key: ValueKey( + 'picture-align-${alignment.name}', + ), + tooltip: label, + icon: Icon(icon, size: AppIconSize.standard), + onPressed: () { + if (!enabled || + canvasDragging || + preview == null || + preview.busy || + preview.visualForProperties( + widget.clip.id, + ) == + null) { + return; + } + unawaited(_align(preview, alignment)); + }, + ), + ], + ), + ), + ], + ), + ), + ]), + ], + section([ + Text( + context.l10n.position, + style: AppTheme.propertySectionTitleStyle(context), + ), + const SizedBox(height: AppSpacing.small), + axes( + TransformChannel.position, + number( + 'picture-x', + 'X', + value.x * canvas.width, + (c, v) => c.copyWith(x: v / canvas.width), + ), + number( + 'picture-y', + 'Y', + value.y * canvas.height, + (c, v) => c.copyWith(y: v / canvas.height), + ), + ), + keyTools(TransformChannel.position), + ]), + section([ + Row( + children: [ + Expanded( + child: number( + 'picture-rotation', + context.l10n.rotation, + value.rotation, + (c, v) => c.copyWith(rotation: v), + unit: '°', + wrapRotation: true, + ), + ), + const SizedBox(width: AppSpacing.small), + keyButton(TransformChannel.rotation), + ], + ), + keyTools(TransformChannel.rotation), + ]), + section([ + Row( + children: [ + Expanded( + child: Text( + context.l10n.scale, + style: AppTheme.propertySectionTitleStyle(context), + ), + ), + IconButton( + key: const Key('picture-lock'), + tooltip: context.l10n.keepAspectRatio, + icon: const Icon(Icons.lock_open_outlined), + selectedIcon: const Icon(Icons.lock_outline), + isSelected: locked, + onPressed: enabled + ? () { + if (preview?.transforms.hasPending == true) return; + preview?.setAspectRatioLocked(!locked); + setState(() => _locked = !locked); + } + : null, + ), + ], + ), + const SizedBox(height: AppSpacing.small), + axes( + TransformChannel.scale, + number( + 'picture-scale-x', + 'W', + value.scale * 100, + (c, v) => c.copyWith( + scale: v / 100, + scaleY: locked ? c.scaleY * v / 100 / c.scale : c.scaleY, + ), + unit: '%', + min: locked ? math.max(1.0, value.scale / value.scaleY) : 1, + max: locked + ? math.min(10000.0, 10000 * value.scale / value.scaleY) + : 10000, + ), + number( + 'picture-scale-y', + 'H', + value.scaleY * 100, + (c, v) => c.copyWith( + scaleY: v / 100, + scale: locked ? c.scale * v / 100 / c.scaleY : c.scale, + ), + unit: '%', + min: locked ? math.max(1.0, value.scaleY / value.scale) : 1, + max: locked + ? math.min(10000.0, 10000 * value.scaleY / value.scale) + : 10000, + ), + ), + keyTools(TransformChannel.scale), + ]), + if (_error != null) + section([ + Text( + _error!, + style: TextStyle(color: Theme.of(context).colorScheme.error), + ), + ]), + ], + ); + // Canvas gestures own edits temporarily, without changing control colors. + return ExcludeFocus( + excluding: canvasDragging, + child: IgnorePointer(ignoring: canvasDragging, child: content), + ); + } + + return ListenableBuilder( + listenable: Listenable.merge([ + widget.session.view(widget.sequence), + if (preview != null) ...[preview, preview.transforms], + ]), + builder: (_, _) => contents(), + ); + } +} + +class _KeyframeTimeline extends StatelessWidget { + const _KeyframeTimeline({ + required this.animation, + required this.enabled, + required this.onSeek, + }); + final ClipAnimation animation; + final bool enabled; + final ValueChanged onSeek; + + @override + Widget build(BuildContext context) { + final colors = Theme.of(context).colorScheme; + final end = animation.lastTick; + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + Text( + context.l10n.keyframes, + style: AppTheme.propertySectionTitleStyle(context), + ), + const Spacer(), + Text( + '${(animation.localTick / TimelineClock.ticksPerSecond).toStringAsFixed(2)} s', + style: Theme.of(context).textTheme.bodySmall, + ), + ], + ), + const SizedBox(height: AppSpacing.small), + for (final channel in TransformChannel.values) + SizedBox( + height: 32, + child: Row( + children: [ + SizedBox( + width: 36, + child: Text( + channel.label(context), + style: Theme.of(context).textTheme.bodySmall, + ), + ), + Expanded( + child: LayoutBuilder( + builder: (context, constraints) { + final extent = (constraints.maxWidth - 20).clamp( + 1.0, + double.infinity, + ); + double x(int tick) => + 10 + + (end == 0 ? 0 : (tick - animation.start) / end).clamp( + 0.0, + 1.0, + ) * + extent; + return GestureDetector( + key: ValueKey('picture-key-track-${channel.name}'), + behavior: HitTestBehavior.opaque, + onTapDown: !enabled + ? null + : (details) { + final fraction = + ((details.localPosition.dx - 10) / extent) + .clamp(0.0, 1.0); + final tick = + ((fraction * end / animation.frameTicks) + .round() * + animation.frameTicks) + .clamp(0, end); + onSeek(animation.start + tick); + }, + child: Stack( + children: [ + Positioned( + left: 10, + right: 10, + top: 15, + height: 1, + child: ColoredBox(color: colors.outlineVariant), + ), + if (animation.containsPlayhead) + Positioned( + left: x(animation.playhead), + top: 3, + bottom: 3, + width: 1, + child: ColoredBox(color: colors.primary), + ), + for (final tick in animation.keyTimes(channel)) + Positioned( + left: x(tick) - AppControlSize.compact / 2, + top: 4, + width: AppControlSize.compact, + height: AppControlSize.compact, + child: IconButton( + key: ValueKey( + 'picture-key-marker-${channel.name}-$tick', + ), + tooltip: + '${channel.label(context)} ${((tick - animation.start) / TimelineClock.ticksPerSecond).toStringAsFixed(2)} s', + padding: EdgeInsets.zero, + onPressed: enabled + ? () => onSeek(tick) + : null, + icon: Transform.rotate( + angle: math.pi / 4, + child: Icon( + Icons.square, + size: 9, + color: tick == animation.playhead + ? colors.primary + : colors.onSurfaceVariant, + ), + ), + ), + ), + ], + ), + ); + }, + ), + ), + ], + ), + ), + ], + ); + } +} diff --git a/lib/features/properties/project_properties.dart b/lib/features/properties/project_properties.dart new file mode 100644 index 0000000..ef6df6d --- /dev/null +++ b/lib/features/properties/project_properties.dart @@ -0,0 +1,116 @@ +import 'package:cutdex/l10n/l10n.dart'; +import 'package:cutdex_sdk/runtime/contracts.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter/material.dart'; + +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex_ui/widgets.dart'; + +import '../../workspace/timeline_session.dart'; +import 'canvas_presets.dart'; +import 'project_settings_dialog.dart'; + +/// Project information uses the live editing session, including unsaved edits. +class ProjectProperties extends StatelessWidget { + const ProjectProperties({super.key, required this.session}); + + final EditorTimelineSession session; + + @override + Widget build(BuildContext context) { + final sequence = session.activeSequenceId; + final timeline = sequence == null + ? null + : session.persistence.timeline(sequence); + final duration = sequence == null + ? 0 + : session.sequenceDurationTicks(sequence); + final frame = timeline?.format.frameDuration; + final fps = frame == null ? null : frame.denominator / frame.numerator; + final canvas = session.canvas; + String number(double value) => value == value.roundToDouble() + ? value.toStringAsFixed(0) + : value.toStringAsFixed(3).replaceFirst(RegExp(r'0+$'), ''); + + return WorkspacePanel( + paintBackground: false, + title: context.l10n.projectProperties, + trailing: TextButton( + key: const ValueKey('project-settings-edit'), + onPressed: () => showAppDialog( + context: context, + builder: (_) => ProjectSettingsDialog(session: session), + ), + child: Text(context.l10n.modify), + ), + headerHeight: AppControlSize.panelToolbar, + headerPadding: const EdgeInsets.symmetric( + horizontal: AppSpacing.panelContentHorizontal, + ), + showHeaderDivider: false, + child: ScrollEdgeFadeBuilder( + builder: (controller) => SingleChildScrollView( + controller: controller, + physics: const ClampingScrollPhysics(), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _Info(context.l10n.timelineName, session.document.name), + _Info( + context.l10n.canvasSize, + '${number(canvas.width)} × ${number(canvas.height)} px', + ), + _Info(context.l10n.canvasRatio, canvas.label(context)), + _Info( + context.l10n.projectColorSpace, + switch (session.projectColorSpace) { + RenderColorSpace.rec2020HLG => 'HDR · Rec.2020 HLG', + RenderColorSpace.rec2020PQ => 'HDR · Rec.2020 PQ', + _ => 'SDR · Rec.709', + }, + ), + _Info( + context.l10n.currentSequence, + timeline?.name ?? context.l10n.none, + ), + _Info( + context.l10n.frameRate, + fps == null ? '—' : '${number(fps)} fps', + ), + _Info( + context.l10n.totalDuration, + '${(duration / TimelineClock.ticksPerSecond).toStringAsFixed(2)} ${context.l10n.seconds}', + ), + ], + ), + ), + ), + ); + } +} + +class _Info extends StatelessWidget { + const _Info(this.label, this.value); + + final String label; + final String value; + + @override + Widget build(BuildContext context) => Padding( + padding: AppSpacing.panelSection, + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + spacing: AppSpacing.small, + children: [ + Text(label, style: Theme.of(context).textTheme.bodySmall), + Expanded( + child: Text( + value, + textAlign: TextAlign.right, + style: Theme.of(context).textTheme.bodyMedium, + ), + ), + ], + ), + ); +} diff --git a/lib/features/properties/project_settings_dialog.dart b/lib/features/properties/project_settings_dialog.dart new file mode 100644 index 0000000..6cea667 --- /dev/null +++ b/lib/features/properties/project_settings_dialog.dart @@ -0,0 +1,227 @@ +import 'package:cutdex/l10n/l10n.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/runtime/contracts.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import 'package:cutdex_ui/widgets.dart'; +import 'package:cutdex_ui/theme.dart'; + +import '../../workspace/timeline_session.dart'; + +class ProjectSettingsDialog extends StatefulWidget { + const ProjectSettingsDialog({super.key, required this.session}); + final EditorTimelineSession session; + + @override + State createState() => _ProjectSettingsDialogState(); +} + +class _ProjectSettingsDialogState extends State { + static final _rates = { + '23.976': RationalTime(1001, 24000), + '24': RationalTime(1, 24), + '25': RationalTime(1, 25), + '29.97': RationalTime(1001, 30000), + '30': RationalTime(1, 30), + '50': RationalTime(1, 50), + '59.94': RationalTime(1001, 60000), + '60': RationalTime(1, 60), + '120': RationalTime(1, 120), + }; + static const _sizes = { + '1920 × 1080': (1920, 1080), + '3840 × 2160': (3840, 2160), + '1280 × 720': (1280, 720), + '1080 × 1920': (1080, 1920), + '1080 × 1080': (1080, 1080), + }; + final _form = GlobalKey(); + late final TextEditingController _width; + late final TextEditingController _height; + late RationalTime _frame; + late RenderColorSpace _color; + String? _preset; + + @override + void initState() { + super.initState(); + final canvas = widget.session.canvas; + _width = TextEditingController(text: canvas.width.toStringAsFixed(0)); + _height = TextEditingController(text: canvas.height.toStringAsFixed(0)); + _frame = widget.session.activeSequenceId == null + ? TimelineFormat.fps24.frameDuration + : widget.session.persistence + .timeline(widget.session.activeSequenceId!) + .format + .frameDuration; + _color = widget.session.projectColorSpace; + _preset = _sizes.entries + .where((e) => e.value.$1 == canvas.width && e.value.$2 == canvas.height) + .firstOrNull + ?.key; + } + + @override + void dispose() { + _width.dispose(); + _height.dispose(); + super.dispose(); + } + + void _save() { + if (!_form.currentState!.validate()) return; + widget.session.setProjectProperties( + sequence: widget.session.activeSequenceId, + canvas: ProjectCanvas( + double.parse(_width.text), + double.parse(_height.text), + ), + frameDuration: _frame, + colorSpace: _color, + ); + Navigator.of(context).pop(); + } + + Widget _dimension( + TextEditingController controller, + String label, + String key, + ) => FormField( + initialValue: controller.text, + validator: (_) { + final value = int.tryParse(controller.text); + return value == null || !ProjectCanvas.isValidDimension(value.toDouble()) + ? context.l10n.projectResolutionInvalid + : null; + }, + builder: (field) => AppTextField( + key: ValueKey(key), + controller: controller, + label: label, + errorText: field.errorText, + keyboardType: TextInputType.number, + inputFormatters: [FilteringTextInputFormatter.digitsOnly], + onChanged: (value) { + field.didChange(value); + setState(() => _preset = null); + }, + ), + ); + + @override + Widget build(BuildContext context) { + final l10n = context.l10n; + final rates = {..._rates}; + if (!rates.values.contains(_frame)) { + rates[(_frame.denominator / _frame.numerator).toStringAsFixed(3)] = + _frame; + } + return AppDialog( + title: l10n.projectSettings, + width: 440, + description: l10n.projectSettingsDescription, + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: Text(l10n.cancel), + ), + FilledButton( + key: const ValueKey('project-settings-save'), + onPressed: _save, + child: Text(l10n.save), + ), + ], + child: SingleChildScrollView( + child: Form( + key: _form, + child: AppFieldGroup( + children: [ + AppField( + label: l10n.canvasSize, + child: AppFieldGroup( + children: [ + AppSelect( + emptyLabel: context.l10n.noMatchingOptions, + key: const ValueKey('project-resolution'), + value: _preset ?? 'custom', + label: l10n.canvasSize, + options: [ + for (final name in _sizes.keys) + AppSelectOption(name, name), + AppSelectOption('custom', l10n.custom), + ], + onChanged: (value) => setState(() { + _preset = value == 'custom' ? null : value; + final size = _sizes[value]; + if (size != null) { + _width.text = '${size.$1}'; + _height.text = '${size.$2}'; + } + }), + ), + Row( + spacing: AppSpacing.compact, + children: [ + Expanded( + child: _dimension( + _width, + l10n.projectWidth, + 'project-width', + ), + ), + Expanded( + child: _dimension( + _height, + l10n.projectHeight, + 'project-height', + ), + ), + ], + ), + ], + ), + ), + AppField( + label: l10n.frameRate, + child: AppSelect( + emptyLabel: context.l10n.noMatchingOptions, + key: const ValueKey('project-frame-rate'), + value: _frame, + label: l10n.frameRate, + options: [ + for (final rate in rates.entries) + AppSelectOption(rate.value, '${rate.key} fps'), + ], + onChanged: (value) => setState(() => _frame = value), + ), + ), + AppField( + label: l10n.projectColorSpace, + child: AppSelect( + emptyLabel: context.l10n.noMatchingOptions, + key: const ValueKey('project-color-space'), + value: _color, + label: l10n.projectColorSpace, + options: const [ + AppSelectOption(RenderColorSpace.rec709, 'SDR · Rec.709'), + AppSelectOption( + RenderColorSpace.rec2020HLG, + 'HDR · Rec.2020 HLG', + ), + AppSelectOption( + RenderColorSpace.rec2020PQ, + 'HDR · Rec.2020 PQ', + ), + ], + onChanged: (value) => setState(() => _color = value), + ), + ), + ], + ), + ), + ), + ); + } +} diff --git a/lib/features/properties/properties_content.dart b/lib/features/properties/properties_content.dart new file mode 100644 index 0000000..005a652 --- /dev/null +++ b/lib/features/properties/properties_content.dart @@ -0,0 +1,331 @@ +import 'package:cutdex/l10n/l10n.dart'; +import 'package:cutdex_sdk/timeline/engine.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import 'package:cutdex_ui/theme.dart'; + +import 'properties_inspector_controller.dart'; + +import 'package:cutdex_ui/widgets.dart'; + +import '../../workspace/timeline_provider.dart'; +import '../../workspace/timeline_session.dart'; +import 'audio_properties.dart'; +import 'caption_properties.dart'; +import 'color_interpretation_properties.dart'; +import 'mask_properties.dart'; +import 'picture_properties.dart'; +import 'project_properties.dart'; +import 'properties_presentation_state.dart'; +import 'speed_properties.dart'; + +export 'properties_presentation_state.dart'; + +typedef PropertyCategoryControls = Widget Function( + BuildContext context, + List categories, + PropertyCategory selected, + ValueChanged onSelected, +); + +class PropertiesContent extends ConsumerWidget { + const PropertiesContent({ + super.key, + required this.projectId, + required this.timelineId, + required this.categoryControls, + required this.categoryHeaderHeight, + }); + final String projectId; + final String timelineId; + final PropertyCategoryControls categoryControls; + final double categoryHeaderHeight; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final state = ref.watch(editorTimelineProvider(projectId, timelineId)); + final content = state.when( + error: (_, _) => WorkspacePanel( + paintBackground: false, + child: _Message(context.l10n.loadClipPropertiesFailed), + ), + data: (session) { + final inspector = ref.watch( + propertiesInspectorProvider((projectId, timelineId)), + ); + if (inspector == null) return const SizedBox.shrink(); + return ListenableBuilder( + listenable: inspector, + builder: (context, _) => _selection(context, inspector, ref), + ); + }, + loading: () => const WorkspacePanel( + key: Key('properties-pending'), + paintBackground: false, + child: SizedBox.expand(), + ), + ); + return Theme( + data: AppTheme.propertiesPanelTheme(Theme.of(context)), + child: content, + ); + } + + Widget _selection( + BuildContext context, + PropertiesInspectorController inspector, + WidgetRef ref, + ) { + final session = inspector.session; + final sequence = inspector.sequence; + final clips = inspector.selectedClips; + if (sequence == null || clips.isEmpty) { + return ProjectProperties(session: session); + } + if (clips.length > 1) { + return WorkspacePanel( + paintBackground: false, + child: _Message(context.l10n.selectedClipsHint(clips.length)), + ); + } + final clip = clips.single; + final payload = clip.payloadRef == null + ? null + : session.payloadFor(clip.payloadRef!); + final binding = clip.payloadRef == null + ? null + : session.mediaBinding(clip.payloadRef!); + final hasAudio = binding?.audioSelection != null; + if (payload?.type == 'caption' || payload?.type == 'caption-role') { + return CaptionProperties( + session: session, + sequence: sequence, + clipId: clip.id.value, + transformProperties: payload?.type == 'caption' + ? PictureProperties( + key: ValueKey((sequence, clip.id, 'caption-transform')), + projectId: projectId, + timelineId: timelineId, + session: session, + sequence: sequence, + clip: clip, + ) + : null, + ); + } + return _ClipProperties( + key: ValueKey((sequence, clip.id)), + categoryControls: categoryControls, + categoryHeaderHeight: categoryHeaderHeight, + category: ref.watch( + propertyCategoryProvider(( + projectId, + timelineId, + '${sequence.value}/${clip.id.value}', + )), + ), + session: session, + sequence: sequence, + clip: clip, + mask: MaskProperties( + projectId: projectId, + timelineId: timelineId, + element: clip.id, + ), + speed: SpeedProperties( + session: session, + sequence: sequence, + clip: clip.id, + ), + audio: AudioProperties( + key: ValueKey((sequence, clip.id, 'audio')), + session: session, + sequence: sequence, + clip: clip, + hasAudio: hasAudio, + ), + picture: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (payload?.type == 'video' && binding?.videoTrackIndex != null) + ColorInterpretationProperties( + projectId: projectId, + timelineId: timelineId, + session: session, + assetId: payload!.assetIds.single, + trackIndex: binding!.videoTrackIndex!, + ), + PictureProperties( + key: ValueKey((sequence, clip.id)), + projectId: projectId, + timelineId: timelineId, + session: session, + sequence: sequence, + clip: clip, + ), + ], + ), + animation: PictureProperties( + key: ValueKey((sequence, clip.id, 'animation')), + projectId: projectId, + timelineId: timelineId, + session: session, + sequence: sequence, + clip: clip, + animationView: true, + ), + type: payload?.type, + hasAudio: hasAudio, + ); + } +} + +class _ClipProperties extends StatefulWidget { + const _ClipProperties({ + super.key, + required this.session, + required this.sequence, + required this.clip, + required this.picture, + required this.mask, + required this.audio, + required this.speed, + required this.animation, + required this.type, + required this.hasAudio, + required this.categoryControls, + required this.categoryHeaderHeight, + required this.category, + }); + final EditorTimelineSession session; + final SequenceId sequence; + final ElementRecord clip; + final Widget picture; + final Widget mask; + final Widget audio; + final Widget speed; + final Widget animation; + final String? type; + final bool hasAudio; + final PropertyCategoryControls categoryControls; + final double categoryHeaderHeight; + final ValueNotifier category; + @override + State<_ClipProperties> createState() => _ClipPropertiesState(); +} + +class _ClipPropertiesState extends State<_ClipProperties> { + PropertyCategory get _selected { + final categories = categoriesForClip(widget.clip, widget.type); + return categories.contains(widget.category.value) + ? widget.category.value! + : categories.first; + } + + void _selectCategory(PropertyCategory category) => + widget.category.value = category; + + @override + Widget build(BuildContext context) => ListenableBuilder( + listenable: widget.category, + builder: (context, _) => _buildProperties(context), + ); + + Widget _buildProperties(BuildContext context) { + final clip = widget.clip; + return WorkspacePanel( + paintBackground: false, + headerHeight: widget.categoryHeaderHeight, + headerPadding: EdgeInsets.zero, + showHeaderDivider: false, + controls: widget.categoryControls( + context, + categoriesForClip(clip, widget.type), + _selected, + _selectCategory, + ), + child: ScrollEdgeFadeBuilder( + key: PageStorageKey((clip.id, _selected)), + builder: (controller) => SingleChildScrollView( + controller: controller, + // Inspector controls stop at their bounds; macOS's default elastic + // physics repeatedly displaces the content during edge scrolling. + physics: const ClampingScrollPhysics(), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + ...switch (_selected) { + PropertyCategory.picture => [widget.picture], + PropertyCategory.mask => [widget.mask], + PropertyCategory.audio => [widget.audio], + PropertyCategory.speed => [widget.speed], + PropertyCategory.animation => [widget.animation], + PropertyCategory.basic => [ + _Property(context.l10n.type, switch (clip.structure) { + ElementStructure.gap => context.l10n.gap, + ElementStructure.container => context.l10n.compoundClip, + ElementStructure.content => + widget.type ?? context.l10n.unboundMedia, + }), + _Property( + context.l10n.status, + clip.enabled ? context.l10n.enable : context.l10n.disable, + ), + ], + }, + ], + ), + ), + ), + ); + } +} + +class _Property extends StatelessWidget { + const _Property(this.label, this.value); + final String label; + final String value; + @override + Widget build(BuildContext context) => Padding( + padding: AppSpacing.panelSection, + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + spacing: AppSpacing.small, + children: [ + Expanded( + child: Text( + label, + style: AppTheme.propertySectionTitleStyle(context), + ), + ), + Expanded( + child: Text( + value, + textAlign: TextAlign.right, + style: Theme.of(context).textTheme.bodyMedium?.copyWith( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + ), + ], + ), + ); +} + +class _Message extends StatelessWidget { + const _Message(this.text); + final String text; + @override + Widget build(BuildContext context) => Center( + child: Padding( + padding: AppSpacing.panelSection, + child: Text( + text, + textAlign: TextAlign.center, + style: Theme.of(context).textTheme.bodySmall, + ), + ), + ); +} diff --git a/lib/features/properties/properties_editor_page.dart b/lib/features/properties/properties_editor_page.dart new file mode 100644 index 0000000..7f54add --- /dev/null +++ b/lib/features/properties/properties_editor_page.dart @@ -0,0 +1,76 @@ +import 'package:flutter/material.dart'; + +import 'properties_content.dart'; + +class PropertiesEditorPage extends StatelessWidget { + const PropertiesEditorPage({ + super.key, + required this.projectId, + required this.timelineId, + }); + final String projectId; + final String timelineId; + @override + Widget build(BuildContext context) => PropertiesContent( + key: const Key('properties-editor-page'), + projectId: projectId, + timelineId: timelineId, + categoryHeaderHeight: 48, + categoryControls: (context, categories, selected, onSelected) => Padding( + padding: const EdgeInsets.symmetric(horizontal: 16), + child: DropdownButton( + key: const Key('property-category-picker'), + isExpanded: true, + underline: const SizedBox.shrink(), + value: selected, + items: [ + for (final category in categories) + DropdownMenuItem( + value: category, + child: Text(category.label(context)), + ), + ], + onChanged: (category) { + if (category != null) onSelected(category); + }, + ), + ), + ); +} + +class PropertiesToolPanel extends StatelessWidget { + const PropertiesToolPanel({ + super.key, + required this.projectId, + required this.timelineId, + }); + final String projectId; + final String timelineId; + @override + Widget build(BuildContext context) => PropertiesContent( + key: const Key('properties-tool-panel'), + projectId: projectId, + timelineId: timelineId, + categoryHeaderHeight: 48, + categoryControls: (context, categories, selected, onSelected) => + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + children: [ + for (final category in categories) + TextButton( + key: ValueKey('property-tab-${category.name}'), + style: TextButton.styleFrom( + minimumSize: const Size(64, 48), + foregroundColor: selected == category + ? Theme.of(context).colorScheme.primary + : null, + ), + onPressed: () => onSelected(category), + child: Text(category.label(context)), + ), + ], + ), + ), + ); +} diff --git a/lib/features/properties/properties_inspector_controller.dart b/lib/features/properties/properties_inspector_controller.dart new file mode 100644 index 0000000..1778735 --- /dev/null +++ b/lib/features/properties/properties_inspector_controller.dart @@ -0,0 +1,94 @@ +import 'package:cutdex_sdk/timeline/engine.dart'; +import 'package:cutdex_sdk/timeline/layout.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../workspace/timeline_provider.dart'; +import '../../workspace/timeline_session.dart'; +import 'properties_presentation_state.dart'; + +final propertiesInspectorProvider = Provider.autoDispose + .family((ref, identity) { + final session = ref + .watch(editorTimelineProvider(identity.$1, identity.$2)) + .value; + if (session == null) return null; + final controller = PropertiesInspectorController(session); + ref.onDispose(controller.dispose); + return controller; + }); + +/// Resolves the shared editing selection without prescribing a device layout. +class PropertiesInspectorController extends ChangeNotifier { + PropertiesInspectorController(this.session) { + session.addListener(_sessionChanged); + _bindView(); + } + final EditorTimelineSession session; + Listenable? _editingChanges; + SequenceId? get sequence => session.activeSequenceId; + + void _bindView() { + final id = sequence; + final next = id == null ? null : session.view(id).editingChanges; + if (identical(next, _editingChanges)) return; + _editingChanges?.removeListener(notifyListeners); + _editingChanges = next; + _editingChanges?.addListener(notifyListeners); + } + + void _sessionChanged() { + _bindView(); + notifyListeners(); + } + + List get selectedClips { + final id = sequence; + if (id == null) return const []; + final view = session.view(id); + final query = view.version.kernelVersion.query(); + final handles = {}; + for (final identity in view.selectedIdentities) { + final handle = switch (identity) { + ElementHandle handle => handle, + LayoutBodyId body => view.elementForIdentity(body), + _ => null, + }; + if (handle != null && query.ownerOf(handle) != null) handles.add(handle); + } + final clips = [for (final handle in handles) query.element(handle)]; + return clips.any((clip) => clip.structure != ElementStructure.gap) + ? clips + : const []; + } + + @override + void dispose() { + session.removeListener(_sessionChanged); + _editingChanges?.removeListener(notifyListeners); + super.dispose(); + } +} + +List categoriesForClip(ElementRecord clip, String? type) { + if (clip.structure != ElementStructure.content) { + return [PropertyCategory.basic]; + } + return switch (type) { + 'video' => [ + PropertyCategory.picture, + PropertyCategory.mask, + PropertyCategory.audio, + PropertyCategory.speed, + PropertyCategory.animation, + ], + 'audio' => [PropertyCategory.audio, PropertyCategory.speed], + 'image' => [ + PropertyCategory.picture, + PropertyCategory.mask, + PropertyCategory.animation, + ], + _ => [PropertyCategory.basic], + }; +} diff --git a/lib/features/properties/properties_panel.dart b/lib/features/properties/properties_panel.dart new file mode 100644 index 0000000..37c93c3 --- /dev/null +++ b/lib/features/properties/properties_panel.dart @@ -0,0 +1,32 @@ +import 'package:flutter/material.dart'; + +import 'package:cutdex_ui/widgets.dart'; + +import 'properties_content.dart'; +export 'properties_presentation_state.dart'; + +/// Desktop inspector uses compact category tabs over shared property editors. +class EditorPropertiesPanel extends StatelessWidget { + const EditorPropertiesPanel({ + super.key, + required this.projectId, + required this.timelineId, + }); + final String projectId; + final String timelineId; + @override + Widget build(BuildContext context) => PropertiesContent( + projectId: projectId, + timelineId: timelineId, + categoryHeaderHeight: CompactPanelTabs.height, + categoryControls: (context, categories, selected, onSelected) => + CompactPanelTabs( + values: categories, + selected: selected, + labelBuilder: (category) => category.label(context), + tabKeyBuilder: (category) => + ValueKey('property-tab-${category.name}'), + onSelected: onSelected, + ), + ); +} diff --git a/lib/features/properties/properties_presentation_state.dart b/lib/features/properties/properties_presentation_state.dart new file mode 100644 index 0000000..f598920 --- /dev/null +++ b/lib/features/properties/properties_presentation_state.dart @@ -0,0 +1,31 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../l10n/l10n.dart'; + +final propertyCategoryProvider = + Provider.family, (String, String, String)>( + (ref, identity) { + final category = ValueNotifier(null); + ref.onDispose(category.dispose); + return category; + }, + ); + +enum PropertyCategory { + picture, + mask, + audio, + speed, + animation, + basic; + + String label(BuildContext context) => switch (this) { + picture => context.l10n.pictureProperties, + mask => context.l10n.mask, + audio => context.l10n.audio, + speed => context.l10n.speedChange, + animation => context.l10n.animation, + basic => context.l10n.basic, + }; +} diff --git a/lib/features/properties/property_number_input.dart b/lib/features/properties/property_number_input.dart new file mode 100644 index 0000000..0f800ca --- /dev/null +++ b/lib/features/properties/property_number_input.dart @@ -0,0 +1,152 @@ +import 'package:cutdex/l10n/l10n.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import 'package:cutdex_ui/widgets.dart'; + +class PropertyNumberInput extends StatefulWidget { + const PropertyNumberInput({ + super.key, + required this.label, + required this.value, + required this.enabled, + required this.readOnly, + required this.submit, + this.unit, + this.decimalPlaces = 2, + this.onScrubStart, + required this.onScrubUpdate, + required this.onScrubEnd, + required this.onScrubCancel, + required this.scrubbing, + required this.editContext, + }) : assert(decimalPlaces >= 0 && decimalPlaces <= 20); + final String? label; + final String? unit; + final int decimalPlaces; + final bool Function()? onScrubStart; + final ValueChanged onScrubUpdate; + final VoidCallback onScrubEnd; + final VoidCallback onScrubCancel; + final bool scrubbing; + final Object editContext; + final double value; + final bool enabled; + final bool readOnly; + final Future Function(double) submit; + @override + State createState() => _PropertyNumberInputState(); +} + +class _PropertyNumberInputState extends State { + late final _text = TextEditingController(text: _format(widget.value)); + final _focus = FocusNode(); + bool _dirty = false; + String? _error; + String _format(double value) { + var text = value.toStringAsFixed(widget.decimalPlaces); + if (text.contains('.')) text = text.replaceFirst(RegExp(r'\.?0+$'), ''); + return text == '-0' ? '0' : text; + } + + @override + void initState() { + super.initState(); + _focus.addListener(_blur); + } + + void _blur() { + if (!_focus.hasFocus) _submit(); + } + + Future _submit() async { + if (!_dirty || !widget.enabled || widget.readOnly) return; + final value = double.tryParse(_text.text); + if (value == null || !value.isFinite) { + setState(() => _error = context.l10n.invalidNumber); + return; + } + _dirty = false; + final accepted = await widget.submit(value); + if (!mounted) return; + setState(() { + _error = accepted ? null : context.l10n.notApplied; + _text.text = _format(widget.value); + }); + } + + @override + void didUpdateWidget(covariant PropertyNumberInput oldWidget) { + super.didUpdateWidget(oldWidget); + if ((oldWidget.enabled && !widget.enabled) || + oldWidget.editContext != widget.editContext || + (!oldWidget.readOnly && widget.readOnly)) { + _dirty = false; + _error = null; + } + final text = _format(widget.value); + // A no-op assignment still resets selection and asks EditableText to + // reveal its caret, competing with the user's scroll on preview updates. + if (!_dirty && _text.text != text) _text.text = text; + } + + @override + void dispose() { + _focus.removeListener(_blur); + _focus.dispose(); + _text.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => Focus( + onKeyEvent: (_, event) { + if (event is KeyDownEvent && + event.logicalKey == LogicalKeyboardKey.escape) { + setState(() { + _dirty = false; + _error = null; + _text.text = _format(widget.value); + }); + _focus.unfocus(); + return KeyEventResult.handled; + } + return KeyEventResult.ignored; + }, + child: AppTextField( + controller: _text, + focusNode: _focus, + enabled: widget.enabled, + readOnly: widget.readOnly, + canRequestFocus: widget.enabled && !widget.readOnly, + keyboardType: const TextInputType.numberWithOptions( + decimal: true, + signed: true, + ), + label: widget.label, + leading: widget.onScrubStart == null + ? null + : AppScrubLabel( + label: widget.label!, + enabled: widget.enabled && (!widget.readOnly || widget.scrubbing), + onStart: () { + _dirty = false; + _error = null; + _text.text = _format(widget.value); + return widget.onScrubStart!(); + }, + onUpdate: widget.onScrubUpdate, + onEnd: widget.onScrubEnd, + onCancel: widget.onScrubCancel, + ), + unit: widget.unit, + errorText: _error, + onChanged: (_) { + _dirty = true; + if (_error != null) setState(() => _error = null); + }, + onEditingComplete: () {}, + onSubmitted: (_) => _submit(), + ), + ); +} diff --git a/lib/features/properties/speed_properties.dart b/lib/features/properties/speed_properties.dart new file mode 100644 index 0000000..dd00a8f --- /dev/null +++ b/lib/features/properties/speed_properties.dart @@ -0,0 +1,318 @@ +import 'dart:math' as math; + +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/timeline/engine.dart'; +import 'package:cutdex_sdk/timeline/layout.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter/material.dart'; + +import '../../l10n/l10n.dart'; + +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex_ui/widgets.dart'; + +import '../../workspace/timeline_session.dart'; + +class SpeedProperties extends StatefulWidget { + const SpeedProperties({ + super.key, + required this.session, + required this.sequence, + required this.clip, + }); + final EditorTimelineSession session; + final SequenceId sequence; + final ElementId clip; + + @override + State createState() => _SpeedPropertiesState(); +} + +class _SpeedPropertiesState extends State { + double? _timeline; + TimelineVersion? _version; + LayoutConnectionEditPreview? _preview; + double? _previewSpeed; + (Object, StackTrace)? _previewFailure; + + double _speed(double position) => + (math.pow(10, position * 3 - 1).toDouble() * 100).round() / 100; + + void _updatePreview(double speed) { + final view = widget.session.view(widget.sequence); + _preview?.cancel(); + _preview = null; + _previewSpeed = null; + _previewFailure = null; + try { + final preview = widget.session.previewClipSpeed( + widget.sequence, + widget.clip, + speed, + ); + _preview = preview; + _previewSpeed = preview == null ? null : speed; + if (preview == null) { + view.clearLayoutPreview(); + } else { + view.showLayoutPreview(preview.result.version); + } + } catch (error, stack) { + _previewFailure = (error, stack); + view.clearLayoutPreview(); + _showError(error); + } + } + + void _commit(double speed) { + final view = widget.session.view(widget.sequence); + if (widget.session.activeSequenceId == widget.sequence && + (_version == null || identical(_version, view.version.kernelVersion))) { + try { + widget.session.runEdit( + 'setSpeed', + widget.sequence, + () { + if (_previewSpeed != speed) _updatePreview(speed); + final preview = _preview; + final failure = _previewFailure; + _preview = null; + _previewSpeed = null; + _previewFailure = null; + if (preview == null) { + view.clearLayoutPreview(); + if (failure != null) { + widget.session.reportEditFailure(failure.$1, failure.$2); + } + } else { + widget.session.commitClipSpeedPreview(widget.sequence, preview); + } + }, + context: { + 'clipIds': [widget.clip.value], + 'entryPoint': 'property', + 'playheadTick': view.playheadTick, + }, + ); + } catch (error) { + _preview?.cancel(); + _preview = null; + _previewSpeed = null; + view.clearLayoutPreview(); + _showError(error); + } + } else { + _discardPreview(); + } + setState(() { + _timeline = null; + _version = null; + }); + } + + void _discardPreview() { + _preview?.cancel(); + _preview = null; + _previewSpeed = null; + _previewFailure = null; + widget.session.view(widget.sequence).clearLayoutPreview(); + } + + void _showError(Object error) { + if (!mounted) return; + ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text(context.l10n.errorMessage(error)))); + } + + @override + void dispose() { + _discardPreview(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final view = widget.session.view(widget.sequence); + return ListenableBuilder( + listenable: Listenable.merge([view, widget.session]), + builder: (context, _) { + final query = view.version.kernelVersion.query(); + final handle = query.elementById(widget.clip); + final record = handle == null ? null : query.element(handle); + final segments = record == null + ? null + : widget.session.clipSpeedSegments(record); + final saved = segments?.length == 1 ? segments!.single.speed : null; + final enabled = + saved != null && widget.session.acceptsEdits && !view.isDragging; + final canReset = + segments != null && widget.session.acceptsEdits && !view.isDragging; + final localPlayhead = handle == null + ? 0 + : view.playheadTick - query.absoluteStart(handle); + final custom = widget.session.isCustomSpeedEnabled( + widget.sequence, + widget.clip, + ); + final canSplit = + custom && + segments != null && + localPlayhead > 0 && + localPlayhead < (record?.duration ?? 0) && + !segments.any((segment) => segment.projectStart == localPlayhead) && + widget.session.acceptsEdits && + !view.isDragging; + final value = + _version == null || identical(_version, view.version.kernelVersion) + ? _timeline ?? saved ?? 1 + : saved ?? 1; + return Padding( + padding: AppSpacing.panelSection, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + Expanded( + child: Text( + context.l10n.speed, + style: AppTheme.propertySectionTitleStyle(context), + ), + ), + Text( + saved == null && segments != null + ? context.l10n.segmentedSpeed + : '${value.toStringAsFixed(2)}×', + key: const Key('clip-speed-value'), + style: Theme.of(context).textTheme.bodyMedium?.copyWith( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + const SizedBox(width: AppSpacing.small), + TextButton( + onPressed: canReset + ? () { + _version = null; + _commit(1); + } + : null, + child: const Text('1×'), + ), + ], + ), + if (saved != null) ...[ + const SizedBox(height: AppSpacing.small), + AppSlider( + key: const Key('clip-speed-slider'), + value: ((math.log(value.clamp(0.1, 100)) / math.ln10 + 1) / 3) + .clamp(0, 1), + semanticFormatterCallback: (position) => + '${_speed(position).toStringAsFixed(2)}×', + onChangeStart: enabled + ? (_) { + _discardPreview(); + _version = view.version.kernelVersion; + } + : null, + onChanged: enabled + ? (position) { + if (_version != null && + !identical( + _version, + view.version.kernelVersion, + )) { + _discardPreview(); + setState(() => _timeline = null); + return; + } + final speed = _speed(position); + setState(() => _timeline = speed); + _updatePreview(speed); + } + : null, + onChangeEnd: enabled + ? (position) => _commit(_speed(position)) + : null, + ), + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text('0.1×', style: Theme.of(context).textTheme.bodySmall), + Text('100×', style: Theme.of(context).textTheme.bodySmall), + ], + ), + ] else if (segments != null) + Text( + context.l10n.speedSegmentCount(segments.length), + style: Theme.of(context).textTheme.bodySmall, + ), + const SizedBox(height: AppSpacing.small), + Row( + children: [ + Expanded( + child: Text( + context.l10n.custom, + style: AppTheme.propertySectionTitleStyle(context), + ), + ), + AppSwitch( + key: const Key('clip-custom-speed-toggle'), + value: custom, + semanticLabel: context.l10n.custom, + onChanged: canReset + ? (value) { + _discardPreview(); + setState(() { + _timeline = null; + _version = null; + }); + widget.session.setCustomSpeedEnabled( + widget.sequence, + widget.clip, + value, + ); + } + : null, + ), + ], + ), + const SizedBox(height: AppSpacing.small), + SizedBox( + width: double.infinity, + height: AppControlSize.propertyControl, + child: OutlinedButton.icon( + key: const Key('split-speed-segment'), + onPressed: canSplit + ? () { + try { + widget.session.splitClipSpeedAt( + widget.sequence, + widget.clip, + localPlayhead, + ); + } catch (error) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(context.l10n.errorMessage(error)), + ), + ); + } + } + : null, + icon: const Icon(Icons.content_cut), + label: Text(context.l10n.splitSpeedAtPlayhead), + ), + ), + if (segments == null) + Text( + context.l10n.speedNotAvailable, + style: Theme.of(context).textTheme.bodySmall, + ), + ], + ), + ); + }, + ); + } +} diff --git a/lib/features/settings/agent_settings_panel.dart b/lib/features/settings/agent_settings_panel.dart new file mode 100644 index 0000000..7f192a3 --- /dev/null +++ b/lib/features/settings/agent_settings_panel.dart @@ -0,0 +1,760 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../integrations/agent/agent_settings.dart'; +import '../../integrations/agent/agent_models.dart'; +import '../../l10n/l10n.dart'; + +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex_ui/widgets.dart'; + +import 'settings_layout.dart'; +import '../../settings/settings_operation.dart'; + +part 'agent_settings_panel.freezed.dart'; + +class AgentSettingsPanel extends ConsumerStatefulWidget { + const AgentSettingsPanel({super.key, this.contentPadding = EdgeInsets.zero}); + + final EdgeInsets contentPadding; + + @override + ConsumerState createState() => _AgentSettingsPanelState(); +} + +class _AgentSettingsPanelState extends ConsumerState + with SingleTickerProviderStateMixin { + late final AnimationController _pageFade = AnimationController( + vsync: this, + duration: const Duration(milliseconds: 140), + value: 1, + ); + bool _showingProviderEditor = false; + AgentProviderSettings? _editingProvider; + bool _transitioning = false; + bool get _saving => + ref.read(settingsOperationProvider('agent-save')).isLoading; + final _scroll = ScrollController(); + + @override + void dispose() { + _pageFade.dispose(); + _scroll.dispose(); + super.dispose(); + } + + Future _showProviderForm( + bool adding, { + AgentProviderSettings? provider, + }) async { + if (_transitioning || _saving || _showingProviderEditor == adding) return; + setState(() => _transitioning = true); + await _pageFade.reverse(); + if (!mounted) return; + if (_scroll.hasClients) _scroll.jumpTo(0); + setState(() { + _showingProviderEditor = adding; + _editingProvider = adding ? provider : null; + }); + await _pageFade.forward(); + if (mounted) setState(() => _transitioning = false); + } + + Future _saveProvider(_ProviderFormValue result) async { + if (_saving) return; + final saved = await ref + .read(settingsOperationProvider('agent-save').notifier) + .run( + () => ref + .read(agentSettingsProvider.notifier) + .upsertProvider( + id: _editingProvider?.id, + name: result.name, + apiType: result.apiType, + baseUrl: result.baseUrl, + models: result.models, + apiKey: result.apiKey, + clearApiKey: result.clearApiKey, + ), + ); + if (!mounted) return; + if (saved) { + await _showProviderForm(false); + } else { + _showSaveError(); + } + } + + void _showSaveError() => ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text(context.l10n.agentSaveSettingsFailed))); + + Future _setProviderEnabled( + AgentProviderSettings provider, + bool enabled, + ) async { + if (_transitioning) return; + final operation = settingsOperationProvider('agent-enable-${provider.id}'); + if (ref.read(operation).isLoading) return; + final saved = await ref + .read(operation.notifier) + .run( + () => ref + .read(agentSettingsProvider.notifier) + .setProviderEnabled(provider.id, enabled), + ); + if (!saved && mounted) _showSaveError(); + } + + @override + Widget build(BuildContext context) => Theme( + data: AppTheme.settingsContentTheme(Theme.of(context)), + child: Builder(builder: _buildContent), + ); + + Widget _buildContent(BuildContext context) { + ref.watch(settingsOperationProvider('agent-save')); + final settings = ref.watch(agentSettingsProvider); + return ScrollConfiguration( + behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false), + child: Scrollbar( + controller: _scroll, + thumbVisibility: true, + child: SingleChildScrollView( + key: const Key('agent-settings-scroll'), + controller: _scroll, + primary: false, + padding: widget.contentPadding, + physics: const ClampingScrollPhysics(), + child: FadeTransition( + key: const Key('agent-provider-page-transition'), + opacity: _pageFade, + child: IgnorePointer( + ignoring: _transitioning, + child: _showingProviderEditor + ? _ProviderEditor( + key: const Key('agent-provider-editor'), + saving: _saving, + provider: _editingProvider, + onBack: () => _showProviderForm(false), + onSave: _saveProvider, + ) + : SettingsPageSection( + key: const Key('agent-provider-list'), + title: context.l10n.agentSettings, + icon: Icons.auto_awesome_outlined, + action: OutlinedButton.icon( + onPressed: settings.asData == null + ? null + : () => _showProviderForm(true), + icon: const Icon(Icons.add), + label: Text(context.l10n.agentAddProvider), + ), + children: [ + for (final provider + in settings.asData?.value.providers ?? + const []) + _ProviderCard( + key: ValueKey('agent-provider-${provider.id}'), + provider: provider, + onEdit: () => + _showProviderForm(true, provider: provider), + onEnabledChanged: (value) => + _setProviderEnabled(provider, value), + ), + ], + ), + ), + ), + ), + ), + ); + } +} + +class _ProviderCard extends StatelessWidget { + const _ProviderCard({ + super.key, + required this.provider, + required this.onEdit, + required this.onEnabledChanged, + }); + + final AgentProviderSettings provider; + final VoidCallback onEdit; + final ValueChanged onEnabledChanged; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final colors = theme.colorScheme; + final icon = switch (provider.apiType) { + 'anthropicMessages' => Icons.auto_awesome_outlined, + 'openAiResponses' => Icons.bolt_outlined, + _ => Icons.forum_outlined, + }; + return Container( + padding: EdgeInsets.zero, + child: Row( + children: [ + Icon(icon, size: AppIconSize.header, color: colors.onSurfaceVariant), + const SizedBox(width: 16), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + provider.name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: theme.textTheme.bodyMedium?.copyWith( + fontWeight: FontWeight.w400, + ), + ), + const SizedBox(height: 2), + Text( + provider.models.map((model) => model.id).join(' · '), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: theme.textTheme.bodySmall?.copyWith( + color: colors.onSurfaceVariant, + ), + ), + ], + ), + ), + const SizedBox(width: 12), + IconButton( + key: ValueKey('agent-provider-edit-${provider.id}'), + tooltip: context.l10n.agentEditProvider, + onPressed: onEdit, + icon: const Icon(Icons.edit_outlined, size: AppIconSize.header), + ), + const SizedBox(width: 8), + AppSwitch( + key: ValueKey('agent-provider-enabled-${provider.id}'), + value: provider.enabled, + semanticLabel: context.l10n.agentEnableProvider, + onChanged: onEnabledChanged, + ), + ], + ), + ); + } +} + +TextStyle _providerInputStyle(BuildContext context) => + Theme.of(context).textTheme.bodyMedium!; + +InputDecoration _providerInputDecoration( + BuildContext context, { + String? hintText, +}) => InputDecoration( + hintText: hintText, + hintStyle: _providerInputStyle(context) + .copyWith(color: Theme.of(context).colorScheme.onSurfaceVariant), +); + +class _ProviderEditor extends StatefulWidget { + const _ProviderEditor({ + super.key, + required this.onBack, + required this.onSave, + required this.saving, + this.provider, + }); + + final VoidCallback onBack; + final ValueChanged<_ProviderFormValue> onSave; + final bool saving; + final AgentProviderSettings? provider; + + @override + State<_ProviderEditor> createState() => _ProviderEditorState(); +} + +class _ProviderEditorState extends State<_ProviderEditor> { + final _formKey = GlobalKey(); + late final TextEditingController _name; + late final TextEditingController _baseUrl; + late final TextEditingController _apiKey; + late List<_ModelControllers> _models; + AgentApiType _apiType = AgentApiType.openAiChatCompletions; + String? _formError; + + @override + void initState() { + super.initState(); + final provider = widget.provider; + _name = TextEditingController(text: provider?.name); + _baseUrl = TextEditingController(text: provider?.baseUrl); + _apiKey = TextEditingController(); + _apiType = + AgentApiType.values + .where((type) => type.name == provider?.apiType) + .firstOrNull ?? + AgentApiType.openAiChatCompletions; + _models = provider == null || provider.models.isEmpty + ? [_ModelControllers()] + : [for (final model in provider.models) _ModelControllers(model)]; + } + + @override + void dispose() { + _name.dispose(); + _baseUrl.dispose(); + _apiKey.dispose(); + for (final model in _models) { + model.dispose(); + } + super.dispose(); + } + + void _submit() { + if (!_formKey.currentState!.validate()) return; + final modelIds = _models.map((model) => model.id.text.trim()).toList(); + if (modelIds.toSet().length != modelIds.length) { + setState(() => _formError = context.l10n.agentModelIdsUnique); + return; + } + widget.onSave( + _ProviderFormValue( + name: _name.text.trim(), + apiType: _apiType, + baseUrl: _baseUrl.text.trim(), + apiKey: _apiKey.text.isEmpty ? null : _apiKey.text, + clearApiKey: false, + models: [for (final model in _models) model.toData()], + ), + ); + } + + @override + Widget build(BuildContext context) => Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + TextButton.icon( + key: const Key('agent-provider-back'), + onPressed: widget.saving ? null : widget.onBack, + icon: const Icon(Icons.arrow_back, size: 16), + label: Text(context.l10n.agentBackToProviders), + ), + ], + ), + const SizedBox(height: AppSpacing.large), + Form( + key: _formKey, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _ConfigurationCard( + title: context.l10n.agentProviderConfiguration, + child: AppFieldGroup( + children: [ + _ProviderIdentityRow( + children: [ + AppField( + label: context.l10n.name, + child: TextFormField( + style: _providerInputStyle(context), + textAlignVertical: TextAlignVertical.center, + cursorHeight: 18, + cursorWidth: 1.5, + strutStyle: StrutStyle.fromTextStyle( + _providerInputStyle(context), + ), + key: const Key('agent-provider-name'), + controller: _name, + decoration: _providerInputDecoration( + context, + hintText: context.l10n.agentProviderNameHint, + ), + validator: (value) => _required(context, value), + ), + ), + AppField( + label: context.l10n.agentApiType, + child: AppSelect( + emptyLabel: context.l10n.noMatchingOptions, + controlHeight: AppSettingsMetrics.inputHeight, + textStyle: _providerInputStyle(context), + value: _apiType, + label: context.l10n.agentApiType, + options: [ + for (final value in AgentApiType.values) + AppSelectOption( + value, + _apiTypeLabel(context, value), + ), + ], + onChanged: (value) => + setState(() => _apiType = value), + ), + ), + ], + ), + AppField( + label: context.l10n.agentBaseUrl, + child: TextFormField( + style: _providerInputStyle(context), + textAlignVertical: TextAlignVertical.center, + cursorHeight: 18, + cursorWidth: 1.5, + strutStyle: StrutStyle.fromTextStyle( + _providerInputStyle(context), + ), + key: const Key('agent-provider-base-url'), + controller: _baseUrl, + keyboardType: TextInputType.url, + decoration: _providerInputDecoration( + context, + hintText: _apiType == AgentApiType.anthropicMessages + ? 'https://api.anthropic.com/v1' + : 'https://api.openai.com/v1', + ), + validator: (value) => _validateUrl(context, value), + ), + ), + ], + ), + ), + const SizedBox(height: AppSpacing.large), + _ConfigurationCard( + title: context.l10n.agentAuthenticationAndModels, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + AppField( + label: context.l10n.agentApiKey, + child: TextFormField( + style: _providerInputStyle(context), + textAlignVertical: TextAlignVertical.center, + cursorHeight: 18, + cursorWidth: 1.5, + strutStyle: StrutStyle.fromTextStyle( + _providerInputStyle(context), + ), + key: const Key('agent-provider-api-key'), + controller: _apiKey, + obscureText: true, + decoration: _providerInputDecoration( + context, + hintText: context.l10n.agentOptional, + ), + validator: (value) => + value != null && + (value.contains('\n') || value.contains('\r')) + ? context.l10n.agentApiKeyOneLine + : null, + ), + ), + const SizedBox(height: AppSpacing.small), + Text( + widget.provider?.credentialId != null + ? context.l10n.agentApiKeyKeep + : context.l10n.agentApiKeyOptional, + style: Theme.of(context).textTheme.bodySmall?.copyWith( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + const SizedBox(height: AppSpacing.extraLarge), + if (_formError != null) ...[ + const SizedBox(height: AppSpacing.small), + Text( + _formError!, + style: TextStyle( + color: Theme.of(context).colorScheme.error, + ), + ), + ], + const SizedBox(height: AppSpacing.small), + for (var index = 0; index < _models.length; index++) + Padding( + padding: const EdgeInsets.only(bottom: AppSpacing.medium), + child: _ModelFields( + index: index, + controllers: _models[index], + canDelete: _models.length > 1, + onDelete: () { + final removed = _models[index]; + setState( + () => _models = [..._models]..removeAt(index), + ); + removed.dispose(); + }, + ), + ), + Align( + alignment: AlignmentDirectional.centerEnd, + child: OutlinedButton.icon( + onPressed: () => setState( + () => _models = [..._models, _ModelControllers()], + ), + icon: const Icon(Icons.add, size: AppIconSize.header), + label: Text(context.l10n.agentAddModel), + ), + ), + const SizedBox(height: AppSpacing.large), + Align( + alignment: AlignmentDirectional.centerEnd, + child: FilledButton( + onPressed: widget.saving ? null : _submit, + child: Text(context.l10n.agentSaveProvider), + ), + ), + ], + ), + ), + ], + ), + ), + ], + ); + + static String? _required(BuildContext context, String? value) => + value == null || value.trim().isEmpty + ? context.l10n.agentRequiredField + : null; + + static String? _validateUrl(BuildContext context, String? value) { + final uri = Uri.tryParse(value?.trim() ?? ''); + return uri == null || + !uri.hasAuthority || + !['http', 'https'].contains(uri.scheme) || + uri.userInfo.isNotEmpty || + uri.hasQuery || + uri.hasFragment + ? context.l10n.agentInvalidBaseUrl + : null; + } + + static String _apiTypeLabel(BuildContext context, AgentApiType value) => + switch (value) { + AgentApiType.openAiChatCompletions => + context.l10n.agentOpenAiChatCompletions, + AgentApiType.openAiResponses => 'OpenAI Responses', + AgentApiType.anthropicMessages => 'Anthropic Messages', + }; +} + +class _ConfigurationCard extends StatelessWidget { + const _ConfigurationCard({required this.title, required this.child}); + + final String title; + final Widget child; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text(title, style: theme.textTheme.labelLarge), + const SizedBox(height: AppSpacing.medium), + Container( + padding: const EdgeInsets.all(AppSpacing.medium), + decoration: BoxDecoration( + color: theme.colorScheme.surfaceContainer, + borderRadius: BorderRadius.circular(AppSettingsMetrics.cardRadius), + border: Border.all(color: theme.colorScheme.outlineVariant), + ), + child: child, + ), + ], + ); + } +} + +class _ProviderIdentityRow extends StatelessWidget { + const _ProviderIdentityRow({required this.children}); + final List children; + + @override + Widget build(BuildContext context) => LayoutBuilder( + builder: (context, constraints) => constraints.maxWidth < 520 + ? AppFieldGroup(children: children) + : Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded(child: children[0]), + const SizedBox(width: 16), + Expanded(child: children[1]), + ], + ), + ); +} + +class _ModelFields extends StatelessWidget { + const _ModelFields({ + required this.index, + required this.controllers, + required this.canDelete, + required this.onDelete, + }); + + final int index; + final _ModelControllers controllers; + final bool canDelete; + final VoidCallback onDelete; + + @override + Widget build(BuildContext context) { + final fields = [ + AppField( + label: context.l10n.agentModelId, + child: TextFormField( + style: _providerInputStyle(context), + textAlignVertical: TextAlignVertical.center, + cursorHeight: 18, + cursorWidth: 1.5, + strutStyle: StrutStyle.fromTextStyle(_providerInputStyle(context)), + key: Key('agent-model-id-$index'), + controller: controllers.id, + decoration: _providerInputDecoration( + context, + hintText: 'my-model-id', + ), + validator: (value) => _ProviderEditorState._required(context, value), + ), + ), + AppField( + label: context.l10n.agentContextWindow, + child: TextFormField( + style: _providerInputStyle(context), + textAlignVertical: TextAlignVertical.center, + cursorHeight: 18, + cursorWidth: 1.5, + strutStyle: StrutStyle.fromTextStyle(_providerInputStyle(context)), + key: Key('agent-model-context-$index'), + controller: controllers.contextWindow, + keyboardType: TextInputType.number, + decoration: _providerInputDecoration(context, hintText: '512000'), + validator: (value) => _optionalPositiveInteger(context, value), + ), + ), + AppField( + label: context.l10n.agentMaxOutputTokens, + child: TextFormField( + style: _providerInputStyle(context), + textAlignVertical: TextAlignVertical.center, + cursorHeight: 18, + cursorWidth: 1.5, + strutStyle: StrutStyle.fromTextStyle(_providerInputStyle(context)), + key: Key('agent-model-output-$index'), + controller: controllers.maxOutputTokens, + keyboardType: TextInputType.number, + decoration: _providerInputDecoration(context, hintText: '4096'), + validator: (value) { + final basic = _optionalPositiveInteger(context, value); + if (basic != null) return basic; + final contextWindow = int.tryParse(controllers.contextWindow.text); + final model = AgentModelSettings( + id: controllers.id.text, + contextWindow: contextWindow, + maxOutputTokens: int.tryParse(value ?? ''), + ); + if (!model.hasValidTokenBudget) { + return context.l10n.agentMaxOutputBelowContext; + } + return model.hasInstructionBudget + ? null + : context.l10n.agentContextBudgetTooSmall; + }, + ), + ), + ]; + final removeButton = SizedBox.square( + dimension: AppSettingsMetrics.inputHeight, + child: IconButton( + style: IconButton.styleFrom( + padding: EdgeInsets.zero, + minimumSize: const Size.square(AppSettingsMetrics.inputHeight), + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + tooltip: context.l10n.agentDeleteModel, + onPressed: canDelete ? onDelete : null, + icon: const Icon(Icons.delete_outline, size: AppIconSize.header), + ), + ); + return LayoutBuilder( + builder: (context, constraints) { + if (constraints.maxWidth < 520) { + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + spacing: AppSpacing.compact, + children: [ + ...fields, + Align( + alignment: AlignmentDirectional.centerEnd, + child: removeButton, + ), + ], + ); + } + return Row( + crossAxisAlignment: CrossAxisAlignment.start, + spacing: AppSpacing.small, + children: [ + for (var i = 0; i < fields.length; i++) + Expanded(flex: i == 0 ? 2 : 1, child: fields[i]), + Padding( + padding: const EdgeInsets.only(top: 26), + child: removeButton, + ), + ], + ); + }, + ); + } + + static String? _optionalPositiveInteger(BuildContext context, String? value) { + if (value == null || value.trim().isEmpty) return null; + final parsed = int.tryParse(value); + return parsed == null || parsed <= 0 + ? context.l10n.agentPositiveInteger + : null; + } +} + +class _ModelControllers { + _ModelControllers([AgentModelSettings? model]) + : id = TextEditingController(text: model?.id), + contextWindow = TextEditingController( + text: model?.contextWindow?.toString(), + ), + maxOutputTokens = TextEditingController( + text: model?.maxOutputTokens?.toString(), + ); + + final TextEditingController id; + final TextEditingController contextWindow; + final TextEditingController maxOutputTokens; + + AgentModelSettings toData() => AgentModelSettings( + id: id.text.trim(), + contextWindow: int.tryParse(contextWindow.text), + maxOutputTokens: int.tryParse(maxOutputTokens.text), + ); + + void dispose() { + id.dispose(); + contextWindow.dispose(); + maxOutputTokens.dispose(); + } +} + +@freezed +abstract class _ProviderFormValue with _$ProviderFormValue { + const factory _ProviderFormValue({ + required String name, + required AgentApiType apiType, + required String baseUrl, + required List models, + required String? apiKey, + required bool clearApiKey, + }) = _ProviderFormData; +} diff --git a/lib/features/settings/agent_settings_panel.freezed.dart b/lib/features/settings/agent_settings_panel.freezed.dart new file mode 100644 index 0000000..3bbdfdf --- /dev/null +++ b/lib/features/settings/agent_settings_panel.freezed.dart @@ -0,0 +1,483 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'agent_settings_panel.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +T _$identity(T value) => value; + +/// @nodoc +mixin _$ProviderFormValue { + String get name; + AgentApiType get apiType; + String get baseUrl; + List get models; + String? get apiKey; + bool get clearApiKey; + + /// Create a copy of _ProviderFormValue + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$ProviderFormValueCopyWith<_ProviderFormValue> get copyWith => + __$ProviderFormValueCopyWithImpl<_ProviderFormValue>( + this as _ProviderFormValue, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as _ProviderFormValue; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _ProviderFormValue && + (identical(other.name, _this.name) || other.name == _this.name) && + (identical(other.apiType, _this.apiType) || + other.apiType == _this.apiType) && + (identical(other.baseUrl, _this.baseUrl) || + other.baseUrl == _this.baseUrl) && + const DeepCollectionEquality().equals(other.models, _this.models) && + (identical(other.apiKey, _this.apiKey) || + other.apiKey == _this.apiKey) && + (identical(other.clearApiKey, _this.clearApiKey) || + other.clearApiKey == _this.clearApiKey)); + } + + @override + int get hashCode { + final _this = this as _ProviderFormValue; + return Object.hash( + runtimeType, + _this.name, + _this.apiType, + _this.baseUrl, + const DeepCollectionEquality().hash(_this.models), + _this.apiKey, + _this.clearApiKey, + ); + } + + @override + String toString() { + final _this = this as _ProviderFormValue; + return '_ProviderFormValue(name: ${_this.name}, apiType: ${_this.apiType}, baseUrl: ${_this.baseUrl}, models: ${_this.models}, apiKey: ${_this.apiKey}, clearApiKey: ${_this.clearApiKey})'; + } +} + +/// @nodoc +abstract mixin class _$ProviderFormValueCopyWith<$Res> { + factory _$ProviderFormValueCopyWith( + _ProviderFormValue value, + $Res Function(_ProviderFormValue) _then, + ) = __$ProviderFormValueCopyWithImpl; + @useResult + $Res call({ + String name, + AgentApiType apiType, + String baseUrl, + List models, + String? apiKey, + bool clearApiKey, + }); +} + +/// @nodoc +class __$ProviderFormValueCopyWithImpl<$Res> + implements _$ProviderFormValueCopyWith<$Res> { + __$ProviderFormValueCopyWithImpl(this._self, this._then); + + final _ProviderFormValue _self; + final $Res Function(_ProviderFormValue) _then; + + /// Create a copy of _ProviderFormValue + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? name = null, + Object? apiType = null, + Object? baseUrl = null, + Object? models = null, + Object? apiKey = freezed, + Object? clearApiKey = null, + }) { + return _then( + _ProviderFormValue( + name: null == name + ? _self.name + : name // ignore: cast_nullable_to_non_nullable + as String, + apiType: null == apiType + ? _self.apiType + : apiType // ignore: cast_nullable_to_non_nullable + as AgentApiType, + baseUrl: null == baseUrl + ? _self.baseUrl + : baseUrl // ignore: cast_nullable_to_non_nullable + as String, + models: null == models + ? _self.models + : models // ignore: cast_nullable_to_non_nullable + as List, + apiKey: freezed == apiKey + ? _self.apiKey + : apiKey // ignore: cast_nullable_to_non_nullable + as String?, + clearApiKey: null == clearApiKey + ? _self.clearApiKey + : clearApiKey // ignore: cast_nullable_to_non_nullable + as bool, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [_ProviderFormValue]. +extension _ProviderFormValuePatterns on _ProviderFormValue { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_ProviderFormData value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ProviderFormData() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_ProviderFormData value) $default, + ) { + final _that = this; + switch (_that) { + case _ProviderFormData(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_ProviderFormData value)? $default, + ) { + final _that = this; + switch (_that) { + case _ProviderFormData() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + String name, + AgentApiType apiType, + String baseUrl, + List models, + String? apiKey, + bool clearApiKey, + )? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ProviderFormData() when $default != null: + return $default( + _that.name, + _that.apiType, + _that.baseUrl, + _that.models, + _that.apiKey, + _that.clearApiKey, + ); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function( + String name, + AgentApiType apiType, + String baseUrl, + List models, + String? apiKey, + bool clearApiKey, + ) + $default, + ) { + final _that = this; + switch (_that) { + case _ProviderFormData(): + return $default( + _that.name, + _that.apiType, + _that.baseUrl, + _that.models, + _that.apiKey, + _that.clearApiKey, + ); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + String name, + AgentApiType apiType, + String baseUrl, + List models, + String? apiKey, + bool clearApiKey, + )? + $default, + ) { + final _that = this; + switch (_that) { + case _ProviderFormData() when $default != null: + return $default( + _that.name, + _that.apiType, + _that.baseUrl, + _that.models, + _that.apiKey, + _that.clearApiKey, + ); + case _: + return null; + } + } +} + +/// @nodoc + +class _ProviderFormData implements _ProviderFormValue { + const _ProviderFormData({ + required this.name, + required this.apiType, + required this.baseUrl, + required List models, + required this.apiKey, + required this.clearApiKey, + }) : _models = models; + + @override + final String name; + @override + final AgentApiType apiType; + @override + final String baseUrl; + final List _models; + @override + List get models { + if (_models is EqualUnmodifiableListView) return _models; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_models); + } + + @override + final String? apiKey; + @override + final bool clearApiKey; + + /// Create a copy of _ProviderFormValue + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$ProviderFormDataCopyWith<_ProviderFormData> get copyWith => + __$ProviderFormDataCopyWithImpl<_ProviderFormData>(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _ProviderFormData && + (identical(other.name, name) || other.name == name) && + (identical(other.apiType, apiType) || other.apiType == apiType) && + (identical(other.baseUrl, baseUrl) || other.baseUrl == baseUrl) && + const DeepCollectionEquality().equals(other.models, _models) && + (identical(other.apiKey, apiKey) || other.apiKey == apiKey) && + (identical(other.clearApiKey, clearApiKey) || + other.clearApiKey == clearApiKey)); + } + + @override + int get hashCode { + return Object.hash( + runtimeType, + name, + apiType, + baseUrl, + const DeepCollectionEquality().hash(_models), + apiKey, + clearApiKey, + ); + } + + @override + String toString() { + return '_ProviderFormValue(name: $name, apiType: $apiType, baseUrl: $baseUrl, models: $models, apiKey: $apiKey, clearApiKey: $clearApiKey)'; + } +} + +/// @nodoc +abstract mixin class _$ProviderFormDataCopyWith<$Res> + implements _$ProviderFormValueCopyWith<$Res> { + factory _$ProviderFormDataCopyWith( + _ProviderFormData value, + $Res Function(_ProviderFormData) _then, + ) = __$ProviderFormDataCopyWithImpl; + @override + @useResult + $Res call({ + String name, + AgentApiType apiType, + String baseUrl, + List models, + String? apiKey, + bool clearApiKey, + }); +} + +/// @nodoc +class __$ProviderFormDataCopyWithImpl<$Res> + implements _$ProviderFormDataCopyWith<$Res> { + __$ProviderFormDataCopyWithImpl(this._self, this._then); + + final _ProviderFormData _self; + final $Res Function(_ProviderFormData) _then; + + /// Create a copy of _ProviderFormValue + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? name = null, + Object? apiType = null, + Object? baseUrl = null, + Object? models = null, + Object? apiKey = freezed, + Object? clearApiKey = null, + }) { + return _then( + _ProviderFormData( + name: null == name + ? _self.name + : name // ignore: cast_nullable_to_non_nullable + as String, + apiType: null == apiType + ? _self.apiType + : apiType // ignore: cast_nullable_to_non_nullable + as AgentApiType, + baseUrl: null == baseUrl + ? _self.baseUrl + : baseUrl // ignore: cast_nullable_to_non_nullable + as String, + models: null == models + ? _self._models + : models // ignore: cast_nullable_to_non_nullable + as List, + apiKey: freezed == apiKey + ? _self.apiKey + : apiKey // ignore: cast_nullable_to_non_nullable + as String?, + clearApiKey: null == clearApiKey + ? _self.clearApiKey + : clearApiKey // ignore: cast_nullable_to_non_nullable + as bool, + ), + ); + } +} diff --git a/lib/features/settings/appearance_settings.dart b/lib/features/settings/appearance_settings.dart new file mode 100644 index 0000000..1c751a7 --- /dev/null +++ b/lib/features/settings/appearance_settings.dart @@ -0,0 +1,35 @@ +import 'package:flutter/material.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import '../../persistence/settings/appearance_settings_repository.dart'; +import '../../settings/appearance.dart'; +import '../../settings/settings_write_queue.dart'; + +export '../../settings/appearance.dart'; + +part 'appearance_settings.g.dart'; + +extension AppAppearanceTheme on AppAppearance { + ThemeMode get themeMode => switch (this) { + AppAppearance.system => ThemeMode.system, + AppAppearance.penLight => ThemeMode.light, + AppAppearance.penDark => ThemeMode.dark, + }; +} + +@Riverpod(keepAlive: true) +class AppearanceSettings extends _$AppearanceSettings { + final _writes = SettingsWriteQueue(); + + @override + Future build() => + ref.watch(appearanceSettingsRepositoryProvider).load(); + + Future setMode(AppAppearance appearance) => _writes.run(() async { + if (!ref.mounted) return; + await future; + if (!ref.mounted) return; + await ref.read(appearanceSettingsRepositoryProvider).save(appearance); + if (ref.mounted) state = AsyncData(appearance); + }); +} diff --git a/lib/features/settings/appearance_settings.g.dart b/lib/features/settings/appearance_settings.g.dart new file mode 100644 index 0000000..6e5731b --- /dev/null +++ b/lib/features/settings/appearance_settings.g.dart @@ -0,0 +1,55 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'appearance_settings.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(AppearanceSettings) +final appearanceSettingsProvider = AppearanceSettingsProvider._(); + +final class AppearanceSettingsProvider + extends $AsyncNotifierProvider { + AppearanceSettingsProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'appearanceSettingsProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$appearanceSettingsHash(); + + @$internal + @override + AppearanceSettings create() => AppearanceSettings(); +} + +String _$appearanceSettingsHash() => + r'df889bcd3ec16a726ebc1bccd98b9e7033989a69'; + +abstract class _$AppearanceSettings extends $AsyncNotifier { + FutureOr build(); + @$mustCallSuper + @override + WhenComplete runBuild() { + final ref = this.ref as $Ref, AppAppearance>; + final element = + ref.element + as $ClassProviderElement< + AnyNotifier, AppAppearance>, + AsyncValue, + Object?, + Object? + >; + return element.handleCreate(ref, build); + } +} diff --git a/lib/features/settings/diagnostic_settings.dart b/lib/features/settings/diagnostic_settings.dart new file mode 100644 index 0000000..29e54e3 --- /dev/null +++ b/lib/features/settings/diagnostic_settings.dart @@ -0,0 +1,57 @@ +import 'dart:io'; + +import 'package:cutdex_ui/widgets.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../diagnostics/app_diagnostics.dart'; +import '../../integrations/platform/file_picker.dart'; +import '../../l10n/l10n.dart'; +import '../../settings/settings_operation.dart'; + +class DiagnosticSettings extends ConsumerStatefulWidget { + const DiagnosticSettings({super.key}); + + @override + ConsumerState createState() => _DiagnosticSettingsState(); +} + +class _DiagnosticSettingsState extends ConsumerState { + bool _exported = false; + + Future _export() async { + setState(() => _exported = false); + final picker = ref.read(filePickerProvider); + await ref.read(settingsOperationProvider('diagnosticsExport').notifier).run( + () async { + final selected = await picker.pickDirectory(); + if (selected == null) return; + final diagnostics = + AppDiagnostics.instance ?? await AppDiagnostics.initialize(); + await diagnostics.export(Directory(selected)); + if (mounted) setState(() => _exported = true); + }, + ); + } + + @override + Widget build(BuildContext context) { + final operation = ref.watch(settingsOperationProvider('diagnosticsExport')); + return AppField( + label: context.l10n.diagnostics, + orientation: AppFieldOrientation.horizontal, + error: operation.hasError ? context.l10n.exportDiagnosticsFailed : null, + child: Column( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + OutlinedButton( + key: const Key('export-diagnostics'), + onPressed: operation.isLoading ? null : _export, + child: Text(context.l10n.exportDiagnostics), + ), + if (_exported) Text(context.l10n.exportDiagnosticsSucceeded), + ], + ), + ); + } +} diff --git a/lib/features/settings/language_settings.dart b/lib/features/settings/language_settings.dart new file mode 100644 index 0000000..3095fa4 --- /dev/null +++ b/lib/features/settings/language_settings.dart @@ -0,0 +1,97 @@ +import 'package:flutter/widgets.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import '../../persistence/settings/language_settings_repository.dart'; +import '../../settings/language.dart'; +import '../../settings/settings_write_queue.dart'; + +export '../../settings/language.dart'; + +part 'language_settings.g.dart'; + +extension AppLanguagePresentation on AppLanguage { + Locale? get locale => switch (this) { + AppLanguage.system => null, + AppLanguage.english => const Locale('en'), + AppLanguage.simplifiedChinese => const Locale.fromSubtags( + languageCode: 'zh', + scriptCode: 'Hans', + ), + AppLanguage.traditionalChinese => const Locale.fromSubtags( + languageCode: 'zh', + scriptCode: 'Hant', + ), + AppLanguage.japanese => const Locale('ja'), + AppLanguage.korean => const Locale('ko'), + AppLanguage.french => const Locale('fr'), + AppLanguage.german => const Locale('de'), + AppLanguage.spanish => const Locale('es'), + AppLanguage.portuguese => const Locale('pt'), + AppLanguage.italian => const Locale('it'), + AppLanguage.russian => const Locale('ru'), + }; + + String get nativeName => switch (this) { + AppLanguage.system => '', + AppLanguage.english => 'English', + AppLanguage.simplifiedChinese => '简体中文', + AppLanguage.traditionalChinese => '繁體中文', + AppLanguage.japanese => '日本語', + AppLanguage.korean => '한국어', + AppLanguage.french => 'Français', + AppLanguage.german => 'Deutsch', + AppLanguage.spanish => 'Español', + AppLanguage.portuguese => 'Português', + AppLanguage.italian => 'Italiano', + AppLanguage.russian => 'Русский', + }; +} + +/// Select a supported language in device preference order, resolving Chinese +/// scripts explicitly when the operating system supplies only a region. +Locale resolveAppLocale( + List? preferredLocales, + Iterable supportedLocales, +) { + for (final preferred in preferredLocales ?? const []) { + if (preferred.languageCode == 'zh') { + final script = + preferred.scriptCode ?? + (const {'TW', 'HK', 'MO'}.contains(preferred.countryCode) + ? 'Hant' + : 'Hans'); + final match = supportedLocales + .where( + (locale) => + locale.languageCode == 'zh' && locale.scriptCode == script, + ) + .firstOrNull; + if (match != null) return match; + } + final match = supportedLocales + .where((locale) => locale.languageCode == preferred.languageCode) + .firstOrNull; + if (match != null) return match; + } + return supportedLocales + .where((locale) => locale.languageCode == 'en') + .firstOrNull ?? + supportedLocales.first; +} + +@Riverpod(keepAlive: true) +class LanguageSettings extends _$LanguageSettings { + final _writes = SettingsWriteQueue(); + + @override + Future build() => + ref.watch(languageSettingsRepositoryProvider).load(); + + Future setLanguage(AppLanguage language) => _writes.run(() async { + if (!ref.mounted) return; + await future; + if (!ref.mounted) return; + await ref.read(languageSettingsRepositoryProvider).save(language); + if (ref.mounted) state = AsyncData(language); + }); +} diff --git a/lib/features/settings/language_settings.g.dart b/lib/features/settings/language_settings.g.dart new file mode 100644 index 0000000..99b677f --- /dev/null +++ b/lib/features/settings/language_settings.g.dart @@ -0,0 +1,54 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'language_settings.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(LanguageSettings) +final languageSettingsProvider = LanguageSettingsProvider._(); + +final class LanguageSettingsProvider + extends $AsyncNotifierProvider { + LanguageSettingsProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'languageSettingsProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$languageSettingsHash(); + + @$internal + @override + LanguageSettings create() => LanguageSettings(); +} + +String _$languageSettingsHash() => r'fcd5bb7f010ea5bb09f9743d9023cd1668214f43'; + +abstract class _$LanguageSettings extends $AsyncNotifier { + FutureOr build(); + @$mustCallSuper + @override + WhenComplete runBuild() { + final ref = this.ref as $Ref, AppLanguage>; + final element = + ref.element + as $ClassProviderElement< + AnyNotifier, AppLanguage>, + AsyncValue, + Object?, + Object? + >; + return element.handleCreate(ref, build); + } +} diff --git a/lib/features/settings/location_settings.dart b/lib/features/settings/location_settings.dart new file mode 100644 index 0000000..8023659 --- /dev/null +++ b/lib/features/settings/location_settings.dart @@ -0,0 +1,139 @@ +import 'dart:async'; + +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import '../../integrations/runtime/processing_resource_repository.dart'; +import '../../persistence/settings/location_settings_repositories.dart'; +import '../../settings/settings_write_queue.dart'; +import '../../workspace/persistence/project_location_directory.dart'; + +part 'location_settings.g.dart'; +part 'location_settings.freezed.dart'; + +enum LocationSettingsError { load, save } + +@freezed +abstract class LocationSettingsState with _$LocationSettingsState { + const factory LocationSettingsState({ + String? directory, + ProjectLocationStatus? status, + @Default(true) bool loading, + @Default(false) bool saving, + LocationSettingsError? error, + }) = _LocationSettingsState; +} + +@riverpod +ProjectLocationDirectory projectLocationDirectory(Ref ref) => + const ProjectLocationDirectory(); + +@riverpod +class ProjectLocationSettings extends _$ProjectLocationSettings { + final _writes = SettingsWriteQueue(); + + @override + LocationSettingsState build() { + final repository = ref.watch(projectLocationSettingsRepositoryProvider); + final directory = ref.watch(projectLocationDirectoryProvider); + unawaited(_writes.run(() => _load(repository, directory))); + return const LocationSettingsState(); + } + + Future reload() => _writes.run(() async { + if (!ref.mounted) return; + await _load( + ref.read(projectLocationSettingsRepositoryProvider), + ref.read(projectLocationDirectoryProvider), + ); + }); + + Future _load( + ProjectLocationSettingsRepository repository, + ProjectLocationDirectory inspector, + ) async { + if (!ref.mounted) return; + state = state.copyWith(loading: true, error: null, status: null); + try { + final directory = await repository.load(); + if (!ref.mounted) return; + state = state.copyWith(directory: directory); + final status = directory == null + ? null + : await inspector.inspect(directory); + if (ref.mounted) state = state.copyWith(status: status); + } catch (_) { + if (ref.mounted) { + state = state.copyWith(error: LocationSettingsError.load); + } + } finally { + if (ref.mounted) state = state.copyWith(loading: false); + } + } + + Future save(String directory) => _writes.run(() async { + if (!ref.mounted) return; + final keepAlive = ref.keepAlive(); + state = state.copyWith(saving: true, error: null); + final repository = ref.read(projectLocationSettingsRepositoryProvider); + final inspector = ref.read(projectLocationDirectoryProvider); + try { + await repository.save(directory); + if (ref.mounted) await _load(repository, inspector); + } catch (_) { + if (ref.mounted) { + state = state.copyWith(error: LocationSettingsError.save); + } + } finally { + if (ref.mounted) state = state.copyWith(saving: false); + keepAlive.close(); + } + }); +} + +@riverpod +class ResourceLocationSettings extends _$ResourceLocationSettings { + final _writes = SettingsWriteQueue(); + + @override + LocationSettingsState build() { + final repository = ref.watch(resourceLocationSettingsRepositoryProvider); + unawaited(_writes.run(() => _load(repository))); + return const LocationSettingsState(); + } + + Future _load(ResourceLocationSettingsRepository repository) async { + if (!ref.mounted) return; + try { + final directory = await repository.load(); + if (ref.mounted) state = state.copyWith(directory: directory); + } catch (_) { + if (ref.mounted) { + state = state.copyWith(error: LocationSettingsError.load); + } + } finally { + if (ref.mounted) state = state.copyWith(loading: false); + } + } + + Future save(String directory) => _writes.run(() async { + if (!ref.mounted) return; + final keepAlive = ref.keepAlive(); + state = state.copyWith(saving: true, error: null); + try { + await ref + .read(resourceLocationSettingsRepositoryProvider) + .save(directory); + if (!ref.mounted) return; + ref.invalidate(processingResourceRepositoryProvider); + state = state.copyWith(directory: directory); + } catch (_) { + if (ref.mounted) { + state = state.copyWith(error: LocationSettingsError.save); + } + } finally { + if (ref.mounted) state = state.copyWith(saving: false); + keepAlive.close(); + } + }); +} diff --git a/lib/features/settings/location_settings.freezed.dart b/lib/features/settings/location_settings.freezed.dart new file mode 100644 index 0000000..ba6fd7b --- /dev/null +++ b/lib/features/settings/location_settings.freezed.dart @@ -0,0 +1,450 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'location_settings.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +T _$identity(T value) => value; + +/// @nodoc +mixin _$LocationSettingsState { + String? get directory; + ProjectLocationStatus? get status; + bool get loading; + bool get saving; + LocationSettingsError? get error; + + /// Create a copy of LocationSettingsState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $LocationSettingsStateCopyWith get copyWith => + _$LocationSettingsStateCopyWithImpl( + this as LocationSettingsState, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as LocationSettingsState; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is LocationSettingsState && + (identical(other.directory, _this.directory) || + other.directory == _this.directory) && + (identical(other.status, _this.status) || + other.status == _this.status) && + (identical(other.loading, _this.loading) || + other.loading == _this.loading) && + (identical(other.saving, _this.saving) || + other.saving == _this.saving) && + (identical(other.error, _this.error) || + other.error == _this.error)); + } + + @override + int get hashCode { + final _this = this as LocationSettingsState; + return Object.hash( + runtimeType, + _this.directory, + _this.status, + _this.loading, + _this.saving, + _this.error, + ); + } + + @override + String toString() { + final _this = this as LocationSettingsState; + return 'LocationSettingsState(directory: ${_this.directory}, status: ${_this.status}, loading: ${_this.loading}, saving: ${_this.saving}, error: ${_this.error})'; + } +} + +/// @nodoc +abstract mixin class $LocationSettingsStateCopyWith<$Res> { + factory $LocationSettingsStateCopyWith( + LocationSettingsState value, + $Res Function(LocationSettingsState) _then, + ) = _$LocationSettingsStateCopyWithImpl; + @useResult + $Res call({ + String? directory, + ProjectLocationStatus? status, + bool loading, + bool saving, + LocationSettingsError? error, + }); +} + +/// @nodoc +class _$LocationSettingsStateCopyWithImpl<$Res> + implements $LocationSettingsStateCopyWith<$Res> { + _$LocationSettingsStateCopyWithImpl(this._self, this._then); + + final LocationSettingsState _self; + final $Res Function(LocationSettingsState) _then; + + /// Create a copy of LocationSettingsState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? directory = freezed, + Object? status = freezed, + Object? loading = null, + Object? saving = null, + Object? error = freezed, + }) { + return _then( + LocationSettingsState( + directory: freezed == directory + ? _self.directory + : directory // ignore: cast_nullable_to_non_nullable + as String?, + status: freezed == status + ? _self.status + : status // ignore: cast_nullable_to_non_nullable + as ProjectLocationStatus?, + loading: null == loading + ? _self.loading + : loading // ignore: cast_nullable_to_non_nullable + as bool, + saving: null == saving + ? _self.saving + : saving // ignore: cast_nullable_to_non_nullable + as bool, + error: freezed == error + ? _self.error + : error // ignore: cast_nullable_to_non_nullable + as LocationSettingsError?, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [LocationSettingsState]. +extension LocationSettingsStatePatterns on LocationSettingsState { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_LocationSettingsState value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _LocationSettingsState() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_LocationSettingsState value) $default, + ) { + final _that = this; + switch (_that) { + case _LocationSettingsState(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_LocationSettingsState value)? $default, + ) { + final _that = this; + switch (_that) { + case _LocationSettingsState() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + String? directory, + ProjectLocationStatus? status, + bool loading, + bool saving, + LocationSettingsError? error, + )? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _LocationSettingsState() when $default != null: + return $default( + _that.directory, + _that.status, + _that.loading, + _that.saving, + _that.error, + ); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function( + String? directory, + ProjectLocationStatus? status, + bool loading, + bool saving, + LocationSettingsError? error, + ) + $default, + ) { + final _that = this; + switch (_that) { + case _LocationSettingsState(): + return $default( + _that.directory, + _that.status, + _that.loading, + _that.saving, + _that.error, + ); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + String? directory, + ProjectLocationStatus? status, + bool loading, + bool saving, + LocationSettingsError? error, + )? + $default, + ) { + final _that = this; + switch (_that) { + case _LocationSettingsState() when $default != null: + return $default( + _that.directory, + _that.status, + _that.loading, + _that.saving, + _that.error, + ); + case _: + return null; + } + } +} + +/// @nodoc + +class _LocationSettingsState implements LocationSettingsState { + const _LocationSettingsState({ + this.directory, + this.status, + this.loading = true, + this.saving = false, + this.error, + }); + + @override + final String? directory; + @override + final ProjectLocationStatus? status; + @override + @JsonKey() + final bool loading; + @override + @JsonKey() + final bool saving; + @override + final LocationSettingsError? error; + + /// Create a copy of LocationSettingsState + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$LocationSettingsStateCopyWith<_LocationSettingsState> get copyWith => + __$LocationSettingsStateCopyWithImpl<_LocationSettingsState>( + this, + _$identity, + ); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _LocationSettingsState && + (identical(other.directory, directory) || + other.directory == directory) && + (identical(other.status, status) || other.status == status) && + (identical(other.loading, loading) || other.loading == loading) && + (identical(other.saving, saving) || other.saving == saving) && + (identical(other.error, error) || other.error == error)); + } + + @override + int get hashCode { + return Object.hash(runtimeType, directory, status, loading, saving, error); + } + + @override + String toString() { + return 'LocationSettingsState(directory: $directory, status: $status, loading: $loading, saving: $saving, error: $error)'; + } +} + +/// @nodoc +abstract mixin class _$LocationSettingsStateCopyWith<$Res> + implements $LocationSettingsStateCopyWith<$Res> { + factory _$LocationSettingsStateCopyWith( + _LocationSettingsState value, + $Res Function(_LocationSettingsState) _then, + ) = __$LocationSettingsStateCopyWithImpl; + @override + @useResult + $Res call({ + String? directory, + ProjectLocationStatus? status, + bool loading, + bool saving, + LocationSettingsError? error, + }); +} + +/// @nodoc +class __$LocationSettingsStateCopyWithImpl<$Res> + implements _$LocationSettingsStateCopyWith<$Res> { + __$LocationSettingsStateCopyWithImpl(this._self, this._then); + + final _LocationSettingsState _self; + final $Res Function(_LocationSettingsState) _then; + + /// Create a copy of LocationSettingsState + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? directory = freezed, + Object? status = freezed, + Object? loading = null, + Object? saving = null, + Object? error = freezed, + }) { + return _then( + _LocationSettingsState( + directory: freezed == directory + ? _self.directory + : directory // ignore: cast_nullable_to_non_nullable + as String?, + status: freezed == status + ? _self.status + : status // ignore: cast_nullable_to_non_nullable + as ProjectLocationStatus?, + loading: null == loading + ? _self.loading + : loading // ignore: cast_nullable_to_non_nullable + as bool, + saving: null == saving + ? _self.saving + : saving // ignore: cast_nullable_to_non_nullable + as bool, + error: freezed == error + ? _self.error + : error // ignore: cast_nullable_to_non_nullable + as LocationSettingsError?, + ), + ); + } +} diff --git a/lib/features/settings/location_settings.g.dart b/lib/features/settings/location_settings.g.dart new file mode 100644 index 0000000..374e114 --- /dev/null +++ b/lib/features/settings/location_settings.g.dart @@ -0,0 +1,166 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'location_settings.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(projectLocationDirectory) +final projectLocationDirectoryProvider = ProjectLocationDirectoryProvider._(); + +final class ProjectLocationDirectoryProvider + extends + $FunctionalProvider< + ProjectLocationDirectory, + ProjectLocationDirectory, + ProjectLocationDirectory + > + with $Provider { + ProjectLocationDirectoryProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'projectLocationDirectoryProvider', + isAutoDispose: true, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$projectLocationDirectoryHash(); + + @$internal + @override + $ProviderElement $createElement( + $ProviderPointer pointer, + ) => $ProviderElement(pointer); + + @override + ProjectLocationDirectory create(Ref ref) { + return projectLocationDirectory(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(ProjectLocationDirectory value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$projectLocationDirectoryHash() => + r'a09b928fd3a8ba8db867b5226eb61ed34eb634f1'; + +@ProviderFor(ProjectLocationSettings) +final projectLocationSettingsProvider = ProjectLocationSettingsProvider._(); + +final class ProjectLocationSettingsProvider + extends $NotifierProvider { + ProjectLocationSettingsProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'projectLocationSettingsProvider', + isAutoDispose: true, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$projectLocationSettingsHash(); + + @$internal + @override + ProjectLocationSettings create() => ProjectLocationSettings(); + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(LocationSettingsState value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$projectLocationSettingsHash() => + r'0142e55d46997be3387944612ab0287f6fd7acf0'; + +abstract class _$ProjectLocationSettings + extends $Notifier { + LocationSettingsState build(); + @$mustCallSuper + @override + WhenComplete runBuild() { + final ref = this.ref as $Ref; + final element = + ref.element + as $ClassProviderElement< + AnyNotifier, + LocationSettingsState, + Object?, + Object? + >; + return element.handleCreate(ref, build); + } +} + +@ProviderFor(ResourceLocationSettings) +final resourceLocationSettingsProvider = ResourceLocationSettingsProvider._(); + +final class ResourceLocationSettingsProvider + extends $NotifierProvider { + ResourceLocationSettingsProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'resourceLocationSettingsProvider', + isAutoDispose: true, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$resourceLocationSettingsHash(); + + @$internal + @override + ResourceLocationSettings create() => ResourceLocationSettings(); + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(LocationSettingsState value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$resourceLocationSettingsHash() => + r'8d9482cd3580029c65fc541c4c8f2d296bce5ad3'; + +abstract class _$ResourceLocationSettings + extends $Notifier { + LocationSettingsState build(); + @$mustCallSuper + @override + WhenComplete runBuild() { + final ref = this.ref as $Ref; + final element = + ref.element + as $ClassProviderElement< + AnyNotifier, + LocationSettingsState, + Object?, + Object? + >; + return element.handleCreate(ref, build); + } +} diff --git a/lib/features/settings/mcp_settings_panel.dart b/lib/features/settings/mcp_settings_panel.dart new file mode 100644 index 0000000..266fb45 --- /dev/null +++ b/lib/features/settings/mcp_settings_panel.dart @@ -0,0 +1,155 @@ +import 'package:cutdex/l10n/l10n.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../integrations/editor_tools.dart'; + +import 'package:cutdex_ui/widgets.dart'; +import 'package:cutdex_ui/theme.dart'; + +import '../../integrations/mcp/mcp_settings.dart'; +import 'settings_layout.dart'; +import '../../settings/settings_operation.dart'; + +class McpSettingsPanel extends ConsumerStatefulWidget { + const McpSettingsPanel({super.key, this.workspace}); + final (String, String)? workspace; + + @override + ConsumerState createState() => _McpSettingsPanelState(); +} + +class _McpSettingsPanelState extends ConsumerState { + String? _port; + String? _error; + + Future _toggle(bool enabled, McpSettingsValue settings) async { + final port = int.tryParse(_port ?? '${settings.port}'); + if (enabled && (port == null || port < 1 || port > 65535)) { + setState(() => _error = context.l10n.invalidPort); + return; + } + setState(() => _error = null); + await ref + .read(settingsOperationProvider('mcp').notifier) + .run( + () => ref + .read(mcpSettingsProvider.notifier) + .saveSettings(enabled: enabled, port: enabled ? port : null), + ); + } + + @override + Widget build(BuildContext context) => Theme( + data: AppTheme.settingsContentTheme(Theme.of(context)), + child: Builder(builder: _buildContent), + ); + + Widget _buildContent(BuildContext context) { + final operation = ref.watch(settingsOperationProvider('mcp')); + final error = + _error ?? (operation.hasError ? context.l10n.saveMcpFailed : null); + final settings = ref.watch(mcpSettingsProvider); + final value = settings.asData?.value; + final ids = widget.workspace; + final connection = ids == null + ? null + : ref.watch(editorMcpConnectionProvider(ids.$1, ids.$2)); + final status = value?.enabled != true + ? context.l10n.disabled + : ids == null + ? context.l10n.waitingForProject + : connection!.hasError + ? context.l10n.startFailed + : connection.isLoading + ? context.l10n.starting + : context.l10n.running; + return SettingsPageSection( + title: 'MCP', + icon: Icons.terminal_outlined, + children: [ + AppField( + label: context.l10n.mcpService, + description: settings.isLoading + ? context.l10n.loadingSettings + : status, + orientation: AppFieldOrientation.horizontal, + child: Align( + alignment: AlignmentDirectional.centerEnd, + child: AppSwitch( + semanticLabel: context.l10n.mcpService, + value: value?.enabled ?? false, + onChanged: value == null || operation.isLoading + ? null + : (enabled) => _toggle(enabled, value), + ), + ), + ), + if (value != null) ...[ + AppField( + orientation: AppFieldOrientation.horizontal, + label: context.l10n.listenPort, + child: SizedBox( + width: AppSettingsMetrics.controlWidth, + child: TextFormField( + style: AppTheme.inputTextStyle(context), + cursorHeight: AppTheme.inputCursorHeight(context), + initialValue: '${value.port}', + enabled: !value.enabled && !operation.isLoading, + keyboardType: TextInputType.number, + decoration: const InputDecoration( + isDense: true, + prefixText: '127.0.0.1 : ', + ), + onChanged: (text) => _port = text, + ), + ), + ), + AppField( + orientation: AppFieldOrientation.horizontal, + label: context.l10n.accessToken, + child: IconButton( + tooltip: context.l10n.copyAccessToken, + icon: const Icon(Icons.copy_outlined), + onPressed: () async { + await Clipboard.setData(ClipboardData(text: value.token)); + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(context.l10n.accessTokenCopied)), + ); + } + }, + ), + ), + ], + if (settings.hasError) + TextButton( + onPressed: () => ref.invalidate(mcpSettingsProvider), + child: Text(context.l10n.loadMcpFailed), + ), + if (value?.enabled == true && connection?.hasError == true) ...[ + Text( + context.l10n.mcpStartError( + context.l10n.errorMessage(connection!.error!), + ), + style: TextStyle(color: Theme.of(context).colorScheme.error), + ), + TextButton( + onPressed: operation.isLoading + ? null + : () => ref.invalidate( + editorMcpConnectionProvider(ids!.$1, ids.$2), + ), + child: Text(context.l10n.retryStart), + ), + ], + if (error != null) + Text( + error, + style: TextStyle(color: Theme.of(context).colorScheme.error), + ), + ], + ); + } +} diff --git a/lib/features/settings/settings_dialog.dart b/lib/features/settings/settings_dialog.dart new file mode 100644 index 0000000..9f56f98 --- /dev/null +++ b/lib/features/settings/settings_dialog.dart @@ -0,0 +1,519 @@ +import 'package:cutdex/l10n/l10n.dart'; + +import 'dart:math' as math; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../integrations/platform/file_picker.dart'; + +import '../../workspace/persistence/project_location_directory.dart'; + +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex_ui/widgets.dart'; + +import 'appearance_settings.dart'; +import 'language_settings.dart'; +import 'location_settings.dart'; +import 'mcp_settings_panel.dart'; +import 'settings_layout.dart'; +import '../../settings/settings_operation.dart'; +import 'update_settings.dart'; +import 'diagnostic_settings.dart'; +import 'agent_settings_panel.dart'; + +const _settingsContentPadding = EdgeInsets.fromLTRB(20, 48, 20, 20); + +Future showSettingsDialog( + BuildContext context, { + (String, String)? workspace, + int initialTab = 0, +}) => showAppDialog( + context: Navigator.of(context, rootNavigator: true).context, + builder: (_) => SettingsDialog(workspace: workspace, initialTab: initialTab), +); + +class SettingsDialog extends ConsumerStatefulWidget { + const SettingsDialog({super.key, this.workspace, this.initialTab = 0}) + : assert(initialTab >= 0 && initialTab <= 2); + + final int initialTab; + + final (String, String)? workspace; + + @override + ConsumerState createState() => _SettingsDialogState(); +} + +class _SettingsDialogState extends ConsumerState { + late int _tab = widget.initialTab; + + Future _setMode(AppAppearance appearance) async { + await ref + .read(settingsOperationProvider('appearance').notifier) + .run( + () => + ref.read(appearanceSettingsProvider.notifier).setMode(appearance), + ); + } + + Future _setLanguage(AppLanguage language) async { + await ref + .read(settingsOperationProvider('language').notifier) + .run( + () => + ref.read(languageSettingsProvider.notifier).setLanguage(language), + ); + } + + @override + Widget build(BuildContext context) => Theme( + data: AppTheme.settingsContentTheme(Theme.of(context)), + child: Builder(builder: _buildDialog), + ); + + Widget _buildDialog(BuildContext context) { + final appearanceSave = ref.watch(settingsOperationProvider('appearance')); + final languageSave = ref.watch(settingsOperationProvider('language')); + final appearance = ref.watch(appearanceSettingsProvider); + final language = ref.watch(languageSettingsProvider); + final viewport = MediaQuery.sizeOf(context); + return AppDialog( + title: context.l10n.settings, + closeLabel: context.l10n.closeSettings, + width: math.min(1120, math.max(560, viewport.width * .9)), + height: math.min(704, math.max(520, viewport.height * .88)), + contentOnly: true, + scrollContent: false, + child: LayoutBuilder( + builder: (context, constraints) => Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + SizedBox( + width: constraints.maxWidth < 600 ? 96 : 220, + child: _SettingsNavigation( + value: _tab, + compact: constraints.maxWidth < 600, + onChanged: (value) => setState(() => _tab = value), + ), + ), + VerticalDivider( + key: const Key('settings-sidebar-divider'), + width: 1, + thickness: 1, + color: Theme.of(context).colorScheme.outlineVariant, + ), + Expanded( + child: ColoredBox( + color: Theme.of(context).colorScheme.surface, + child: IndexedStack( + index: _tab, + children: [ + ExcludeFocus( + excluding: _tab != 0, + child: TickerMode( + enabled: _tab == 0, + child: SingleChildScrollView( + primary: false, + padding: _settingsContentPadding, + child: SettingsPageSection( + title: context.l10n.general, + icon: Icons.settings_outlined, + children: [ + AppField( + label: context.l10n.appearance, + orientation: AppFieldOrientation.horizontal, + error: + (appearanceSave.hasError + ? context.l10n.saveAppearanceFailed + : null) ?? + (appearance.hasError + ? context.l10n.loadAppearanceFailed + : null), + child: SizedBox( + width: AppSettingsMetrics.controlWidth, + child: AppSelect( + emptyLabel: context.l10n.noMatchingOptions, + controlHeight: + AppSettingsMetrics.controlHeight, + value: + appearance.asData?.value ?? + AppAppearance.system, + label: context.l10n.theme, + options: [ + AppSelectOption( + AppAppearance.system, + context.l10n.system, + ), + AppSelectOption( + AppAppearance.penLight, + 'Pen · ${context.l10n.light}', + ), + AppSelectOption( + AppAppearance.penDark, + 'Pen · ${context.l10n.dark}', + ), + ], + onChanged: + appearanceSave.isLoading || + appearance.isLoading + ? null + : _setMode, + ), + ), + ), + AppField( + label: context.l10n.language, + orientation: AppFieldOrientation.horizontal, + error: + (languageSave.hasError + ? context.l10n.saveLanguageFailed + : null) ?? + (language.hasError + ? context.l10n.loadLanguageFailed + : null), + child: SizedBox( + width: AppSettingsMetrics.controlWidth, + child: AppSelect( + emptyLabel: context.l10n.noMatchingOptions, + controlHeight: + AppSettingsMetrics.controlHeight, + value: + language.asData?.value ?? + AppLanguage.system, + label: context.l10n.language, + options: [ + for (final option in AppLanguage.values) + AppSelectOption( + option, + option == AppLanguage.system + ? context.l10n.system + : option.nativeName, + ), + ], + onChanged: + languageSave.isLoading || + language.isLoading + ? null + : _setLanguage, + ), + ), + ), + const _ProjectLocationField(), + const _ResourceLocationField(), + const UpdateSettings(), + const DiagnosticSettings(), + ], + ), + ), + ), + ), + ExcludeFocus( + excluding: _tab != 1, + child: TickerMode( + enabled: _tab == 1, + child: const AgentSettingsPanel( + contentPadding: _settingsContentPadding, + ), + ), + ), + ExcludeFocus( + excluding: _tab != 2, + child: TickerMode( + enabled: _tab == 2, + child: SingleChildScrollView( + primary: false, + padding: _settingsContentPadding, + child: McpSettingsPanel(workspace: widget.workspace), + ), + ), + ), + ], + ), + ), + ), + ], + ), + ), + ); + } +} + +class _SettingsNavigation extends StatelessWidget { + const _SettingsNavigation({ + required this.value, + required this.compact, + required this.onChanged, + }); + + final int value; + final bool compact; + final ValueChanged onChanged; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final entries = [ + (context.l10n.general, Icons.settings_outlined), + (context.l10n.agentSettings, Icons.auto_awesome_outlined), + ('MCP', Icons.terminal_outlined), + ]; + return ColoredBox( + key: const Key('settings-sidebar'), + color: AppTheme.settingsSidebarBackground(context), + child: ListView( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 16), + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(8, 0, 8, 20), + child: Text( + context.l10n.settings, + style: theme.textTheme.titleSmall?.copyWith(fontSize: 16), + ), + ), + for (var index = 0; index < entries.length; index++) + Padding( + padding: const EdgeInsets.only(bottom: 1), + child: Semantics( + selected: value == index, + child: Tooltip( + message: entries[index].$1, + child: TextButton( + key: ValueKey('settings-navigation-$index'), + onPressed: () => onChanged(index), + style: TextButton.styleFrom( + minimumSize: const Size(0, 30), + padding: const EdgeInsets.symmetric(horizontal: 8), + foregroundColor: theme.colorScheme.onSurface, + backgroundColor: value == index + ? theme.colorScheme.onSurface.withValues(alpha: .078) + : Colors.transparent, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(8), + ), + alignment: AlignmentDirectional.centerStart, + ), + child: Row( + children: [ + if (!compact) ...[ + Icon(entries[index].$2, size: 16), + const SizedBox(width: 8), + ], + Expanded( + child: Text( + entries[index].$1, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + ), + ), + ), + ), + ], + ), + ); + } +} + +class _ResourceLocationField extends ConsumerWidget { + const _ResourceLocationField(); + + Future _choose( + BuildContext context, + WidgetRef ref, + String? initialDirectory, + ) async { + final directory = await ref + .read(filePickerProvider) + .pickDirectory( + initialDirectory: initialDirectory, + confirmButtonText: context.l10n.select, + ); + if (directory == null || !context.mounted) return; + await ref.read(resourceLocationSettingsProvider.notifier).save(directory); + } + + @override + Widget build(BuildContext context, WidgetRef ref) { + final settings = ref.watch(resourceLocationSettingsProvider); + final error = switch (settings.error) { + LocationSettingsError.load => context.l10n.loadResourceLocationFailed, + LocationSettingsError.save => context.l10n.saveResourceLocationFailed, + null => null, + }; + return AppField( + label: context.l10n.resourceLocation, + orientation: AppFieldOrientation.horizontal, + error: error, + child: SizedBox( + width: 420, + child: Row( + children: [ + Expanded( + child: Tooltip( + message: + settings.directory ?? context.l10n.resourceLocationNotSet, + child: _MiddleEllipsisText( + settings.directory ?? context.l10n.resourceLocationNotSet, + key: const Key('resource-location-value'), + textAlign: TextAlign.right, + ), + ), + ), + const SizedBox(width: AppSpacing.compact), + OutlinedButton( + key: const Key('choose-resource-location'), + onPressed: settings.loading || settings.saving + ? null + : () => _choose(context, ref, settings.directory), + child: Text(context.l10n.modify), + ), + ], + ), + ), + ); + } +} + +class _ProjectLocationField extends ConsumerWidget { + const _ProjectLocationField(); + + Future _choose( + BuildContext context, + WidgetRef ref, + String? initialDirectory, + ) async { + final directory = await ref + .read(filePickerProvider) + .pickDirectory( + initialDirectory: initialDirectory, + confirmButtonText: context.l10n.select, + ); + if (directory == null || !context.mounted) return; + await ref.read(projectLocationSettingsProvider.notifier).save(directory); + } + + @override + Widget build(BuildContext context, WidgetRef ref) { + final settings = ref.watch(projectLocationSettingsProvider); + final error = switch (settings.error) { + LocationSettingsError.load => context.l10n.loadProjectLocationFailed, + LocationSettingsError.save => context.l10n.saveProjectLocationFailed, + null => null, + }; + return AppField( + label: context.l10n.projectLocation, + orientation: AppFieldOrientation.horizontal, + description: settings.status == ProjectLocationStatus.missing + ? context.l10n.projectLocationMissing + : null, + error: + error ?? + switch (settings.status) { + ProjectLocationStatus.unavailable => + context.l10n.projectLocationUnavailable, + ProjectLocationStatus.notWritable => + context.l10n.projectLocationNotWritable, + _ => null, + }, + child: SizedBox( + width: 420, + child: Row( + children: [ + Expanded( + child: Tooltip( + message: + settings.directory ?? context.l10n.projectLocationNotSet, + child: _MiddleEllipsisText( + settings.directory ?? context.l10n.projectLocationNotSet, + key: const Key('project-location-value'), + textAlign: TextAlign.right, + ), + ), + ), + const SizedBox(width: AppSpacing.compact), + if (error != null || + settings.status == ProjectLocationStatus.unavailable || + settings.status == ProjectLocationStatus.notWritable) + TextButton( + key: const Key('retry-project-location'), + onPressed: settings.loading || settings.saving + ? null + : ref.read(projectLocationSettingsProvider.notifier).reload, + child: Text(context.l10n.retry), + ), + OutlinedButton( + key: const Key('choose-project-location'), + onPressed: settings.loading || settings.saving + ? null + : () => _choose(context, ref, settings.directory), + child: Text(context.l10n.modify), + ), + ], + ), + ), + ); + } +} + +class _MiddleEllipsisText extends StatelessWidget { + const _MiddleEllipsisText( + this.text, { + super.key, + this.textAlign = TextAlign.start, + }); + + final String text; + final TextAlign textAlign; + + @override + Widget build(BuildContext context) { + final style = DefaultTextStyle.of(context).style; + final direction = Directionality.of(context); + return LayoutBuilder( + builder: (context, constraints) => Text( + _ellipsize(text, constraints.maxWidth, style, direction), + maxLines: 1, + textAlign: textAlign, + ), + ); + } + + static String _ellipsize( + String value, + double maxWidth, + TextStyle style, + TextDirection direction, + ) { + bool fits(String candidate) { + final painter = TextPainter( + text: TextSpan(text: candidate, style: style), + maxLines: 1, + textDirection: direction, + )..layout(maxWidth: maxWidth); + return !painter.didExceedMaxLines && painter.width <= maxWidth; + } + + if (!maxWidth.isFinite || fits(value)) return value; + var low = 0; + var high = value.length; + while (low < high) { + final keep = (low + high + 1) ~/ 2; + final leading = (keep + 1) ~/ 2; + final candidate = + '${value.substring(0, leading)}…' + '${value.substring(value.length - (keep - leading))}'; + if (fits(candidate)) { + low = keep; + } else { + high = keep - 1; + } + } + final leading = (low + 1) ~/ 2; + return '${value.substring(0, leading)}…' + '${value.substring(value.length - (low - leading))}'; + } +} diff --git a/lib/features/settings/settings_layout.dart b/lib/features/settings/settings_layout.dart new file mode 100644 index 0000000..52fe723 --- /dev/null +++ b/lib/features/settings/settings_layout.dart @@ -0,0 +1,73 @@ +import 'package:flutter/material.dart'; + +import 'package:cutdex_ui/theme.dart'; + +class SettingsPageSection extends StatelessWidget { + const SettingsPageSection({ + super.key, + required this.title, + required this.icon, + required this.children, + this.action, + }); + + final String title; + final IconData icon; + final List children; + final Widget? action; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Align( + alignment: Alignment.topCenter, + child: ConstrainedBox( + constraints: const BoxConstraints( + maxWidth: AppSettingsMetrics.contentWidth, + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text(title, style: theme.textTheme.titleLarge), + const SizedBox(height: 40), + Row( + children: [ + Expanded(child: Text(title, style: theme.textTheme.labelLarge)), + ?action, + ], + ), + const SizedBox(height: AppSpacing.medium), + DecoratedBox( + decoration: BoxDecoration( + color: theme.colorScheme.surfaceContainer, + borderRadius: BorderRadius.circular( + AppSettingsMetrics.cardRadius, + ), + border: Border.all(color: theme.colorScheme.outlineVariant), + ), + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.medium, + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (var index = 0; index < children.length; index++) ...[ + Padding( + padding: const EdgeInsets.symmetric( + vertical: AppSettingsMetrics.rowVerticalPadding, + ), + child: children[index], + ), + if (index < children.length - 1) const Divider(height: 1), + ], + ], + ), + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/features/settings/update_controller.dart b/lib/features/settings/update_controller.dart new file mode 100644 index 0000000..18079f9 --- /dev/null +++ b/lib/features/settings/update_controller.dart @@ -0,0 +1,65 @@ +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import '../../integrations/app_updates.dart'; +import '../../integrations/app_update_coordinator.dart'; +import '../../settings/settings_operation.dart'; + +part 'update_controller.g.dart'; + +@riverpod +class UpdateController extends _$UpdateController { + int _eventRevision = 0; + UpdateStatus? _latestEvent; + + @override + Future build() { + ref.watch(appUpdateLifecycleProvider); + final subscription = ref.watch(appUpdateBridgeProvider).events.listen(( + status, + ) { + _eventRevision++; + _latestEvent = status; + if (ref.mounted) state = AsyncData(_latestEvent!); + }); + ref.onDispose(subscription.cancel); + return _load(); + } + + Future _load() async { + final revision = _eventRevision; + try { + final status = await ref.read(appUpdateBridgeProvider).status(); + return revision != _eventRevision && _latestEvent != null + ? _latestEvent! + : status; + } catch (_) { + return const UpdateStatus(); + } + } + + Future check() => _invoke((bridge) => bridge.check()); + Future download() => _invoke((bridge) => bridge.download()); + Future install() async { + final link = ref.keepAlive(); + try { + await ref.read(settingsOperationProvider('updates').notifier).run( + () async { + await installWindowsUpdate(ref); + }, + ); + } finally { + link.close(); + } + } + + Future setAutomaticChecks(bool value) => + _invoke((bridge) => bridge.setAutomaticChecks(value)); + + Future _invoke(Future Function(AppUpdateBridge) action) async { + await ref.read(settingsOperationProvider('updates').notifier).run(() async { + await action(ref.read(appUpdateBridgeProvider)); + final next = await _load(); + if (ref.mounted) state = AsyncData(next); + }); + } +} diff --git a/lib/features/settings/update_controller.g.dart b/lib/features/settings/update_controller.g.dart new file mode 100644 index 0000000..df7fd25 --- /dev/null +++ b/lib/features/settings/update_controller.g.dart @@ -0,0 +1,54 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'update_controller.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(UpdateController) +final updateControllerProvider = UpdateControllerProvider._(); + +final class UpdateControllerProvider + extends $AsyncNotifierProvider { + UpdateControllerProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'updateControllerProvider', + isAutoDispose: true, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$updateControllerHash(); + + @$internal + @override + UpdateController create() => UpdateController(); +} + +String _$updateControllerHash() => r'896a08b90b032eee312d0c759e3323352ca441db'; + +abstract class _$UpdateController extends $AsyncNotifier { + FutureOr build(); + @$mustCallSuper + @override + WhenComplete runBuild() { + final ref = this.ref as $Ref, UpdateStatus>; + final element = + ref.element + as $ClassProviderElement< + AnyNotifier, UpdateStatus>, + AsyncValue, + Object?, + Object? + >; + return element.handleCreate(ref, build); + } +} diff --git a/lib/features/settings/update_settings.dart b/lib/features/settings/update_settings.dart new file mode 100644 index 0000000..fc742f0 --- /dev/null +++ b/lib/features/settings/update_settings.dart @@ -0,0 +1,108 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; + +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../settings/settings_operation.dart'; +import '../../integrations/app_updates.dart'; +import 'update_controller.dart'; +import '../../l10n/l10n.dart'; + +import 'package:cutdex_ui/widgets.dart'; + +class UpdateSettings extends ConsumerWidget { + const UpdateSettings({super.key}); + + @override + Widget build(BuildContext context, WidgetRef ref) { + if (!supportsAppUpdates) { + return const SizedBox.shrink(); + } + final status = ref.watch(updateControllerProvider).value; + final operation = ref.watch(settingsOperationProvider('updates')); + final controller = ref.read(updateControllerProvider.notifier); + final configured = status?.configured == true; + final version = status?.version ?? ''; + final build = status?.build ?? ''; + final windows = defaultTargetPlatform == TargetPlatform.windows; + final busy = + operation.isLoading || + const [ + UpdatePhase.checking, + UpdatePhase.downloading, + UpdatePhase.installing, + ].contains(status?.phase); + return AppField( + label: context.l10n.softwareUpdates, + orientation: AppFieldOrientation.horizontal, + error: operation.hasError || status?.error.isNotEmpty == true + ? (windows + ? context.l10n.updateOperationFailed + : context.l10n.updateCheckFailed) + : null, + child: Column( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Wrap( + alignment: WrapAlignment.end, + crossAxisAlignment: WrapCrossAlignment.center, + spacing: 12, + children: [ + if (version.isNotEmpty) Text('$version ($build)'), + OutlinedButton( + key: const Key('check-for-updates'), + onPressed: + configured && + !busy && + (!windows || status?.canCheck == true) + ? controller.check + : null, + child: Text(context.l10n.checkForUpdates), + ), + ], + ), + if (windows && status?.phase == UpdatePhase.checking) + Text(context.l10n.checkingForUpdates), + if (windows && status?.phase == UpdatePhase.current) + Text(context.l10n.appIsUpToDate), + if (windows && status?.phase == UpdatePhase.downloading) ...[ + Text(context.l10n.downloadingUpdate(status!.progress)), + SizedBox( + width: 200, + child: LinearProgressIndicator(value: status.progress / 100), + ), + ], + if (windows && status?.availableVersion.isNotEmpty == true) ...[ + Text(context.l10n.updateAvailable(status!.availableVersion)), + if (status.phase == UpdatePhase.available) + OutlinedButton( + key: const Key('download-update'), + onPressed: busy ? null : controller.download, + child: Text(context.l10n.downloadUpdate), + ), + if (status.phase == UpdatePhase.ready) + OutlinedButton( + key: const Key('install-update'), + onPressed: busy ? null : controller.install, + child: Text(context.l10n.restartToUpdate), + ), + ], + if (configured) + Row( + mainAxisSize: MainAxisSize.min, + children: [ + Flexible(child: Text(context.l10n.automaticallyCheckUpdates)), + AppSwitch( + semanticLabel: context.l10n.automaticallyCheckUpdates, + value: status!.automaticChecks, + onChanged: busy ? null : controller.setAutomaticChecks, + ), + ], + ) + else if (status != null) + Text(context.l10n.updatesUnavailable), + ], + ), + ); + } +} diff --git a/lib/features/timeline/timeline_asset_drop_target.dart b/lib/features/timeline/timeline_asset_drop_target.dart new file mode 100644 index 0000000..24fc52f --- /dev/null +++ b/lib/features/timeline/timeline_asset_drop_target.dart @@ -0,0 +1,110 @@ +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../workspace/projects.dart'; +import '../../workspace/timeline_session.dart'; +import '../media/media_asset_drag.dart'; +import 'timeline_external_drop_target.dart'; + +class TimelineAssetDropTarget extends ConsumerStatefulWidget { + const TimelineAssetDropTarget({ + super.key, + required this.projectId, + required this.session, + required this.sequenceId, + required this.child, + }); + final String projectId; + final EditorTimelineSession session; + final SequenceId sequenceId; + final Widget child; + + @override + ConsumerState createState() => + _TimelineAssetDropTargetState(); +} + +class _TimelineAssetDropTargetState + extends ConsumerState { + final _target = GlobalKey(); + final _incoming = ValueNotifier(null); + MediaAssetDrag? _drag; + + void _updateIncoming(DragTargetDetails details) { + if (!_accepts(details.data)) return; + final asset = ref + .read(projectsProvider) + .asData + ?.value + .assets + .where((asset) => asset.id == details.data.assetId) + .firstOrNull; + if (asset == null) return; + if (_drag != details.data) { + _clearIncoming(); + _drag = details.data; + } + details.data.feedbackVisible.value = false; + _incoming.value = (asset: asset, globalPosition: details.offset); + } + + void _clearIncoming() { + _drag?.feedbackVisible.value = true; + _drag = null; + _incoming.value = null; + } + + @override + void dispose() { + _clearIncoming(); + _incoming.dispose(); + super.dispose(); + } + + bool _inserting = false; + + bool _accepts(MediaAssetDrag data) { + final state = ref.read(projectsProvider).asData?.value; + return !_inserting && + data.projectId == widget.projectId && + state?.activeProject?.id == widget.projectId && + state?.timeline?.id == widget.session.document.id && + state?.projectBusy == false; + } + + Future _drop(DragTargetDetails details) async { + if (!_accepts(details.data)) return; + _updateIncoming(details); + _inserting = true; + try { + await _target.currentState?.drop(); + } finally { + if (mounted) { + _clearIncoming(); + _inserting = false; + } + } + } + + @override + Widget build(BuildContext context) => DragTarget( + hitTestBehavior: HitTestBehavior.opaque, + onWillAcceptWithDetails: (details) { + final accepts = _accepts(details.data); + if (accepts) _updateIncoming(details); + return accepts; + }, + onMove: _updateIncoming, + onLeave: (_) => _clearIncoming(), + onAcceptWithDetails: _drop, + builder: (context, candidates, rejected) => TimelineExternalDropTarget( + key: _target, + projectId: widget.projectId, + session: widget.session, + sequenceId: widget.sequenceId, + incoming: _incoming, + child: widget.child, + ), + ); +} diff --git a/lib/features/timeline/timeline_drop_preparation.dart b/lib/features/timeline/timeline_drop_preparation.dart new file mode 100644 index 0000000..4158708 --- /dev/null +++ b/lib/features/timeline/timeline_drop_preparation.dart @@ -0,0 +1,252 @@ +import 'package:cutdex/errors/app_failure.dart'; + +import 'dart:async'; + +import 'package:cutdex_sdk/project.dart'; +import 'package:flutter/foundation.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import '../../workspace/external_media_import.dart'; +import '../../workspace/media_import.dart'; +import '../../workspace/prepared_media_metadata.dart'; +import '../../workspace/projects.dart'; +import '../../workspace/preview_target.dart'; +import '../../workspace/timeline_session.dart'; + +part 'timeline_drop_preparation.g.dart'; +part 'timeline_drop_preparation.freezed.dart'; + +@freezed +sealed class TimelineDropSource with _$TimelineDropSource { + const factory TimelineDropSource.file(ExternalMediaFile file) = DroppedFile; + const factory TimelineDropSource.asset(AssetDocument asset) = DroppedAsset; +} + +@freezed +abstract class PreparedTimelineMedia with _$PreparedTimelineMedia { + const factory PreparedTimelineMedia({ + required TimelineDropSource source, + required MediaReference media, + required PreparedMediaMetadata metadata, + }) = _PreparedTimelineMedia; +} + +@freezed +abstract class TimelineDropState with _$TimelineDropState { + const factory TimelineDropState({ + @Default(AsyncData(null)) + AsyncValue preparation, + @Default(AsyncData(null)) AsyncValue commit, + }) = _TimelineDropState; +} + +/// Probing and importing share the captured project, independent of pointer movement. +@riverpod +class TimelineDropPreparation extends _$TimelineDropPreparation { + int _revision = 0; + Future? _pending; + final _operations = >>{}; + @override + TimelineDropState build( + String projectId, + EditorTimelineSession session, + SequenceId sequence, + ) => const TimelineDropState(); + void reset() { + final revision = ++_revision; + scheduleMicrotask(() { + if (ref.mounted && revision == _revision) { + state = const TimelineDropState(); + } + }); + } + + bool get _active { + if (!ref.mounted) return false; + final workspace = ref.read(projectsProvider).value; + return session.acceptsEdits && + workspace?.activeProject?.id == projectId && + workspace?.timeline?.id == session.document.id; + } + + Future waitForPreparation() => _pending ?? Future.value(); + + /// Capture this drag's work before reset changes the current revision. + /// Errors remain visible to callers, while native access can always be released. + Future waitForCompletion() => + Future.wait(_operations[_revision]?.toList() ?? >[]) + .then((_) {}); + + void _track(Future work, int revision) { + final operations = _operations.putIfAbsent(revision, () => {}); + final settled = work.then( + (_) {}, + onError: (Object _, StackTrace _) {}, + ); + operations.add(settled); + unawaited( + settled.then((_) { + operations.remove(settled); + if (operations.isEmpty) _operations.remove(revision); + }), + ); + } + + Future probe(TimelineDropSource source) { + final revision = ++_revision; + state = const TimelineDropState(preparation: AsyncLoading()); + final lease = ref.keepAlive(); + final work = _probe(source, revision); + _pending = work; + final completion = work.whenComplete(() { + if (identical(_pending, work)) _pending = null; + lease.close(); + }); + _track(completion, revision); + return completion; + } + + Future _probe(TimelineDropSource source, int revision) async { + final runtime = ref.read(runtimeConnectionProvider); + try { + final image = + source is DroppedAsset && source.asset.metadata['kind'] == 'image'; + Future load(MediaReference media) async { + final metadata = image + ? PreparedMediaMetadata.image() + : PreparedMediaMetadata.fromInfo(await runtime.probe(media)); + return PreparedTimelineMedia( + source: source, + media: media, + metadata: metadata, + ); + } + + final value = switch (source) { + DroppedAsset(:final asset) => + await ref + .read(projectsProvider.notifier) + .withAssetMedia(projectId, asset, load), + DroppedFile(:final file) => await load( + MediaReference( + id: file.localPath!, + uri: Uri.file( + file.localPath!, + windows: + !kIsWeb && defaultTargetPlatform == TargetPlatform.windows, + ), + ), + ), + }; + if (ref.mounted && revision == _revision && _active) { + state = state.copyWith(preparation: AsyncData(value)); + } + } catch (error, stack) { + if (ref.mounted && revision == _revision) { + state = state.copyWith(preparation: AsyncError(error, stack)); + } + } + } + + Future commit( + Future Function(AssetDocument asset, MediaReference media) insert, { + required bool Function() isCurrent, + void Function()? validatePlacement, + }) { + if (state.commit.isLoading) return Future.value(); + final revision = _revision; + final work = _commit( + insert, + revision: revision, + isCurrent: isCurrent, + validatePlacement: validatePlacement, + ); + _track(work, revision); + return work; + } + + Future _commit( + Future Function(AssetDocument asset, MediaReference media) insert, { + required int revision, + required bool Function() isCurrent, + void Function()? validatePlacement, + }) async { + final lease = ref.keepAlive(); + final release = session.retainViews(); + state = state.copyWith(commit: const AsyncLoading()); + try { + await waitForPreparation(); + if (!ref.mounted || revision != _revision || !_active || !isCurrent()) { + return; + } + final preparation = state.preparation; + if (preparation.hasError) { + Error.throwWithStackTrace( + preparation.error!, + preparation.stackTrace ?? StackTrace.current, + ); + } + final prepared = preparation.value; + if (prepared == null) { + throw AppException(AppErrorCode.mediaReadFailed); + } + validatePlacement?.call(); + final AssetDocument? asset; + switch (prepared.source) { + case DroppedAsset(asset: final asAsset): + asset = asAsset; + case DroppedFile(:final file): + final imported = await ref + .read(externalMediaImportProvider(projectId).notifier) + .importFiles([file]); + asset = imported?.selected.firstOrNull; + if (asset == null) { + throw AppException.fromFailure( + imported?.result?.failures.firstOrNull?.failure ?? + const AppFailure(AppErrorCode.mediaImportFailed), + ); + } + } + if (!ref.mounted || revision != _revision || !_active || !isCurrent()) { + return; + } + await ref.read(projectsProvider.notifier).withAssetMedia( + projectId, + asset, + (media) async { + if (!ref.mounted || + revision != _revision || + !_active || + !isCurrent()) { + return; + } + await insert(asset!, media); + }, + ); + if (ref.mounted && revision == _revision && _active && isCurrent()) { + ref + .read( + previewNavigationProvider( + projectId, + session.document.id, + ).notifier, + ) + .showTimeline(); + } + } catch (error, stack) { + if (ref.mounted && revision == _revision) { + state = state.copyWith(commit: AsyncError(error, stack)); + } + rethrow; + } finally { + if (ref.mounted && revision == _revision && state.commit.isLoading) { + state = state.copyWith(commit: const AsyncData(null)); + } + release(); + lease.close(); + } + } +} diff --git a/lib/features/timeline/timeline_drop_preparation.freezed.dart b/lib/features/timeline/timeline_drop_preparation.freezed.dart new file mode 100644 index 0000000..9b91212 --- /dev/null +++ b/lib/features/timeline/timeline_drop_preparation.freezed.dart @@ -0,0 +1,1140 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'timeline_drop_preparation.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +T _$identity(T value) => value; + +/// @nodoc +mixin _$TimelineDropSource implements DiagnosticableTreeMixin { + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + properties..add(DiagnosticsProperty('type', 'TimelineDropSource')); + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is TimelineDropSource); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { + return 'TimelineDropSource()'; + } +} + +/// @nodoc +class $TimelineDropSourceCopyWith<$Res> { + $TimelineDropSourceCopyWith( + TimelineDropSource _, + $Res Function(TimelineDropSource) __, + ); +} + +/// Adds pattern-matching-related methods to [TimelineDropSource]. +extension TimelineDropSourcePatterns on TimelineDropSource { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap({ + TResult Function(DroppedFile value)? file, + TResult Function(DroppedAsset value)? asset, + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case DroppedFile() when file != null: + return file(_that); + case DroppedAsset() when asset != null: + return asset(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map({ + required TResult Function(DroppedFile value) file, + required TResult Function(DroppedAsset value) asset, + }) { + final _that = this; + switch (_that) { + case DroppedFile(): + return file(_that); + case DroppedAsset(): + return asset(_that); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(DroppedFile value)? file, + TResult? Function(DroppedAsset value)? asset, + }) { + final _that = this; + switch (_that) { + case DroppedFile() when file != null: + return file(_that); + case DroppedAsset() when asset != null: + return asset(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen({ + TResult Function(ExternalMediaFile file)? file, + TResult Function(AssetDocument asset)? asset, + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case DroppedFile() when file != null: + return file(_that.file); + case DroppedAsset() when asset != null: + return asset(_that.asset); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when({ + required TResult Function(ExternalMediaFile file) file, + required TResult Function(AssetDocument asset) asset, + }) { + final _that = this; + switch (_that) { + case DroppedFile(): + return file(_that.file); + case DroppedAsset(): + return asset(_that.asset); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function(ExternalMediaFile file)? file, + TResult? Function(AssetDocument asset)? asset, + }) { + final _that = this; + switch (_that) { + case DroppedFile() when file != null: + return file(_that.file); + case DroppedAsset() when asset != null: + return asset(_that.asset); + case _: + return null; + } + } +} + +/// @nodoc + +class DroppedFile with DiagnosticableTreeMixin implements TimelineDropSource { + const DroppedFile(this.file); + + final ExternalMediaFile file; + + /// Create a copy of TimelineDropSource + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $DroppedFileCopyWith get copyWith => + _$DroppedFileCopyWithImpl(this, _$identity); + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + properties + ..add(DiagnosticsProperty('type', 'TimelineDropSource.file')) + ..add(DiagnosticsProperty('file', file)); + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is DroppedFile && + (identical(other.file, file) || other.file == file)); + } + + @override + int get hashCode { + return Object.hash(runtimeType, file); + } + + @override + String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { + return 'TimelineDropSource.file(file: $file)'; + } +} + +/// @nodoc +abstract mixin class $DroppedFileCopyWith<$Res> + implements $TimelineDropSourceCopyWith<$Res> { + factory $DroppedFileCopyWith( + DroppedFile value, + $Res Function(DroppedFile) _then, + ) = _$DroppedFileCopyWithImpl; + @useResult + $Res call({ExternalMediaFile file}); + + $ExternalMediaFileCopyWith<$Res> get file; +} + +/// @nodoc +class _$DroppedFileCopyWithImpl<$Res> implements $DroppedFileCopyWith<$Res> { + _$DroppedFileCopyWithImpl(this._self, this._then); + + final DroppedFile _self; + final $Res Function(DroppedFile) _then; + + /// Create a copy of TimelineDropSource + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({Object? file = null}) { + return _then( + DroppedFile( + null == file + ? _self.file + : file // ignore: cast_nullable_to_non_nullable + as ExternalMediaFile, + ), + ); + } + + /// Create a copy of TimelineDropSource + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $ExternalMediaFileCopyWith<$Res> get file { + return $ExternalMediaFileCopyWith<$Res>(_self.file, (value) { + return _then(_self.copyWith(file: value)); + }); + } +} + +/// @nodoc + +class DroppedAsset with DiagnosticableTreeMixin implements TimelineDropSource { + const DroppedAsset(this.asset); + + final AssetDocument asset; + + /// Create a copy of TimelineDropSource + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $DroppedAssetCopyWith get copyWith => + _$DroppedAssetCopyWithImpl(this, _$identity); + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + properties + ..add(DiagnosticsProperty('type', 'TimelineDropSource.asset')) + ..add(DiagnosticsProperty('asset', asset)); + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is DroppedAsset && + (identical(other.asset, asset) || other.asset == asset)); + } + + @override + int get hashCode { + return Object.hash(runtimeType, asset); + } + + @override + String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { + return 'TimelineDropSource.asset(asset: $asset)'; + } +} + +/// @nodoc +abstract mixin class $DroppedAssetCopyWith<$Res> + implements $TimelineDropSourceCopyWith<$Res> { + factory $DroppedAssetCopyWith( + DroppedAsset value, + $Res Function(DroppedAsset) _then, + ) = _$DroppedAssetCopyWithImpl; + @useResult + $Res call({AssetDocument asset}); +} + +/// @nodoc +class _$DroppedAssetCopyWithImpl<$Res> implements $DroppedAssetCopyWith<$Res> { + _$DroppedAssetCopyWithImpl(this._self, this._then); + + final DroppedAsset _self; + final $Res Function(DroppedAsset) _then; + + /// Create a copy of TimelineDropSource + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({Object? asset = null}) { + return _then( + DroppedAsset( + null == asset + ? _self.asset + : asset // ignore: cast_nullable_to_non_nullable + as AssetDocument, + ), + ); + } +} + +/// @nodoc +mixin _$PreparedTimelineMedia implements DiagnosticableTreeMixin { + TimelineDropSource get source; + MediaReference get media; + PreparedMediaMetadata get metadata; + + /// Create a copy of PreparedTimelineMedia + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $PreparedTimelineMediaCopyWith get copyWith => + _$PreparedTimelineMediaCopyWithImpl( + this as PreparedTimelineMedia, + _$identity, + ); + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + final _this = this as PreparedTimelineMedia; + properties + ..add(DiagnosticsProperty('type', 'PreparedTimelineMedia')) + ..add(DiagnosticsProperty('source', _this.source)) + ..add(DiagnosticsProperty('media', _this.media)) + ..add(DiagnosticsProperty('metadata', _this.metadata)); + } + + @override + bool operator ==(Object other) { + final _this = this as PreparedTimelineMedia; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is PreparedTimelineMedia && + (identical(other.source, _this.source) || + other.source == _this.source) && + (identical(other.media, _this.media) || + other.media == _this.media) && + (identical(other.metadata, _this.metadata) || + other.metadata == _this.metadata)); + } + + @override + int get hashCode { + final _this = this as PreparedTimelineMedia; + return Object.hash(runtimeType, _this.source, _this.media, _this.metadata); + } + + @override + String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { + final _this = this as PreparedTimelineMedia; + return 'PreparedTimelineMedia(source: ${_this.source}, media: ${_this.media}, metadata: ${_this.metadata})'; + } +} + +/// @nodoc +abstract mixin class $PreparedTimelineMediaCopyWith<$Res> { + factory $PreparedTimelineMediaCopyWith( + PreparedTimelineMedia value, + $Res Function(PreparedTimelineMedia) _then, + ) = _$PreparedTimelineMediaCopyWithImpl; + @useResult + $Res call({ + TimelineDropSource source, + MediaReference media, + PreparedMediaMetadata metadata, + }); + + $TimelineDropSourceCopyWith<$Res> get source; +} + +/// @nodoc +class _$PreparedTimelineMediaCopyWithImpl<$Res> + implements $PreparedTimelineMediaCopyWith<$Res> { + _$PreparedTimelineMediaCopyWithImpl(this._self, this._then); + + final PreparedTimelineMedia _self; + final $Res Function(PreparedTimelineMedia) _then; + + /// Create a copy of PreparedTimelineMedia + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? source = null, + Object? media = null, + Object? metadata = null, + }) { + return _then( + PreparedTimelineMedia( + source: null == source + ? _self.source + : source // ignore: cast_nullable_to_non_nullable + as TimelineDropSource, + media: null == media + ? _self.media + : media // ignore: cast_nullable_to_non_nullable + as MediaReference, + metadata: null == metadata + ? _self.metadata + : metadata // ignore: cast_nullable_to_non_nullable + as PreparedMediaMetadata, + ), + ); + } + + /// Create a copy of PreparedTimelineMedia + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $TimelineDropSourceCopyWith<$Res> get source { + return $TimelineDropSourceCopyWith<$Res>(_self.source, (value) { + return _then(_self.copyWith(source: value)); + }); + } +} + +/// Adds pattern-matching-related methods to [PreparedTimelineMedia]. +extension PreparedTimelineMediaPatterns on PreparedTimelineMedia { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_PreparedTimelineMedia value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _PreparedTimelineMedia() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_PreparedTimelineMedia value) $default, + ) { + final _that = this; + switch (_that) { + case _PreparedTimelineMedia(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_PreparedTimelineMedia value)? $default, + ) { + final _that = this; + switch (_that) { + case _PreparedTimelineMedia() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + TimelineDropSource source, + MediaReference media, + PreparedMediaMetadata metadata, + )? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _PreparedTimelineMedia() when $default != null: + return $default(_that.source, _that.media, _that.metadata); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function( + TimelineDropSource source, + MediaReference media, + PreparedMediaMetadata metadata, + ) + $default, + ) { + final _that = this; + switch (_that) { + case _PreparedTimelineMedia(): + return $default(_that.source, _that.media, _that.metadata); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + TimelineDropSource source, + MediaReference media, + PreparedMediaMetadata metadata, + )? + $default, + ) { + final _that = this; + switch (_that) { + case _PreparedTimelineMedia() when $default != null: + return $default(_that.source, _that.media, _that.metadata); + case _: + return null; + } + } +} + +/// @nodoc + +class _PreparedTimelineMedia + with DiagnosticableTreeMixin + implements PreparedTimelineMedia { + const _PreparedTimelineMedia({ + required this.source, + required this.media, + required this.metadata, + }); + + @override + final TimelineDropSource source; + @override + final MediaReference media; + @override + final PreparedMediaMetadata metadata; + + /// Create a copy of PreparedTimelineMedia + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$PreparedTimelineMediaCopyWith<_PreparedTimelineMedia> get copyWith => + __$PreparedTimelineMediaCopyWithImpl<_PreparedTimelineMedia>( + this, + _$identity, + ); + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + properties + ..add(DiagnosticsProperty('type', 'PreparedTimelineMedia')) + ..add(DiagnosticsProperty('source', source)) + ..add(DiagnosticsProperty('media', media)) + ..add(DiagnosticsProperty('metadata', metadata)); + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _PreparedTimelineMedia && + (identical(other.source, source) || other.source == source) && + (identical(other.media, media) || other.media == media) && + (identical(other.metadata, metadata) || + other.metadata == metadata)); + } + + @override + int get hashCode { + return Object.hash(runtimeType, source, media, metadata); + } + + @override + String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { + return 'PreparedTimelineMedia(source: $source, media: $media, metadata: $metadata)'; + } +} + +/// @nodoc +abstract mixin class _$PreparedTimelineMediaCopyWith<$Res> + implements $PreparedTimelineMediaCopyWith<$Res> { + factory _$PreparedTimelineMediaCopyWith( + _PreparedTimelineMedia value, + $Res Function(_PreparedTimelineMedia) _then, + ) = __$PreparedTimelineMediaCopyWithImpl; + @override + @useResult + $Res call({ + TimelineDropSource source, + MediaReference media, + PreparedMediaMetadata metadata, + }); + + @override + $TimelineDropSourceCopyWith<$Res> get source; +} + +/// @nodoc +class __$PreparedTimelineMediaCopyWithImpl<$Res> + implements _$PreparedTimelineMediaCopyWith<$Res> { + __$PreparedTimelineMediaCopyWithImpl(this._self, this._then); + + final _PreparedTimelineMedia _self; + final $Res Function(_PreparedTimelineMedia) _then; + + /// Create a copy of PreparedTimelineMedia + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? source = null, + Object? media = null, + Object? metadata = null, + }) { + return _then( + _PreparedTimelineMedia( + source: null == source + ? _self.source + : source // ignore: cast_nullable_to_non_nullable + as TimelineDropSource, + media: null == media + ? _self.media + : media // ignore: cast_nullable_to_non_nullable + as MediaReference, + metadata: null == metadata + ? _self.metadata + : metadata // ignore: cast_nullable_to_non_nullable + as PreparedMediaMetadata, + ), + ); + } + + /// Create a copy of PreparedTimelineMedia + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $TimelineDropSourceCopyWith<$Res> get source { + return $TimelineDropSourceCopyWith<$Res>(_self.source, (value) { + return _then(_self.copyWith(source: value)); + }); + } +} + +/// @nodoc +mixin _$TimelineDropState implements DiagnosticableTreeMixin { + AsyncValue get preparation; + AsyncValue get commit; + + /// Create a copy of TimelineDropState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $TimelineDropStateCopyWith get copyWith => + _$TimelineDropStateCopyWithImpl( + this as TimelineDropState, + _$identity, + ); + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + final _this = this as TimelineDropState; + properties + ..add(DiagnosticsProperty('type', 'TimelineDropState')) + ..add(DiagnosticsProperty('preparation', _this.preparation)) + ..add(DiagnosticsProperty('commit', _this.commit)); + } + + @override + bool operator ==(Object other) { + final _this = this as TimelineDropState; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is TimelineDropState && + (identical(other.preparation, _this.preparation) || + other.preparation == _this.preparation) && + (identical(other.commit, _this.commit) || + other.commit == _this.commit)); + } + + @override + int get hashCode { + final _this = this as TimelineDropState; + return Object.hash(runtimeType, _this.preparation, _this.commit); + } + + @override + String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { + final _this = this as TimelineDropState; + return 'TimelineDropState(preparation: ${_this.preparation}, commit: ${_this.commit})'; + } +} + +/// @nodoc +abstract mixin class $TimelineDropStateCopyWith<$Res> { + factory $TimelineDropStateCopyWith( + TimelineDropState value, + $Res Function(TimelineDropState) _then, + ) = _$TimelineDropStateCopyWithImpl; + @useResult + $Res call({ + AsyncValue preparation, + AsyncValue commit, + }); +} + +/// @nodoc +class _$TimelineDropStateCopyWithImpl<$Res> + implements $TimelineDropStateCopyWith<$Res> { + _$TimelineDropStateCopyWithImpl(this._self, this._then); + + final TimelineDropState _self; + final $Res Function(TimelineDropState) _then; + + /// Create a copy of TimelineDropState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({Object? preparation = null, Object? commit = null}) { + return _then( + TimelineDropState( + preparation: null == preparation + ? _self.preparation + : preparation // ignore: cast_nullable_to_non_nullable + as AsyncValue, + commit: null == commit + ? _self.commit + : commit // ignore: cast_nullable_to_non_nullable + as AsyncValue, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [TimelineDropState]. +extension TimelineDropStatePatterns on TimelineDropState { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_TimelineDropState value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _TimelineDropState() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_TimelineDropState value) $default, + ) { + final _that = this; + switch (_that) { + case _TimelineDropState(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_TimelineDropState value)? $default, + ) { + final _that = this; + switch (_that) { + case _TimelineDropState() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + AsyncValue preparation, + AsyncValue commit, + )? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _TimelineDropState() when $default != null: + return $default(_that.preparation, _that.commit); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function( + AsyncValue preparation, + AsyncValue commit, + ) + $default, + ) { + final _that = this; + switch (_that) { + case _TimelineDropState(): + return $default(_that.preparation, _that.commit); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + AsyncValue preparation, + AsyncValue commit, + )? + $default, + ) { + final _that = this; + switch (_that) { + case _TimelineDropState() when $default != null: + return $default(_that.preparation, _that.commit); + case _: + return null; + } + } +} + +/// @nodoc + +class _TimelineDropState + with DiagnosticableTreeMixin + implements TimelineDropState { + const _TimelineDropState({ + this.preparation = const AsyncData(null), + this.commit = const AsyncData(null), + }); + + @override + @JsonKey() + final AsyncValue preparation; + @override + @JsonKey() + final AsyncValue commit; + + /// Create a copy of TimelineDropState + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$TimelineDropStateCopyWith<_TimelineDropState> get copyWith => + __$TimelineDropStateCopyWithImpl<_TimelineDropState>(this, _$identity); + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + properties + ..add(DiagnosticsProperty('type', 'TimelineDropState')) + ..add(DiagnosticsProperty('preparation', preparation)) + ..add(DiagnosticsProperty('commit', commit)); + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _TimelineDropState && + (identical(other.preparation, preparation) || + other.preparation == preparation) && + (identical(other.commit, commit) || other.commit == commit)); + } + + @override + int get hashCode { + return Object.hash(runtimeType, preparation, commit); + } + + @override + String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { + return 'TimelineDropState(preparation: $preparation, commit: $commit)'; + } +} + +/// @nodoc +abstract mixin class _$TimelineDropStateCopyWith<$Res> + implements $TimelineDropStateCopyWith<$Res> { + factory _$TimelineDropStateCopyWith( + _TimelineDropState value, + $Res Function(_TimelineDropState) _then, + ) = __$TimelineDropStateCopyWithImpl; + @override + @useResult + $Res call({ + AsyncValue preparation, + AsyncValue commit, + }); +} + +/// @nodoc +class __$TimelineDropStateCopyWithImpl<$Res> + implements _$TimelineDropStateCopyWith<$Res> { + __$TimelineDropStateCopyWithImpl(this._self, this._then); + + final _TimelineDropState _self; + final $Res Function(_TimelineDropState) _then; + + /// Create a copy of TimelineDropState + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({Object? preparation = null, Object? commit = null}) { + return _then( + _TimelineDropState( + preparation: null == preparation + ? _self.preparation + : preparation // ignore: cast_nullable_to_non_nullable + as AsyncValue, + commit: null == commit + ? _self.commit + : commit // ignore: cast_nullable_to_non_nullable + as AsyncValue, + ), + ); + } +} diff --git a/lib/features/timeline/timeline_drop_preparation.g.dart b/lib/features/timeline/timeline_drop_preparation.g.dart new file mode 100644 index 0000000..e8b5a84 --- /dev/null +++ b/lib/features/timeline/timeline_drop_preparation.g.dart @@ -0,0 +1,133 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'timeline_drop_preparation.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning +/// Probing and importing share the captured project, independent of pointer movement. + +@ProviderFor(TimelineDropPreparation) +final timelineDropPreparationProvider = TimelineDropPreparationFamily._(); + +/// Probing and importing share the captured project, independent of pointer movement. +final class TimelineDropPreparationProvider + extends $NotifierProvider { + /// Probing and importing share the captured project, independent of pointer movement. + TimelineDropPreparationProvider._({ + required TimelineDropPreparationFamily super.from, + required (String, EditorTimelineSession, SequenceId) super.argument, + }) : super( + retry: null, + name: r'timelineDropPreparationProvider', + isAutoDispose: true, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$timelineDropPreparationHash(); + + @override + String toString() { + return r'timelineDropPreparationProvider' + '' + '$argument'; + } + + @$internal + @override + TimelineDropPreparation create() => TimelineDropPreparation(); + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(TimelineDropState value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } + + @override + bool operator ==(Object other) { + return other is TimelineDropPreparationProvider && + other.argument == argument; + } + + @override + int get hashCode { + return argument.hashCode; + } +} + +String _$timelineDropPreparationHash() => + r'4b762178d02d2e5b002ea252d8d516cfc59231a8'; + +/// Probing and importing share the captured project, independent of pointer movement. + +final class TimelineDropPreparationFamily extends $Family + with + $ClassFamilyOverride< + TimelineDropPreparation, + TimelineDropState, + TimelineDropState, + TimelineDropState, + (String, EditorTimelineSession, SequenceId) + > { + TimelineDropPreparationFamily._() + : super( + retry: null, + name: r'timelineDropPreparationProvider', + dependencies: null, + $allTransitiveDependencies: null, + isAutoDispose: true, + ); + + /// Probing and importing share the captured project, independent of pointer movement. + + TimelineDropPreparationProvider call( + String projectId, + EditorTimelineSession session, + SequenceId sequence, + ) => TimelineDropPreparationProvider._( + argument: (projectId, session, sequence), + from: this, + ); + + @override + String toString() => r'timelineDropPreparationProvider'; +} + +/// Probing and importing share the captured project, independent of pointer movement. + +abstract class _$TimelineDropPreparation extends $Notifier { + late final _$args = ref.$arg as (String, EditorTimelineSession, SequenceId); + String get projectId => _$args.$1; + EditorTimelineSession get session => _$args.$2; + SequenceId get sequence => _$args.$3; + + TimelineDropState build( + String projectId, + EditorTimelineSession session, + SequenceId sequence, + ); + @$mustCallSuper + @override + WhenComplete runBuild() { + final ref = this.ref as $Ref; + final element = + ref.element + as $ClassProviderElement< + AnyNotifier, + TimelineDropState, + Object?, + Object? + >; + return element.handleCreate( + ref, + () => build(_$args.$1, _$args.$2, _$args.$3), + ); + } +} diff --git a/lib/features/timeline/timeline_external_drop_target.dart b/lib/features/timeline/timeline_external_drop_target.dart new file mode 100644 index 0000000..74de1b3 --- /dev/null +++ b/lib/features/timeline/timeline_external_drop_target.dart @@ -0,0 +1,406 @@ +import 'package:cutdex/errors/app_failure.dart'; + +import 'dart:async'; + +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/timeline/layout.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:cutdex_sdk/timeline_ui.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; + +import '../../l10n/l10n.dart'; +import '../../integrations/app_failure_adapter.dart'; + +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../workspace/projects.dart'; +import '../../workspace/media_import.dart'; +import '../../workspace/timeline_session.dart'; + +import 'package:cutdex_ui/widgets.dart'; +import 'package:cutdex_native/cutdex_native.dart'; + +import '../../integrations/platform/native_file_drop_policy.dart'; +import 'timeline_drop_preparation.dart'; + +typedef TimelineIncomingAsset = ({AssetDocument asset, Offset globalPosition}); + +/// OS and project drags share a provisional clip without publishing changes. +class TimelineExternalDropTarget extends ConsumerStatefulWidget { + const TimelineExternalDropTarget({ + super.key, + required this.projectId, + required this.session, + required this.sequenceId, + required this.child, + this.incoming, + }); + final String projectId; + final EditorTimelineSession session; + final SequenceId sequenceId; + final Widget child; + final ValueListenable? incoming; + @override + ConsumerState createState() => + TimelineExternalDropTargetState(); +} + +class TimelineExternalDropTargetState + extends ConsumerState { + static const dropPolicy = NativeFileDropPolicy.timeline; + late final connection = NativeFileDropConnection( + regionId: 'timeline', + hidesSourceImage: true, + onEvent: event, + ); + TimelineDropPreparationProvider get _preparationProvider => + timelineDropPreparationProvider( + widget.projectId, + widget.session, + widget.sequenceId, + ); + late TimelineDropPreparation _preparer; + final surface = GlobalKey(); + int? sessionId; + int generation = 0; + ExternalMediaFile? file; + AssetDocument? projectAsset; + bool get hasPreview => file != null || projectAsset != null; + EditorIncomingClip? incomingClip; + ({int tick, int top, ConnectionSide? side})? lastPlacement; + + void updateClip() { + final prepared = preparedMedia; + if (!hasPreview || prepared == null || error != null) return; + final box = surface.currentContext?.findRenderObject() as RenderBox?; + if (box == null || !box.hasSize) return; + final viewport = TimelineViewportRect( + width: box.size.width, + height: box.size.height, + ); + final y = view.camera.worldYForScreen(position.dy, viewport); + final geometry = view.geometry; + final side = y < geometry.primaryTop + ? ConnectionSide.above + : y >= geometry.primaryTop + geometry.primaryHeight + ? ConnectionSide.below + : null; + final raw = view.camera.tickAtScreenX( + position.dx, + viewport, + rounding: TimelineTickRounding.nearest, + ); + final frame = view.format.frameGrid.quantumTicks; + final tick = raw <= 0 ? 0 : ((raw + frame ~/ 2) ~/ frame) * frame; + final top = (y - 12).round(); + final placement = (tick: tick, top: top, side: side); + try { + incomingClip ??= widget.session.beginIncomingClip( + sequence: widget.sequenceId, + name: projectAsset?.name ?? file!.displayName, + duration: prepared.metadata.duration, + kind: prepared.metadata.kind.name, + hasAudio: prepared.metadata.hasAudio, + media: prepared.media, + ); + if (lastPlacement != placement || incomingClip!.layout == null) { + incomingClip!.update(start: tick, side: side, top: top); + lastPlacement = placement; + } + placementError = null; + view.showIncomingClip( + incomingClip!.layout!, + element: incomingClip!.incoming.source, + start: tick, + top: top, + audioOnly: incomingClip!.kind == 'audio', + position: position, + viewport: viewport, + ); + } catch (e) { + placementError = appFailureFromError(e); + view.clearIncomingClip(); + } + } + + PreparedTimelineMedia? get preparedMedia => + ref.read(_preparationProvider).preparation.value; + Offset position = Offset.zero; + + late TimelineViewController view; + bool get busy => ref.read(_preparationProvider).commit.isLoading; + AppFailure? get error => ref.read(_preparationProvider).preparation.hasError + ? const AppFailure(AppErrorCode.mediaReadFailed) + : null; + AppFailure? placementError; + Rect? region; + bool get windows => + !kIsWeb && defaultTargetPlatform == TargetPlatform.windows; + bool get native => + !kIsWeb && (defaultTargetPlatform == TargetPlatform.macOS || windows); + bool get enabled { + final s = ref.read(projectsProvider).asData?.value; + return !busy && + s?.projectBusy == false && + s?.activeProject?.id == widget.projectId && + s?.timeline?.id == widget.session.document.id; + } + + bool get active => enabled && TickerMode.valuesOf(context).enabled; + + TimelineCamera? lastCamera; + void viewChanged() { + if (!hasPreview || busy) return; + if (incomingClip?.layout != null && !view.isDragging) { + final g = generation; + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted && g == generation && !busy) setState(clear); + }); + return; + } + final camera = view.camera; + if (identical(lastCamera, camera)) return; + lastCamera = camera; + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted || !hasPreview || busy) return; + setState(updateClip); + }); + } + + @override + void didUpdateWidget(covariant TimelineExternalDropTarget oldWidget) { + super.didUpdateWidget(oldWidget); + final changedView = + oldWidget.session != widget.session || + oldWidget.sequenceId != widget.sequenceId; + if (oldWidget.incoming != widget.incoming) { + oldWidget.incoming?.removeListener(incomingChanged); + widget.incoming?.addListener(incomingChanged); + } + if (changedView) view.removeListener(viewChanged); + if (changedView || + oldWidget.projectId != widget.projectId || + oldWidget.incoming != widget.incoming && projectAsset != null) { + clear(); + } + if (changedView || oldWidget.projectId != widget.projectId) { + _preparer = ref.read(_preparationProvider.notifier); + } + if (changedView) { + view = widget.session.view(widget.sequenceId)..addListener(viewChanged); + } + } + + @override + void initState() { + super.initState(); + _preparer = ref.read(_preparationProvider.notifier); + if (native) { + connection.bind(); + } + widget.incoming?.addListener(incomingChanged); + view = widget.session.view(widget.sequenceId)..addListener(viewChanged); + } + + void incomingChanged() { + final incoming = widget.incoming?.value; + if (!mounted) return; + if (incoming == null) { + if (projectAsset != null && !busy) setState(clear); + return; + } + if (!active) return; + final box = surface.currentContext?.findRenderObject() as RenderBox?; + if (box == null || !box.hasSize) return; + position = box.globalToLocal(incoming.globalPosition); + if (projectAsset?.id == incoming.asset.id) { + setState(updateClip); + return; + } + setState(() { + clear(); + projectAsset = incoming.asset; + }); + prepareMedia(); + } + + void enterExternal(int id, String path, Offset localPosition) { + if (!active || !dropPolicy.accepts([ExternalMediaFile(path: path)])) { + return; + } + setState(() { + clear(); + sessionId = id; + file = ExternalMediaFile(path: path); + position = localPosition; + }); + prepareMedia(); + } + + void moveExternal(int id, Offset localPosition) { + if (!active || sessionId != id) return; + setState(() { + position = localPosition; + updateClip(); + }); + } + + void exitExternal(int id) { + if (sessionId == id && !busy) setState(clear); + } + + Future dropExternal(int id, Offset localPosition) async { + if (!active || sessionId != id) return; + position = localPosition; + await drop(); + } + + Future sendRegion(Rect? bounds) => + connection.setRegion(bounds, dropPolicy.configuration); + + void report(Rect r) { + if (!mounted || !connection.isOwner) return; + final next = active ? r : null; + if (region == next) return; + region = next; + unawaited(sendRegion(next)); + if (next == null && hasPreview && !busy) setState(clear); + } + + Future release(int id, Future pending) async { + await pending; + await connection.release(id); + } + + void clear() { + if (incomingClip != null) { + view.clearIncomingClip(); + } + incomingClip?.cancel(); + incomingClip = null; + lastPlacement = null; + lastCamera = null; + if (native && sessionId != null) { + unawaited(release(sessionId!, _preparer.waitForCompletion())); + } + generation++; + sessionId = null; + file = null; + projectAsset = null; + _preparer.reset(); + placementError = null; + } + + Future event(NativeFileDropEvent event) async { + if (!mounted || !connection.isOwner) return; + final id = event.session; + final localPosition = event.position; + switch (event.phase) { + case NativeFileDropPhase.enter: + final files = [ + for (final path in event.paths) ExternalMediaFile(path: path), + ]; + if (!active || !dropPolicy.accepts(files)) { + await release(id, Future.value()); + return; + } + enterExternal(id, event.paths.single, localPosition); + case NativeFileDropPhase.move: + moveExternal(id, localPosition); + case NativeFileDropPhase.exit: + exitExternal(id); + case NativeFileDropPhase.drop: + await dropExternal(id, localPosition); + } + } + + void prepareMedia() { + final source = projectAsset == null + ? TimelineDropSource.file(file!) + : TimelineDropSource.asset(projectAsset!); + unawaited(_preparer.probe(source)); + } + + Future drop() async { + if (!active || !hasPreview) return; + final box = surface.currentContext?.findRenderObject() as RenderBox?; + if (box == null || !(Offset.zero & box.size).contains(position)) { + setState(clear); + return; + } + final g = generation; + try { + await _preparer.commit( + (asset, media) async { + incomingClip!.commit(assetId: asset.id, uri: media.uri); + }, + isCurrent: () => mounted && g == generation, + validatePlacement: () { + updateClip(); + if (incomingClip?.layout == null || + error != null || + placementError != null) { + throw AppException.fromFailure( + error ?? + placementError ?? + const AppFailure(AppErrorCode.mediaReadFailed), + ); + } + }, + ); + } catch (e) { + if (mounted) { + ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text(context.l10n.errorMessage(e)))); + } + } finally { + if (mounted && g == generation) { + setState(clear); + } + } + } + + @override + void dispose() { + widget.incoming?.removeListener(incomingChanged); + view.removeListener(viewChanged); + clear(); + // Flutter mounts the replacement before disposing the old target. Only + // the current owner may unregister the shared native channel and region. + if (native) connection.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + TickerMode.valuesOf(context); + ref.watch(projectsProvider); + ref.watch(_preparationProvider); + ref.listen(_preparationProvider.select((state) => state.preparation), ( + _, + next, + ) { + if (mounted && hasPreview && !next.isLoading) setState(updateClip); + }); + final preview = Stack( + key: surface, + fit: StackFit.expand, + children: [ + widget.child, + if (busy || hasPreview && incomingClip == null && error == null) + const DelayedLoadingIndicator( + child: Align( + alignment: Alignment.topCenter, + child: LinearProgressIndicator(), + ), + ), + ], + ); + return native + ? NativeBoundsReporter(onBounds: report, child: preview) + : preview; + } +} diff --git a/lib/features/timeline/timeline_panel.dart b/lib/features/timeline/timeline_panel.dart new file mode 100644 index 0000000..a079bc4 --- /dev/null +++ b/lib/features/timeline/timeline_panel.dart @@ -0,0 +1,1072 @@ +import 'package:cutdex/l10n/l10n.dart'; +import 'package:cutdex_sdk/timeline/engine.dart'; +import 'package:cutdex_sdk/timeline/layout.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/project.dart'; + +import 'package:cutdex_sdk/timeline_ui.dart'; + +import '../../workspace/timeline_provider.dart'; +import '../../workspace/projects.dart'; + +import '../../integrations/runtime/timeline_thumbnails.dart'; +import '../../integrations/runtime/timeline_waveforms.dart'; + +import 'package:flutter/material.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex_ui/widgets.dart'; + +import '../media/transcription_dialog.dart'; +import '../media/background_removal_dialog.dart'; +import '../projects/widgets/name_dialog.dart'; +import '../../workspace/timeline_session.dart'; +import '../../workspace/preview_target.dart'; +import 'timeline_asset_drop_target.dart'; +import 'timeline_speed_editor.dart'; + +class EditorTimelinePanel extends ConsumerWidget { + const EditorTimelinePanel({ + super.key, + required this.projectId, + required this.timelineId, + }); + final String projectId; + final String timelineId; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final provider = editorTimelineProvider(projectId, timelineId); + final timeline = ref.watch(provider); + final projectState = ref.watch(projectsProvider).asData?.value; + final timelines = projectState?.activeProject?.id == projectId + ? projectState!.timelines + : const []; + return Theme( + data: AppTheme.timelinePanelTheme(Theme.of(context)), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _TimelineTabsBar( + projectId: projectId, + timelineId: timelineId, + timelines: timelines, + creating: projectState?.creatingTimeline ?? false, + openingTimelineId: projectState?.openingTimelineId, + ), + const Divider(height: 1), + Expanded( + child: timeline.when( + loading: () => const WorkspacePanel( + key: Key('timeline-pending'), + child: SizedBox.expand(), + ), + error: (_, _) => WorkspacePanel( + child: Center( + child: SingleChildScrollView( + primary: false, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + context.l10n.openTimelineFailed, + textAlign: TextAlign.center, + ), + TextButton( + onPressed: () => ref.invalidate(provider), + child: Text(context.l10n.retry), + ), + ], + ), + ), + ), + ), + data: (session) => Listener( + behavior: HitTestBehavior.translucent, + onPointerDown: (_) { + if (const bool.fromEnvironment('CUTDEX_PREVIEW_TRACE')) { + debugPrint( + 'CUTDEX_PREVIEW ' + '${DateTime.now().millisecondsSinceEpoch} ' + 'dart pointer-down', + ); + } + ref + .read( + previewNavigationProvider( + projectId, + timelineId, + ).notifier, + ) + .showTimeline(); + }, + child: _TimelineEditor(session: session, projectId: projectId), + ), + ), + ), + ], + ), + ); + } +} + +class _TimelineTabsBar extends ConsumerStatefulWidget { + const _TimelineTabsBar({ + required this.projectId, + required this.timelineId, + required this.timelines, + required this.creating, + required this.openingTimelineId, + }); + + final String projectId; + final String timelineId; + final List timelines; + final bool creating; + final String? openingTimelineId; + + @override + ConsumerState<_TimelineTabsBar> createState() => _TimelineTabsBarState(); +} + +class _TimelineTabsBarState extends ConsumerState<_TimelineTabsBar> { + static const _barHeight = 26.0; + static const _menuWidth = 220.0; + final _scrollController = ScrollController(); + final _selectedMenuItemKey = GlobalKey(); + final _selectedTabKey = GlobalKey(); + + bool get _operationsBusy => + widget.creating || + widget.openingTimelineId != null || + (ref.read(projectsProvider).value?.projectBusy ?? false); + + Future _openTimeline(TimelineSummary timeline) async { + if (_operationsBusy || timeline.id == widget.timelineId) return; + await ref + .read(projectsProvider.notifier) + .openTimeline(widget.projectId, timeline.id); + } + + Future _setTimelinePinned(TimelineSummary timeline) async { + if (_operationsBusy) return; + await ref + .read(projectsProvider.notifier) + .setTimelinePinned(timeline.id, !timeline.pinned); + } + + @override + void initState() { + super.initState(); + _showSelectedTab(); + } + + @override + void didUpdateWidget(covariant _TimelineTabsBar oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.timelineId != widget.timelineId) { + _showSelectedTab(); + } + } + + void _showSelectedTab() { + WidgetsBinding.instance.addPostFrameCallback((_) { + final selected = _selectedTabKey.currentContext; + if (selected != null) { + Scrollable.ensureVisible( + selected, + alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtEnd, + ); + Scrollable.ensureVisible( + selected, + alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart, + ); + } + }); + } + + void _showSelectedMenuItem() { + WidgetsBinding.instance.addPostFrameCallback((_) { + final selected = _selectedMenuItemKey.currentContext; + if (selected != null) { + Scrollable.ensureVisible(selected, alignment: 0.5); + } + }); + } + + Future _renameTimeline(TimelineSummary timeline) async { + if (_operationsBusy) return; + final project = ref.read(projectsProvider).value?.activeProject; + if (project?.id != widget.projectId) return; + final name = await askName( + context, + title: context.l10n.rename, + label: context.l10n.name, + initialValue: timeline.name, + submitLabel: context.l10n.rename, + ); + if (name == null || !mounted || name == timeline.name) return; + await ref + .read(projectsProvider.notifier) + .renameTimeline(project!, timeline.id, name); + } + + Future _deleteTimeline(TimelineSummary timeline) async { + if (_operationsBusy || widget.timelines.length <= 1) return; + final confirmed = await showAppDialog( + context: context, + builder: (dialogContext) => AppDialog( + title: context.l10n.delete, + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogContext, false), + child: Text(context.l10n.cancel), + ), + FilledButton( + onPressed: () => Navigator.pop(dialogContext, true), + child: Text(context.l10n.delete), + ), + ], + child: Text(context.l10n.deleteTimelineConfirmation(timeline.name)), + ), + ); + if (confirmed == true && mounted) { + await ref.read(projectsProvider.notifier).deleteTimeline(timeline.id); + } + } + + Future _createTimeline() async { + if (_operationsBusy) return; + if (widget.timelines.length >= Projects.maxTimelineCount) { + ScaffoldMessenger.maybeOf(context)?.showSnackBar( + SnackBar( + content: Text( + context.l10n.timelineLimitReached(Projects.maxTimelineCount), + ), + ), + ); + return; + } + await ref + .read(projectsProvider.notifier) + .createTimeline(name: _nextName(context)); + } + + @override + void dispose() { + _scrollController.dispose(); + super.dispose(); + } + + String _nextName(BuildContext context) { + final names = widget.timelines.map((timeline) => timeline.name).toSet(); + for (var index = 1; ; index++) { + final candidate = context.l10n.defaultTimelineName(index); + if (!names.contains(candidate)) return candidate; + } + } + + @override + Widget build(BuildContext context) { + return ColoredBox( + color: Theme.of(context).colorScheme.surface, + child: SizedBox( + key: const Key('timeline-tabs-bar'), + height: _barHeight, + child: Row( + children: [ + SizedBox.square( + dimension: _barHeight, + child: IconButton( + key: const Key('timeline-add-button'), + tooltip: context.l10n.createTimelineHint, + onPressed: _createTimeline, + padding: EdgeInsets.zero, + constraints: const BoxConstraints.tightFor( + width: _barHeight, + height: _barHeight, + ), + icon: const Icon(Icons.add, size: AppIconSize.small), + ), + ), + Expanded( + child: ScrollEdgeFade( + controller: _scrollController, + axis: Axis.horizontal, + child: Listener( + onPointerSignal: (event) { + if (event is! PointerScrollEvent || + !_scrollController.hasClients) { + return; + } + final delta = event.scrollDelta.dy != 0 + ? event.scrollDelta.dy + : event.scrollDelta.dx; + if (delta == 0) return; + final position = _scrollController.position; + _scrollController.jumpTo( + (position.pixels + delta).clamp( + position.minScrollExtent, + position.maxScrollExtent, + ), + ); + }, + child: SingleChildScrollView( + key: const Key('timeline-tabs-list'), + controller: _scrollController, + scrollDirection: Axis.horizontal, + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.tiny, + ), + child: Row( + children: [ + for ( + var index = 0; + index < widget.timelines.length; + index++ + ) ...[ + if (index > 0) + const SizedBox(width: AppSpacing.hairline), + _buildTab(context, widget.timelines[index]), + ], + ], + ), + ), + ), + ), + ), + ), + SizedBox.square( + dimension: _barHeight, + child: AppPopover( + width: _menuWidth, + maxHeight: 320, + alignment: AlignmentDirectional.bottomEnd, + child: SingleChildScrollView( + primary: false, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (final timeline in widget.timelines) + KeyedSubtree( + key: timeline.id == widget.timelineId + ? _selectedMenuItemKey + : null, + child: AppMenuItem( + key: ValueKey('timeline-menu-${timeline.id}'), + label: timeline.name, + selected: timeline.id == widget.timelineId, + selectOption: true, + onPressed: () => _openTimeline(timeline), + ), + ), + ], + ), + ), + builder: (context, toggle) => IconButton( + key: const Key('timeline-list-button'), + tooltip: context.l10n.timelines, + onPressed: () { + toggle(); + _showSelectedMenuItem(); + }, + padding: EdgeInsets.zero, + constraints: const BoxConstraints.tightFor( + width: _barHeight, + height: _barHeight, + ), + icon: const Icon(Icons.more_horiz, size: AppIconSize.small), + ), + ), + ), + ], + ), + ), + ); + } + + Widget _buildTab(BuildContext context, TimelineSummary timeline) { + final selected = timeline.id == widget.timelineId; + return KeyedSubtree( + key: selected ? _selectedTabKey : null, + child: AppContextMenu( + itemsBuilder: (context) => [ + AppMenuItem( + key: ValueKey('timeline-pin-${timeline.id}'), + label: timeline.pinned + ? context.l10n.unpinTimeline + : context.l10n.pinTimeline, + icon: Icons.push_pin_outlined, + onPressed: () => _setTimelinePinned(timeline), + ), + AppMenuItem( + key: ValueKey('timeline-rename-${timeline.id}'), + label: context.l10n.rename, + icon: Icons.drive_file_rename_outline, + onPressed: () => _renameTimeline(timeline), + ), + AppMenuItem( + key: ValueKey('timeline-delete-${timeline.id}'), + label: context.l10n.delete, + icon: Icons.delete_outline, + destructive: true, + onPressed: widget.timelines.length <= 1 + ? null + : () => _deleteTimeline(timeline), + ), + ], + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 3), + child: TextButton( + key: ValueKey('timeline-tab-${timeline.id}'), + onPressed: () => _openTimeline(timeline), + style: ButtonStyle( + minimumSize: const WidgetStatePropertyAll(Size(0, 20)), + maximumSize: const WidgetStatePropertyAll( + Size(double.infinity, 20), + ), + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + textStyle: WidgetStatePropertyAll( + Theme.of(context).textTheme.labelLarge?.copyWith( + fontSize: 12, + height: 1.3, + fontWeight: FontWeight.w400, + ), + ), + padding: const WidgetStatePropertyAll( + EdgeInsets.symmetric(horizontal: AppSpacing.small), + ), + foregroundColor: WidgetStatePropertyAll( + selected + ? Theme.of(context).colorScheme.onSurface + : Theme.of(context).colorScheme.onSurfaceVariant, + ), + backgroundColor: WidgetStatePropertyAll( + selected + ? Theme.of(context).colorScheme.onSurface + .withValues(alpha: .05) + : Colors.transparent, + ), + overlayColor: WidgetStateProperty.resolveWith((states) { + if (states.contains(WidgetState.hovered) || + states.contains(WidgetState.focused) || + states.contains(WidgetState.pressed)) { + return Theme.of(context).colorScheme.onSurface + .withValues(alpha: .078); + } + return Colors.transparent; + }), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (timeline.pinned) ...[ + const Icon(Icons.push_pin, size: 10), + const SizedBox(width: AppSpacing.tiny), + ], + Text( + timeline.name, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ], + ), + ), + ), + ), + ); + } +} + +class _TimelineEditor extends StatefulWidget { + const _TimelineEditor({required this.session, required this.projectId}); + final String projectId; + final EditorTimelineSession session; + + @override + State<_TimelineEditor> createState() => _TimelineEditorState(); +} + +class _TimelineEditorState extends State<_TimelineEditor> { + EditorTimelineSession get session => widget.session; + String get projectId => widget.projectId; + late RuntimeTimelineThumbnails _thumbnails; + late RuntimeTimelineWaveforms _waveforms; + + @override + void initState() { + super.initState(); + _createMediaCaches(); + } + + @override + void didUpdateWidget(covariant _TimelineEditor oldWidget) { + super.didUpdateWidget(oldWidget); + if (!identical(oldWidget.session, widget.session)) { + _thumbnails.dispose(); + _waveforms.dispose(); + _createMediaCaches(); + } + } + + void _createMediaCaches() { + _thumbnails = RuntimeTimelineThumbnails( + resolveTrackSelection: (ref) => session.mediaBinding(ref)?.videoSelection, + resolveMedia: (ref) { + final binding = session.mediaBinding(ref); + if (session.unavailableAssets.containsKey(binding?.media.id)) { + return null; + } + return binding?.videoTrackIndex == null ? null : binding!.media; + }, + ); + _waveforms = RuntimeTimelineWaveforms( + resolveTrackSelection: (ref) => session.mediaBinding(ref)?.audioSelection, + resolveGain: session.waveformGain, + gainChanges: session.audioGainPreview, + resolveMedia: (ref) { + final binding = session.mediaBinding(ref); + if (session.unavailableAssets.containsKey(binding?.media.id)) { + return null; + } + return binding?.audioTrackIndex == null ? null : binding!.media; + }, + ); + } + + @override + void dispose() { + _thumbnails.dispose(); + _waveforms.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => ListenableBuilder( + listenable: session, + builder: (context, _) => _build(context), + ); + + TranscriptionClipTarget? _captionTarget( + TimelineViewController controller, + SequenceId sequence, + ) { + if (!session.acceptsEdits || + controller.isDragging || + controller.selectedIdentities.length != 1) { + return null; + } + final handle = switch (controller.selectedIdentities.single) { + ElementHandle value => value, + LayoutBodyId value => controller.elementForIdentity(value), + _ => null, + }; + final query = controller.version.kernelVersion.query(); + if (handle == null || query.ownerOf(handle) == null) return null; + final clip = query.element(handle); + final binding = clip.payloadRef == null + ? null + : session.mediaBinding(clip.payloadRef!); + if (binding == null || + binding.audioTrackIndex == null || + session.unavailableAssets.containsKey(binding.media.id)) { + return null; + } + return TranscriptionClipTarget( + sequence: sequence, + clipId: clip.id.value, + mediaId: binding.media.id, + name: clip.name ?? context.l10n.clip, + audioStream: binding.audioTrackIndex!, + ); + } + + BackgroundRemovalClipTarget? _backgroundRemovalTarget( + TimelineViewController controller, + SequenceId sequence, + ) { + if (!session.acceptsEdits || + controller.isDragging || + controller.selectedIdentities.length != 1) { + return null; + } + final handle = controller.elementForIdentity( + controller.selectedIdentities.single, + ); + final query = controller.version.kernelVersion.query(); + if (handle == null || query.ownerOf(handle) == null) return null; + final clip = query.element(handle); + final binding = clip.payloadRef == null + ? null + : session.mediaBinding(clip.payloadRef!); + if (binding?.videoTrackIndex == null || + session.unavailableAssets.containsKey(binding!.media.id)) { + return null; + } + return BackgroundRemovalClipTarget( + sequence: sequence, + clipId: clip.id.value, + mediaId: binding.media.id, + name: clip.name ?? context.l10n.clip, + ); + } + + List _selectedCaptionCues(TimelineViewController controller) { + final query = controller.version.kernelVersion.query(); + final result = []; + for (final identity in controller.selectedIdentities) { + final handle = controller.elementForIdentity(identity); + if (handle == null || query.ownerOf(handle) == null) return []; + final ref = query.element(handle).payloadRef; + if (ref == null || session.payloadFor(ref)?.type != 'caption') { + return []; + } + result.add(handle); + } + return result; + } + + bool _canSplitCaption( + TimelineViewController controller, + List cues, + ) { + if (cues.length != 1 || controller.isDragging) return false; + final query = controller.version.kernelVersion.query(); + final start = query.absoluteStart(cues.single); + return controller.playheadTick > start && + controller.playheadTick < start + query.element(cues.single).duration; + } + + void _splitCaption( + SequenceId sequence, + TimelineViewController controller, + ElementHandle cue, + ) { + final query = controller.version.kernelVersion.query(); + final offset = controller.playheadTick - query.absoluteStart(cue); + session.splitCaption( + sequence, + SplitCaption( + captionId: query.element(cue).id.value, + offset: CommandTime(offset, TimelineClock.ticksPerSecond), + expectedVersion: session.version, + ), + ); + } + + void _runCaptionEdit(BuildContext context, void Function() edit) { + try { + edit(); + } on CommandRejected catch (error) { + ScaffoldMessenger.maybeOf(context)?.showSnackBar( + SnackBar( + content: Text( + error.code == 'staleVersion' + ? context.l10n.captionChanged + : context.l10n.editCaptionError( + context.l10n.errorMessage(error), + ), + ), + ), + ); + } + } + + Widget _toolbarButton({ + Key? key, + required String tooltip, + required VoidCallback? onPressed, + required IconData icon, + String? semanticLabel, + }) => IconButton( + key: key, + tooltip: tooltip, + onPressed: onPressed, + iconSize: AppIconSize.header, + padding: EdgeInsets.zero, + constraints: const BoxConstraints.tightFor( + width: AppControlSize.headerButton, + height: AppControlSize.headerButton, + ), + style: IconButton.styleFrom( + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + icon: Icon(icon, semanticLabel: semanticLabel), + ); + + Widget _build(BuildContext context) { + final sequenceId = session.activeSequenceId; + if (sequenceId == null) { + return WorkspacePanel( + child: Center(child: Text(context.l10n.noTimelineSequence)), + ); + } + final controller = session.view(sequenceId); + final captionCues = _selectedCaptionCues(controller); + final canSplitCaption = _canSplitCaption(controller, captionCues); + return WorkspacePanel( + headerHeight: 32, + headerPadding: EdgeInsets.zero, + controls: ListenableBuilder( + listenable: Listenable.merge([ + controller.contentChanges, + controller.playheadChanges, + session, + ]), + builder: (context, _) => SizedBox( + key: const Key('timeline-toolbar'), + height: 32, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: AppSpacing.gap), + child: LayoutBuilder( + builder: (context, constraints) => SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: ConstrainedBox( + constraints: BoxConstraints(minWidth: constraints.maxWidth), + child: IntrinsicWidth( + child: Row( + children: [ + Row( + mainAxisSize: MainAxisSize.min, + spacing: AppSpacing.tiny, + children: [ + _toolbarButton( + tooltip: context.l10n.undo, + onPressed: controller.canUndo + ? controller.undo + : null, + icon: Icons.undo, + ), + _toolbarButton( + tooltip: context.l10n.redo, + onPressed: controller.canRedo + ? controller.redo + : null, + icon: Icons.redo, + ), + _toolbarButton( + tooltip: context.l10n.splitAtPlayhead, + onPressed: canSplitCaption + ? () => _runCaptionEdit( + context, + () => _splitCaption( + sequenceId, + controller, + captionCues.single, + ), + ) + : controller.canCutSelection + ? controller.cutSelectionAtPlayhead + : null, + icon: Icons.content_cut, + ), + _toolbarButton( + key: const ValueKey('timeline-trim-left'), + tooltip: context.l10n.trimLeftTooltip, + onPressed: controller.canCutSelection + ? controller.trimLeftAtPlayhead + : null, + icon: Icons.align_horizontal_left, + semanticLabel: context.l10n.trimLeft, + ), + _toolbarButton( + key: const ValueKey('timeline-trim-right'), + tooltip: context.l10n.trimRightTooltip, + onPressed: controller.canCutSelection + ? controller.trimRightAtPlayhead + : null, + icon: Icons.align_horizontal_right, + semanticLabel: context.l10n.trimRight, + ), + _toolbarButton( + key: const ValueKey('timeline-delete-selection'), + tooltip: context.l10n.deleteSelectedClips, + onPressed: () { + if (!controller.canDeleteSelection) return; + controller.deleteSelection(); + }, + icon: Icons.delete_outline, + ), + ], + ), + const Spacer(), + if (controller.commandRejection != null) + Tooltip( + message: controller.commandRejection!, + child: const Icon(Icons.info_outline), + ), + ], + ), + ), + ), + ), + ), + ), + ), + ), + child: ListenableBuilder( + listenable: controller.contentChanges, + builder: (context, child) => AppContextMenu( + itemsBuilder: (_) { + final target = _captionTarget(controller, sequenceId); + final backgroundRemovalTarget = _backgroundRemovalTarget( + controller, + sequenceId, + ); + final query = controller.version.kernelVersion.query(); + final handle = + !controller.isDragging && + controller.selectedIdentities.length == 1 + ? controller.elementForIdentity( + controller.selectedIdentities.single, + ) + : null; + final clip = handle == null || query.ownerOf(handle) == null + ? null + : query.element(handle); + final detachTarget = clip?.id; + final restoreAudio = + clip != null && + clip.payloadRef != null && + session.payloadFor(clip.payloadRef!)?.type == 'video' && + (ClipAudioGain.isDetached(clip) || + ClipAudioGain.fromRecord(clip).muted); + return [ + AppMenuItem( + label: restoreAudio + ? context.l10n.restoreAudio + : context.l10n.detachAudio, + icon: restoreAudio + ? Icons.volume_up_outlined + : Icons.audio_file_outlined, + onPressed: + session.acceptsEdits && + detachTarget != null && + (restoreAudio || + session.canDetachAudio(sequenceId, detachTarget)) + ? () { + try { + if (restoreAudio) { + session.commands.setAudio( + sequence: sequenceId, + clip: detachTarget, + muted: false, + ); + } else { + session.detachAudio(sequenceId, detachTarget); + } + } catch (error) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(context.l10n.errorMessage(error)), + ), + ); + } + } + : null, + ), + AppMenuItem( + label: context.l10n.separateVocals, + icon: Icons.graphic_eq, + onPressed: null, + ), + AppMenuItem( + label: context.l10n.removeBackground, + icon: Icons.person_remove_outlined, + onPressed: backgroundRemovalTarget == null + ? null + : () => showAppDialog( + context: context, + builder: (_) => BackgroundRemovalDialog( + session: session, + target: backgroundRemovalTarget, + ), + ), + ), + AppMenuItem( + label: context.l10n.generateCaptions, + icon: Icons.subtitles_outlined, + onPressed: target == null + ? null + : () => showAppDialog( + context: context, + builder: (_) => TranscriptionDialog.forCurrentTask( + session: session, + target: target, + ), + ), + ), + AppMenuItem( + label: context.l10n.deleteSelectedClips, + icon: Icons.delete_outline, + destructive: true, + onPressed: controller.canDeleteSelection + ? controller.deleteSelection + : null, + ), + ]; + }, + child: child!, + ), + child: Column( + children: [ + Expanded( + child: Directionality( + textDirection: TextDirection.ltr, + child: TimelineViewport( + leadingPadding: AppSpacing.medium, + controller: controller, + child: TimelineAssetDropTarget( + projectId: projectId, + session: session, + sequenceId: sequenceId, + child: TimelineInteractionRegion( + controller: controller, + keyframes: true, + child: Stack( + fit: StackFit.expand, + children: [ + TimelineView( + key: const Key('editor-timeline-surface'), + controller: controller, + classifyContent: session.classify, + contentStatus: session.mediaStatus, + contentTitle: session.contentTitle, + contentStatusChanges: session, + thumbnails: _thumbnails, + waveforms: _waveforms, + showKeyframes: true, + paintClipHeader: TimelineSpeedEditor.headerPainter( + context, + session: session, + sequence: sequenceId, + ), + overlay: TimelineSpeedEditor( + session: session, + sequence: sequenceId, + controller: controller, + ), + ), + ListenableBuilder( + listenable: controller.contentChanges, + builder: (context, _) => + controller.contentEndTick == 0 && + !controller.isDragging + ? TimelineEmptyDropZone( + primaryTop: controller.geometry.primaryTop + .toDouble(), + primaryHeight: controller + .geometry + .primaryHeight + .toDouble(), + verticalOffset: + controller.camera.verticalOffset, + ) + : const SizedBox.shrink(), + ), + ], + ), + ), + ), + ), + ), + ), + ], + ), + ), + ); + } +} + +class TimelineEmptyDropZone extends StatelessWidget { + const TimelineEmptyDropZone({ + super.key, + required this.primaryTop, + required this.primaryHeight, + required this.verticalOffset, + }); + + final double primaryTop; + final double primaryHeight; + final double verticalOffset; + + @override + Widget build(BuildContext context) => IgnorePointer( + child: LayoutBuilder( + builder: (context, constraints) { + final height = primaryHeight + .clamp(0.0, constraints.maxHeight) + .toDouble(); + final top = (primaryTop - verticalOffset) + .clamp(0.0, constraints.maxHeight - height) + .toDouble(); + return Stack( + children: [ + Positioned( + top: top, + left: AppSpacing.medium, + right: AppSpacing.medium, + height: height, + child: CustomPaint( + key: const ValueKey('timeline-empty-drop-zone'), + painter: _DashedDropZonePainter( + color: AppTheme.sidebarDividerColor(context), + ), + child: Center( + child: Text( + context.l10n.timelineDropToStart, + style: Theme.of(context).textTheme.labelLarge?.copyWith( + color: Theme.of(context).colorScheme.onSurface, + fontWeight: FontWeight.w600, + ), + ), + ), + ), + ), + ], + ); + }, + ), + ); +} + +class _DashedDropZonePainter extends CustomPainter { + const _DashedDropZonePainter({required this.color}); + + final Color color; + static const _radius = Radius.circular(8); + static const _dash = 5.0; + static const _gap = 3.0; + + @override + void paint(Canvas canvas, Size size) { + if (size.isEmpty) return; + final rect = RRect.fromRectAndRadius( + Rect.fromLTWH(1, 1, size.width - 2, size.height - 2), + _radius, + ); + final path = Path()..addRRect(rect); + final paint = Paint() + ..color = color + ..style = PaintingStyle.stroke + ..strokeWidth = 2; + for (final metric in path.computeMetrics()) { + var start = 0.0; + while (start < metric.length) { + canvas.drawPath( + metric.extractPath(start, (start + _dash).clamp(0, metric.length)), + paint, + ); + start += _dash + _gap; + } + } + } + + @override + bool shouldRepaint(_DashedDropZonePainter oldDelegate) => + color != oldDelegate.color; +} diff --git a/lib/features/timeline/timeline_speed_editor.dart b/lib/features/timeline/timeline_speed_editor.dart new file mode 100644 index 0000000..573659f --- /dev/null +++ b/lib/features/timeline/timeline_speed_editor.dart @@ -0,0 +1,412 @@ +import 'dart:math' as math; + +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/timeline/engine.dart'; +import 'package:cutdex_sdk/timeline/layout.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:cutdex_sdk/timeline_ui.dart'; +import 'package:flutter/material.dart'; + +import '../../l10n/l10n.dart'; + +import '../../workspace/timeline_session.dart'; +import 'timeline_speed_layout.dart'; + +class TimelineSpeedEditor extends StatelessWidget { + const TimelineSpeedEditor({ + super.key, + required this.session, + required this.sequence, + required this.controller, + }); + + final EditorTimelineSession session; + final SequenceId sequence; + final TimelineViewController controller; + + static TimelineClipHeaderPainter headerPainter( + BuildContext context, { + required EditorTimelineSession session, + required SequenceId sequence, + }) { + final ink = Theme.of(context).colorScheme.onSurface; + final surface = TimelineThemeData.of(context).backgroundColor; + final background = Color.alphaBlend(ink.withValues(alpha: .08), surface); + final style = Theme.of(context).textTheme.labelSmall + ?.copyWith(color: ink, fontSize: 10, height: 1.2); + final scaler = MediaQuery.textScalerOf(context); + return (canvas, clipLayout, clip, pixelsPerTick) { + if (!session.isCustomSpeedEnabled(sequence, clip.id)) return; + final segments = session.clipSpeedSegments(clip); + if (segments == null) return; + final layout = TimelineSpeedLayout( + clip: clipLayout, + segments: segments, + pixelsPerTick: pixelsPerTick, + ); + canvas.save(); + canvas.translate(clipLayout.bounds.left, clipLayout.bounds.top); + for (final segment in layout.segments) { + final bar = segment.bar; + if (bar.isEmpty) continue; + final speed = segment.speed; + canvas.drawRRect( + RRect.fromRectAndRadius(bar, const Radius.circular(5)), + Paint()..color = background, + ); + if (!segment.label.isEmpty) { + final label = TextPainter( + text: TextSpan(text: '${(speed * 100).round()}%', style: style), + textDirection: TextDirection.ltr, + textScaler: scaler, + maxLines: 1, + ellipsis: '…', + )..layout(maxWidth: segment.label.width); + label.paint( + canvas, + Offset( + segment.label.center.dx - label.width / 2, + segment.label.top, + ), + ); + label.dispose(); + } + canvas.save(); + canvas.clipRect(bar); + canvas.drawRRect( + RRect.fromRectAndRadius( + segment.handle, + const Radius.circular(TimelineSpeedSegmentLayout.handleRadius), + ), + Paint()..color = ink.withValues(alpha: .498), + ); + canvas.restore(); + } + canvas.restore(); + }; + } + + @override + Widget build(BuildContext context) => ListenableBuilder( + listenable: Listenable.merge([session, controller.contentChanges]), + builder: (context, _) => LayoutBuilder( + builder: (context, constraints) { + final frame = controller.project( + TimelineViewportRect( + width: constraints.maxWidth, + height: constraints.maxHeight, + ), + ); + final query = frame.version.kernelVersion.query(); + final viewportBounds = + Offset.zero & Size(constraints.maxWidth, constraints.maxHeight); + final bars = []; + void addHeader( + ElementHandle handle, + TimelineClipLayout clipLayout, { + bool ghost = false, + }) { + final record = query.element(handle); + if (!session.isCustomSpeedEnabled(sequence, record.id)) return; + final segments = session.clipSpeedSegments(record); + if (segments == null) return; + final layout = TimelineSpeedLayout( + clip: clipLayout, + segments: segments, + pixelsPerTick: controller.camera.pixelsPerTick, + ); + final bounds = clipLayout.toViewport(layout.bounds); + if (bounds.isEmpty || !bounds.overlaps(viewportBounds)) { + return; + } + bars.add( + Positioned( + key: ValueKey((sequence, record.id)), + left: bounds.left, + top: bounds.top, + width: bounds.width, + height: bounds.height, + child: IgnorePointer( + ignoring: ghost, + child: _ClipSpeedEditor( + session: session, + sequence: sequence, + clip: record.id, + controller: controller, + layout: layout, + ), + ), + ), + ); + } + + for (var index = 0; index < frame.length; index++) { + if (frame.kindAt(index) == TimelineViewportItemKind.transition) { + continue; + } + final identity = frame.identityAt(index); + final handle = controller.elementForIdentity(identity); + if (handle == null) continue; + final bodyId = identity is LayoutBodyId + ? identity + : LayoutBodyId.element(handle); + // The resident item is a landing reservation while the moving clip + // is painted separately at its pointer-following ghost coordinates. + if (controller.dragGhostFor(bodyId) != null) continue; + addHeader(handle, controller.clipLayoutAt(frame, index)); + } + for (final ghost in controller.dragGhosts) { + final body = ghost.body; + addHeader( + body.id.owner, + controller.clipLayout( + controller.dragGhostBounds(ghost, frame.viewport), + owner: body.id.owner, + ), + ghost: true, + ); + } + return Stack(clipBehavior: Clip.none, children: bars); + }, + ), + ); +} + +class _ClipSpeedEditor extends StatefulWidget { + const _ClipSpeedEditor({ + required this.session, + required this.sequence, + required this.clip, + required this.controller, + required this.layout, + }); + + final EditorTimelineSession session; + final SequenceId sequence; + final ElementId clip; + final TimelineViewController controller; + final TimelineSpeedLayout layout; + + @override + State<_ClipSpeedEditor> createState() => _ClipSpeedEditorState(); +} + +class _ClipSpeedEditorState extends State<_ClipSpeedEditor> { + int? _dragDuration; + ClipSpeedSegment? _dragSegment; + TimelineVersion? _dragVersion; + LayoutConnectionEditPreview? _preview; + (Object, StackTrace)? _previewFailure; + int? _dragIndex; + double _dragPixels = 0; + + void _startDrag(int index, ClipSpeedSegment segment) { + _previewFailure = null; + _dragIndex = index; + _dragVersion = widget.controller.version.kernelVersion; + _dragDuration = segment.projectDuration; + _dragSegment = segment; + _dragPixels = 0; + widget.controller.clearRetainedTrimOutline(); + } + + void _updateDrag(DragUpdateDetails details) { + final index = _dragIndex; + final segment = _dragSegment; + if (index == null || segment == null) return; + if (!identical(_dragVersion, widget.controller.version.kernelVersion)) { + _cancelDrag(); + return; + } + _dragPixels += details.delta.dx; + final minimum = math.max(1, (segment.sourceDuration / 100).ceil()); + final maximum = math.max(minimum, (segment.sourceDuration / 0.1).floor()); + final ticks = (_dragPixels / widget.controller.camera.pixelsPerTick) + .round(); + final duration = (segment.projectDuration + ticks).clamp(minimum, maximum); + if (_dragDuration == duration) return; + _dragDuration = duration; + _updatePreview(segmentIndex: index, duration: duration); + } + + void _updatePreview({required int segmentIndex, required int duration}) { + _preview?.cancel(); + _preview = null; + _previewFailure = null; + try { + if (!widget.session.isCustomSpeedEnabled(widget.sequence, widget.clip)) { + widget.controller.clearLayoutPreview(); + return; + } + final preview = widget.session.previewClipSpeedSegmentDuration( + widget.sequence, + widget.clip, + segmentIndex, + duration, + ); + _preview = preview; + if (preview == null) { + widget.controller.clearLayoutPreview(); + } else { + widget.controller.showLayoutPreview(preview.result.version); + } + } catch (error, stack) { + _previewFailure = (error, stack); + widget.controller.clearLayoutPreview(); + _showError(error); + } + } + + void _endDrag() { + final index = _dragIndex; + final version = _dragVersion; + final preview = _preview; + final failure = _previewFailure; + final duration = _dragDuration; + _previewFailure = null; + _preview = null; + _clearDrag(); + if (index == null || version == null) { + preview?.cancel(); + widget.controller.clearLayoutPreview(); + return; + } + if (!identical(version, widget.controller.version.kernelVersion)) { + preview?.cancel(); + widget.controller.clearLayoutPreview(); + return; + } + try { + widget.session.runEdit( + 'setSpeedSegment', + widget.sequence, + () { + if (preview == null) { + widget.controller.clearLayoutPreview(); + if (failure != null) { + widget.session.reportEditFailure(failure.$1, failure.$2); + } + } else { + widget.session.commitClipSpeedPreview(widget.sequence, preview); + } + }, + context: { + 'clipIds': [widget.clip.value], + 'segmentIndex': index, + 'durationTick': duration, + 'entryPoint': 'timelineSpeed', + 'playheadTick': widget.controller.playheadTick, + }, + ); + } catch (error) { + preview?.cancel(); + widget.controller.clearLayoutPreview(); + _showError(error); + } + } + + void _cancelDrag() { + _previewFailure = null; + _preview?.cancel(); + _preview = null; + widget.controller.clearLayoutPreview(); + _clearDrag(); + } + + void _showError(Object error) { + if (!mounted) return; + ScaffoldMessenger.of( + context, + ).showSnackBar(SnackBar(content: Text(context.l10n.errorMessage(error)))); + } + + void _clearDrag() { + _dragIndex = null; + _dragVersion = null; + _dragDuration = null; + _dragSegment = null; + _dragPixels = 0; + } + + @override + void dispose() { + if (_preview != null) { + _preview!.cancel(); + widget.controller.clearLayoutPreview(); + } + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final cells = widget.layout.segments; + return ClipRect( + child: Stack( + children: [ + for (var index = 0; index < cells.length; index++) + if (!cells[index].cell.isEmpty) + Positioned.fromRect( + rect: cells[index].cell.shift(-widget.layout.bounds.topLeft), + child: _SpeedSegmentBar( + index: index, + layout: cells[index], + onDragStart: (_) => _startDrag(index, cells[index].segment), + onDragUpdate: _updateDrag, + onDragEnd: (_) => _endDrag(), + onDragCancel: _cancelDrag, + ), + ), + ], + ), + ); + } +} + +class _SpeedSegmentBar extends StatelessWidget { + const _SpeedSegmentBar({ + required this.index, + required this.layout, + required this.onDragStart, + required this.onDragUpdate, + required this.onDragEnd, + required this.onDragCancel, + }); + + final int index; + final TimelineSpeedSegmentLayout layout; + final GestureDragStartCallback onDragStart; + final GestureDragUpdateCallback onDragUpdate; + final GestureDragEndCallback onDragEnd; + final VoidCallback onDragCancel; + + @override + Widget build(BuildContext context) { + return SizedBox( + key: ValueKey('speed-segment-$index'), + child: Semantics( + label: '${(layout.speed * 100).round()}%', + child: Stack( + fit: StackFit.expand, + children: [ + Positioned.fromRect( + rect: layout.handleHit.shift(-layout.cell.topLeft), + child: MouseRegion( + cursor: SystemMouseCursors.resizeLeftRight, + child: GestureDetector( + key: ValueKey('speed-segment-handle-$index'), + behavior: HitTestBehavior.opaque, + // Own every drag direction; speed uses only horizontal motion. + onPanStart: onDragStart, + onPanUpdate: onDragUpdate, + onPanEnd: onDragEnd, + onPanCancel: onDragCancel, + child: const SizedBox.expand(), + ), + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/features/timeline/timeline_speed_layout.dart b/lib/features/timeline/timeline_speed_layout.dart new file mode 100644 index 0000000..0873367 --- /dev/null +++ b/lib/features/timeline/timeline_speed_layout.dart @@ -0,0 +1,95 @@ +import 'dart:math' as math; +import 'dart:ui'; + +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/timeline_ui.dart'; + +/// Speed segments in the clip's local coordinates. Paint and hit targets use +/// the same cells, including the minimum pixel width and clipping at low zoom. +final class TimelineSpeedLayout { + TimelineSpeedLayout({ + required TimelineClipLayout clip, + required Iterable segments, + required double pixelsPerTick, + }) { + bounds = Rect.fromLTWH( + clip.header.left, + clip.header.top, + clip.header.width, + math.min( + clip.header.height, + EditorLayoutConfiguration.speedSectionHeight.toDouble(), + ), + ); + var left = bounds.left; + final cells = []; + for (final segment in segments) { + final width = math.max(1.0, segment.projectDuration * pixelsPerTick); + final right = math.min(bounds.right, left + width); + final cell = Rect.fromLTWH( + math.min(left, bounds.right), + bounds.top, + math.max(0, right - left), + bounds.height, + ); + cells.add(TimelineSpeedSegmentLayout(segment, cell)); + left += width; + } + this.segments = List.unmodifiable(cells); + } + + late final Rect bounds; + late final List segments; +} + +final class TimelineSpeedSegmentLayout { + TimelineSpeedSegmentLayout(this.segment, this.cell) { + bar = Rect.fromLTWH( + cell.left, + cell.top, + math.max(0, cell.width - segmentGap), + cell.height, + ); + label = Rect.fromLTWH( + bar.left + math.min(labelPadding, bar.width / 2), + bar.top + 1, + math.max(0, bar.width - labelPadding * 2), + math.max(0, bar.height - 2), + ); + final horizontalInset = math.min(handleInset, bar.width / 2); + final verticalInset = math.min(handleInset, bar.height / 2); + final handleRight = bar.right - horizontalInset; + final availableWidth = math.max(0.0, bar.width - horizontalInset * 2); + final handleTop = bar.top + verticalInset; + final handleHeight = math.max(0.0, bar.height - verticalInset * 2); + handle = Rect.fromLTWH( + handleRight - math.min(handleWidth, availableWidth), + handleTop, + math.min(handleWidth, availableWidth), + handleHeight, + ); + final hitWidth = math.min(handleHitWidth, bar.width); + handleHit = Rect.fromLTWH( + (handle.center.dx - hitWidth / 2).clamp(bar.left, bar.right - hitWidth), + bar.top, + hitWidth, + bar.height, + ); + } + + static const segmentGap = 2.0; + static const labelPadding = 8.0; + static const handleInset = 3.0; + static const handleWidth = 2.0; + static const handleHitWidth = 10.0; + static const handleRadius = 1.0; + + final ClipSpeedSegment segment; + final Rect cell; + late final Rect bar; + late final Rect label; + late final Rect handle; + late final Rect handleHit; + + double get speed => segment.speed; +} diff --git a/lib/integrations/agent/agent_credentials.dart b/lib/integrations/agent/agent_credentials.dart new file mode 100644 index 0000000..8333ae8 --- /dev/null +++ b/lib/integrations/agent/agent_credentials.dart @@ -0,0 +1,51 @@ +import 'dart:io'; + +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +part 'agent_credentials.g.dart'; + +abstract interface class AgentCredentialStore { + Future read(String id); + Future write(String id, String value); + Future delete(String id); +} + +@Riverpod(keepAlive: true) +AgentCredentialStore agentCredentialStore(Ref ref) { + final storage = Platform.isMacOS + ? const FlutterSecureStorage( + mOptions: MacOsOptions(usesDataProtectionKeychain: false), + ) + : const FlutterSecureStorage(); + return FlutterSecureAgentCredentialStore(storage); +} + +class FlutterSecureAgentCredentialStore implements AgentCredentialStore { + FlutterSecureAgentCredentialStore(this._storage); + + final FlutterSecureStorage _storage; + + @override + Future read(String id) => _storage.read(key: id); + + @override + Future write(String id, String value) => + _storage.write(key: id, value: value); + + @override + Future delete(String id) => _storage.delete(key: id); +} + +class MemoryAgentCredentialStore implements AgentCredentialStore { + final Map _values = {}; + + @override + Future read(String id) async => _values[id]; + + @override + Future write(String id, String value) async => _values[id] = value; + + @override + Future delete(String id) async => _values.remove(id); +} diff --git a/lib/integrations/agent/agent_credentials.g.dart b/lib/integrations/agent/agent_credentials.g.dart new file mode 100644 index 0000000..574ad96 --- /dev/null +++ b/lib/integrations/agent/agent_credentials.g.dart @@ -0,0 +1,58 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'agent_credentials.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(agentCredentialStore) +final agentCredentialStoreProvider = AgentCredentialStoreProvider._(); + +final class AgentCredentialStoreProvider + extends + $FunctionalProvider< + AgentCredentialStore, + AgentCredentialStore, + AgentCredentialStore + > + with $Provider { + AgentCredentialStoreProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'agentCredentialStoreProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$agentCredentialStoreHash(); + + @$internal + @override + $ProviderElement $createElement( + $ProviderPointer pointer, + ) => $ProviderElement(pointer); + + @override + AgentCredentialStore create(Ref ref) { + return agentCredentialStore(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(AgentCredentialStore value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$agentCredentialStoreHash() => + r'5905f9d4740138df60d6f32dd3fde66489be97c3'; diff --git a/lib/integrations/agent/agent_models.dart b/lib/integrations/agent/agent_models.dart new file mode 100644 index 0000000..b014a70 --- /dev/null +++ b/lib/integrations/agent/agent_models.dart @@ -0,0 +1,69 @@ +import 'package:cutdex_agent/cutdex_agent.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +import 'agent_prompt_policy.dart'; + +part 'agent_models.freezed.dart'; + +enum AgentApiType { openAiChatCompletions, openAiResponses, anthropicMessages } + +@freezed +abstract class AgentModelSettings with _$AgentModelSettings { + const AgentModelSettings._(); + + const factory AgentModelSettings({ + required String id, + int? contextWindow, + int? maxOutputTokens, + }) = _AgentModelSettings; + + /// Reserve at most half of a small window when output is unspecified. + int get effectiveMaxOutputTokens => + maxOutputTokens ?? + (contextWindow == null || contextWindow! >= 8192 + ? 4096 + : contextWindow! ~/ 2); + + int get effectiveMaxInputTokens => + contextWindow == null ? 32000 : contextWindow! - effectiveMaxOutputTokens; + + bool get hasInstructionBudget => + effectiveMaxInputTokens >= + ContextBuilder().measureInput(system: AgentPromptPolicy.editorAssistant); + + bool get hasValidTokenBudget => + effectiveMaxInputTokens > 0 && effectiveMaxOutputTokens > 0; +} + +@freezed +abstract class AgentProviderSettings with _$AgentProviderSettings { + const AgentProviderSettings._(); + + const factory AgentProviderSettings({ + required String id, + required String name, + required String apiType, + required String baseUrl, + required List models, + String? credentialId, + @Default(true) bool enabled, + }) = _AgentProviderSettings; +} + +@freezed +abstract class AgentSettingsState with _$AgentSettingsState { + const AgentSettingsState._(); + + const factory AgentSettingsState({ + @Default(false) bool enabled, + @Default([]) List providers, + String? selectedProviderId, + String? selectedModelId, + @Default(0) int revision, + }) = _AgentSettingsState; +} + +abstract interface class AgentSettingsRepository { + Future load(); + Future save(AgentSettingsState settings); +} diff --git a/lib/integrations/agent/agent_models.freezed.dart b/lib/integrations/agent/agent_models.freezed.dart new file mode 100644 index 0000000..1b83905 --- /dev/null +++ b/lib/integrations/agent/agent_models.freezed.dart @@ -0,0 +1,1318 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'agent_models.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +T _$identity(T value) => value; + +/// @nodoc +mixin _$AgentModelSettings { + String get id; + int? get contextWindow; + int? get maxOutputTokens; + + /// Create a copy of AgentModelSettings + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $AgentModelSettingsCopyWith get copyWith => + _$AgentModelSettingsCopyWithImpl( + this as AgentModelSettings, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as AgentModelSettings; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is AgentModelSettings && + (identical(other.id, _this.id) || other.id == _this.id) && + (identical(other.contextWindow, _this.contextWindow) || + other.contextWindow == _this.contextWindow) && + (identical(other.maxOutputTokens, _this.maxOutputTokens) || + other.maxOutputTokens == _this.maxOutputTokens)); + } + + @override + int get hashCode { + final _this = this as AgentModelSettings; + return Object.hash( + runtimeType, + _this.id, + _this.contextWindow, + _this.maxOutputTokens, + ); + } + + @override + String toString() { + final _this = this as AgentModelSettings; + return 'AgentModelSettings(id: ${_this.id}, contextWindow: ${_this.contextWindow}, maxOutputTokens: ${_this.maxOutputTokens})'; + } +} + +/// @nodoc +abstract mixin class $AgentModelSettingsCopyWith<$Res> { + factory $AgentModelSettingsCopyWith( + AgentModelSettings value, + $Res Function(AgentModelSettings) _then, + ) = _$AgentModelSettingsCopyWithImpl; + @useResult + $Res call({String id, int? contextWindow, int? maxOutputTokens}); +} + +/// @nodoc +class _$AgentModelSettingsCopyWithImpl<$Res> + implements $AgentModelSettingsCopyWith<$Res> { + _$AgentModelSettingsCopyWithImpl(this._self, this._then); + + final AgentModelSettings _self; + final $Res Function(AgentModelSettings) _then; + + /// Create a copy of AgentModelSettings + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + Object? contextWindow = freezed, + Object? maxOutputTokens = freezed, + }) { + return _then( + AgentModelSettings( + id: null == id + ? _self.id + : id // ignore: cast_nullable_to_non_nullable + as String, + contextWindow: freezed == contextWindow + ? _self.contextWindow + : contextWindow // ignore: cast_nullable_to_non_nullable + as int?, + maxOutputTokens: freezed == maxOutputTokens + ? _self.maxOutputTokens + : maxOutputTokens // ignore: cast_nullable_to_non_nullable + as int?, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [AgentModelSettings]. +extension AgentModelSettingsPatterns on AgentModelSettings { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_AgentModelSettings value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _AgentModelSettings() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_AgentModelSettings value) $default, + ) { + final _that = this; + switch (_that) { + case _AgentModelSettings(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_AgentModelSettings value)? $default, + ) { + final _that = this; + switch (_that) { + case _AgentModelSettings() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function(String id, int? contextWindow, int? maxOutputTokens)? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _AgentModelSettings() when $default != null: + return $default(_that.id, _that.contextWindow, _that.maxOutputTokens); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function(String id, int? contextWindow, int? maxOutputTokens) + $default, + ) { + final _that = this; + switch (_that) { + case _AgentModelSettings(): + return $default(_that.id, _that.contextWindow, _that.maxOutputTokens); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function(String id, int? contextWindow, int? maxOutputTokens)? + $default, + ) { + final _that = this; + switch (_that) { + case _AgentModelSettings() when $default != null: + return $default(_that.id, _that.contextWindow, _that.maxOutputTokens); + case _: + return null; + } + } +} + +/// @nodoc + +class _AgentModelSettings extends AgentModelSettings { + const _AgentModelSettings({ + required this.id, + this.contextWindow, + this.maxOutputTokens, + }) : super._(); + + @override + final String id; + @override + final int? contextWindow; + @override + final int? maxOutputTokens; + + /// Create a copy of AgentModelSettings + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$AgentModelSettingsCopyWith<_AgentModelSettings> get copyWith => + __$AgentModelSettingsCopyWithImpl<_AgentModelSettings>(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _AgentModelSettings && + (identical(other.id, id) || other.id == id) && + (identical(other.contextWindow, contextWindow) || + other.contextWindow == contextWindow) && + (identical(other.maxOutputTokens, maxOutputTokens) || + other.maxOutputTokens == maxOutputTokens)); + } + + @override + int get hashCode { + return Object.hash(runtimeType, id, contextWindow, maxOutputTokens); + } + + @override + String toString() { + return 'AgentModelSettings(id: $id, contextWindow: $contextWindow, maxOutputTokens: $maxOutputTokens)'; + } +} + +/// @nodoc +abstract mixin class _$AgentModelSettingsCopyWith<$Res> + implements $AgentModelSettingsCopyWith<$Res> { + factory _$AgentModelSettingsCopyWith( + _AgentModelSettings value, + $Res Function(_AgentModelSettings) _then, + ) = __$AgentModelSettingsCopyWithImpl; + @override + @useResult + $Res call({String id, int? contextWindow, int? maxOutputTokens}); +} + +/// @nodoc +class __$AgentModelSettingsCopyWithImpl<$Res> + implements _$AgentModelSettingsCopyWith<$Res> { + __$AgentModelSettingsCopyWithImpl(this._self, this._then); + + final _AgentModelSettings _self; + final $Res Function(_AgentModelSettings) _then; + + /// Create a copy of AgentModelSettings + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? id = null, + Object? contextWindow = freezed, + Object? maxOutputTokens = freezed, + }) { + return _then( + _AgentModelSettings( + id: null == id + ? _self.id + : id // ignore: cast_nullable_to_non_nullable + as String, + contextWindow: freezed == contextWindow + ? _self.contextWindow + : contextWindow // ignore: cast_nullable_to_non_nullable + as int?, + maxOutputTokens: freezed == maxOutputTokens + ? _self.maxOutputTokens + : maxOutputTokens // ignore: cast_nullable_to_non_nullable + as int?, + ), + ); + } +} + +/// @nodoc +mixin _$AgentProviderSettings { + String get id; + String get name; + String get apiType; + String get baseUrl; + List get models; + String? get credentialId; + bool get enabled; + + /// Create a copy of AgentProviderSettings + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $AgentProviderSettingsCopyWith get copyWith => + _$AgentProviderSettingsCopyWithImpl( + this as AgentProviderSettings, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as AgentProviderSettings; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is AgentProviderSettings && + (identical(other.id, _this.id) || other.id == _this.id) && + (identical(other.name, _this.name) || other.name == _this.name) && + (identical(other.apiType, _this.apiType) || + other.apiType == _this.apiType) && + (identical(other.baseUrl, _this.baseUrl) || + other.baseUrl == _this.baseUrl) && + const DeepCollectionEquality().equals(other.models, _this.models) && + (identical(other.credentialId, _this.credentialId) || + other.credentialId == _this.credentialId) && + (identical(other.enabled, _this.enabled) || + other.enabled == _this.enabled)); + } + + @override + int get hashCode { + final _this = this as AgentProviderSettings; + return Object.hash( + runtimeType, + _this.id, + _this.name, + _this.apiType, + _this.baseUrl, + const DeepCollectionEquality().hash(_this.models), + _this.credentialId, + _this.enabled, + ); + } + + @override + String toString() { + final _this = this as AgentProviderSettings; + return 'AgentProviderSettings(id: ${_this.id}, name: ${_this.name}, apiType: ${_this.apiType}, baseUrl: ${_this.baseUrl}, models: ${_this.models}, credentialId: ${_this.credentialId}, enabled: ${_this.enabled})'; + } +} + +/// @nodoc +abstract mixin class $AgentProviderSettingsCopyWith<$Res> { + factory $AgentProviderSettingsCopyWith( + AgentProviderSettings value, + $Res Function(AgentProviderSettings) _then, + ) = _$AgentProviderSettingsCopyWithImpl; + @useResult + $Res call({ + String id, + String name, + String apiType, + String baseUrl, + List models, + String? credentialId, + bool enabled, + }); +} + +/// @nodoc +class _$AgentProviderSettingsCopyWithImpl<$Res> + implements $AgentProviderSettingsCopyWith<$Res> { + _$AgentProviderSettingsCopyWithImpl(this._self, this._then); + + final AgentProviderSettings _self; + final $Res Function(AgentProviderSettings) _then; + + /// Create a copy of AgentProviderSettings + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + Object? name = null, + Object? apiType = null, + Object? baseUrl = null, + Object? models = null, + Object? credentialId = freezed, + Object? enabled = null, + }) { + return _then( + AgentProviderSettings( + id: null == id + ? _self.id + : id // ignore: cast_nullable_to_non_nullable + as String, + name: null == name + ? _self.name + : name // ignore: cast_nullable_to_non_nullable + as String, + apiType: null == apiType + ? _self.apiType + : apiType // ignore: cast_nullable_to_non_nullable + as String, + baseUrl: null == baseUrl + ? _self.baseUrl + : baseUrl // ignore: cast_nullable_to_non_nullable + as String, + models: null == models + ? _self.models + : models // ignore: cast_nullable_to_non_nullable + as List, + credentialId: freezed == credentialId + ? _self.credentialId + : credentialId // ignore: cast_nullable_to_non_nullable + as String?, + enabled: null == enabled + ? _self.enabled + : enabled // ignore: cast_nullable_to_non_nullable + as bool, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [AgentProviderSettings]. +extension AgentProviderSettingsPatterns on AgentProviderSettings { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_AgentProviderSettings value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _AgentProviderSettings() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_AgentProviderSettings value) $default, + ) { + final _that = this; + switch (_that) { + case _AgentProviderSettings(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_AgentProviderSettings value)? $default, + ) { + final _that = this; + switch (_that) { + case _AgentProviderSettings() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + String id, + String name, + String apiType, + String baseUrl, + List models, + String? credentialId, + bool enabled, + )? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _AgentProviderSettings() when $default != null: + return $default( + _that.id, + _that.name, + _that.apiType, + _that.baseUrl, + _that.models, + _that.credentialId, + _that.enabled, + ); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function( + String id, + String name, + String apiType, + String baseUrl, + List models, + String? credentialId, + bool enabled, + ) + $default, + ) { + final _that = this; + switch (_that) { + case _AgentProviderSettings(): + return $default( + _that.id, + _that.name, + _that.apiType, + _that.baseUrl, + _that.models, + _that.credentialId, + _that.enabled, + ); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + String id, + String name, + String apiType, + String baseUrl, + List models, + String? credentialId, + bool enabled, + )? + $default, + ) { + final _that = this; + switch (_that) { + case _AgentProviderSettings() when $default != null: + return $default( + _that.id, + _that.name, + _that.apiType, + _that.baseUrl, + _that.models, + _that.credentialId, + _that.enabled, + ); + case _: + return null; + } + } +} + +/// @nodoc + +class _AgentProviderSettings extends AgentProviderSettings { + const _AgentProviderSettings({ + required this.id, + required this.name, + required this.apiType, + required this.baseUrl, + required List models, + this.credentialId, + this.enabled = true, + }) : _models = models, + super._(); + + @override + final String id; + @override + final String name; + @override + final String apiType; + @override + final String baseUrl; + final List _models; + @override + List get models { + if (_models is EqualUnmodifiableListView) return _models; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_models); + } + + @override + final String? credentialId; + @override + @JsonKey() + final bool enabled; + + /// Create a copy of AgentProviderSettings + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$AgentProviderSettingsCopyWith<_AgentProviderSettings> get copyWith => + __$AgentProviderSettingsCopyWithImpl<_AgentProviderSettings>( + this, + _$identity, + ); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _AgentProviderSettings && + (identical(other.id, id) || other.id == id) && + (identical(other.name, name) || other.name == name) && + (identical(other.apiType, apiType) || other.apiType == apiType) && + (identical(other.baseUrl, baseUrl) || other.baseUrl == baseUrl) && + const DeepCollectionEquality().equals(other.models, _models) && + (identical(other.credentialId, credentialId) || + other.credentialId == credentialId) && + (identical(other.enabled, enabled) || other.enabled == enabled)); + } + + @override + int get hashCode { + return Object.hash( + runtimeType, + id, + name, + apiType, + baseUrl, + const DeepCollectionEquality().hash(_models), + credentialId, + enabled, + ); + } + + @override + String toString() { + return 'AgentProviderSettings(id: $id, name: $name, apiType: $apiType, baseUrl: $baseUrl, models: $models, credentialId: $credentialId, enabled: $enabled)'; + } +} + +/// @nodoc +abstract mixin class _$AgentProviderSettingsCopyWith<$Res> + implements $AgentProviderSettingsCopyWith<$Res> { + factory _$AgentProviderSettingsCopyWith( + _AgentProviderSettings value, + $Res Function(_AgentProviderSettings) _then, + ) = __$AgentProviderSettingsCopyWithImpl; + @override + @useResult + $Res call({ + String id, + String name, + String apiType, + String baseUrl, + List models, + String? credentialId, + bool enabled, + }); +} + +/// @nodoc +class __$AgentProviderSettingsCopyWithImpl<$Res> + implements _$AgentProviderSettingsCopyWith<$Res> { + __$AgentProviderSettingsCopyWithImpl(this._self, this._then); + + final _AgentProviderSettings _self; + final $Res Function(_AgentProviderSettings) _then; + + /// Create a copy of AgentProviderSettings + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? id = null, + Object? name = null, + Object? apiType = null, + Object? baseUrl = null, + Object? models = null, + Object? credentialId = freezed, + Object? enabled = null, + }) { + return _then( + _AgentProviderSettings( + id: null == id + ? _self.id + : id // ignore: cast_nullable_to_non_nullable + as String, + name: null == name + ? _self.name + : name // ignore: cast_nullable_to_non_nullable + as String, + apiType: null == apiType + ? _self.apiType + : apiType // ignore: cast_nullable_to_non_nullable + as String, + baseUrl: null == baseUrl + ? _self.baseUrl + : baseUrl // ignore: cast_nullable_to_non_nullable + as String, + models: null == models + ? _self._models + : models // ignore: cast_nullable_to_non_nullable + as List, + credentialId: freezed == credentialId + ? _self.credentialId + : credentialId // ignore: cast_nullable_to_non_nullable + as String?, + enabled: null == enabled + ? _self.enabled + : enabled // ignore: cast_nullable_to_non_nullable + as bool, + ), + ); + } +} + +/// @nodoc +mixin _$AgentSettingsState { + bool get enabled; + List get providers; + String? get selectedProviderId; + String? get selectedModelId; + int get revision; + + /// Create a copy of AgentSettingsState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $AgentSettingsStateCopyWith get copyWith => + _$AgentSettingsStateCopyWithImpl( + this as AgentSettingsState, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as AgentSettingsState; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is AgentSettingsState && + (identical(other.enabled, _this.enabled) || + other.enabled == _this.enabled) && + const DeepCollectionEquality().equals( + other.providers, + _this.providers, + ) && + (identical(other.selectedProviderId, _this.selectedProviderId) || + other.selectedProviderId == _this.selectedProviderId) && + (identical(other.selectedModelId, _this.selectedModelId) || + other.selectedModelId == _this.selectedModelId) && + (identical(other.revision, _this.revision) || + other.revision == _this.revision)); + } + + @override + int get hashCode { + final _this = this as AgentSettingsState; + return Object.hash( + runtimeType, + _this.enabled, + const DeepCollectionEquality().hash(_this.providers), + _this.selectedProviderId, + _this.selectedModelId, + _this.revision, + ); + } + + @override + String toString() { + final _this = this as AgentSettingsState; + return 'AgentSettingsState(enabled: ${_this.enabled}, providers: ${_this.providers}, selectedProviderId: ${_this.selectedProviderId}, selectedModelId: ${_this.selectedModelId}, revision: ${_this.revision})'; + } +} + +/// @nodoc +abstract mixin class $AgentSettingsStateCopyWith<$Res> { + factory $AgentSettingsStateCopyWith( + AgentSettingsState value, + $Res Function(AgentSettingsState) _then, + ) = _$AgentSettingsStateCopyWithImpl; + @useResult + $Res call({ + bool enabled, + List providers, + String? selectedProviderId, + String? selectedModelId, + int revision, + }); +} + +/// @nodoc +class _$AgentSettingsStateCopyWithImpl<$Res> + implements $AgentSettingsStateCopyWith<$Res> { + _$AgentSettingsStateCopyWithImpl(this._self, this._then); + + final AgentSettingsState _self; + final $Res Function(AgentSettingsState) _then; + + /// Create a copy of AgentSettingsState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? enabled = null, + Object? providers = null, + Object? selectedProviderId = freezed, + Object? selectedModelId = freezed, + Object? revision = null, + }) { + return _then( + AgentSettingsState( + enabled: null == enabled + ? _self.enabled + : enabled // ignore: cast_nullable_to_non_nullable + as bool, + providers: null == providers + ? _self.providers + : providers // ignore: cast_nullable_to_non_nullable + as List, + selectedProviderId: freezed == selectedProviderId + ? _self.selectedProviderId + : selectedProviderId // ignore: cast_nullable_to_non_nullable + as String?, + selectedModelId: freezed == selectedModelId + ? _self.selectedModelId + : selectedModelId // ignore: cast_nullable_to_non_nullable + as String?, + revision: null == revision + ? _self.revision + : revision // ignore: cast_nullable_to_non_nullable + as int, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [AgentSettingsState]. +extension AgentSettingsStatePatterns on AgentSettingsState { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_AgentSettingsState value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _AgentSettingsState() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_AgentSettingsState value) $default, + ) { + final _that = this; + switch (_that) { + case _AgentSettingsState(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_AgentSettingsState value)? $default, + ) { + final _that = this; + switch (_that) { + case _AgentSettingsState() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + bool enabled, + List providers, + String? selectedProviderId, + String? selectedModelId, + int revision, + )? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _AgentSettingsState() when $default != null: + return $default( + _that.enabled, + _that.providers, + _that.selectedProviderId, + _that.selectedModelId, + _that.revision, + ); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function( + bool enabled, + List providers, + String? selectedProviderId, + String? selectedModelId, + int revision, + ) + $default, + ) { + final _that = this; + switch (_that) { + case _AgentSettingsState(): + return $default( + _that.enabled, + _that.providers, + _that.selectedProviderId, + _that.selectedModelId, + _that.revision, + ); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + bool enabled, + List providers, + String? selectedProviderId, + String? selectedModelId, + int revision, + )? + $default, + ) { + final _that = this; + switch (_that) { + case _AgentSettingsState() when $default != null: + return $default( + _that.enabled, + _that.providers, + _that.selectedProviderId, + _that.selectedModelId, + _that.revision, + ); + case _: + return null; + } + } +} + +/// @nodoc + +class _AgentSettingsState extends AgentSettingsState { + const _AgentSettingsState({ + this.enabled = false, + List providers = const [], + this.selectedProviderId, + this.selectedModelId, + this.revision = 0, + }) : _providers = providers, + super._(); + + @override + @JsonKey() + final bool enabled; + final List _providers; + @override + @JsonKey() + List get providers { + if (_providers is EqualUnmodifiableListView) return _providers; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_providers); + } + + @override + final String? selectedProviderId; + @override + final String? selectedModelId; + @override + @JsonKey() + final int revision; + + /// Create a copy of AgentSettingsState + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$AgentSettingsStateCopyWith<_AgentSettingsState> get copyWith => + __$AgentSettingsStateCopyWithImpl<_AgentSettingsState>(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _AgentSettingsState && + (identical(other.enabled, enabled) || other.enabled == enabled) && + const DeepCollectionEquality().equals( + other.providers, + _providers, + ) && + (identical(other.selectedProviderId, selectedProviderId) || + other.selectedProviderId == selectedProviderId) && + (identical(other.selectedModelId, selectedModelId) || + other.selectedModelId == selectedModelId) && + (identical(other.revision, revision) || + other.revision == revision)); + } + + @override + int get hashCode { + return Object.hash( + runtimeType, + enabled, + const DeepCollectionEquality().hash(_providers), + selectedProviderId, + selectedModelId, + revision, + ); + } + + @override + String toString() { + return 'AgentSettingsState(enabled: $enabled, providers: $providers, selectedProviderId: $selectedProviderId, selectedModelId: $selectedModelId, revision: $revision)'; + } +} + +/// @nodoc +abstract mixin class _$AgentSettingsStateCopyWith<$Res> + implements $AgentSettingsStateCopyWith<$Res> { + factory _$AgentSettingsStateCopyWith( + _AgentSettingsState value, + $Res Function(_AgentSettingsState) _then, + ) = __$AgentSettingsStateCopyWithImpl; + @override + @useResult + $Res call({ + bool enabled, + List providers, + String? selectedProviderId, + String? selectedModelId, + int revision, + }); +} + +/// @nodoc +class __$AgentSettingsStateCopyWithImpl<$Res> + implements _$AgentSettingsStateCopyWith<$Res> { + __$AgentSettingsStateCopyWithImpl(this._self, this._then); + + final _AgentSettingsState _self; + final $Res Function(_AgentSettingsState) _then; + + /// Create a copy of AgentSettingsState + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? enabled = null, + Object? providers = null, + Object? selectedProviderId = freezed, + Object? selectedModelId = freezed, + Object? revision = null, + }) { + return _then( + _AgentSettingsState( + enabled: null == enabled + ? _self.enabled + : enabled // ignore: cast_nullable_to_non_nullable + as bool, + providers: null == providers + ? _self._providers + : providers // ignore: cast_nullable_to_non_nullable + as List, + selectedProviderId: freezed == selectedProviderId + ? _self.selectedProviderId + : selectedProviderId // ignore: cast_nullable_to_non_nullable + as String?, + selectedModelId: freezed == selectedModelId + ? _self.selectedModelId + : selectedModelId // ignore: cast_nullable_to_non_nullable + as String?, + revision: null == revision + ? _self.revision + : revision // ignore: cast_nullable_to_non_nullable + as int, + ), + ); + } +} diff --git a/lib/integrations/agent/agent_prompt_policy.dart b/lib/integrations/agent/agent_prompt_policy.dart new file mode 100644 index 0000000..244bc5b --- /dev/null +++ b/lib/integrations/agent/agent_prompt_policy.dart @@ -0,0 +1,28 @@ +import 'dart:convert'; + +abstract final class AgentPromptPolicy { + static String forTimeline(String projectId, String timelineId) => + '$editorAssistant\n' + '当前界面编辑目标(用户明确指定其他目标时,以用户要求为准):${jsonEncode({'projectId': projectId, 'timelineId': timelineId})}。' + '已有适用于当前目标的成功工具结果时复用其 workspaceId。仅首次没有目标 ID、切换目标或工作区失效时调用 cutdex_workspaces;toolSetId 引用同一返回中的 toolSets。当前任务内复用已确认的 ID,不要在每次模型回复、工具调用或上下文压缩后重复发现工作区;仅在目标切换或工作区失效时重新查询。' + 'application 工作区只处理项目管理;时间线查询和片段编辑必须使用对应的时间线工作区。'; + static const editorAssistant = + '你是 Cutdex 视频剪辑助手,请使用用户的语言回答。' + '音频分析使用 audio_analyze,先从 timeline_query 确定音频 clipId 和 sourceRange;startSeconds/durationSeconds 是素材时间,单次最多120秒,长素材按区间读取。波形峰值、RMS和高能量片段只是高潮候选,不等于语义高潮;重音候选不等于已识别小节强拍。置信度或分辨率不足时明确说明,不要编造节拍。' + '用户要求实际卡点剪辑时,调用 timeline_planBeatCuts 并设置 requireCuts:true;仅查看方案时为false。指定音频参考片段和要剪切的主时间线片段,每拍every:1、两拍every:2,phase小于every。工具负责裁剪/变速时间映射和帧对齐,严格按返回actions顺序逐一调用timeline_split,使用每次成功操作返回的最新expectedVersion。不要对剪辑后的项目重算或替换原计划,不要擅自切割音频参考。完成后project_save,结束前程序会按原计划核验切点和素材范围。mode:split保留内容只做分割;用户要求多个镜头卡点切换且允许裁剪时,用mode:fitClips,把全部主时间线素材按现有顺序缩短到连续节拍,严格执行返回的timeline_trim操作。工具不会自动选素材或重排;需要选材时先安排素材再制定卡点计划,不能把单纯分割称为已经换镜头。' + '修改片段名称或静态参数前,调用 editor_expect_clips 登记用户要求的全部目标、最终名称和参数默认值;未要求调整结构时保留 preserveLayout:true。音量参数 ID 为 cutdex.audio.gainDb。新建翻译轨道后、写入译文前调用 editor_expect_translation,登记源和目标 roleId。结束时程序会重新读取工程核验数量、身份、时间和已声明参数;有差异时按具体问题修正,不要重新登记来降低原标准。先完成 project_save,再报告保存完成。声明范围之外的要求不能声称已由程序核验。' + '语义检查只提供带原文、译文和疑点的复核建议;不能仅凭一次语义评分自动改写正确译文。结构通过不等于翻译准确、自然或适合交付。遇到原文不清楚要明确列出待复核项,不能猜测事实,也不能把占位或省略号当作已完成翻译。' + '字幕翻译可使用内置 subtitle_translate(需要支持的字幕文件和可用模型),也可读取 caption_query 的原文由你直接翻译。用户要求新增字幕轨道时,保留原字幕,用 captionTrack_create 创建目标语言轨道,再用 caption_addTranslations 按返回的 roleId 逐条或分批添加译文。翻译时每条只提供 text 和 sourceCaptionId(原字幕 captionId),由工具复制精确时间,避免抄写或计算时间数字。翻译风格未指定时使用自然准确的译文,不必为可选风格偏好暂停执行。' + '批量字幕任务优先 caption_list:不传 roleId 先列轨道,再指定源 roleId 每页读取 20 条,翻译并用 caption_addTranslations 写入后才读取下一页。通过 update_plan checkpoint 记录源 roleId、目标 roleId、nextOffset 和最新版本;上下文压缩后从 nextOffset 继续,不能重新全量查询或重复写入。caption_list 已完成字幕编辑前的状态查询,字幕任务不需要全量 timeline_query;结束时用 caption_list 核对轨道数量和保存状态。' + '同一时间线的写操作必须逐次调用并等待返回,再使用更新后的版本;不要在同一条模型回复中批量发出共享同一个 expectedVersion 的独立写操作。只有专用批量工具才能原子批量编辑。' + '上下文压缩本身不会改变工程状态,也不会使已确认的工作区和版本失效。即使摘要泛称版本可能过时,也应复用本轮最近一次成功查询或提交的版本;不要陷入压缩后重新查询、查询后再次压缩的循环。' + '编辑前查询时间线;只核对少量片段时使用 clipIds 和 parameterIds,结构查询用 includeParameters:false;连续编辑可使用上一次成功提交返回的最新 expectedVersion。无状态变化时不要重复查询同一时间线;发生版本冲突或结果未知时重新查询。' + 'clip_setTransform 的画面位置使用相对画布中心的像素坐标;' + 'keyframe_edit/keyframe_editMany 的 canvas.position.x/y 则使用归一化值,x 向右为正、y 向上为正,必须将像素除以画布宽高,不能直接传像素。' + '编辑时间使用时间线时间;查询关键帧的 sourceTime 是素材时间,需结合片段起点和 sourceRange 换算。' + '仅报告工具确认的结果;预览异步同步,提交成功不等于预览或导出完成。' + '结果未知时先核对状态,不要重复执行编辑。' + '完成编辑后按修改过的片段和参数查询时间线,核对实际结果与 saveState,再报告最新的保存状态。' + '总时长以时间线查询的 duration 为准,不能沿用编辑前的时长或把重叠 lane 时长相加。' + '查询结果中的 preview:notRequested 仅指该次查询未请求预览,不表示实际预览未同步;需要报告预览时调用 preview_query。'; +} diff --git a/lib/integrations/agent/agent_provider.dart b/lib/integrations/agent/agent_provider.dart new file mode 100644 index 0000000..d02532b --- /dev/null +++ b/lib/integrations/agent/agent_provider.dart @@ -0,0 +1,4 @@ +export 'agent_models.dart'; +export 'agent_runtime.dart'; +export 'agent_settings.dart'; +export 'agent_session_store.dart'; diff --git a/lib/integrations/agent/agent_runtime.dart b/lib/integrations/agent/agent_runtime.dart new file mode 100644 index 0000000..5680c33 --- /dev/null +++ b/lib/integrations/agent/agent_runtime.dart @@ -0,0 +1,20 @@ +import 'package:cutdex_agent/cutdex_agent.dart'; + +/// Runtime-only dependencies for one selected provider/model. +class AgentRuntime { + const AgentRuntime({ + required this.model, + required this.contextBuilder, + required this.revision, + required this.sessionIdentity, + this.providerId, + this.modelId, + }); + + final ModelAdapter model; + final ContextBuilder contextBuilder; + final int revision; + final String sessionIdentity; + final String? providerId; + final String? modelId; +} diff --git a/lib/integrations/agent/agent_runtime_factory.dart b/lib/integrations/agent/agent_runtime_factory.dart new file mode 100644 index 0000000..5d7cab6 --- /dev/null +++ b/lib/integrations/agent/agent_runtime_factory.dart @@ -0,0 +1,102 @@ +import 'package:cutdex_agent/cutdex_agent.dart'; +import 'package:cutdex_agent/io.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import 'agent_credentials.dart'; +import 'agent_models.dart'; +import 'agent_runtime.dart'; + +part 'agent_runtime_factory.g.dart'; + +@Riverpod(keepAlive: true) +AgentRuntimeFactory agentRuntimeFactory(Ref ref) { + return AgentRuntimeFactory(ref.watch(agentCredentialStoreProvider)); +} + +/// Converts persisted provider metadata into runtime-only Agent dependencies. +class AgentRuntimeFactory { + const AgentRuntimeFactory(this._credentials); + + final AgentCredentialStore _credentials; + + Future create(AgentSettingsState settings) async { + if (!settings.enabled) return null; + return createFor( + settings, + providerId: settings.selectedProviderId, + modelId: settings.selectedModelId, + ); + } + + Future createFor( + AgentSettingsState settings, { + required String? providerId, + required String? modelId, + }) async { + if (!settings.enabled) return null; + final provider = settings.providers + .where((candidate) => candidate.id == providerId) + .firstOrNull; + final model = provider?.models + .where((candidate) => candidate.id == modelId) + .firstOrNull; + if (provider == null || !provider.enabled || model == null) return null; + final apiType = AgentApiType.values + .where((candidate) => candidate.name == provider.apiType) + .firstOrNull; + if (apiType == null) return null; + + final credentialId = provider.credentialId; + final apiKey = credentialId == null + ? '' + : await _credentials.read(credentialId) ?? ''; + final adapter = switch (apiType) { + AgentApiType.openAiChatCompletions => OpenAiChatAdapter( + baseUrl: Uri.parse(provider.baseUrl), + model: model.id, + apiKey: apiKey, + ), + AgentApiType.openAiResponses => OpenAiResponsesAdapter( + baseUrl: Uri.parse(provider.baseUrl), + model: model.id, + apiKey: apiKey, + ), + AgentApiType.anthropicMessages => AnthropicMessagesAdapter( + baseUrl: Uri.parse(provider.baseUrl), + model: model.id, + apiKey: apiKey, + ), + }; + return AgentRuntime( + model: adapter, + contextBuilder: HarnessContextBuilder( + directTools: const {'cutdex_workspaces'}, + summarizer: ModelContextSummarizer( + model: adapter, + budget: ContextBuilder( + maxInputTokens: model.effectiveMaxInputTokens, + maxOutputTokens: model.effectiveMaxOutputTokens, + ), + instructions: + 'For video editing preserve project, timeline, sequence ' + 'and clip IDs, lane relationships, source versus timeline time, ' + 'keyframe units, mask identifiers, committed edits and unsaved ' + 'or uncertain results. Preserve user constraints and pending edits. ' + 'Preserve the latest confirmed workspace and version IDs and ' + 'whether any later edit or error invalidated them. Compaction ' + 'alone does not invalidate a successful query or commit. Reuse ' + 'its version for the next sequential write; do not add a pending ' + 'query merely because a summary was created. Requery only when ' + 'the target changes or a stale/uncertain ' + 'result requires reconciliation. Preserve durable resultId references and cursors needed for pending reads. Do not copy full curves or unrelated tool call IDs. Keep the summary concise: group completed edits by target, retain only latest valid version, exact pending actions and user constraints. Do not repeat the same IDs under multiple headings.', + ), + maxInputTokens: model.effectiveMaxInputTokens, + maxOutputTokens: model.effectiveMaxOutputTokens, + ), + revision: settings.revision, + sessionIdentity: '${provider.id}\u0000${model.id}', + providerId: provider.id, + modelId: model.id, + ); + } +} diff --git a/lib/integrations/agent/agent_runtime_factory.g.dart b/lib/integrations/agent/agent_runtime_factory.g.dart new file mode 100644 index 0000000..574831e --- /dev/null +++ b/lib/integrations/agent/agent_runtime_factory.g.dart @@ -0,0 +1,58 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'agent_runtime_factory.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(agentRuntimeFactory) +final agentRuntimeFactoryProvider = AgentRuntimeFactoryProvider._(); + +final class AgentRuntimeFactoryProvider + extends + $FunctionalProvider< + AgentRuntimeFactory, + AgentRuntimeFactory, + AgentRuntimeFactory + > + with $Provider { + AgentRuntimeFactoryProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'agentRuntimeFactoryProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$agentRuntimeFactoryHash(); + + @$internal + @override + $ProviderElement $createElement( + $ProviderPointer pointer, + ) => $ProviderElement(pointer); + + @override + AgentRuntimeFactory create(Ref ref) { + return agentRuntimeFactory(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(AgentRuntimeFactory value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$agentRuntimeFactoryHash() => + r'e937512aa2ab3c32b8270bedac59ae179639377a'; diff --git a/lib/integrations/agent/agent_session_store.dart b/lib/integrations/agent/agent_session_store.dart new file mode 100644 index 0000000..93642c7 --- /dev/null +++ b/lib/integrations/agent/agent_session_store.dart @@ -0,0 +1,18 @@ +import 'dart:io'; + +import 'package:cutdex_agent/cutdex_agent.dart'; +import 'package:cutdex_agent/io.dart'; +import 'package:path/path.dart' as p; +import 'package:path_provider/path_provider.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +part 'agent_session_store.g.dart'; + +/// Owns the durable Agent checkpoint journal for the lifetime of the app. +@Riverpod(keepAlive: true) +FutureOr agentSessionStore(Ref ref) async { + final support = await getApplicationSupportDirectory(); + return FileSessionStore( + Directory(p.join(support.path, 'Cutdex', 'Agent', 'Sessions')), + ); +} diff --git a/lib/integrations/agent/agent_session_store.g.dart b/lib/integrations/agent/agent_session_store.g.dart new file mode 100644 index 0000000..412dbe2 --- /dev/null +++ b/lib/integrations/agent/agent_session_store.g.dart @@ -0,0 +1,53 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'agent_session_store.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning +/// Owns the durable Agent checkpoint journal for the lifetime of the app. + +@ProviderFor(agentSessionStore) +final agentSessionStoreProvider = AgentSessionStoreProvider._(); + +/// Owns the durable Agent checkpoint journal for the lifetime of the app. + +final class AgentSessionStoreProvider + extends + $FunctionalProvider< + AsyncValue, + SessionStore, + FutureOr + > + with $FutureModifier, $FutureProvider { + /// Owns the durable Agent checkpoint journal for the lifetime of the app. + AgentSessionStoreProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'agentSessionStoreProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$agentSessionStoreHash(); + + @$internal + @override + $FutureProviderElement $createElement( + $ProviderPointer pointer, + ) => $FutureProviderElement(pointer); + + @override + FutureOr create(Ref ref) { + return agentSessionStore(ref); + } +} + +String _$agentSessionStoreHash() => r'9a27b793eb8891e72040a71e9900d074ae069da4'; diff --git a/lib/integrations/agent/agent_settings.dart b/lib/integrations/agent/agent_settings.dart new file mode 100644 index 0000000..5bbff49 --- /dev/null +++ b/lib/integrations/agent/agent_settings.dart @@ -0,0 +1,80 @@ +import 'dart:async'; + +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import '../../settings/settings_write_queue.dart'; +import 'agent_models.dart'; +import 'agent_runtime.dart'; +import 'agent_runtime_factory.dart'; +import 'agent_settings_service.dart'; + +part 'agent_settings.g.dart'; + +/// Presentation-facing state holder. Persistence and credentials are delegated +/// to [AgentSettingsService]. +@Riverpod(keepAlive: true) +class AgentSettings extends _$AgentSettings { + late AgentSettingsService _service; + final _writes = SettingsWriteQueue(); + + @override + Future build() async { + _service = ref.watch(agentSettingsServiceProvider); + return _service.load(); + } + + Future setEnabled(bool enabled) => + _replace((current) => _service.setEnabled(current, enabled)); + + Future setProviderEnabled(String providerId, bool enabled) => _replace( + (current) => _service.setProviderEnabled(current, providerId, enabled), + ); + + Future selectModel(String providerId, String modelId) => + _replace((current) => _service.selectModel(current, providerId, modelId)); + + Future upsertProvider({ + String? id, + required String name, + required AgentApiType apiType, + required String baseUrl, + required List models, + String? apiKey, + bool clearApiKey = false, + }) => _replace( + (current) => _service.upsertProvider( + current, + id: id, + name: name, + apiType: apiType, + baseUrl: baseUrl, + models: models, + apiKey: apiKey, + clearApiKey: clearApiKey, + ), + ); + + Future deleteProvider(String providerId) => + _replace((current) => _service.deleteProvider(current, providerId)); + + Future _replace( + Future Function(AgentSettingsState) update, + ) { + return _writes.run(() async { + if (!ref.mounted) return; + final current = await future; + if (!ref.mounted) return; + final next = await update(current); + if (ref.mounted) state = AsyncData(next); + }); + } +} + +@Riverpod(keepAlive: true) +FutureOr agentRuntime(Ref ref) async { + final factory = ref.watch(agentRuntimeFactoryProvider); + final settings = ref.watch(agentSettingsProvider); + final value = settings.asData?.value; + if (value != null) return factory.create(value); + return factory.create(await ref.watch(agentSettingsProvider.future)); +} diff --git a/lib/integrations/agent/agent_settings.g.dart b/lib/integrations/agent/agent_settings.g.dart new file mode 100644 index 0000000..0eacaf1 --- /dev/null +++ b/lib/integrations/agent/agent_settings.g.dart @@ -0,0 +1,103 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'agent_settings.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning +/// Presentation-facing state holder. Persistence and credentials are delegated +/// to [AgentSettingsService]. + +@ProviderFor(AgentSettings) +final agentSettingsProvider = AgentSettingsProvider._(); + +/// Presentation-facing state holder. Persistence and credentials are delegated +/// to [AgentSettingsService]. +final class AgentSettingsProvider + extends $AsyncNotifierProvider { + /// Presentation-facing state holder. Persistence and credentials are delegated + /// to [AgentSettingsService]. + AgentSettingsProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'agentSettingsProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$agentSettingsHash(); + + @$internal + @override + AgentSettings create() => AgentSettings(); +} + +String _$agentSettingsHash() => r'484af184c2ccf373b8d0955d737ce64b5a085c54'; + +/// Presentation-facing state holder. Persistence and credentials are delegated +/// to [AgentSettingsService]. + +abstract class _$AgentSettings extends $AsyncNotifier { + FutureOr build(); + @$mustCallSuper + @override + WhenComplete runBuild() { + final ref = + this.ref as $Ref, AgentSettingsState>; + final element = + ref.element + as $ClassProviderElement< + AnyNotifier, AgentSettingsState>, + AsyncValue, + Object?, + Object? + >; + return element.handleCreate(ref, build); + } +} + +@ProviderFor(agentRuntime) +final agentRuntimeProvider = AgentRuntimeProvider._(); + +final class AgentRuntimeProvider + extends + $FunctionalProvider< + AsyncValue, + AgentRuntime?, + FutureOr + > + with $FutureModifier, $FutureProvider { + AgentRuntimeProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'agentRuntimeProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$agentRuntimeHash(); + + @$internal + @override + $FutureProviderElement $createElement( + $ProviderPointer pointer, + ) => $FutureProviderElement(pointer); + + @override + FutureOr create(Ref ref) { + return agentRuntime(ref); + } +} + +String _$agentRuntimeHash() => r'fa5447ca986924e6f1fe82ee20f6b7c3b41a96c4'; diff --git a/lib/integrations/agent/agent_settings_service.dart b/lib/integrations/agent/agent_settings_service.dart new file mode 100644 index 0000000..eae8fd9 --- /dev/null +++ b/lib/integrations/agent/agent_settings_service.dart @@ -0,0 +1,259 @@ +import 'package:riverpod_annotation/riverpod_annotation.dart'; +import 'package:uuid/uuid.dart'; + +import '../../persistence/app_settings_repositories.dart'; +import 'agent_credentials.dart'; +import 'agent_models.dart'; + +part 'agent_settings_service.g.dart'; + +@Riverpod(keepAlive: true) +AgentSettingsService agentSettingsService(Ref ref) { + return AgentSettingsService( + repository: ref.watch(agentSettingsRepositoryProvider), + credentials: ref.watch(agentCredentialStoreProvider), + ); +} + +/// Owns validation and consistency across settings storage and secure storage. +class AgentSettingsService { + const AgentSettingsService({ + required this._repository, + required this._credentials, + }); + + final AgentSettingsRepository _repository; + final AgentCredentialStore _credentials; + + Future load() => _repository.load(); + + Future setEnabled( + AgentSettingsState current, + bool enabled, + ) => _save(current, current.copyWith(enabled: enabled)); + + Future setProviderEnabled( + AgentSettingsState current, + String providerId, + bool enabled, + ) { + if (!current.providers.any((provider) => provider.id == providerId)) { + throw ArgumentError('Unknown Agent provider'); + } + final providers = [ + for (final provider in current.providers) + if (provider.id == providerId) + provider.copyWith(enabled: enabled) + else + provider, + ]; + return _save( + current, + _normalizeSelection( + current.copyWith( + providers: providers, + enabled: enabled ? true : current.enabled, + ), + ), + ); + } + + Future selectModel( + AgentSettingsState current, + String providerId, + String modelId, + ) async { + final provider = current.providers + .where((candidate) => candidate.id == providerId) + .firstOrNull; + if (provider == null || + !provider.enabled || + !provider.models.any((candidate) => candidate.id == modelId)) { + throw ArgumentError('Unknown Agent model selection'); + } + return _save( + current, + current.copyWith( + enabled: true, + selectedProviderId: providerId, + selectedModelId: modelId, + ), + ); + } + + Future upsertProvider( + AgentSettingsState current, { + String? id, + required String name, + required AgentApiType apiType, + required String baseUrl, + required List models, + String? apiKey, + bool clearApiKey = false, + }) async { + final providerId = id ?? const Uuid().v4(); + final existing = current.providers + .where((provider) => provider.id == providerId) + .firstOrNull; + _validateProvider(name, baseUrl, models, apiKey); + + var credentialId = existing?.credentialId; + var credentialWriteAttempted = false; + String? previousSecret; + String? credentialToDelete; + if (clearApiKey && credentialId != null) { + credentialToDelete = credentialId; + credentialId = null; + } else if (apiKey != null && apiKey.isNotEmpty) { + credentialId ??= 'cutdex-agent-provider-$providerId'; + if (existing?.credentialId != null) { + previousSecret = await _credentials.read(credentialId); + } + credentialWriteAttempted = true; + try { + await _credentials.write(credentialId, apiKey); + } catch (error, stackTrace) { + await _restoreCredential(credentialId, previousSecret); + Error.throwWithStackTrace(error, stackTrace); + } + } + + final normalizedModels = [ + for (final model in models) model.copyWith(id: model.id.trim()), + ]; + final provider = AgentProviderSettings( + id: providerId, + name: name.trim(), + apiType: apiType.name, + baseUrl: baseUrl.trim(), + credentialId: credentialId, + enabled: existing?.enabled ?? true, + models: List.unmodifiable(normalizedModels), + ); + final providers = [ + for (final candidate in current.providers) + if (candidate.id != providerId) candidate, + provider, + ]; + + try { + final saved = await _save( + current, + _normalizeSelection( + current.copyWith( + providers: providers, + enabled: (existing?.enabled ?? true) ? true : current.enabled, + ), + ), + ); + if (credentialToDelete != null) { + await _deleteOrphan(credentialToDelete); + } + return saved; + } catch (error, stackTrace) { + if (credentialWriteAttempted && credentialId != null) { + await _restoreCredential(credentialId, previousSecret); + } + Error.throwWithStackTrace(error, stackTrace); + } + } + + Future deleteProvider( + AgentSettingsState current, + String providerId, + ) async { + final removed = current.providers + .where((provider) => provider.id == providerId) + .firstOrNull; + if (removed == null) return current; + final providers = current.providers + .where((provider) => provider.id != providerId) + .toList(); + final saved = await _save( + current, + _normalizeSelection(current.copyWith(providers: providers)), + ); + if (removed.credentialId case final credentialId?) { + await _deleteOrphan(credentialId); + } + return saved; + } + + Future _save( + AgentSettingsState current, + AgentSettingsState next, + ) async { + final revised = next.copyWith(revision: current.revision + 1); + await _repository.save(revised); + return revised; + } + + Future _deleteOrphan(String credentialId) async { + try { + await _credentials.delete(credentialId); + } catch (_) { + // Metadata is authoritative. An inaccessible orphan can be cleaned later. + } + } + + Future _restoreCredential( + String credentialId, + String? previousSecret, + ) async { + try { + if (previousSecret == null) { + await _credentials.delete(credentialId); + } else { + await _credentials.write(credentialId, previousSecret); + } + } catch (_) { + // Preserve the original storage or repository failure for the caller. + } + } + + static AgentSettingsState _normalizeSelection(AgentSettingsState settings) { + final available = settings.providers.where( + (provider) => provider.enabled && provider.models.isNotEmpty, + ); + final selected = available + .where((provider) => provider.id == settings.selectedProviderId) + .firstOrNull; + final provider = selected ?? available.firstOrNull; + final model = + provider?.models + .where((model) => model.id == settings.selectedModelId) + .firstOrNull ?? + provider?.models.firstOrNull; + return settings.copyWith( + selectedProviderId: provider?.id, + selectedModelId: model?.id, + ); + } + + static void _validateProvider( + String name, + String baseUrl, + List models, + String? apiKey, + ) { + final uri = Uri.tryParse(baseUrl.trim()); + if (name.trim().isEmpty || + uri == null || + !uri.hasAuthority || + !['http', 'https'].contains(uri.scheme) || + uri.userInfo.isNotEmpty || + uri.hasQuery || + uri.hasFragment || + models.isEmpty || + models.any((model) => model.id.trim().isEmpty) || + models.map((model) => model.id.trim()).toSet().length != + models.length || + models.any( + (model) => !model.hasValidTokenBudget || !model.hasInstructionBudget, + ) || + (apiKey?.contains('\n') ?? false) || + (apiKey?.contains('\r') ?? false)) { + throw ArgumentError('Invalid Agent provider configuration'); + } + } +} diff --git a/lib/integrations/agent/agent_settings_service.g.dart b/lib/integrations/agent/agent_settings_service.g.dart new file mode 100644 index 0000000..7292436 --- /dev/null +++ b/lib/integrations/agent/agent_settings_service.g.dart @@ -0,0 +1,58 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'agent_settings_service.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(agentSettingsService) +final agentSettingsServiceProvider = AgentSettingsServiceProvider._(); + +final class AgentSettingsServiceProvider + extends + $FunctionalProvider< + AgentSettingsService, + AgentSettingsService, + AgentSettingsService + > + with $Provider { + AgentSettingsServiceProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'agentSettingsServiceProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$agentSettingsServiceHash(); + + @$internal + @override + $ProviderElement $createElement( + $ProviderPointer pointer, + ) => $ProviderElement(pointer); + + @override + AgentSettingsService create(Ref ref) { + return agentSettingsService(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(AgentSettingsService value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$agentSettingsServiceHash() => + r'76935437a9221e7add0706e92634ae8a21496fa2'; diff --git a/lib/integrations/agent/conversation_repository.dart b/lib/integrations/agent/conversation_repository.dart new file mode 100644 index 0000000..d3e06c9 --- /dev/null +++ b/lib/integrations/agent/conversation_repository.dart @@ -0,0 +1,389 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:cutdex_agent/cutdex_agent.dart'; +import 'package:cutdex_agent/io.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:path/path.dart' as p; +import 'package:path_provider/path_provider.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; +import 'package:uuid/uuid.dart'; + +import '../../persistence/app_settings_repositories.dart'; +import '../../errors/app_failure.dart'; + +part 'conversation_repository.g.dart'; +part 'conversation_repository.freezed.dart'; + +@Riverpod(keepAlive: true) +ConversationLocation conversationLocation(Ref ref) => ConversationLocation( + ref.watch(conversationLocationSettingsRepositoryProvider), +); + +@Riverpod(keepAlive: true) +FutureOr conversationRepository(Ref ref) async => + ConversationRepository( + await ref.watch(conversationLocationProvider).load(), + ); + +/// The location pointer is replaceable; the conversation files are not app data. +class ConversationLocation { + ConversationLocation( + this._settings, { + Future Function()? documentsDirectory, + }) : _documentsDirectory = + documentsDirectory ?? getApplicationDocumentsDirectory; + + final ConversationLocationSettingsRepository _settings; + final Future Function() _documentsDirectory; + + Future load() async { + final configured = await _settings.load(); + if (configured != null) { + final root = Directory(configured); + if (!root.isAbsolute || !await root.exists()) { + throw AppException( + AppErrorCode.agentLocationUnavailable, + diagnostic: root.path, + ); + } + return root; + } + final documents = await _documentsDirectory(); + return Directory(p.join(documents.path, 'Cutdex', 'Conversations')); + } + + Future useExisting(Directory root) async { + if (!root.isAbsolute || !await root.exists()) { + throw AppException( + AppErrorCode.agentLocationUnavailable, + diagnostic: root.path, + ); + } + if (!await ConversationRepository(root).verify()) { + throw const FormatException('Invalid conversation directory'); + } + await _settings.save(root.path); + } + + Future relocate(Directory source, Directory target) async { + if (!target.isAbsolute || await target.exists()) { + throw const FileSystemException( + 'Destination must be an unused directory', + ); + } + final sourcePath = p.normalize(source.absolute.path); + final targetPath = p.normalize(target.absolute.path); + if (targetPath == sourcePath || p.isWithin(sourcePath, targetPath)) { + throw const FileSystemException( + 'Destination cannot be inside the current conversations directory', + ); + } + final staging = await target.parent.createTemp('.cutdex-conversations-'); + try { + await _copyDirectory(source, staging); + if (!(await ConversationRepository(staging).verify())) { + throw const FormatException('Copied conversations failed validation'); + } + await staging.rename(target.path); + await _settings.save(target.path); + } finally { + if (await staging.exists()) await staging.delete(recursive: true); + } + } + + static Future _copyDirectory(Directory source, Directory target) async { + if (!await source.exists()) return; + await for (final entry in source.list(followLinks: false)) { + final destination = p.join(target.path, p.basename(entry.path)); + if (entry is Directory) { + final child = await Directory(destination).create(); + await _copyDirectory(entry, child); + } else if (entry is File) { + await entry.copy(destination); + } else { + throw const FileSystemException('Unsupported conversation entry'); + } + } + } +} + +@freezed +abstract class ConversationMetadata with _$ConversationMetadata { + const factory ConversationMetadata({ + required String id, + required String projectId, + required String title, + required DateTime createdAt, + required DateTime updatedAt, + required String providerId, + required String modelId, + required String timelineId, + @JsonKey(required: true, disallowNullValue: true) required bool pending, + @JsonKey(required: true, disallowNullValue: true) + required List responseDurationsMs, + }) = _ConversationMetadata; + + factory ConversationMetadata.fromJson(Map json) => + _$ConversationMetadataFromJson(json); +} + +/// Owns project-to-conversation membership; the Agent owns journal contents. +class ConversationRepository { + ConversationRepository(this.root); + + final Directory root; + static const _uuid = Uuid(); + final Set _pendingInProcess = {}; + + String _projectName(String id) => + base64Url.encode(utf8.encode(id)).replaceAll('=', ''); + + Directory _project(String id, {bool trash = false}) => + Directory(p.joinAll([root.path, if (trash) 'Trash', _projectName(id)])); + + Directory directory( + String projectId, + String conversationId, { + bool trash = false, + }) { + if (!Uuid.isValidUUID(fromString: conversationId)) { + throw ArgumentError.value(conversationId, 'conversationId'); + } + return Directory( + p.join(_project(projectId, trash: trash).path, conversationId), + ); + } + + FileSessionStore store(ConversationMetadata conversation) => + FileSessionStore(directory(conversation.projectId, conversation.id)); + + Future begin({ + required String projectId, + required String timelineId, + required String providerId, + required String modelId, + required String title, + }) async { + final now = DateTime.now().toUtc(); + final item = ConversationMetadata( + id: _uuid.v4(), + projectId: projectId, + title: title.trim(), + createdAt: now, + updatedAt: now, + providerId: providerId, + modelId: modelId, + timelineId: timelineId, + pending: true, + responseDurationsMs: const [], + ); + await directory(projectId, item.id).create(recursive: true); + await _write(item); + _pendingInProcess.add(item.id); + return item; + } + + Future publish(ConversationMetadata item) async { + final snapshot = await store(item).read(item.id); + if (snapshot == null || + !snapshot.history.any((message) => message.role == MessageRole.user)) { + throw StateError('Conversation has no saved user message'); + } + final published = item.copyWith( + pending: false, + updatedAt: DateTime.now().toUtc(), + ); + await _write(published); + _pendingInProcess.remove(item.id); + return published; + } + + Future read( + String projectId, + String id, { + bool trash = false, + }) async { + final file = File( + p.join(directory(projectId, id, trash: trash).path, 'metadata.json'), + ); + if (!await file.exists()) return null; + final json = (jsonDecode(await file.readAsString()) as Map) + .cast(); + final item = ConversationMetadata.fromJson(json); + if (item.id != id || item.projectId != projectId) { + throw const FormatException('Conversation identity mismatch'); + } + return item; + } + + Future> list( + String projectId, { + bool trash = false, + }) async { + final parent = _project(projectId, trash: trash); + if (!await parent.exists()) return []; + final result = []; + await for (final entry in parent.list(followLinks: false)) { + if (entry is! Directory) continue; + try { + final item = await read( + projectId, + p.basename(entry.path), + trash: trash, + ); + if (item == null) { + continue; + } + if (item.pending && !trash) { + if (_pendingInProcess.contains(item.id)) continue; + final snapshot = await store(item).read(item.id); + if (snapshot?.history.any( + (message) => message.role == MessageRole.user, + ) == + true) { + result.add(await publish(item)); + } else { + await entry.delete(recursive: true); + } + } else { + result.add(item); + } + } on FormatException { + // One corrupt metadata file must not hide the remaining conversations. + } on BadKeyException { + // Entries outside the current metadata contract stay untouched. + } on TypeError { + // Malformed field types are isolated to the affected conversation. + } on FileSystemException { + // A damaged or inaccessible entry does not hide its siblings. + } on ArgumentError { + // Ignore unrelated folders without treating them as conversations. + } + } + result.sort((a, b) => b.updatedAt.compareTo(a.updatedAt)); + return result; + } + + Future selected(String projectId) async { + final state = File(p.join(_project(projectId).path, 'state.json')); + try { + final json = (jsonDecode(await state.readAsString()) as Map) + .cast(); + if (json['version'] != 1) { + throw const FormatException('Unsupported conversation state'); + } + final id = json['conversationId'] as String?; + if (id != null && await read(projectId, id) != null) return id; + } on FileSystemException { + // Missing selection is recovered from the conversation list. + } on FormatException { + // The selection is disposable view state. + } on BadKeyException { + // Select only conversations that satisfy the current metadata contract. + } on TypeError { + // A malformed selection is disposable view state. + } on ArgumentError { + // An invalid UUID is disposable view state. + } + return (await list(projectId)).firstOrNull?.id; + } + + Future select(String projectId, String? id) async { + if (id != null && await read(projectId, id) == null) { + throw ArgumentError.value(id, 'conversationId'); + } + final parent = _project(projectId); + await parent.create(recursive: true); + await _writeJson(File(p.join(parent.path, 'state.json')), { + 'version': 1, + 'conversationId': id, + }); + } + + Future update(ConversationMetadata item) async { + if (await read(item.projectId, item.id) == null) { + throw StateError('Conversation no longer exists'); + } + final updated = item.copyWith(updatedAt: DateTime.now().toUtc()); + await _write(updated); + return updated; + } + + Future trash(String projectId, String id) async { + final source = directory(projectId, id); + if (!await source.exists()) return; + final wasSelected = await selected(projectId) == id; + final destination = directory(projectId, id, trash: true); + await destination.parent.create(recursive: true); + await source.rename(destination.path); + if (wasSelected) await select(projectId, null); + } + + Future restore(String projectId, String id) async { + final source = directory(projectId, id, trash: true); + if (!await source.exists()) throw ArgumentError.value(id, 'conversationId'); + final target = directory(projectId, id); + if (await target.exists()) throw StateError('Conversation already exists'); + await target.parent.create(recursive: true); + await source.rename(target.path); + } + + Future deletePermanently(String projectId, String id) async { + if (await selected(projectId) == id) await select(projectId, null); + for (final trash in [false, true]) { + final target = directory(projectId, id, trash: trash); + if (await target.exists()) await target.delete(recursive: true); + } + } + + Future verify() async { + if (!await root.exists()) return true; + if (!await _verifyProjects(root)) return false; + final trash = Directory(p.join(root.path, 'Trash')); + if (await trash.exists() && !await _verifyProjects(trash)) return false; + return true; + } + + Future _verifyProjects(Directory parent) async { + await for (final project in parent.list(followLinks: false)) { + if (project is! Directory || p.basename(project.path) == 'Trash') { + continue; + } + await for (final entry in project.list(followLinks: false)) { + if (entry is! Directory) continue; + try { + final file = File(p.join(entry.path, 'metadata.json')); + final json = (jsonDecode(await file.readAsString()) as Map) + .cast(); + final item = ConversationMetadata.fromJson(json); + if (item.id != p.basename(entry.path) || + _projectName(item.projectId) != p.basename(project.path)) { + return false; + } + await FileSessionStore(entry).verify(item.id); + } catch (_) { + return false; + } + } + } + return true; + } + + Future _write(ConversationMetadata item) => _writeJson( + File(p.join(directory(item.projectId, item.id).path, 'metadata.json')), + item.toJson(), + ); + + Future _writeJson(File target, Map json) async { + await target.parent.create(recursive: true); + final temp = File('${target.path}.${_uuid.v4()}.tmp'); + try { + await temp.writeAsString(jsonEncode(json), flush: true); + await temp.rename(target.path); + } finally { + if (await temp.exists()) await temp.delete(); + } + } +} diff --git a/lib/integrations/agent/conversation_repository.freezed.dart b/lib/integrations/agent/conversation_repository.freezed.dart new file mode 100644 index 0000000..e8b3d95 --- /dev/null +++ b/lib/integrations/agent/conversation_repository.freezed.dart @@ -0,0 +1,626 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'conversation_repository.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +T _$identity(T value) => value; + +/// @nodoc +mixin _$ConversationMetadata { + String get id; + String get projectId; + String get title; + DateTime get createdAt; + DateTime get updatedAt; + String get providerId; + String get modelId; + String get timelineId; + @JsonKey(required: true, disallowNullValue: true) + bool get pending; + @JsonKey(required: true, disallowNullValue: true) + List get responseDurationsMs; + + /// Create a copy of ConversationMetadata + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $ConversationMetadataCopyWith get copyWith => + _$ConversationMetadataCopyWithImpl( + this as ConversationMetadata, + _$identity, + ); + + /// Serializes this ConversationMetadata to a JSON map. + Map toJson(); + + @override + bool operator ==(Object other) { + final _this = this as ConversationMetadata; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is ConversationMetadata && + (identical(other.id, _this.id) || other.id == _this.id) && + (identical(other.projectId, _this.projectId) || + other.projectId == _this.projectId) && + (identical(other.title, _this.title) || + other.title == _this.title) && + (identical(other.createdAt, _this.createdAt) || + other.createdAt == _this.createdAt) && + (identical(other.updatedAt, _this.updatedAt) || + other.updatedAt == _this.updatedAt) && + (identical(other.providerId, _this.providerId) || + other.providerId == _this.providerId) && + (identical(other.modelId, _this.modelId) || + other.modelId == _this.modelId) && + (identical(other.timelineId, _this.timelineId) || + other.timelineId == _this.timelineId) && + (identical(other.pending, _this.pending) || + other.pending == _this.pending) && + const DeepCollectionEquality().equals( + other.responseDurationsMs, + _this.responseDurationsMs, + )); + } + + @JsonKey(includeFromJson: false, includeToJson: false) + @override + int get hashCode { + final _this = this as ConversationMetadata; + return Object.hash( + runtimeType, + _this.id, + _this.projectId, + _this.title, + _this.createdAt, + _this.updatedAt, + _this.providerId, + _this.modelId, + _this.timelineId, + _this.pending, + const DeepCollectionEquality().hash(_this.responseDurationsMs), + ); + } + + @override + String toString() { + final _this = this as ConversationMetadata; + return 'ConversationMetadata(id: ${_this.id}, projectId: ${_this.projectId}, title: ${_this.title}, createdAt: ${_this.createdAt}, updatedAt: ${_this.updatedAt}, providerId: ${_this.providerId}, modelId: ${_this.modelId}, timelineId: ${_this.timelineId}, pending: ${_this.pending}, responseDurationsMs: ${_this.responseDurationsMs})'; + } +} + +/// @nodoc +abstract mixin class $ConversationMetadataCopyWith<$Res> { + factory $ConversationMetadataCopyWith( + ConversationMetadata value, + $Res Function(ConversationMetadata) _then, + ) = _$ConversationMetadataCopyWithImpl; + @useResult + $Res call({ + String id, + String projectId, + String title, + DateTime createdAt, + DateTime updatedAt, + String providerId, + String modelId, + String timelineId, + @JsonKey(required: true, disallowNullValue: true) bool pending, + @JsonKey(required: true, disallowNullValue: true) + List responseDurationsMs, + }); +} + +/// @nodoc +class _$ConversationMetadataCopyWithImpl<$Res> + implements $ConversationMetadataCopyWith<$Res> { + _$ConversationMetadataCopyWithImpl(this._self, this._then); + + final ConversationMetadata _self; + final $Res Function(ConversationMetadata) _then; + + /// Create a copy of ConversationMetadata + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + Object? projectId = null, + Object? title = null, + Object? createdAt = null, + Object? updatedAt = null, + Object? providerId = null, + Object? modelId = null, + Object? timelineId = null, + Object? pending = null, + Object? responseDurationsMs = null, + }) { + return _then( + ConversationMetadata( + id: null == id + ? _self.id + : id // ignore: cast_nullable_to_non_nullable + as String, + projectId: null == projectId + ? _self.projectId + : projectId // ignore: cast_nullable_to_non_nullable + as String, + title: null == title + ? _self.title + : title // ignore: cast_nullable_to_non_nullable + as String, + createdAt: null == createdAt + ? _self.createdAt + : createdAt // ignore: cast_nullable_to_non_nullable + as DateTime, + updatedAt: null == updatedAt + ? _self.updatedAt + : updatedAt // ignore: cast_nullable_to_non_nullable + as DateTime, + providerId: null == providerId + ? _self.providerId + : providerId // ignore: cast_nullable_to_non_nullable + as String, + modelId: null == modelId + ? _self.modelId + : modelId // ignore: cast_nullable_to_non_nullable + as String, + timelineId: null == timelineId + ? _self.timelineId + : timelineId // ignore: cast_nullable_to_non_nullable + as String, + pending: null == pending + ? _self.pending + : pending // ignore: cast_nullable_to_non_nullable + as bool, + responseDurationsMs: null == responseDurationsMs + ? _self.responseDurationsMs + : responseDurationsMs // ignore: cast_nullable_to_non_nullable + as List, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [ConversationMetadata]. +extension ConversationMetadataPatterns on ConversationMetadata { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_ConversationMetadata value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ConversationMetadata() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_ConversationMetadata value) $default, + ) { + final _that = this; + switch (_that) { + case _ConversationMetadata(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_ConversationMetadata value)? $default, + ) { + final _that = this; + switch (_that) { + case _ConversationMetadata() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + String id, + String projectId, + String title, + DateTime createdAt, + DateTime updatedAt, + String providerId, + String modelId, + String timelineId, + @JsonKey(required: true, disallowNullValue: true) bool pending, + @JsonKey(required: true, disallowNullValue: true) + List responseDurationsMs, + )? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ConversationMetadata() when $default != null: + return $default( + _that.id, + _that.projectId, + _that.title, + _that.createdAt, + _that.updatedAt, + _that.providerId, + _that.modelId, + _that.timelineId, + _that.pending, + _that.responseDurationsMs, + ); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function( + String id, + String projectId, + String title, + DateTime createdAt, + DateTime updatedAt, + String providerId, + String modelId, + String timelineId, + @JsonKey(required: true, disallowNullValue: true) bool pending, + @JsonKey(required: true, disallowNullValue: true) + List responseDurationsMs, + ) + $default, + ) { + final _that = this; + switch (_that) { + case _ConversationMetadata(): + return $default( + _that.id, + _that.projectId, + _that.title, + _that.createdAt, + _that.updatedAt, + _that.providerId, + _that.modelId, + _that.timelineId, + _that.pending, + _that.responseDurationsMs, + ); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + String id, + String projectId, + String title, + DateTime createdAt, + DateTime updatedAt, + String providerId, + String modelId, + String timelineId, + @JsonKey(required: true, disallowNullValue: true) bool pending, + @JsonKey(required: true, disallowNullValue: true) + List responseDurationsMs, + )? + $default, + ) { + final _that = this; + switch (_that) { + case _ConversationMetadata() when $default != null: + return $default( + _that.id, + _that.projectId, + _that.title, + _that.createdAt, + _that.updatedAt, + _that.providerId, + _that.modelId, + _that.timelineId, + _that.pending, + _that.responseDurationsMs, + ); + case _: + return null; + } + } +} + +/// @nodoc +@JsonSerializable() +class _ConversationMetadata implements ConversationMetadata { + const _ConversationMetadata({ + required this.id, + required this.projectId, + required this.title, + required this.createdAt, + required this.updatedAt, + required this.providerId, + required this.modelId, + required this.timelineId, + @JsonKey(required: true, disallowNullValue: true) required this.pending, + @JsonKey(required: true, disallowNullValue: true) + required List responseDurationsMs, + }) : _responseDurationsMs = responseDurationsMs; + factory _ConversationMetadata.fromJson(Map json) => + _$ConversationMetadataFromJson(json); + + @override + final String id; + @override + final String projectId; + @override + final String title; + @override + final DateTime createdAt; + @override + final DateTime updatedAt; + @override + final String providerId; + @override + final String modelId; + @override + final String timelineId; + @override + @JsonKey(required: true, disallowNullValue: true) + final bool pending; + final List _responseDurationsMs; + @override + @JsonKey(required: true, disallowNullValue: true) + List get responseDurationsMs { + if (_responseDurationsMs is EqualUnmodifiableListView) + return _responseDurationsMs; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_responseDurationsMs); + } + + /// Create a copy of ConversationMetadata + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$ConversationMetadataCopyWith<_ConversationMetadata> get copyWith => + __$ConversationMetadataCopyWithImpl<_ConversationMetadata>( + this, + _$identity, + ); + + @override + Map toJson() { + return _$ConversationMetadataToJson(this); + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _ConversationMetadata && + (identical(other.id, id) || other.id == id) && + (identical(other.projectId, projectId) || + other.projectId == projectId) && + (identical(other.title, title) || other.title == title) && + (identical(other.createdAt, createdAt) || + other.createdAt == createdAt) && + (identical(other.updatedAt, updatedAt) || + other.updatedAt == updatedAt) && + (identical(other.providerId, providerId) || + other.providerId == providerId) && + (identical(other.modelId, modelId) || other.modelId == modelId) && + (identical(other.timelineId, timelineId) || + other.timelineId == timelineId) && + (identical(other.pending, pending) || other.pending == pending) && + const DeepCollectionEquality().equals( + other.responseDurationsMs, + _responseDurationsMs, + )); + } + + @JsonKey(includeFromJson: false, includeToJson: false) + @override + int get hashCode { + return Object.hash( + runtimeType, + id, + projectId, + title, + createdAt, + updatedAt, + providerId, + modelId, + timelineId, + pending, + const DeepCollectionEquality().hash(_responseDurationsMs), + ); + } + + @override + String toString() { + return 'ConversationMetadata(id: $id, projectId: $projectId, title: $title, createdAt: $createdAt, updatedAt: $updatedAt, providerId: $providerId, modelId: $modelId, timelineId: $timelineId, pending: $pending, responseDurationsMs: $responseDurationsMs)'; + } +} + +/// @nodoc +abstract mixin class _$ConversationMetadataCopyWith<$Res> + implements $ConversationMetadataCopyWith<$Res> { + factory _$ConversationMetadataCopyWith( + _ConversationMetadata value, + $Res Function(_ConversationMetadata) _then, + ) = __$ConversationMetadataCopyWithImpl; + @override + @useResult + $Res call({ + String id, + String projectId, + String title, + DateTime createdAt, + DateTime updatedAt, + String providerId, + String modelId, + String timelineId, + @JsonKey(required: true, disallowNullValue: true) bool pending, + @JsonKey(required: true, disallowNullValue: true) + List responseDurationsMs, + }); +} + +/// @nodoc +class __$ConversationMetadataCopyWithImpl<$Res> + implements _$ConversationMetadataCopyWith<$Res> { + __$ConversationMetadataCopyWithImpl(this._self, this._then); + + final _ConversationMetadata _self; + final $Res Function(_ConversationMetadata) _then; + + /// Create a copy of ConversationMetadata + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? id = null, + Object? projectId = null, + Object? title = null, + Object? createdAt = null, + Object? updatedAt = null, + Object? providerId = null, + Object? modelId = null, + Object? timelineId = null, + Object? pending = null, + Object? responseDurationsMs = null, + }) { + return _then( + _ConversationMetadata( + id: null == id + ? _self.id + : id // ignore: cast_nullable_to_non_nullable + as String, + projectId: null == projectId + ? _self.projectId + : projectId // ignore: cast_nullable_to_non_nullable + as String, + title: null == title + ? _self.title + : title // ignore: cast_nullable_to_non_nullable + as String, + createdAt: null == createdAt + ? _self.createdAt + : createdAt // ignore: cast_nullable_to_non_nullable + as DateTime, + updatedAt: null == updatedAt + ? _self.updatedAt + : updatedAt // ignore: cast_nullable_to_non_nullable + as DateTime, + providerId: null == providerId + ? _self.providerId + : providerId // ignore: cast_nullable_to_non_nullable + as String, + modelId: null == modelId + ? _self.modelId + : modelId // ignore: cast_nullable_to_non_nullable + as String, + timelineId: null == timelineId + ? _self.timelineId + : timelineId // ignore: cast_nullable_to_non_nullable + as String, + pending: null == pending + ? _self.pending + : pending // ignore: cast_nullable_to_non_nullable + as bool, + responseDurationsMs: null == responseDurationsMs + ? _self._responseDurationsMs + : responseDurationsMs // ignore: cast_nullable_to_non_nullable + as List, + ), + ); + } +} diff --git a/lib/integrations/agent/conversation_repository.g.dart b/lib/integrations/agent/conversation_repository.g.dart new file mode 100644 index 0000000..085c7ce --- /dev/null +++ b/lib/integrations/agent/conversation_repository.g.dart @@ -0,0 +1,143 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'conversation_repository.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +_ConversationMetadata _$ConversationMetadataFromJson( + Map json, +) { + $checkKeys( + json, + requiredKeys: const ['pending', 'responseDurationsMs'], + disallowNullValues: const ['pending', 'responseDurationsMs'], + ); + return _ConversationMetadata( + id: json['id'] as String, + projectId: json['projectId'] as String, + title: json['title'] as String, + createdAt: DateTime.parse(json['createdAt'] as String), + updatedAt: DateTime.parse(json['updatedAt'] as String), + providerId: json['providerId'] as String, + modelId: json['modelId'] as String, + timelineId: json['timelineId'] as String, + pending: json['pending'] as bool, + responseDurationsMs: (json['responseDurationsMs'] as List) + .map((e) => (e as num?)?.toInt()) + .toList(), + ); +} + +Map _$ConversationMetadataToJson( + _ConversationMetadata instance, +) => { + 'id': instance.id, + 'projectId': instance.projectId, + 'title': instance.title, + 'createdAt': instance.createdAt.toIso8601String(), + 'updatedAt': instance.updatedAt.toIso8601String(), + 'providerId': instance.providerId, + 'modelId': instance.modelId, + 'timelineId': instance.timelineId, + 'pending': instance.pending, + 'responseDurationsMs': instance.responseDurationsMs, +}; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(conversationLocation) +final conversationLocationProvider = ConversationLocationProvider._(); + +final class ConversationLocationProvider + extends + $FunctionalProvider< + ConversationLocation, + ConversationLocation, + ConversationLocation + > + with $Provider { + ConversationLocationProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'conversationLocationProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$conversationLocationHash(); + + @$internal + @override + $ProviderElement $createElement( + $ProviderPointer pointer, + ) => $ProviderElement(pointer); + + @override + ConversationLocation create(Ref ref) { + return conversationLocation(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(ConversationLocation value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$conversationLocationHash() => + r'f087694520af1c0f37a5311284768415a95b3811'; + +@ProviderFor(conversationRepository) +final conversationRepositoryProvider = ConversationRepositoryProvider._(); + +final class ConversationRepositoryProvider + extends + $FunctionalProvider< + AsyncValue, + ConversationRepository, + FutureOr + > + with + $FutureModifier, + $FutureProvider { + ConversationRepositoryProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'conversationRepositoryProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$conversationRepositoryHash(); + + @$internal + @override + $FutureProviderElement $createElement( + $ProviderPointer pointer, + ) => $FutureProviderElement(pointer); + + @override + FutureOr create(Ref ref) { + return conversationRepository(ref); + } +} + +String _$conversationRepositoryHash() => + r'674fa602f63c49495d4c9c6773dd98ebd0bf30b2'; diff --git a/lib/integrations/agent/editor_acceptance.dart b/lib/integrations/agent/editor_acceptance.dart new file mode 100644 index 0000000..df53233 --- /dev/null +++ b/lib/integrations/agent/editor_acceptance.dart @@ -0,0 +1,448 @@ +import 'dart:convert'; + +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_agent/cutdex_agent.dart'; + +/// Deterministic, read-only acceptance for explicitly declared editor outcomes. +/// Contracts live in successful tool results, so compaction and restart cannot +/// erase or silently weaken them. Semantic quality is deliberately out of scope. +class EditorAcceptance { + EditorAcceptance(Iterable tools) + : _tools = {for (final tool in tools) tool.name: tool}; + + final Map _tools; + static const _registration = { + 'editor_expect_clips', + 'editor_expect_translation', + 'timeline_planBeatCuts', + }; + static const _coveredWrites = {'clip_setAudio', 'caption_addTranslations'}; + + List get tools => [ + AgentTool( + name: 'editor_expect_clips', + description: 'Before changing clips, declare expected final names and static parameter default values. Captures exact clip count, ordering, timing and connections to preserve. Every declared clip is checked from CURRENT project state before completion. Register all requested targets, not only those already edited. Re-registering cannot weaken an earlier contract in the same user task. Animated keyframe values are not checked by this tool.', + parameters: { + 'type': 'object', + 'properties': { + 'workspaceId': {'type': 'string'}, + 'preserveLayout': { + 'type': 'boolean', + 'description': 'Default true; false only when the user also requests layout or timing changes.', + }, + 'clips': { + 'type': 'array', + 'minItems': 1, + 'maxItems': 200, + 'items': { + 'type': 'object', + 'additionalProperties': false, + 'properties': { + 'clipId': {'type': 'string'}, + 'name': {'type': 'string'}, + 'parameters': { + 'type': 'array', + 'maxItems': 32, + 'items': { + 'type': 'object', + 'additionalProperties': false, + 'properties': { + 'parameterId': {'type': 'string'}, + 'value': {'type': 'number'}, + }, + 'required': ['parameterId', 'value'], + }, + }, + }, + 'required': ['clipId'], + }, + }, + }, + 'required': ['workspaceId', 'clips'], + 'additionalProperties': false, + }, + validate: _validateClips, + execute: (call, context) async { + final args = call.arguments; + final view = await _read('timeline_query', { + 'workspaceId': args['workspaceId'], + 'includeParameters': false, + }, context); + final ids = (view.data['clips'] as List) + .map((c) => (c as Map)['clipId']) + .toSet(); + final contracts = []; + for (final row in args['clips'] as List) { + if (!ids.contains(row['clipId'])) { + return ToolResult('Unknown clipId ${row['clipId']}', isError: true); + } + contracts.add({ + 'kind': 'clip', + 'workspaceId': args['workspaceId'], + 'expected': row, + if (args['preserveLayout'] != false) + 'layoutHash': editorEvidenceHash(editorLayout(view.data)), + }); + } + return ToolResult( + 'Registered deterministic clip outcomes; semantic quality is not certified', + data: {'contracts': contracts, 'version': view.version}, + ); + }, + // A started registration with no durable result must not recapture a new + // baseline after concurrent edits. The normal unknown-outcome path applies. + ), + AgentTool( + name: 'editor_expect_translation', + description: 'After creating the new target track and BEFORE writing translations, register sourceRoleId and targetRoleId. Reads all source pages at one version. Completion checks source unchanged, track identities/count unchanged, target cue count and timing multiset equal source, unique target IDs and nonempty text. This does NOT certify translation meaning or fluency; semantic concerns are review suggestions, never automatic rewrite instructions.', + parameters: { + 'type': 'object', + 'additionalProperties': false, + 'properties': { + for (final key in ['workspaceId', 'sourceRoleId', 'targetRoleId']) + key: {'type': 'string'}, + }, + 'required': ['workspaceId', 'sourceRoleId', 'targetRoleId'], + }, + validate: (a) => + [ + 'workspaceId', + 'sourceRoleId', + 'targetRoleId', + ].any((k) => a[k] is! String || (a[k] as String).isEmpty) || + a['sourceRoleId'] == a['targetRoleId'] + ? 'Supply distinct source and target tracks and a workspace' + : null, + execute: (call, context) async { + final a = call.arguments; + final tracks = await _read('caption_list', { + 'workspaceId': a['workspaceId'], + }, context); + final ids = editorTrackIds(tracks.data); + if (!ids.contains(a['sourceRoleId']) || + !ids.contains(a['targetRoleId'])) { + return ToolResult( + 'Source or target track does not exist', + isError: true, + ); + } + final source = await _cues( + a['workspaceId'] as String, + a['sourceRoleId'] as String, + context, + tracks.version, + ); + return ToolResult( + 'Registered translation structure; semantic quality remains unverified', + data: { + 'contracts': [ + { + 'kind': 'translation', + ...a, + 'trackIds': ids, + 'sourceHash': editorEvidenceHash(source), + 'sourceCount': source.length, + }, + ], + 'version': tracks.version, + }, + ); + }, + ), + ]; + + String? _validateClips(Map a) { + if (a['workspaceId'] is! String || + (a['workspaceId'] as String).isEmpty || + a['clips'] is! List || + (a['clips'] as List).isEmpty || + (a['clips'] as List).length > 200 || + (a['preserveLayout'] != null && a['preserveLayout'] is! bool)) { + return 'Invalid clip expectations'; + } + final ids = {}; + for (final row in a['clips'] as List) { + if (row is! Map || + row['clipId'] is! String || + !ids.add(row['clipId'] as String) || + (row['name'] != null && row['name'] is! String)) { + return 'Supply unique clip IDs and valid names'; + } + final parameters = row['parameters']; + if (parameters != null && parameters is! List) { + return 'parameters must be an array'; + } + if (row['name'] == null && + (parameters == null || (parameters as List).isEmpty)) { + return 'Declare a name or parameter value'; + } + final params = {}; + for (final p in parameters as List? ?? const []) { + if (p is! Map || + p['parameterId'] is! String || + !params.add(p['parameterId'] as String) || + p['value'] is! num || + !(p['value'] as num).isFinite) { + return 'Supply unique parameter IDs and finite values'; + } + } + } + return null; + } + + Future check( + SessionSnapshot snapshot, + CancellationToken token, + ) async { + final calls = {}; + final contracts = >{}; + final issues = >[]; + final writes = []; + for (final message in snapshot.history.skip(snapshot.runStart)) { + for (final call in message.calls) { + calls[call.id] = call; + } + if (message.role != MessageRole.tool || message.isError) continue; + final call = calls[message.callId]; + if (call == null) continue; + if (_coveredWrites.contains(call.name)) writes.add(call); + if (!_registration.contains(call.name)) continue; + final result = jsonDecode(message.text) as Map; + final payload = result['data'] as Map; + final List registrations; + if (call.name == 'timeline_planBeatCuts') { + final plan = payload['data'] as Map; + if (plan['requireCuts'] != true) continue; + registrations = [ + { + ...(plan['contract'] as Map), + 'workspaceId': call.arguments['workspaceId'], + }, + ]; + } else { + registrations = payload['contracts'] as List; + } + for (final raw in registrations) { + final c = (raw as Map).cast(); + final key = + '${c['workspaceId']}:${c['kind']}:${c['kind'] == 'clip' ? (c['expected'] as Map)['clipId'] : c['targetRoleId']}'; + if (contracts.containsKey(key) && + editorEvidenceHash(contracts[key]) != editorEvidenceHash(c)) { + issues.add({ + 'kind': 'contractChanged', + 'target': key, + 'reason': 'Earlier acceptance criteria cannot be replaced within this task.', + }); + } else { + contracts[key] = c; + } + } + } + // Never infer a complete user goal from writes alone. Require explicit + // expectations for supported editing operations and disclose coverage. + for (final call in writes) { + final workspace = call.arguments['workspaceId']; + final covered = contracts.values.any((c) { + if (c['workspaceId'] != workspace) return false; + if (call.name == 'clip_setAudio') { + if (c['kind'] != 'clip') return false; + final expected = c['expected'] as Map; + if (expected['clipId'] != call.arguments['clipId']) return false; + final parameters = (expected['parameters'] as List? ?? const []) + .map((p) => (p as Map)['parameterId']) + .toSet(); + return (!call.arguments.containsKey('db') || + parameters.contains('cutdex.audio.gainDb')) && + (!call.arguments.containsKey('muted') || + parameters.contains('cutdex.audio.mute')); + } + return c['kind'] == 'translation' && + c['targetRoleId'] == call.arguments['roleId']; + }); + if (!covered) { + issues.add({ + 'kind': 'missingExpectation', + 'tool': call.name, + 'arguments': call.arguments, + 'reason': 'Declare the original requested outcomes with editor_expect_clips or editor_expect_translation. Include every requested target, not just successful writes.', + }); + } + } + if (issues.isNotEmpty) { + return ToolResult( + 'Acceptance requirements are unresolved', + isError: true, + data: {'issues': issues}, + ); + } + final context = ToolContext( + sessionId: snapshot.id, + runId: snapshot.runId!, + operationId: + 'verification:${snapshot.id}:${snapshot.runId}:${snapshot.turns}', + cancellation: token, + onProgress: (_) {}, + ); + final versions = {}; + final views = {}; + try { + for (final c in contracts.values) { + token.throwIfCancelled(); + final workspace = c['workspaceId'] as String; + final view = views[workspace] ??= await _read('timeline_query', { + 'workspaceId': workspace, + }, context); + versions[workspace] = view.version; + if (view.data['saveState'] != 'saved') { + issues.add({ + 'kind': 'saveState', + 'workspaceId': workspace, + 'actual': view.data['saveState'], + 'expected': 'saved', + 'action': 'Use project_save, then recheck.', + }); + } + Map? tracks; + List> source = const [], target = const []; + final expectation = EditorExpectation.fromJson(c); + if (expectation.needsCaptions) { + final page = await _read('caption_list', { + 'workspaceId': workspace, + }, context); + _sameVersion(page.version, view.version); + tracks = page.data; + source = await _cues( + workspace, + c['sourceRoleId'] as String, + context, + view.version, + ); + target = await _cues( + workspace, + c['targetRoleId'] as String, + context, + view.version, + ); + } + issues.addAll( + verifyEditorOutcome( + expectation, + EditorOutcomeEvidence( + timeline: view.data, + tracks: tracks, + sourceCues: source, + targetCues: target, + ), + ), + ); + } + // No receipt is reused as current evidence. Catch edits during multi-page + // reads as well as changes between workspaces while verification runs. + for (final entry in versions.entries) { + final current = await _read('timeline_query', { + 'workspaceId': entry.key, + 'includeParameters': false, + }, context); + _sameVersion(current.version, entry.value); + } + } on AgentCancelled { + rethrow; + } catch (_) { + return ToolResult( + 'Current project evidence unavailable or changed during verification; query current state and retry. No acceptance granted.', + isError: true, + data: { + 'issues': [ + ...issues, + {'kind': 'unavailableEvidence'}, + ], + }, + ); + } + return ToolResult( + issues.isEmpty + ? 'Declared deterministic outcomes verified from current project state; semantic quality is not certified.' + : 'Current project differs from the requested outcomes. Repair these specific differences and recheck.', + isError: issues.isNotEmpty, + data: { + 'scope': 'declaredDeterministicOutcomes', + 'semanticQuality': 'unverified', + 'contracts': contracts.length, + 'versions': versions, + 'issues': issues, + 'artifactHashes': { + for (final e in views.entries) + e.key: editorEvidenceHash(e.value.data), + }, + }, + ); + } + + Future<_View> _read( + String name, + Map arguments, + ToolContext context, + ) async { + context.cancellation.throwIfCancelled(); + final tool = _tools[name]; + if (tool == null || tool.validate(arguments) != null) { + throw StateError('Query unavailable'); + } + final result = await tool.execute( + ToolCall(id: context.operationId, name: name, arguments: arguments), + context, + ); + context.cancellation.throwIfCancelled(); + final version = result.data['version']; + final data = result.data['data']; + if (result.isError || version is! String || data is! Map) { + throw StateError('Invalid current state'); + } + return _View(data.cast(), version); + } + + Future>> _cues( + String workspace, + String role, + ToolContext context, + String version, + ) async { + final cues = >[]; + var offset = 0; + while (true) { + final page = await _read('caption_list', { + 'workspaceId': workspace, + 'roleId': role, + 'offset': offset, + 'limit': 100, + }, context); + _sameVersion(page.version, version); + final rows = (page.data['cues'] as List) + .map((e) => (e as Map).cast()) + .toList(); + cues.addAll(rows); + if (cues.length > 20000) throw StateError('Caption verification limit'); + final next = page.data['nextOffset']; + if (next == null) { + if (cues.length != page.data['total']) { + throw StateError('Incomplete caption read'); + } + return cues; + } + if (next is! int || next <= offset || rows.isEmpty) { + throw StateError('Invalid cursor'); + } + offset = next; + } + } + + static void _sameVersion(String a, String b) { + if (a != b) throw StateError('State changed during verification'); + } +} + +class _View { + const _View(this.data, this.version); + final Map data; + final String version; +} diff --git a/lib/integrations/agent/editor_agent_tools.dart b/lib/integrations/agent/editor_agent_tools.dart new file mode 100644 index 0000000..7170cac --- /dev/null +++ b/lib/integrations/agent/editor_agent_tools.dart @@ -0,0 +1,216 @@ +import 'package:cutdex_sdk/editor.dart'; + +import 'dart:convert'; + +import 'package:cutdex_agent/cutdex_agent.dart'; +import 'package:cutdex_sdk/tools.dart'; + +/// Protocol adaptation only. The dispatchers belong to the open project. +List editorAgentTools( + Map workspaces, { + bool dynamicWorkspaces = false, + Future Function(ToolContext)? beforeInvoke, + Future Function(ToolCall, ToolContext, CommandResult)? afterInvoke, +}) { + ToolResult result(CommandResult value) { + final data = value.toJson(); + final payload = data['data']; + if (payload is Map) { + data['data'] = { + ...payload, + if (payload['clips'] is List) + 'clips': (payload['clips']! as List).map(_compactClip).toList(), + // Full schemas are loaded on demand through runtime tool discovery. + if (payload['tools'] is List) + 'tools': [ + for (final tool in payload['tools']! as List) + if (tool is Map) + {'name': tool['name'], 'readOnly': tool['readOnly']} + else + tool, + ], + }; + } + return ToolResult(value.message, isError: value.isError, data: data); + } + + (EditorToolDispatcher, Map) resolve( + Map args, + ) { + final dispatcher = workspaces[args['workspaceId']]; + if (dispatcher == null) { + throw CommandRejected( + 'missingWorkspace', + 'Unknown workspaceId. Copy an exact ID from ${jsonEncode(workspaces.keys.toList())}. ' + 'Call cutdex_workspaces for supported tools.', + ); + } + return (dispatcher, {...args}..remove('workspaceId')); + } + + String operation(ToolContext context) => + jsonEncode(['agent', context.operationId]); + final definitions = { + if (dynamicWorkspaces) + for (final definition in editorToolDefinitions) + definition.name: definition, + for (final tools in workspaces.values) + for (final definition in tools.definitions) definition.name: definition, + }; + Future listWorkspaces(ToolContext context) async { + await beforeInvoke?.call(context); + final toolSets = >{}; + final ids = {}; + final targets = >[]; + for (final entry in workspaces.entries) { + final names = [ + for (final tool in entry.value.definitions) + tool.name.replaceAll('.', '_'), + ]..sort(); + final key = jsonEncode(names); + final id = ids.putIfAbsent(key, () => 'tools${ids.length}'); + toolSets[id] = names; + targets.add({'workspaceId': entry.key, 'toolSetId': id}); + } + return ToolResult(jsonEncode({'targets': targets, 'toolSets': toolSets})); + } + + return [ + AgentTool( + name: 'cutdex_workspaces', + description: 'List workspace IDs and their supported tools. application manages projects; use a timeline workspace for timeline queries and clip edits. Every call requires an explicit workspaceId from this list.', + parameters: const { + 'type': 'object', + 'properties': {}, + 'additionalProperties': false, + }, + validate: (args) => args.isEmpty ? null : 'No arguments expected', + execute: (_, context) => listWorkspaces(context), + // Discovery is read-only: obtain fresh data after an interrupted call. + recover: (_, context) async => + ToolRecovery.completed(await listWorkspaces(context)), + ), + for (final definition in definitions.values) + AgentTool( + name: definition.name.replaceAll('.', '_'), + description: definition.description, + parameters: { + ...definition.inputSchema, + 'properties': { + ...definition.inputSchema['properties']! as Map, + 'workspaceId': {'type': 'string'}, + }, + 'required': [ + ...definition.inputSchema['required']! as List, + 'workspaceId', + ], + }, + validate: (args) { + try { + final (dispatcher, arguments) = resolve(args); + if (!dispatcher.definitions.any( + (tool) => tool.name == definition.name, + )) { + final available = [ + for (final entry in workspaces.entries) + if (entry.value.definitions.any( + (tool) => tool.name == definition.name, + )) + entry.key, + ]; + return 'This workspace does not support ${definition.name}. ' + 'Use a workspaceId from ${jsonEncode(available)}. ' + 'Call cutdex_workspaces to inspect workspace tools.'; + } + decodeEditorCommand(definition.name, arguments); + return null; + } on CommandRejected catch (error) { + return error.message; + } catch (_) { + return 'Invalid arguments'; + } + }, + execute: (call, context) async { + await beforeInvoke?.call(context); + final (dispatcher, arguments) = resolve(call.arguments); + final value = await dispatcher.invoke( + name: definition.name, + arguments: arguments, + context: CommandContext( + operationId: operation(context), + isCancelled: () => context.cancellation.isCancelled, + ), + ); + if (value.status == CommandStatus.unknown) { + throw StateError( + 'Reconcile the original operation before retrying', + ); + } + if (!value.isError) await afterInvoke?.call(call, context, value); + return result(value); + }, + recover: (call, context) async { + await beforeInvoke?.call(context); + final (dispatcher, arguments) = resolve(call.arguments); + if (definition.readOnly) { + // Read-only dispatches deliberately have no operation receipt. + // Re-query current state; never apply this rule to edits. + final value = await dispatcher.invoke( + name: definition.name, + arguments: arguments, + context: CommandContext( + operationId: operation(context), + isCancelled: () => context.cancellation.isCancelled, + ), + ); + return value.status == CommandStatus.unknown + ? const ToolRecovery.unknown() + : ToolRecovery.completed(result(value)); + } + final OperationReceipt receipt; + try { + receipt = await dispatcher.recoverInvocation( + operationId: operation(context), + name: definition.name, + arguments: arguments, + ); + } on CommandRejected { + return const ToolRecovery.unknown(); + } + return switch (receipt.state) { + OperationState.notStarted => const ToolRecovery.notStarted(), + OperationState.running => const ToolRecovery.running(), + OperationState.completed + when receipt.result!.status != CommandStatus.unknown => + ToolRecovery.completed(result(receipt.result!)), + _ => const ToolRecovery.unknown(), + }; + }, + ), + ]; +} + +// Keep authored values and keys intact; omit repetitive empty/default metadata +// only in the Agent projection. MCP and the authoritative command result retain +// the full parameter definitions. +Object? _compactClip(Object? value) { + if (value is! Map || value['parameters'] is! List) { + return value; + } + return { + ...value, + 'parameters': [ + for (final parameter in value['parameters']! as List) + if (parameter is Map) + Map.from(parameter)..removeWhere( + (key, value) => + (key == 'unit' && value == '') || + (key == 'keyframes' && value is List && value.isEmpty) || + (key == 'minimum' && value == -1000000) || + (key == 'maximum' && value == 1000000), + ) + else + parameter, + ], + }; +} diff --git a/lib/integrations/app_failure_adapter.dart b/lib/integrations/app_failure_adapter.dart new file mode 100644 index 0000000..6d122ad --- /dev/null +++ b/lib/integrations/app_failure_adapter.dart @@ -0,0 +1,60 @@ +import 'dart:io'; + +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/project.dart'; + +import '../errors/app_failure.dart'; + +/// Adapts SDK errors by code. Unknown errors retain their complete diagnostics. +AppFailure appFailureFromError(Object error) { + if (error is AppException) return error.failure; + if (error is AppFailure) return error; + final AppErrorCode code; + switch (error) { + case CommandRejected(:final code): + final mapped = switch (code) { + 'missingMedia' => AppErrorCode.mediaNoLongerExists, + 'staleVersion' || + 'invalidSelection' || + 'missingClip' => AppErrorCode.timelineChanged, + 'missingTimeline' || + 'timelineNotOpen' => AppErrorCode.openTimelineFailed, + 'projectNotOpen' => AppErrorCode.openMatchingProject, + 'missingProject' => AppErrorCode.openProjectFirst, + 'projectIdMismatch' => AppErrorCode.projectMismatch, + 'unsupported' || + 'unavailable' || + 'busy' || + 'cancelled' || + 'workspaceBusy' || + 'projectCreationFailed' || + 'invalidArguments' => AppErrorCode.operationFailed, + _ => AppErrorCode.diagnostic, + }; + return AppFailure(mapped, diagnostic: error.toString()); + case ProjectFileException(:final code): + final mapped = switch (code) { + ProjectFileError.notFound => AppErrorCode.projectMissingDirectory, + ProjectFileError.closed => AppErrorCode.projectSessionClosed, + ProjectFileError.conflict => AppErrorCode.projectMismatch, + _ => AppErrorCode.projectAccessFailed, + }; + return AppFailure(mapped, diagnostic: error.toString()); + default: + code = AppErrorCode.diagnostic; + } + return AppFailure(code, diagnostic: error.toString()); +} + +/// Project operations provide context for otherwise unclassified I/O failures. +AppFailure projectFailureFromError(Object error) => switch (error) { + FileSystemException() => AppFailure( + AppErrorCode.projectAccessFailed, + diagnostic: error.toString(), + ), + AppException() || + CommandRejected() || + ProjectFileException() || + StateError() => appFailureFromError(error), + _ => AppFailure(AppErrorCode.operationFailed, diagnostic: error.toString()), +}; diff --git a/lib/integrations/app_update_bridge.dart b/lib/integrations/app_update_bridge.dart new file mode 100644 index 0000000..c0eeb04 --- /dev/null +++ b/lib/integrations/app_update_bridge.dart @@ -0,0 +1,81 @@ +import 'dart:async'; + +import '../diagnostics/app_diagnostics.dart'; + +import 'package:deskup/deskup.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +export 'package:deskup/deskup.dart' show UpdateStatus, UpdatePhase; + +part 'app_update_bridge.g.dart'; + +const appUpdatesChannel = MethodChannel('deskup'); +const appLifecycleChannel = MethodChannel('cutdex/lifecycle'); + +bool get supportsAppUpdates => Deskup.isSupported; + +@Riverpod(keepAlive: true) +AppUpdateBridge appUpdateBridge(Ref ref) { + final bridge = AppUpdateBridge(); + ref.onDispose(bridge.dispose); + return bridge; +} + +// Application adapter: Riverpod ownership and the macOS workspace quit gate. +class AppUpdateBridge { + AppUpdateBridge([MethodChannel channel = appUpdatesChannel]) + : _updater = Deskup(channel: channel); + + final Deskup _updater; + Stream get events => _updater.events; + bool _started = false; + bool _disposed = false; + Future Function()? _prepareToQuit; + + void start(Future Function() prepareToQuit) { + if (_disposed) return; + _prepareToQuit = prepareToQuit; + if (_started) return; + _started = true; + if (defaultTargetPlatform == TargetPlatform.macOS) { + appLifecycleChannel.setMethodCallHandler((call) async { + if (_disposed) return null; + if (call.method != 'prepareToQuit') throw MissingPluginException(); + await _prepareToQuit!(); + return true; + }); + unawaited( + appLifecycleChannel + .invokeMethod('ready') + .catchError(_initializationError), + ); + } + unawaited(_updater.initialize().catchError(_initializationError)); + } + + void _initializationError(Object error, StackTrace stack) { + if (!_disposed && error is! MissingPluginException) { + AppDiagnostics.failure('updates', 'initialize', error, stack); + } + } + + Future status() => _updater.status(); + Future check() => _updater.check(); + Future download() => _updater.download(); + Future validateInstall() => _updater.validateInstall(); + Future install() => _updater.install(); + Future setAutomaticChecks(bool enabled) => + _updater.setAutomaticChecks(enabled); + + void dispose() { + if (_disposed) return; + _disposed = true; + _prepareToQuit = null; + if (_started && defaultTargetPlatform == TargetPlatform.macOS) { + appLifecycleChannel.setMethodCallHandler(null); + } + _updater.dispose(); + } +} diff --git a/lib/integrations/app_update_bridge.g.dart b/lib/integrations/app_update_bridge.g.dart new file mode 100644 index 0000000..d215253 --- /dev/null +++ b/lib/integrations/app_update_bridge.g.dart @@ -0,0 +1,52 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'app_update_bridge.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(appUpdateBridge) +final appUpdateBridgeProvider = AppUpdateBridgeProvider._(); + +final class AppUpdateBridgeProvider + extends + $FunctionalProvider + with $Provider { + AppUpdateBridgeProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'appUpdateBridgeProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$appUpdateBridgeHash(); + + @$internal + @override + $ProviderElement $createElement($ProviderPointer pointer) => + $ProviderElement(pointer); + + @override + AppUpdateBridge create(Ref ref) { + return appUpdateBridge(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(AppUpdateBridge value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$appUpdateBridgeHash() => r'f119181b32e1785027092937071c1bfc59b7ed7e'; diff --git a/lib/integrations/app_update_coordinator.dart b/lib/integrations/app_update_coordinator.dart new file mode 100644 index 0000000..c50e2e9 --- /dev/null +++ b/lib/integrations/app_update_coordinator.dart @@ -0,0 +1,39 @@ +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import '../features/assistant/agent_conversation_service.dart'; +import '../workspace/projects.dart'; +import 'app_update_bridge.dart'; + +Future prepareForAppUpdateQuit(Ref ref) async { + await ref.read(agentConversationRegistryProvider).cancelAll(); + await ref.read(projectsProvider.notifier).prepareToQuit(); +} + +// Keep the saved workspace recoverable if the updater cannot be launched. +Future installWindowsUpdate(Ref ref) async { + final bridge = ref.read(appUpdateBridgeProvider); + await bridge.validateInstall(); + final registry = ref.read(agentConversationRegistryProvider); + await registry.cancelAll(); + await registry.whilePaused(() async { + final projects = ref.read(projectsProvider.notifier); + await ref.read(projectsProvider.future); + final snapshot = ref.read(projectsProvider).requireValue; + await projects.prepareToQuit(); + try { + await bridge.install(); + } catch (_) { + ref.invalidate(projectsProvider); + if (snapshot.activeProject case final project?) { + await ref + .read(projectsProvider.notifier) + .open( + project.path, + expectedId: project.id, + timelineId: snapshot.timeline?.id, + ); + } + rethrow; + } + }); +} diff --git a/lib/integrations/app_updates.dart b/lib/integrations/app_updates.dart new file mode 100644 index 0000000..635f182 --- /dev/null +++ b/lib/integrations/app_updates.dart @@ -0,0 +1,14 @@ +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import 'app_update_bridge.dart'; +import 'app_update_coordinator.dart'; + +export 'app_update_bridge.dart'; + +part 'app_updates.g.dart'; + +@Riverpod(keepAlive: true) +void appUpdateLifecycle(Ref ref) { + if (!supportsAppUpdates) return; + ref.watch(appUpdateBridgeProvider).start(() => prepareForAppUpdateQuit(ref)); +} diff --git a/lib/integrations/app_updates.g.dart b/lib/integrations/app_updates.g.dart new file mode 100644 index 0000000..5d1cb25 --- /dev/null +++ b/lib/integrations/app_updates.g.dart @@ -0,0 +1,52 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'app_updates.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(appUpdateLifecycle) +final appUpdateLifecycleProvider = AppUpdateLifecycleProvider._(); + +final class AppUpdateLifecycleProvider + extends $FunctionalProvider + with $Provider { + AppUpdateLifecycleProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'appUpdateLifecycleProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$appUpdateLifecycleHash(); + + @$internal + @override + $ProviderElement $createElement($ProviderPointer pointer) => + $ProviderElement(pointer); + + @override + void create(Ref ref) { + return appUpdateLifecycle(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(void value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$appUpdateLifecycleHash() => + r'df3b0fe12a77300a414051e87149de36b0d8b977'; diff --git a/lib/integrations/application_command_dependencies.dart b/lib/integrations/application_command_dependencies.dart new file mode 100644 index 0000000..e904272 --- /dev/null +++ b/lib/integrations/application_command_dependencies.dart @@ -0,0 +1,70 @@ +import 'dart:ui'; + +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../features/settings/language_settings.dart'; +import '../l10n/app_localizations.dart'; +import '../workspace/project_state.dart'; +import '../workspace/projects.dart'; +import '../workspace/preview_target.dart'; +import '../workspace/timeline_provider.dart'; +import '../workspace/timeline_session.dart'; + +abstract interface class ApplicationCommandDependencies { + Future projectState(); + Future createProject(String name); + Future openProject(String path, {String? expectedId}); + Future createTimeline(String name); + Future openTimeline(String projectId, String timelineId); + Future timeline(String projectId, String timelineId); + PreviewTarget preview(String projectId, String timelineId); +} + +/// Riverpod is confined to the composition adapter, not the command host. +class RiverpodApplicationCommandDependencies + implements ApplicationCommandDependencies { + const RiverpodApplicationCommandDependencies(this._ref); + + final Ref _ref; + + Projects get _projects => _ref.read(projectsProvider.notifier); + + @override + Future projectState() => _ref.read(projectsProvider.future); + + @override + Future createProject(String name) { + final configured = _ref.read(languageSettingsProvider).asData?.value; + final locale = + configured?.locale ?? + resolveAppLocale( + PlatformDispatcher.instance.locales, + AppLocalizations.supportedLocales, + ); + return _projects.createProject( + name, + initialTimelineName: lookupAppLocalizations(locale) + .defaultTimelineName(1), + ); + } + + @override + Future openProject(String path, {String? expectedId}) => + _projects.open(path, expectedId: expectedId); + + @override + Future createTimeline(String name) => + _projects.createTimeline(name: name); + + @override + Future openTimeline(String projectId, String timelineId) => + _projects.openTimeline(projectId, timelineId); + + @override + Future timeline(String projectId, String timelineId) => + _ref.read(editorTimelineProvider(projectId, timelineId).future); + + @override + PreviewTarget preview(String projectId, String timelineId) => + _ref.read(previewTargetProvider(projectId, timelineId)); +} diff --git a/lib/integrations/application_command_host.dart b/lib/integrations/application_command_host.dart new file mode 100644 index 0000000..4797e69 --- /dev/null +++ b/lib/integrations/application_command_host.dart @@ -0,0 +1,289 @@ +import 'dart:io'; + +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:cutdex_sdk/tools.dart'; + +import '../workspace/project_state.dart'; +import 'application_command_dependencies.dart'; + +/// Application navigation adapter; project persistence and playback stay with owners. +class ApplicationCommandHost implements EditorCommandHost { + ApplicationCommandHost(this.dependencies, {required this.refresh}); + final ApplicationCommandDependencies dependencies; + final Future Function() refresh; + @override + Set get supportedOperations => applicationOperations; + + @override + Future execute( + EditorCommand command, + CommandContext context, + ) async { + final state = await dependencies.projectState(); + if (context.isCancelled()) { + throw const CommandRejected('cancelled', 'Cancelled before execution'); + } + if (!supportedOperations.contains(command.operation)) { + throw const CommandRejected( + 'unsupported', + 'Choose a sequence workspace for editing', + ); + } + if (!applicationReadOperations.contains(command.operation) && + state.projectBusy) { + throw const CommandRejected( + 'workspaceBusy', + 'Another workspace operation is running', + ); + } + void requireProject(String id) { + if (state.activeProject?.id != id) { + throw const CommandRejected( + 'missingProject', + 'Open the addressed project first', + ); + } + } + + void requireTimeline(String projectId, String timelineId) { + requireProject(projectId); + if (state.timeline?.id != timelineId) { + throw const CommandRejected( + 'missingTimeline', + 'Open the addressed timeline first', + ); + } + } + + Map projectData(RecentProject project) => { + 'projectId': project.id, + 'name': project.name, + 'path': project.path, + }; + CommandResult result(Map data) => CommandResult( + status: CommandStatus.succeeded, + message: 'Workspace state', + data: data, + ); + switch (command) { + case QueryProjects(): + return result({ + 'active': state.activeProject == null + ? null + : projectData(state.activeProject!), + 'recent': state.recent.map(projectData).toList(), + 'busy': state.projectBusy, + }); + case ListTimelines(): + requireProject(command.projectId); + return result({ + 'projectId': command.projectId, + 'activeTimelineId': state.timeline?.id, + 'timelines': [ + for (final timeline in state.timelines) + {'timelineId': timeline.id, 'name': timeline.name}, + ], + 'sequences': [ + for (final sequence in state.timeline?.sequences ?? []) + {'sequenceId': sequence.id.value, 'name': sequence.name}, + ], + }); + case CreateProject(): + if (command.name.trim().isEmpty) { + throw const CommandRejected( + 'invalidArguments', + 'Use a nonempty project name', + ); + } + if (!await dependencies.createProject(command.name)) { + final current = await dependencies.projectState(); + throw CommandRejected( + 'projectCreationFailed', + current.error?.toString() ?? 'Project creation did not complete', + ); + } + await refresh(); + final current = await dependencies.projectState(); + return result({ + 'project': projectData(current.activeProject!), + 'activeTimelineId': current.timeline?.id, + }); + case OpenProject(): + if (!File(command.path).isAbsolute) { + throw const CommandRejected( + 'invalidArguments', + 'Use an absolute project path', + ); + } + final String canonicalPath; + try { + canonicalPath = await Directory(command.path).resolveSymbolicLinks(); + } on FileSystemException { + throw const CommandRejected( + 'missingProject', + 'Project path is not readable', + ); + } + final known = [ + ?state.activeProject, + ...state.recent, + ].where((project) => project.path == canonicalPath).firstOrNull; + if (known != null && + command.projectId != null && + known.id != command.projectId) { + throw CommandRejected( + 'projectIdMismatch', + 'This path belongs to project ${known.id}. Use project.query to read the current project.', + ); + } + final opened = await dependencies.openProject( + command.path, + expectedId: command.projectId, + ); + if (!opened) throw StateError('Project open did not complete'); + await refresh(); + final current = await dependencies.projectState(); + return result({ + 'project': projectData(current.activeProject!), + 'activeTimelineId': current.timeline?.id, + }); + case CreateTimeline(): + requireProject(command.projectId); + if (command.name.trim().isEmpty) { + throw const CommandRejected( + 'invalidArguments', + 'Timeline name is empty', + ); + } + final before = state.timelines.map((timeline) => timeline.id).toSet(); + if (!await dependencies.createTimeline(command.name)) { + throw StateError('Timeline creation did not complete'); + } + await refresh(); + final current = await dependencies.projectState(); + final created = current.timelines + .where((timeline) => !before.contains(timeline.id)) + .single; + return result({ + 'projectId': command.projectId, + 'timelineId': created.id, + 'name': created.name, + 'activeTimelineId': current.timeline?.id, + }); + case OpenTimeline(): + requireProject(command.projectId); + if (!state.timelines.any( + (timeline) => timeline.id == command.timelineId, + )) { + throw const CommandRejected( + 'missingTimeline', + 'Timeline does not exist', + ); + } + if (state.timeline?.id != command.timelineId && + !await dependencies.openTimeline( + command.projectId, + command.timelineId, + )) { + throw StateError('Timeline open did not complete'); + } + await refresh(); + return result({ + 'projectId': command.projectId, + 'timelineId': command.timelineId, + 'activeTimelineId': command.timelineId, + 'sequences': [ + for (final sequence + in (await dependencies.projectState()).timeline!.sequences) + {'sequenceId': sequence.id.value, 'name': sequence.name}, + ], + }); + case SelectSequence(): + requireTimeline(command.projectId, command.timelineId); + if (!state.timeline!.sequences.any( + (s) => s.id.value == command.sequenceId, + )) { + throw const CommandRejected( + 'missingSequence', + 'Sequence does not exist', + ); + } + final session = await dependencies.timeline( + command.projectId, + command.timelineId, + ); + if (context.isCancelled()) { + throw const CommandRejected( + 'cancelled', + 'Cancelled before selection', + ); + } + session.commands.ensureOpen(null); + await dependencies + .preview(command.projectId, command.timelineId) + .closeSource(); + session.commands.ensureOpen(null); + session.selectSequence(SequenceId(command.sequenceId)); + return result({'sequenceId': command.sequenceId}); + case SourcePreviewCommand(): + requireTimeline(command.projectId, command.timelineId); + final target = dependencies.preview( + command.projectId, + command.timelineId, + ); + switch (command.action) { + case SourcePreviewAction.query: + break; + case SourcePreviewAction.open: + final asset = state.assets + .where((a) => a.id == command.mediaId) + .firstOrNull; + if (asset == null) { + throw const CommandRejected( + 'missingMedia', + 'Media is not in the current project', + ); + } + await target.openSource(asset); + case SourcePreviewAction.close: + await target.closeSource(); + case SourcePreviewAction.play || + SourcePreviewAction.pause || + SourcePreviewAction.seek: + if (command.mediaId == null) { + throw const CommandRejected( + 'invalidArguments', + 'Source media ID is required', + ); + } + await target.control( + command.mediaId!, + command.action, + at: command.at, + ); + } + final source = target.source; + return result({ + 'mediaId': target.asset?.id, + 'available': source != null, + 'ready': source != null && !source.busy && source.error == null, + 'playing': source?.playing ?? false, + 'failed': source?.error != null, + 'position': CommandTime( + source?.positionTick ?? 0, + TimelineClock.ticksPerSecond, + ).toJson(), + 'duration': CommandTime( + source?.durationTick ?? 0, + TimelineClock.ticksPerSecond, + ).toJson(), + }); + default: + throw const CommandRejected( + 'unsupported', + 'Unsupported application operation', + ); + } + } +} diff --git a/lib/integrations/editor_command_host.dart b/lib/integrations/editor_command_host.dart new file mode 100644 index 0000000..8ee7720 --- /dev/null +++ b/lib/integrations/editor_command_host.dart @@ -0,0 +1,180 @@ +import 'dart:async'; + +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/timeline/engine.dart'; +import 'package:cutdex_sdk/timeline/layout.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:cutdex_sdk/tools.dart'; + +import '../workspace/timeline_session.dart'; + +final _sessionTools = Expando>(); +final _toolReferences = Expando>(); + +/// Remove a dispatcher from its session cache before closing admission. +Future releaseEditorTools( + EditorSession session, + EditorToolDispatcher dispatcher, +) async { + final references = _toolReferences[session]; + final remaining = (references?[dispatcher] ?? 1) - 1; + if (remaining > 0) { + references![dispatcher] = remaining; + return; + } + references?.remove(dispatcher); + _sessionTools[session]?.removeWhere( + (_, value) => identical(value, dispatcher), + ); + await dispatcher.dispose(); +} + +EditorToolDispatcher editorToolsFor( + EditorSession session, + SequenceId sequence, +) { + session.commands.ensureOpen(sequence); + var tools = _sessionTools[session]; + if (tools == null) { + final owned = {}; + _sessionTools[session] = tools = owned; + session.onDispose(() { + for (final dispatcher in owned.values) { + unawaited(dispatcher.dispose()); + } + }); + } + final dispatcher = tools.putIfAbsent( + sequence, + () => EditorToolDispatcher(host: _EditorCommandHost(session, sequence)), + ); + final references = _toolReferences[session] ??= {}; + references[dispatcher] = (references[dispatcher] ?? 0) + 1; + return dispatcher; +} + +/// Maps SDK command outcomes to tools and adapts the app-owned UI selection. +final class _EditorCommandHost extends EditorSessionCommandHost { + const _EditorCommandHost(super.session, super.sequence); + + @override + Set get supportedOperations => { + ...session.supportedCommandOperations.where( + (operation) => operation != EditorOperation.startVocalSeparation, + ), + if (session is EditorTimelineSession) ...{ + EditorOperation.querySelection, + EditorOperation.setSelection, + }, + }; + + @override + Future execute( + EditorCommand command, + CommandContext context, + ) async { + if (command is StartVocalSeparation) { + throw const CommandRejected( + 'unsupported', + 'Vocal separation is temporarily unavailable', + ); + } + return _execute(command, context); + } + + Future _execute( + EditorCommand command, + CommandContext context, + ) async { + if (command is QuerySelection || command is SetSelection) { + session.commands.ensureOpen(sequence); + if (context.isCancelled()) { + throw const CommandRejected('cancelled', 'Cancelled before execution'); + } + if (!supportedOperations.contains(command.operation)) { + throw const CommandRejected( + 'unsupported', + 'Operation is not available', + ); + } + if (command.expectedVersion != null && + command.expectedVersion != session.version) { + throw const CommandRejected( + 'staleVersion', + 'Read the current state before editing', + ); + } + return _selection(command); + } + return super.execute(command, context); + } + + CommandResult _selection(EditorCommand command) { + final ui = session as EditorTimelineSession; + final view = ui.view(sequence); + final query = view.version.kernelVersion.query(); + if (command is SetSelection) { + if (view.isDragging) { + throw const CommandRejected('busy', 'Finish the current gesture first'); + } + if (command.clipIds.length > 1024 || + command.clipIds.toSet().length != command.clipIds.length) { + throw const CommandRejected( + 'invalidArguments', + 'Invalid clip selection', + ); + } + final handles = []; + for (final id in command.clipIds) { + final handle = query.elementById(ElementId(id)); + if (handle == null || query.ownerOf(handle) == null) { + throw const CommandRejected( + 'missingClip', + 'Selected clip does not exist', + ); + } + handles.add(handle); + } + view.setSelection([ + for (final handle in handles) + session.captionComponentFor(sequence, handle) ?? + (query.connectionForTarget(handle) == null + ? handle + : LayoutBodyId.element(handle)), + ]); + } + final selected = {}; + for (final identity in view.selectedIdentities) { + final handle = switch (identity) { + ElementHandle value => value, + LayoutBodyId value => view.elementForIdentity(value), + _ => null, + }; + if (handle != null && query.ownerOf(handle) != null) { + selected.add(query.element(handle).id.value); + } + } + final keyframe = view.selectedKeyframe; + return CommandResult( + status: CommandStatus.succeeded, + message: 'UI selection', + version: session.version, + data: { + 'sequenceId': sequence.value, + 'active': ui.activeSequenceId == sequence, + 'clipIds': selected.toList(), + 'keyframe': keyframe == null + ? null + : { + 'clipId': query.element(keyframe.element).id.value, + 'offset': _time(keyframe.offset), + }, + }, + ); + } +} + +Map _time(int ticks) { + final value = TimelineClock.standard.fromTicks(ticks); + return {'numerator': '${value.numerator}', 'denominator': value.denominator}; +} diff --git a/lib/integrations/editor_tool_access.dart b/lib/integrations/editor_tool_access.dart new file mode 100644 index 0000000..ad495f5 --- /dev/null +++ b/lib/integrations/editor_tool_access.dart @@ -0,0 +1,45 @@ +import 'package:cutdex_agent/cutdex_agent.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/mcp.dart'; +import 'package:cutdex_sdk/tools.dart'; + +import 'agent/editor_agent_tools.dart'; +import 'tool_workspace_registry.dart'; + +/// Immutable composition result exposing protocol projections of one registry. +class EditorToolAccess { + EditorToolAccess(EditorSession session) : this._(EditorToolRegistry(session)); + + EditorToolAccess.application(EditorCommandHost host) + : this._(EditorToolRegistry.application(host)); + + EditorToolAccess._(this.registry); + + final EditorToolRegistry registry; + + Object get owner => registry.owner; + Map get workspaces => registry.workspaces; + + void attach(EditorSession? session, {String? projectId}) => + registry.attach(session, projectId: projectId); + + Future dispose() => registry.dispose(); + + late final List agentTools = editorAgentTools( + registry.workspaces, + dynamicWorkspaces: registry.dynamicWorkspaces, + ); + + late final server = CutdexMcpServer( + resolveWorkspaces: registry.dynamicWorkspaces + ? () => [ + for (final entry in registry.workspaces.entries) + McpWorkspace(id: entry.key, title: entry.key, tools: entry.value), + ] + : null, + workspaces: [ + for (final entry in registry.workspaces.entries) + McpWorkspace(id: entry.key, title: entry.key, tools: entry.value), + ], + ); +} diff --git a/lib/integrations/editor_tools.dart b/lib/integrations/editor_tools.dart new file mode 100644 index 0000000..4313688 --- /dev/null +++ b/lib/integrations/editor_tools.dart @@ -0,0 +1,287 @@ +import 'dart:async'; + +import 'package:freezed_annotation/freezed_annotation.dart'; + +import 'package:cutdex_agent/cutdex_agent.dart'; +import 'package:cutdex_sdk/tools.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import '../workspace/projects.dart'; +import '../workspace/timeline_provider.dart'; +import 'agent/editor_acceptance.dart'; +import 'agent/editor_agent_tools.dart'; +import 'application_command_dependencies.dart'; +import 'application_command_host.dart'; +import 'editor_command_host.dart'; +import 'editor_tool_access.dart'; +import 'mcp/mcp_endpoint_controller.dart'; +import 'mcp/mcp_settings.dart'; + +export 'mcp/mcp_endpoint_controller.dart' show EditorMcpEndpoint; +export 'editor_tool_access.dart' show EditorToolAccess; + +part 'editor_tools.g.dart'; +part 'editor_tools.freezed.dart'; + +@Riverpod(keepAlive: true) +EditorMcpEndpoint _editorMcpEndpoint(Ref ref) { + final endpoint = EditorMcpEndpoint(); + ref.onDispose(() { + unawaited(endpoint.close()); + }); + return endpoint; +} + +@freezed +abstract class EditorMcpConfiguration with _$EditorMcpConfiguration { + const factory EditorMcpConfiguration({ + required int port, + required String token, + }) = _EditorMcpConfiguration; +} + +@Riverpod(keepAlive: true) +EditorMcpConfiguration editorMcpConfiguration(Ref ref) { + final settings = ref.watch(mcpSettingsProvider).asData?.value; + return EditorMcpConfiguration( + port: settings?.enabled == true ? settings!.port : 0, + token: settings?.token ?? '', + ); +} + +@Riverpod(keepAlive: true) +EditorToolAccess applicationToolAccess(Ref ref) { + late final EditorToolAccess access; + (String, String)? timelineIds; + void Function()? releaseTimeline; + Future refresh() async { + final current = await ref.read(projectsProvider.future); + if (!ref.mounted) return; + final projectId = current.activeProject?.id; + final timelineId = current.timeline?.id; + if (projectId == null || timelineId == null) { + releaseTimeline?.call(); + releaseTimeline = null; + timelineIds = null; + access.attach(null); + return; + } + final ids = (projectId, timelineId); + final provider = editorTimelineProvider(ids.$1, ids.$2); + if (timelineIds != ids) { + releaseTimeline?.call(); + // Tools own an active timeline even when no editor widget is watching it. + final subscription = ref.listen(provider, (_, _) {}); + releaseTimeline = subscription.close; + timelineIds = ids; + } + var session = await ref.read(provider.future); + if (!ref.mounted) return; + if (!session.acceptsEdits) { + ref.invalidate(provider); + session = await ref.read(provider.future); + } + if (!ref.mounted) return; + final latest = ref.read(projectsProvider).asData?.value; + if (ref.mounted && + latest?.activeProject?.id == projectId && + latest?.timeline?.id == timelineId) { + access.attach(session, projectId: projectId); + } + } + + access = EditorToolAccess.application( + ApplicationCommandHost( + RiverpodApplicationCommandDependencies(ref), + refresh: refresh, + ), + ); + ref.listen(projectsProvider, (_, next) { + if (next.asData?.value.projectBusy == false) { + unawaited(refresh().catchError((Object _) {})); + } + }); + ref.onDispose(() { + releaseTimeline?.call(); + unawaited(access.dispose()); + }); + unawaited(refresh().catchError((Object _) {})); + return access; +} + +@riverpod +FutureOr editorToolAccess( + Ref ref, + String projectId, + String timelineId, +) async { + final session = await ref.watch( + editorTimelineProvider(projectId, timelineId).future, + ); + final access = ref.watch(applicationToolAccessProvider); + final current = ref.read(projectsProvider).asData?.value; + if (current?.activeProject?.id == projectId && + current?.timeline?.id == timelineId && + session.acceptsEdits) { + access.attach(session, projectId: projectId); + } + return access; +} + +@Riverpod(keepAlive: true) +FutureOr applicationMcpConnection(Ref ref) async { + final configuration = ref.watch(editorMcpConfigurationProvider); + final endpoint = ref.watch(_editorMcpEndpointProvider); + if (configuration.port == 0) { + await endpoint.stop(); + return; + } + final access = ref.watch(applicationToolAccessProvider); + var disposed = false; + ref.onDispose(() { + disposed = true; + }); + final bridge = await endpoint.open( + access.server, + port: configuration.port, + token: configuration.token, + ); + if (disposed) { + await endpoint.release(bridge); + return; + } + ref.onDispose(() => unawaited(endpoint.release(bridge))); +} + +@riverpod +FutureOr editorMcpConnection( + Ref ref, + String projectId, + String timelineId, +) async { + await ref.watch(editorToolAccessProvider(projectId, timelineId).future); + await ref.watch(applicationMcpConnectionProvider.future); +} + +class EditorAgentBinding { + const EditorAgentBinding({ + required this.owner, + required this.tools, + this.release, + this.completionCheck, + this.ensureTimeline, + }); + final Object owner; + final List tools; + final Future Function()? release; + final CompletionCheck? completionCheck; + final Future Function(String timelineId)? ensureTimeline; +} + +/// Leases explicit run targets; opening another timeline adds that target. +Future createEditorAgentBinding( + Ref ref, + String projectId, + String timelineId, +) async { + await ref.read(editorTimelineProvider(projectId, timelineId).future); + final lease = await ref + .read(projectsProvider.notifier) + .leaseTimeline(projectId, timelineId); + final leases = {timelineId: lease}; + try { + final session = lease.session; + final dispatchers = {}; + final application = ref.read(applicationToolAccessProvider); + if (application.workspaces['application'] case final dispatcher?) { + dispatchers['application'] = dispatcher; + } + for (final sequence in session.document.sequences) { + dispatchers['sequence:${sequence.id.value}'] = editorToolsFor( + session, + sequence.id, + ); + } + Future ensureTimeline(String target) async { + if (leases.containsKey(target)) return; + final added = await ref + .read(projectsProvider.notifier) + .leaseTimeline(projectId, target); + leases[target] = added; + for (final sequence in added.session.document.sequences) { + dispatchers['sequence:${sequence.id.value}'] = editorToolsFor( + added.session, + sequence.id, + ); + } + } + + final tools = editorAgentTools( + dispatchers, + dynamicWorkspaces: true, + afterInvoke: (call, context, result) async { + if (!{ + 'timeline_create', + 'timeline_open', + 'sequence_select', + }.contains(call.name)) { + return; + } + if (call.arguments['projectId'] != projectId) return; + final target = call.name == 'timeline_create' + ? result.data['timelineId'] + : call.arguments['timelineId']; + if (target is! String) return; + await ensureTimeline(target); + }, + beforeInvoke: (context) async { + try { + for (final owned in leases.values) { + await owned.validate(); + } + } catch (_) { + context.cancellation.cancel(); + rethrow; + } + }, + ); + final acceptance = EditorAcceptance(tools); + return EditorAgentBinding( + owner: session, + tools: [...tools, ...acceptance.tools], + completionCheck: acceptance.check, + ensureTimeline: ensureTimeline, + release: () async { + try { + for (final owned in leases.values) { + for (final sequence in owned.session.document.sequences) { + final dispatcher = dispatchers['sequence:${sequence.id.value}']; + if (dispatcher != null) { + await releaseEditorTools(owned.session, dispatcher); + } + } + } + } finally { + for (final owned in leases.values) { + await owned.release(); + } + } + }, + ); + } catch (_) { + await lease.release(); + rethrow; + } +} + +@Riverpod(name: 'editorAgentToolsProvider') +FutureOr editorAgentToolsBinding( + Ref ref, + String projectId, + String timelineId, +) async { + final access = await ref.watch( + editorToolAccessProvider(projectId, timelineId).future, + ); + return EditorAgentBinding(owner: access.owner, tools: access.agentTools); +} diff --git a/lib/integrations/editor_tools.freezed.dart b/lib/integrations/editor_tools.freezed.dart new file mode 100644 index 0000000..b9e4ace --- /dev/null +++ b/lib/integrations/editor_tools.freezed.dart @@ -0,0 +1,328 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'editor_tools.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +T _$identity(T value) => value; + +/// @nodoc +mixin _$EditorMcpConfiguration { + int get port; + String get token; + + /// Create a copy of EditorMcpConfiguration + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $EditorMcpConfigurationCopyWith get copyWith => + _$EditorMcpConfigurationCopyWithImpl( + this as EditorMcpConfiguration, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as EditorMcpConfiguration; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is EditorMcpConfiguration && + (identical(other.port, _this.port) || other.port == _this.port) && + (identical(other.token, _this.token) || + other.token == _this.token)); + } + + @override + int get hashCode { + final _this = this as EditorMcpConfiguration; + return Object.hash(runtimeType, _this.port, _this.token); + } + + @override + String toString() { + final _this = this as EditorMcpConfiguration; + return 'EditorMcpConfiguration(port: ${_this.port}, token: ${_this.token})'; + } +} + +/// @nodoc +abstract mixin class $EditorMcpConfigurationCopyWith<$Res> { + factory $EditorMcpConfigurationCopyWith( + EditorMcpConfiguration value, + $Res Function(EditorMcpConfiguration) _then, + ) = _$EditorMcpConfigurationCopyWithImpl; + @useResult + $Res call({int port, String token}); +} + +/// @nodoc +class _$EditorMcpConfigurationCopyWithImpl<$Res> + implements $EditorMcpConfigurationCopyWith<$Res> { + _$EditorMcpConfigurationCopyWithImpl(this._self, this._then); + + final EditorMcpConfiguration _self; + final $Res Function(EditorMcpConfiguration) _then; + + /// Create a copy of EditorMcpConfiguration + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({Object? port = null, Object? token = null}) { + return _then( + EditorMcpConfiguration( + port: null == port + ? _self.port + : port // ignore: cast_nullable_to_non_nullable + as int, + token: null == token + ? _self.token + : token // ignore: cast_nullable_to_non_nullable + as String, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [EditorMcpConfiguration]. +extension EditorMcpConfigurationPatterns on EditorMcpConfiguration { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_EditorMcpConfiguration value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _EditorMcpConfiguration() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_EditorMcpConfiguration value) $default, + ) { + final _that = this; + switch (_that) { + case _EditorMcpConfiguration(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_EditorMcpConfiguration value)? $default, + ) { + final _that = this; + switch (_that) { + case _EditorMcpConfiguration() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function(int port, String token)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _EditorMcpConfiguration() when $default != null: + return $default(_that.port, _that.token); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function(int port, String token) $default, + ) { + final _that = this; + switch (_that) { + case _EditorMcpConfiguration(): + return $default(_that.port, _that.token); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function(int port, String token)? $default, + ) { + final _that = this; + switch (_that) { + case _EditorMcpConfiguration() when $default != null: + return $default(_that.port, _that.token); + case _: + return null; + } + } +} + +/// @nodoc + +class _EditorMcpConfiguration implements EditorMcpConfiguration { + const _EditorMcpConfiguration({required this.port, required this.token}); + + @override + final int port; + @override + final String token; + + /// Create a copy of EditorMcpConfiguration + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$EditorMcpConfigurationCopyWith<_EditorMcpConfiguration> get copyWith => + __$EditorMcpConfigurationCopyWithImpl<_EditorMcpConfiguration>( + this, + _$identity, + ); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _EditorMcpConfiguration && + (identical(other.port, port) || other.port == port) && + (identical(other.token, token) || other.token == token)); + } + + @override + int get hashCode { + return Object.hash(runtimeType, port, token); + } + + @override + String toString() { + return 'EditorMcpConfiguration(port: $port, token: $token)'; + } +} + +/// @nodoc +abstract mixin class _$EditorMcpConfigurationCopyWith<$Res> + implements $EditorMcpConfigurationCopyWith<$Res> { + factory _$EditorMcpConfigurationCopyWith( + _EditorMcpConfiguration value, + $Res Function(_EditorMcpConfiguration) _then, + ) = __$EditorMcpConfigurationCopyWithImpl; + @override + @useResult + $Res call({int port, String token}); +} + +/// @nodoc +class __$EditorMcpConfigurationCopyWithImpl<$Res> + implements _$EditorMcpConfigurationCopyWith<$Res> { + __$EditorMcpConfigurationCopyWithImpl(this._self, this._then); + + final _EditorMcpConfiguration _self; + final $Res Function(_EditorMcpConfiguration) _then; + + /// Create a copy of EditorMcpConfiguration + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({Object? port = null, Object? token = null}) { + return _then( + _EditorMcpConfiguration( + port: null == port + ? _self.port + : port // ignore: cast_nullable_to_non_nullable + as int, + token: null == token + ? _self.token + : token // ignore: cast_nullable_to_non_nullable + as String, + ), + ); + } +} diff --git a/lib/integrations/editor_tools.g.dart b/lib/integrations/editor_tools.g.dart new file mode 100644 index 0000000..f50fa38 --- /dev/null +++ b/lib/integrations/editor_tools.g.dart @@ -0,0 +1,425 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'editor_tools.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(_editorMcpEndpoint) +final _editorMcpEndpointProvider = _EditorMcpEndpointProvider._(); + +final class _EditorMcpEndpointProvider + extends + $FunctionalProvider< + EditorMcpEndpoint, + EditorMcpEndpoint, + EditorMcpEndpoint + > + with $Provider { + _EditorMcpEndpointProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'_editorMcpEndpointProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$_editorMcpEndpointHash(); + + @$internal + @override + $ProviderElement $createElement( + $ProviderPointer pointer, + ) => $ProviderElement(pointer); + + @override + EditorMcpEndpoint create(Ref ref) { + return _editorMcpEndpoint(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(EditorMcpEndpoint value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$_editorMcpEndpointHash() => + r'cc4a1bf7bdbbbf2e4762f5c4068e8f305ac569d5'; + +@ProviderFor(editorMcpConfiguration) +final editorMcpConfigurationProvider = EditorMcpConfigurationProvider._(); + +final class EditorMcpConfigurationProvider + extends + $FunctionalProvider< + EditorMcpConfiguration, + EditorMcpConfiguration, + EditorMcpConfiguration + > + with $Provider { + EditorMcpConfigurationProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'editorMcpConfigurationProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$editorMcpConfigurationHash(); + + @$internal + @override + $ProviderElement $createElement( + $ProviderPointer pointer, + ) => $ProviderElement(pointer); + + @override + EditorMcpConfiguration create(Ref ref) { + return editorMcpConfiguration(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(EditorMcpConfiguration value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$editorMcpConfigurationHash() => + r'0ccb0b48d75534620d5e4abe40008c94b1007341'; + +@ProviderFor(applicationToolAccess) +final applicationToolAccessProvider = ApplicationToolAccessProvider._(); + +final class ApplicationToolAccessProvider + extends + $FunctionalProvider< + EditorToolAccess, + EditorToolAccess, + EditorToolAccess + > + with $Provider { + ApplicationToolAccessProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'applicationToolAccessProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$applicationToolAccessHash(); + + @$internal + @override + $ProviderElement $createElement($ProviderPointer pointer) => + $ProviderElement(pointer); + + @override + EditorToolAccess create(Ref ref) { + return applicationToolAccess(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(EditorToolAccess value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$applicationToolAccessHash() => + r'93564d9cdcbdc3247fef6c9f5fd24dd833f8aca5'; + +@ProviderFor(editorToolAccess) +final editorToolAccessProvider = EditorToolAccessFamily._(); + +final class EditorToolAccessProvider + extends + $FunctionalProvider< + AsyncValue, + EditorToolAccess, + FutureOr + > + with $FutureModifier, $FutureProvider { + EditorToolAccessProvider._({ + required EditorToolAccessFamily super.from, + required (String, String) super.argument, + }) : super( + retry: null, + name: r'editorToolAccessProvider', + isAutoDispose: true, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$editorToolAccessHash(); + + @override + String toString() { + return r'editorToolAccessProvider' + '' + '$argument'; + } + + @$internal + @override + $FutureProviderElement $createElement( + $ProviderPointer pointer, + ) => $FutureProviderElement(pointer); + + @override + FutureOr create(Ref ref) { + final argument = this.argument as (String, String); + return editorToolAccess(ref, argument.$1, argument.$2); + } + + @override + bool operator ==(Object other) { + return other is EditorToolAccessProvider && other.argument == argument; + } + + @override + int get hashCode { + return argument.hashCode; + } +} + +String _$editorToolAccessHash() => r'af03c156e8533b9f2535235df32cb086eceb86be'; + +final class EditorToolAccessFamily extends $Family + with + $FunctionalFamilyOverride< + FutureOr, + (String, String) + > { + EditorToolAccessFamily._() + : super( + retry: null, + name: r'editorToolAccessProvider', + dependencies: null, + $allTransitiveDependencies: null, + isAutoDispose: true, + ); + + EditorToolAccessProvider call(String projectId, String timelineId) => + EditorToolAccessProvider._(argument: (projectId, timelineId), from: this); + + @override + String toString() => r'editorToolAccessProvider'; +} + +@ProviderFor(applicationMcpConnection) +final applicationMcpConnectionProvider = ApplicationMcpConnectionProvider._(); + +final class ApplicationMcpConnectionProvider + extends $FunctionalProvider, void, FutureOr> + with $FutureModifier, $FutureProvider { + ApplicationMcpConnectionProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'applicationMcpConnectionProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$applicationMcpConnectionHash(); + + @$internal + @override + $FutureProviderElement $createElement($ProviderPointer pointer) => + $FutureProviderElement(pointer); + + @override + FutureOr create(Ref ref) { + return applicationMcpConnection(ref); + } +} + +String _$applicationMcpConnectionHash() => + r'1ee22c117137a4f6264e3e17404c554855594ed7'; + +@ProviderFor(editorMcpConnection) +final editorMcpConnectionProvider = EditorMcpConnectionFamily._(); + +final class EditorMcpConnectionProvider + extends $FunctionalProvider, void, FutureOr> + with $FutureModifier, $FutureProvider { + EditorMcpConnectionProvider._({ + required EditorMcpConnectionFamily super.from, + required (String, String) super.argument, + }) : super( + retry: null, + name: r'editorMcpConnectionProvider', + isAutoDispose: true, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$editorMcpConnectionHash(); + + @override + String toString() { + return r'editorMcpConnectionProvider' + '' + '$argument'; + } + + @$internal + @override + $FutureProviderElement $createElement($ProviderPointer pointer) => + $FutureProviderElement(pointer); + + @override + FutureOr create(Ref ref) { + final argument = this.argument as (String, String); + return editorMcpConnection(ref, argument.$1, argument.$2); + } + + @override + bool operator ==(Object other) { + return other is EditorMcpConnectionProvider && other.argument == argument; + } + + @override + int get hashCode { + return argument.hashCode; + } +} + +String _$editorMcpConnectionHash() => + r'990ea2ef5c40b8a2230af24f39cfb6a3a30ca09d'; + +final class EditorMcpConnectionFamily extends $Family + with $FunctionalFamilyOverride, (String, String)> { + EditorMcpConnectionFamily._() + : super( + retry: null, + name: r'editorMcpConnectionProvider', + dependencies: null, + $allTransitiveDependencies: null, + isAutoDispose: true, + ); + + EditorMcpConnectionProvider call(String projectId, String timelineId) => + EditorMcpConnectionProvider._( + argument: (projectId, timelineId), + from: this, + ); + + @override + String toString() => r'editorMcpConnectionProvider'; +} + +@ProviderFor(editorAgentToolsBinding) +final editorAgentToolsProvider = EditorAgentToolsBindingFamily._(); + +final class EditorAgentToolsBindingProvider + extends + $FunctionalProvider< + AsyncValue, + EditorAgentBinding, + FutureOr + > + with + $FutureModifier, + $FutureProvider { + EditorAgentToolsBindingProvider._({ + required EditorAgentToolsBindingFamily super.from, + required (String, String) super.argument, + }) : super( + retry: null, + name: r'editorAgentToolsProvider', + isAutoDispose: true, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$editorAgentToolsBindingHash(); + + @override + String toString() { + return r'editorAgentToolsProvider' + '' + '$argument'; + } + + @$internal + @override + $FutureProviderElement $createElement( + $ProviderPointer pointer, + ) => $FutureProviderElement(pointer); + + @override + FutureOr create(Ref ref) { + final argument = this.argument as (String, String); + return editorAgentToolsBinding(ref, argument.$1, argument.$2); + } + + @override + bool operator ==(Object other) { + return other is EditorAgentToolsBindingProvider && + other.argument == argument; + } + + @override + int get hashCode { + return argument.hashCode; + } +} + +String _$editorAgentToolsBindingHash() => + r'c38d5aeae513a8cfa744e03b6cba34a000cd6db6'; + +final class EditorAgentToolsBindingFamily extends $Family + with + $FunctionalFamilyOverride< + FutureOr, + (String, String) + > { + EditorAgentToolsBindingFamily._() + : super( + retry: null, + name: r'editorAgentToolsProvider', + dependencies: null, + $allTransitiveDependencies: null, + isAutoDispose: true, + ); + + EditorAgentToolsBindingProvider call(String projectId, String timelineId) => + EditorAgentToolsBindingProvider._( + argument: (projectId, timelineId), + from: this, + ); + + @override + String toString() => r'editorAgentToolsProvider'; +} diff --git a/lib/integrations/mcp/local_mcp_bridge.dart b/lib/integrations/mcp/local_mcp_bridge.dart new file mode 100644 index 0000000..7159ed0 --- /dev/null +++ b/lib/integrations/mcp/local_mcp_bridge.dart @@ -0,0 +1,98 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:cutdex_sdk/mcp.dart'; + +/// Private loopback transport for the stdio launcher. This is not an MCP HTTP +/// endpoint. The first line authenticates; remaining bytes are MCP stdio frames. +class LocalMcpBridge { + LocalMcpBridge._(this._listener, this._server, this._token) { + _listener.listen(_accept); + } + final ServerSocket _listener; + final CutdexMcpServer _server; + final String _token; + final _sockets = {}; + final _sessions = >{}; + bool _closed = false; + int get port => _listener.port; + + static Future start( + CutdexMcpServer server, { + required int port, + required String token, + }) async { + if (port < 0 || + port > 65535 || + token.length < 32 || + token.length > 1024 || + token.contains('\n') || + token.contains('\r')) { + throw ArgumentError( + 'MCP requires a valid port and a 32-1024 character token', + ); + } + final socket = await ServerSocket.bind(InternetAddress.loopbackIPv4, port); + return LocalMcpBridge._(socket, server, token); + } + + void _accept(Socket socket) { + if (_closed || _sockets.length >= 32) { + socket.destroy(); + return; + } + _sockets.add(socket); + final task = _serve(socket); + _sessions.add(task); + unawaited( + task.whenComplete(() { + _sessions.remove(task); + }), + ); + } + + Future _serve(Socket socket) async { + final input = StreamIterator>(socket); + try { + final bytes = []; + final deadline = DateTime.now().add(const Duration(seconds: 5)); + while (await input.moveNext().timeout( + deadline.difference(DateTime.now()), + )) { + final chunk = input.current; + final newline = chunk.indexOf(10); + final count = newline < 0 ? chunk.length : newline; + if (bytes.length + count > 4096) return; + bytes.addAll(chunk.take(count)); + if (newline < 0) continue; + if (utf8.decode(bytes) != _token) return; + Stream> frames() async* { + if (newline + 1 < chunk.length) yield chunk.sublist(newline + 1); + while (await input.moveNext()) { + yield input.current; + } + } + + await serveMcpStdio(_server, input: frames(), output: socket); + return; + } + } catch (_) { + // Transport failures end this connection, not the project or other clients. + } finally { + socket.destroy(); + await input.cancel(); + _sockets.remove(socket); + } + } + + Future close() async { + if (_closed) return; + _closed = true; + await _listener.close(); + for (final socket in _sockets.toList()) { + socket.destroy(); + } + await Future.wait(_sessions.toList()); + } +} diff --git a/lib/integrations/mcp/mcp_endpoint_controller.dart b/lib/integrations/mcp/mcp_endpoint_controller.dart new file mode 100644 index 0000000..671874c --- /dev/null +++ b/lib/integrations/mcp/mcp_endpoint_controller.dart @@ -0,0 +1,52 @@ +import 'dart:async'; + +import 'package:cutdex_sdk/mcp.dart'; + +import 'local_mcp_bridge.dart'; + +/// Serializes endpoint replacement so late cleanup cannot close its successor. +class EditorMcpEndpoint { + Future _tail = Future.value(); + LocalMcpBridge? _current; + bool _closed = false; + + Future _run(Future Function() action) { + final result = _tail.then((_) => action()); + _tail = result.then((_) {}, onError: (Object _, StackTrace _) {}); + return result; + } + + Future open( + CutdexMcpServer server, { + required int port, + required String token, + }) => _run(() async { + if (_closed) throw StateError('MCP endpoint owner is closed'); + await _current?.close(); + _current = null; + return _current = await LocalMcpBridge.start( + server, + port: port, + token: token, + ); + }); + + Future release(LocalMcpBridge bridge) => _run(() async { + if (!identical(_current, bridge)) return; + await bridge.close(); + _current = null; + }); + + Future close() { + _closed = true; + return _run(() async { + await _current?.close(); + _current = null; + }); + } + + Future stop() => _run(() async { + await _current?.close(); + _current = null; + }); +} diff --git a/lib/integrations/mcp/mcp_settings.dart b/lib/integrations/mcp/mcp_settings.dart new file mode 100644 index 0000000..f90639b --- /dev/null +++ b/lib/integrations/mcp/mcp_settings.dart @@ -0,0 +1,64 @@ +import 'dart:convert'; +import 'dart:math'; + +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import '../../persistence/settings/mcp_settings_repository.dart'; +import '../../settings/mcp_settings_value.dart'; +import '../../settings/settings_write_queue.dart'; + +export '../../settings/mcp_settings_value.dart'; + +part 'mcp_settings.g.dart'; + +@Riverpod(keepAlive: true) +class McpSettings extends _$McpSettings { + late McpSettingsRepository _repository; + final _writes = SettingsWriteQueue(); + + @override + Future build() async { + _repository = ref.watch(mcpSettingsRepositoryProvider); + final saved = await _repository.load(); + if (saved != null) { + _validate(saved); + return saved; + } + final random = Random.secure(); + final value = McpSettingsValue( + enabled: false, + port: 47831, + token: base64UrlEncode(List.generate(32, (_) => random.nextInt(256))), + ); + await _persist(value); + return value; + } + + Future saveSettings({bool? enabled, int? port}) { + return _writes.run(() async { + if (!ref.mounted) return; + final current = await future; + if (!ref.mounted) return; + final next = current.copyWith( + enabled: enabled ?? current.enabled, + port: port ?? current.port, + ); + _validate(next); + await _persist(next); + if (ref.mounted) state = AsyncData(next); + }); + } + + void _validate(McpSettingsValue value) { + if (value.port < 1 || + value.port > 65535 || + value.token.length < 32 || + value.token.length > 1024 || + value.token.contains('\r') || + value.token.contains('\n')) { + throw ArgumentError('Invalid MCP configuration'); + } + } + + Future _persist(McpSettingsValue value) => _repository.save(value); +} diff --git a/lib/integrations/mcp/mcp_settings.g.dart b/lib/integrations/mcp/mcp_settings.g.dart new file mode 100644 index 0000000..170a7ef --- /dev/null +++ b/lib/integrations/mcp/mcp_settings.g.dart @@ -0,0 +1,55 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'mcp_settings.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(McpSettings) +final mcpSettingsProvider = McpSettingsProvider._(); + +final class McpSettingsProvider + extends $AsyncNotifierProvider { + McpSettingsProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'mcpSettingsProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$mcpSettingsHash(); + + @$internal + @override + McpSettings create() => McpSettings(); +} + +String _$mcpSettingsHash() => r'122c5ad73d0eec5808c546eb66dde6c4b0f29a8a'; + +abstract class _$McpSettings extends $AsyncNotifier { + FutureOr build(); + @$mustCallSuper + @override + WhenComplete runBuild() { + final ref = + this.ref as $Ref, McpSettingsValue>; + final element = + ref.element + as $ClassProviderElement< + AnyNotifier, McpSettingsValue>, + AsyncValue, + Object?, + Object? + >; + return element.handleCreate(ref, build); + } +} diff --git a/lib/integrations/platform/device_experience.dart b/lib/integrations/platform/device_experience.dart new file mode 100644 index 0000000..3b06312 --- /dev/null +++ b/lib/integrations/platform/device_experience.dart @@ -0,0 +1,67 @@ +import 'dart:ui' as ui; + +import 'package:cutdex_native/cutdex_native.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +/// A host/device experience, independent of window size and connected inputs. +enum DeviceExperience { desktop, tablet, phone } + +final deviceExperienceProvider = Provider((ref) { + final display = ui.PlatformDispatcher.instance.views.firstOrNull?.display; + return DeviceExperienceDetector.fallback( + platform: defaultTargetPlatform, + displaySize: display?.size ?? ui.Size.zero, + pixelRatio: display?.devicePixelRatio ?? 1, + ); +}); + +/// Resolves once at startup; resizing, rotation and keyboard events do not run it. +abstract final class DeviceExperienceDetector { + static DeviceExperience fallback({ + required TargetPlatform platform, + required ui.Size displaySize, + required double pixelRatio, + }) { + if (platform != TargetPlatform.android && platform != TargetPlatform.iOS) { + return DeviceExperience.desktop; + } + // This is the full display, never MediaQuery's application window. + return pixelRatio > 0 && displaySize.shortestSide / pixelRatio >= 600 + ? DeviceExperience.tablet + : DeviceExperience.phone; + } + + static Future detect({ + required TargetPlatform platform, + required ui.Size displaySize, + required double pixelRatio, + bool web = false, + }) async { + final defaultExperience = fallback( + platform: platform, + displaySize: displaySize, + pixelRatio: pixelRatio, + ); + if (web || + (platform != TargetPlatform.android && + platform != TargetPlatform.iOS)) { + return defaultExperience; + } + final info = await NativeDeviceInfo.read(); + if (platform == TargetPlatform.iOS) { + return switch (info?.interfaceIdiom) { + NativeInterfaceIdiom.pad => DeviceExperience.tablet, + NativeInterfaceIdiom.mac => DeviceExperience.desktop, + NativeInterfaceIdiom.phone => DeviceExperience.phone, + null => defaultExperience, + }; + } + final shortestSide = info?.displayShortestSideDp; + return shortestSide == null + ? defaultExperience + : shortestSide >= 600 + ? DeviceExperience.tablet + : DeviceExperience.phone; + } +} diff --git a/lib/integrations/platform/editor_window_chrome.dart b/lib/integrations/platform/editor_window_chrome.dart new file mode 100644 index 0000000..12cc0b4 --- /dev/null +++ b/lib/integrations/platform/editor_window_chrome.dart @@ -0,0 +1,100 @@ +import 'package:flutter/material.dart'; + +import 'window_caption_controls.dart'; + +import 'package:cutdex_native/cutdex_native.dart'; + +/// Shared native titlebar layout; a close callback opts into editor navigation. +class EditorWindowChrome extends StatefulWidget { + const EditorWindowChrome({ + super.key, + required this.headerHeight, + this.onCloseRequested, + required this.builder, + }); + + static const trafficLightWidth = 88.0; + static bool get isWindows => WindowChromeSession.isWindows; + static double get leadingWidth => isWindows ? 0 : trafficLightWidth; + final double headerHeight; + final VoidCallback? onCloseRequested; + final Widget Function(BuildContext context, bool integrated) builder; + + @override + State createState() => _EditorWindowChromeState(); +} + +class _EditorWindowChromeState extends State { + late final _session = WindowChromeSession( + headerHeight: widget.headerHeight, + onCloseRequested: widget.onCloseRequested, + ); + bool _integrated = false; + + @override + void initState() { + super.initState(); + _session.addListener(_integrationChanged); + _session.attach(); + } + + void _integrationChanged() { + if (_integrated != _session.integrated) { + setState(() => _integrated = _session.integrated); + } + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _session.setInteractive(ModalRoute.of(context)?.isCurrent ?? true); + } + + @override + void didUpdateWidget(covariant EditorWindowChrome oldWidget) { + super.didUpdateWidget(oldWidget); + _session.configure( + headerHeight: widget.headerHeight, + onCloseRequested: widget.onCloseRequested, + ); + } + + @override + void dispose() { + _session.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + if (!_integrated || !EditorWindowChrome.isWindows) { + return widget.builder(context, _integrated); + } + return LayoutBuilder( + builder: (context, constraints) => WindowHeaderLayout( + captionBounds: Rect.fromLTWH( + constraints.maxWidth - WindowCaptionControls.width, + 0, + WindowCaptionControls.width, + widget.headerHeight, + ), + child: Stack( + fit: StackFit.expand, + children: [ + Builder(builder: (context) => widget.builder(context, true)), + Positioned( + top: 0, + right: 0, + width: WindowCaptionControls.width, + height: widget.headerHeight, + child: WindowCaptionControls( + session: _session, + height: widget.headerHeight, + ), + ), + ], + ), + ), + ); + } +} diff --git a/lib/integrations/platform/file_picker.dart b/lib/integrations/platform/file_picker.dart new file mode 100644 index 0000000..f4dc8c7 --- /dev/null +++ b/lib/integrations/platform/file_picker.dart @@ -0,0 +1,58 @@ +import 'package:filegate/filegate.dart'; +import 'package:flutter/services.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import '../../workspace/media_import.dart'; + +part 'file_picker.g.dart'; + +@Riverpod(keepAlive: true) +AppFilePicker filePicker(Ref ref) => const AppFilePicker(); + +class AppFilePicker { + const AppFilePicker(); + + Future pickDirectory({ + String? initialDirectory, + String? confirmButtonText, + }) async { + final entry = await const Filegate().pickDirectory( + initialDirectory: initialDirectory, + confirmButtonText: confirmButtonText, + ); + return entry == null ? null : _localPath(entry); + } + + Future> pickFiles({ + required List allowedExtensions, + }) async { + final entries = await const Filegate().pickFiles( + allowMultiple: true, + allowedExtensions: allowedExtensions, + persistAccess: false, + ); + return [ + for (final entry in entries ?? []) + if (entry.isContentUri) + ExternalMediaFile.content( + uri: entry.uri!, + name: entry.name, + byteLength: entry.size, + ) + else + ExternalMediaFile(path: _localPath(entry)), + ]; + } + + String _localPath(PickedEntry entry) { + final path = entry.fileSystemPath; + if (path == null) { + throw PlatformException( + code: 'unsupported_location', + message: 'Cutdex requires a local file system path.', + details: entry.path, + ); + } + return path; + } +} diff --git a/lib/integrations/platform/file_picker.g.dart b/lib/integrations/platform/file_picker.g.dart new file mode 100644 index 0000000..8eac758 --- /dev/null +++ b/lib/integrations/platform/file_picker.g.dart @@ -0,0 +1,51 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'file_picker.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(filePicker) +final filePickerProvider = FilePickerProvider._(); + +final class FilePickerProvider + extends $FunctionalProvider + with $Provider { + FilePickerProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'filePickerProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$filePickerHash(); + + @$internal + @override + $ProviderElement $createElement($ProviderPointer pointer) => + $ProviderElement(pointer); + + @override + AppFilePicker create(Ref ref) { + return filePicker(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(AppFilePicker value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$filePickerHash() => r'8f869df0d25e7b43e434586c35e8e6aed225245d'; diff --git a/lib/integrations/platform/media_source_reader.dart b/lib/integrations/platform/media_source_reader.dart new file mode 100644 index 0000000..2143946 --- /dev/null +++ b/lib/integrations/platform/media_source_reader.dart @@ -0,0 +1,15 @@ +import 'package:filegate/filegate.dart'; + +/// Streams provider documents without exposing filegate to workspace logic. +class MediaSourceReader { + const MediaSourceReader(); + + Stream> openRead(Uri uri) async* { + final session = const Filegate().openRead(uri.toString()); + try { + yield* session.stream; + } finally { + await session.cancel(); + } + } +} diff --git a/lib/integrations/platform/native_file_drop_policy.dart b/lib/integrations/platform/native_file_drop_policy.dart new file mode 100644 index 0000000..6021332 --- /dev/null +++ b/lib/integrations/platform/native_file_drop_policy.dart @@ -0,0 +1,28 @@ +import 'package:cutdex_native/cutdex_native.dart'; + +import '../../workspace/media_file_extensions.dart'; +import '../../workspace/media_import.dart'; + +/// File acceptance shared by Flutter and the native drop destinations. +enum NativeFileDropPolicy { + mediaLibrary, + timeline, + attachments; + + List? get allowedExtensions => switch (this) { + timeline => selectableTimelineFileExtensions, + // Library imports validate each file so mixed batches retain valid media. + mediaLibrary || attachments => null, + }; + + int? get maximumFileCount => this == timeline ? 1 : null; + + bool accepts(List files) => + files.every((file) => file.localPath != null) && + configuration.accepts([for (final file in files) file.localPath!]); + + NativeDropConfiguration get configuration => NativeDropConfiguration( + allowedExtensions: allowedExtensions, + maximumFileCount: maximumFileCount, + ); +} diff --git a/lib/integrations/platform/native_project_drop_region.dart b/lib/integrations/platform/native_project_drop_region.dart new file mode 100644 index 0000000..14773f3 --- /dev/null +++ b/lib/integrations/platform/native_project_drop_region.dart @@ -0,0 +1,41 @@ +import 'package:cutdex_native/cutdex_native.dart'; +import 'package:flutter/widgets.dart'; + +import '../../workspace/media_import.dart'; +import 'native_file_drop_policy.dart'; + +/// Applies application media rules to a generic native file destination. +class NativeProjectDropRegion extends StatelessWidget { + const NativeProjectDropRegion({ + super.key, + this.regionId = 'media-library', + this.policy = NativeFileDropPolicy.mediaLibrary, + required this.enabled, + required this.onEnter, + required this.onExit, + required this.onDrop, + required this.child, + }); + final String regionId; + final NativeFileDropPolicy policy; + final bool enabled; + final ValueChanged> onEnter; + final VoidCallback onExit; + final Future Function(List) onDrop; + final Widget child; + + List _files(List paths) => [ + for (final path in paths) ExternalMediaFile(path: path), + ]; + + @override + Widget build(BuildContext context) => NativeFileDropRegion( + regionId: regionId, + configuration: policy.configuration, + enabled: enabled, + onEnter: (paths) => onEnter(_files(paths)), + onExit: onExit, + onDrop: (paths) => onDrop(_files(paths)), + child: child, + ); +} diff --git a/lib/integrations/platform/platform_capabilities.dart b/lib/integrations/platform/platform_capabilities.dart new file mode 100644 index 0000000..e673e6d --- /dev/null +++ b/lib/integrations/platform/platform_capabilities.dart @@ -0,0 +1,22 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +final platformCapabilitiesProvider = Provider( + (ref) => PlatformCapabilities( + localFileSelection: !kIsWeb, + nativeFileDrop: + !kIsWeb && + (defaultTargetPlatform == TargetPlatform.macOS || + defaultTargetPlatform == TargetPlatform.windows), + ), +); + +/// Describes supported integration paths, never a workspace size class. +final class PlatformCapabilities { + const PlatformCapabilities({ + required this.localFileSelection, + required this.nativeFileDrop, + }); + final bool localFileSelection; + final bool nativeFileDrop; +} diff --git a/lib/integrations/platform/window_caption_controls.dart b/lib/integrations/platform/window_caption_controls.dart new file mode 100644 index 0000000..b9386a7 --- /dev/null +++ b/lib/integrations/platform/window_caption_controls.dart @@ -0,0 +1,98 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; + +import '../../l10n/l10n.dart'; + +import 'package:cutdex_native/cutdex_native.dart'; + +/// Windows caption buttons; native window state only rebuilds this strip. +class WindowCaptionControls extends StatelessWidget { + const WindowCaptionControls({ + super.key, + required this.session, + required this.height, + }); + static const buttonWidth = 46.0; + static const width = buttonWidth * 3; + final WindowChromeSession session; + final double height; + + @override + Widget build(BuildContext context) => ListenableBuilder( + listenable: session, + builder: (context, _) => Material( + color: Theme.of(context).colorScheme.surface, + child: Row( + children: [ + _button( + context, + WindowCaptionCommand.minimize, + Icons.remove, + context.l10n.windowMinimize, + ), + _button( + context, + WindowCaptionCommand.toggleMaximize, + session.maximized ? Icons.filter_none : Icons.crop_square, + session.maximized + ? context.l10n.windowRestore + : context.l10n.windowMaximize, + role: HeaderControlRole.maximize, + hovered: session.maximizeHovered, + ), + _button( + context, + WindowCaptionCommand.close, + Icons.close, + MaterialLocalizations.of(context).closeButtonTooltip, + ), + ], + ), + ), + ); + + Widget _button( + BuildContext context, + WindowCaptionCommand command, + IconData icon, + String label, { + HeaderControlRole role = HeaderControlRole.control, + bool hovered = false, + }) { + final colors = Theme.of(context).colorScheme; + final close = command == WindowCaptionCommand.close; + final key = command == WindowCaptionCommand.toggleMaximize + ? 'maximize' + : command.name; + return HeaderControlRegion( + role: role, + child: SizedBox( + width: buttonWidth, + height: height, + child: IconButton( + key: Key('window-$key'), + tooltip: label, + onPressed: () => unawaited(session.perform(command)), + icon: Icon(icon, size: 16), + style: ButtonStyle( + padding: const WidgetStatePropertyAll(EdgeInsets.zero), + shape: const WidgetStatePropertyAll(RoundedRectangleBorder()), + backgroundColor: WidgetStateProperty.resolveWith( + (states) => states.contains(WidgetState.hovered) || hovered + ? close + ? const Color(0xffc42b1c) + : colors.onSurface.withValues(alpha: 0.08) + : Colors.transparent, + ), + foregroundColor: WidgetStateProperty.resolveWith( + (states) => close && states.contains(WidgetState.hovered) + ? Colors.white + : colors.onSurface, + ), + ), + ), + ), + ); + } +} diff --git a/lib/integrations/runtime/editor_export.dart b/lib/integrations/runtime/editor_export.dart new file mode 100644 index 0000000..6b89141 --- /dev/null +++ b/lib/integrations/runtime/editor_export.dart @@ -0,0 +1,71 @@ +import 'dart:io'; +import 'dart:convert'; + +import 'package:crypto/crypto.dart'; + +import 'export_publication.dart'; + +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/runtime.dart'; + +/// Native session and output-file adapter. Compilation belongs to editor. +final class RuntimeEditorExport implements RecoverableEditorExportService { + const RuntimeEditorExport(this.runtime); + final CutdexRuntime runtime; + + @override + Future probe(MediaReference media) => runtime.probe(media); + + @override + Future capabilities() async { + final features = await runtime.capabilities(); + return EditorExportCapabilities( + imageProbe: + features.query('media.imageProbe') == + CapabilityAvailability.available, + toneMapping: + features.query('render.toneMapping') == + CapabilityAvailability.available, + ); + } + + @override + Future recoverExport(Uri destination, String operationId) => + ExportPublication(destination, operationId).recover(); + + @override + Future exportRecoverable( + ExecutionPlan plan, + Uri destination, + String operationId, + ) => ExportPublication(destination, operationId).run( + sha256.convert(utf8.encode(jsonEncode(plan.toMap()))).toString(), + (staging) => export(plan, staging), + ); + + @override + Future export(ExecutionPlan plan, Uri destination) async { + if (await FileSystemEntity.type( + destination.toFilePath(), + followLinks: false, + ) != + FileSystemEntityType.notFound) { + throw const CommandRejected( + 'destinationExists', + 'Destination already exists', + ); + } + if (!await File.fromUri(destination).parent.exists()) { + throw const CommandRejected( + 'invalidDestination', + 'Destination directory does not exist', + ); + } + final session = await runtime.createSession(); + try { + return await session.export(plan, destination); + } finally { + await session.close(); + } + } +} diff --git a/lib/integrations/runtime/export_publication.dart b/lib/integrations/runtime/export_publication.dart new file mode 100644 index 0000000..92f760d --- /dev/null +++ b/lib/integrations/runtime/export_publication.dart @@ -0,0 +1,108 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:crypto/crypto.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:path/path.dart' as p; + +/// A completed staging file and its digest are durable before publication. +/// Only this operation's recorded output is eligible for recovery. +final class ExportPublication { + ExportPublication(this.destination, this.operationId); + final Uri destination; + final String operationId; + File get output => File.fromUri(destination); + Directory get directory => Directory( + p.join( + output.parent.path, + '.cutdex-export-${sha256.convert(utf8.encode('$operationId|$destination'))}', + ), + ); + File get staged => File(p.join(directory.path, 'output.mp4')); + File get receipt => File(p.join(directory.path, 'receipt.json')); + + Future _digest(File file) async => + (await sha256.bind(file.openRead()).first).toString(); + Future _save(Map value) async { + final temporary = File('${receipt.path}.tmp'); + await temporary.writeAsString(jsonEncode(value), flush: true); + await temporary.rename(receipt.path); + } + + Future recover() async { + if (!await receipt.exists()) return null; + final value = (jsonDecode(await receipt.readAsString()) as Map) + .cast(); + if (value['operationId'] != operationId || + value['destination'] != destination.toString()) { + throw const CommandRejected( + 'operationIdConflict', + 'Export receipt belongs to another request', + ); + } + if (value['sha256'] == null) return null; + final candidate = await output.exists() ? output : staged; + if (!await candidate.exists() || + await candidate.length() != value['bytes'] || + await _digest(candidate) != value['sha256']) { + throw const CommandRejected( + 'exportArtifactChanged', + 'Export output is missing or changed; choose a new destination to retry', + ); + } + if (candidate.path == staged.path) await staged.rename(output.path); + return destination; + } + + Future run(String fingerprint, Future Function(Uri) encode) async { + if (await receipt.exists()) { + final value = jsonDecode(await receipt.readAsString()) as Map; + if (value['fingerprint'] != fingerprint) { + throw const CommandRejected( + 'operationIdConflict', + 'Export snapshot changed', + ); + } + } + final recovered = await recover(); + if (recovered != null) return recovered; + if (await output.exists()) { + throw const CommandRejected( + 'destinationExists', + 'Destination already exists', + ); + } + if (!await output.parent.exists()) { + throw const CommandRejected( + 'invalidDestination', + 'Destination directory does not exist', + ); + } + if (await receipt.exists()) { + throw const CommandRejected( + 'exportInterrupted', + 'Export was interrupted before publication; explicitly retry with a new operation', + ); + } + await directory.create(); + final record = { + 'operationId': operationId, + 'destination': destination.toString(), + 'fingerprint': fingerprint, + }; + await _save(record); + await encode(staged.uri); + final handle = await staged.open(mode: FileMode.append); + try { + await handle.flush(); + } finally { + await handle.close(); + } + await _save({ + ...record, + 'bytes': await staged.length(), + 'sha256': await _digest(staged), + }); + return (await recover())!; + } +} diff --git a/lib/integrations/runtime/media_presentations.dart b/lib/integrations/runtime/media_presentations.dart new file mode 100644 index 0000000..2747f98 --- /dev/null +++ b/lib/integrations/runtime/media_presentations.dart @@ -0,0 +1,27 @@ +import 'dart:typed_data'; + +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/timeline_ui.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import 'media_thumbnails.dart'; +import 'media_waveforms.dart'; + +part 'media_presentations.g.dart'; + +@riverpod +Future mediaCover( + Ref ref, + AssetDocument asset, { + int timeMilliseconds = 0, +}) => ref + .watch(mediaThumbnailsProvider) + .load(asset, timeMilliseconds: timeMilliseconds); + +@riverpod +Future mediaDuration(Ref ref, AssetDocument asset) => + ref.watch(mediaThumbnailsProvider).duration(asset); + +@riverpod +Future mediaWaveform(Ref ref, AssetDocument asset) => + ref.watch(mediaWaveformsProvider).load(asset); diff --git a/lib/integrations/runtime/media_presentations.g.dart b/lib/integrations/runtime/media_presentations.g.dart new file mode 100644 index 0000000..d2daba9 --- /dev/null +++ b/lib/integrations/runtime/media_presentations.g.dart @@ -0,0 +1,241 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'media_presentations.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(mediaCover) +final mediaCoverProvider = MediaCoverFamily._(); + +final class MediaCoverProvider + extends + $FunctionalProvider< + AsyncValue, + Uint8List?, + FutureOr + > + with $FutureModifier, $FutureProvider { + MediaCoverProvider._({ + required MediaCoverFamily super.from, + required (AssetDocument, {int timeMilliseconds}) super.argument, + }) : super( + retry: null, + name: r'mediaCoverProvider', + isAutoDispose: true, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$mediaCoverHash(); + + @override + String toString() { + return r'mediaCoverProvider' + '' + '$argument'; + } + + @$internal + @override + $FutureProviderElement $createElement($ProviderPointer pointer) => + $FutureProviderElement(pointer); + + @override + FutureOr create(Ref ref) { + final argument = this.argument as (AssetDocument, {int timeMilliseconds}); + return mediaCover( + ref, + argument.$1, + timeMilliseconds: argument.timeMilliseconds, + ); + } + + @override + bool operator ==(Object other) { + return other is MediaCoverProvider && other.argument == argument; + } + + @override + int get hashCode { + return argument.hashCode; + } +} + +String _$mediaCoverHash() => r'34b3ae0fa1106a3448028e34ca2f0c64838a3d6a'; + +final class MediaCoverFamily extends $Family + with + $FunctionalFamilyOverride< + FutureOr, + (AssetDocument, {int timeMilliseconds}) + > { + MediaCoverFamily._() + : super( + retry: null, + name: r'mediaCoverProvider', + dependencies: null, + $allTransitiveDependencies: null, + isAutoDispose: true, + ); + + MediaCoverProvider call(AssetDocument asset, {int timeMilliseconds = 0}) => + MediaCoverProvider._( + argument: (asset, timeMilliseconds: timeMilliseconds), + from: this, + ); + + @override + String toString() => r'mediaCoverProvider'; +} + +@ProviderFor(mediaDuration) +final mediaDurationProvider = MediaDurationFamily._(); + +final class MediaDurationProvider + extends $FunctionalProvider, double?, FutureOr> + with $FutureModifier, $FutureProvider { + MediaDurationProvider._({ + required MediaDurationFamily super.from, + required AssetDocument super.argument, + }) : super( + retry: null, + name: r'mediaDurationProvider', + isAutoDispose: true, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$mediaDurationHash(); + + @override + String toString() { + return r'mediaDurationProvider' + '' + '($argument)'; + } + + @$internal + @override + $FutureProviderElement $createElement($ProviderPointer pointer) => + $FutureProviderElement(pointer); + + @override + FutureOr create(Ref ref) { + final argument = this.argument as AssetDocument; + return mediaDuration(ref, argument); + } + + @override + bool operator ==(Object other) { + return other is MediaDurationProvider && other.argument == argument; + } + + @override + int get hashCode { + return argument.hashCode; + } +} + +String _$mediaDurationHash() => r'065f3604e588f088d9fe4454a77a71a4eaed57b6'; + +final class MediaDurationFamily extends $Family + with $FunctionalFamilyOverride, AssetDocument> { + MediaDurationFamily._() + : super( + retry: null, + name: r'mediaDurationProvider', + dependencies: null, + $allTransitiveDependencies: null, + isAutoDispose: true, + ); + + MediaDurationProvider call(AssetDocument asset) => + MediaDurationProvider._(argument: asset, from: this); + + @override + String toString() => r'mediaDurationProvider'; +} + +@ProviderFor(mediaWaveform) +final mediaWaveformProvider = MediaWaveformFamily._(); + +final class MediaWaveformProvider + extends + $FunctionalProvider< + AsyncValue, + TimelineWaveform?, + FutureOr + > + with + $FutureModifier, + $FutureProvider { + MediaWaveformProvider._({ + required MediaWaveformFamily super.from, + required AssetDocument super.argument, + }) : super( + retry: null, + name: r'mediaWaveformProvider', + isAutoDispose: true, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$mediaWaveformHash(); + + @override + String toString() { + return r'mediaWaveformProvider' + '' + '($argument)'; + } + + @$internal + @override + $FutureProviderElement $createElement( + $ProviderPointer pointer, + ) => $FutureProviderElement(pointer); + + @override + FutureOr create(Ref ref) { + final argument = this.argument as AssetDocument; + return mediaWaveform(ref, argument); + } + + @override + bool operator ==(Object other) { + return other is MediaWaveformProvider && other.argument == argument; + } + + @override + int get hashCode { + return argument.hashCode; + } +} + +String _$mediaWaveformHash() => r'7556aade813f27763c5407b5decc65b20e5db616'; + +final class MediaWaveformFamily extends $Family + with $FunctionalFamilyOverride, AssetDocument> { + MediaWaveformFamily._() + : super( + retry: null, + name: r'mediaWaveformProvider', + dependencies: null, + $allTransitiveDependencies: null, + isAutoDispose: true, + ); + + MediaWaveformProvider call(AssetDocument asset) => + MediaWaveformProvider._(argument: asset, from: this); + + @override + String toString() => r'mediaWaveformProvider'; +} diff --git a/lib/integrations/runtime/media_thumbnails.dart b/lib/integrations/runtime/media_thumbnails.dart new file mode 100644 index 0000000..51cb18d --- /dev/null +++ b/lib/integrations/runtime/media_thumbnails.dart @@ -0,0 +1,130 @@ +import 'dart:io'; +import 'dart:ui' as ui; + +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:flutter/foundation.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import '../../workspace/media_binding.dart'; +import '../../workspace/projects.dart'; + +import 'package:flutter_riverpod/flutter_riverpod.dart' + show ProviderListenableSelect; +part 'media_thumbnails.g.dart'; + +@Riverpod(keepAlive: true) +MediaThumbnails mediaThumbnails(Ref ref) { + final projectId = ref.watch( + projectsProvider.select((s) => s.asData?.value.activeProject?.id), + ); + return MediaThumbnails( + loadMedia: (asset, action) => ref + .read(projectsProvider.notifier) + .withAssetMedia(projectId, asset, action), + ); +} + +/// Small runtime-generated browser covers, kept outside the project document. +class MediaThumbnails { + MediaThumbnails({required this.loadMedia}); + final AssetMediaLoader loadMedia; + final _runtime = CutdexRuntime(); + final _cache = <(String, int?, int), Future>{}; + final _durations = <(String, int?), Future>{}; + Future _tail = Future.value(); + + Future duration(AssetDocument asset) { + final key = (asset.location, asset.byteLength); + if (_durations.containsKey(key)) return _durations[key]!; + if (_durations.length >= 64) _durations.remove(_durations.keys.first); + return _durations[key] = () async { + try { + final info = await loadMedia(asset, _runtime.probe); + final seconds = info.duration.numerator / info.duration.denominator; + return seconds.isFinite && seconds > 0 ? seconds : null; + } catch (_) { + return null; + } + }(); + } + + Future load(AssetDocument asset, {int timeMilliseconds = 0}) { + final key = (asset.location, asset.byteLength, timeMilliseconds); + final cached = _cache.remove(key); + if (cached != null) { + _cache[key] = cached; + return cached; + } + // Bound encoded cover retention and concurrent native generation. + if (_cache.length >= 64) _cache.remove(_cache.keys.first); + final future = _tail.then((_) async { + if (asset.metadata['kind'] == 'image') { + final image = await _imagePreview(asset); + if (image != null) return image; + } + try { + final thumbnail = await loadMedia( + asset, + (media) => _runtime.thumbnail( + ThumbnailRequest( + media: media, + time: MediaTime(timeMilliseconds, 1000), + ), + ), + ); + return thumbnail.data; + } catch (_) { + return null; + } + }); + _cache[key] = future; + _tail = future.then((_) {}); + return future; + } + + Future _imagePreview(AssetDocument asset) async { + if (kIsWeb) return null; + try { + return await loadMedia(asset, (media) async { + if (media.uri.scheme != 'file') return null; + final file = File.fromUri(media.uri); + if (!file.existsSync()) return null; + final bytes = await file.readAsBytes(); + final buffer = await ui.ImmutableBuffer.fromUint8List(bytes); + try { + final descriptor = await ui.ImageDescriptor.encoded(buffer); + try { + final longestSide = descriptor.width > descriptor.height + ? descriptor.width + : descriptor.height; + final scale = longestSide > 320 ? 320 / longestSide : 1.0; + final codec = await descriptor.instantiateCodec( + targetWidth: (descriptor.width * scale).round(), + targetHeight: (descriptor.height * scale).round(), + ); + try { + final frame = await codec.getNextFrame(); + try { + return (await frame.image.toByteData( + format: ui.ImageByteFormat.png, + ))?.buffer.asUint8List(); + } finally { + frame.image.dispose(); + } + } finally { + codec.dispose(); + } + } finally { + descriptor.dispose(); + } + } finally { + buffer.dispose(); + } + }); + } catch (_) { + // Formats not handled by Flutter can still use the native thumbnailer. + return null; + } + } +} diff --git a/lib/integrations/runtime/media_thumbnails.g.dart b/lib/integrations/runtime/media_thumbnails.g.dart new file mode 100644 index 0000000..3aa614b --- /dev/null +++ b/lib/integrations/runtime/media_thumbnails.g.dart @@ -0,0 +1,52 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'media_thumbnails.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(mediaThumbnails) +final mediaThumbnailsProvider = MediaThumbnailsProvider._(); + +final class MediaThumbnailsProvider + extends + $FunctionalProvider + with $Provider { + MediaThumbnailsProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'mediaThumbnailsProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$mediaThumbnailsHash(); + + @$internal + @override + $ProviderElement $createElement($ProviderPointer pointer) => + $ProviderElement(pointer); + + @override + MediaThumbnails create(Ref ref) { + return mediaThumbnails(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(MediaThumbnails value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$mediaThumbnailsHash() => r'80b7a58411b734ef13efcbd01eeef5ef125d06d4'; diff --git a/lib/integrations/runtime/media_waveforms.dart b/lib/integrations/runtime/media_waveforms.dart new file mode 100644 index 0000000..aa9a10a --- /dev/null +++ b/lib/integrations/runtime/media_waveforms.dart @@ -0,0 +1,67 @@ +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline_ui.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import '../../workspace/media_binding.dart'; +import '../../workspace/projects.dart'; + +import 'package:flutter_riverpod/flutter_riverpod.dart' + show ProviderListenableSelect; +part 'media_waveforms.g.dart'; + +@Riverpod(keepAlive: true) +MediaWaveforms mediaWaveforms(Ref ref) { + final projectId = ref.watch( + projectsProvider.select((s) => s.asData?.value.activeProject?.id), + ); + return MediaWaveforms( + loadMedia: (asset, action) => ref + .read(projectsProvider.notifier) + .withAssetMedia(projectId, asset, action), + ); +} + +/// Browser envelopes use the same native request/cache as timeline waveforms. +class MediaWaveforms { + MediaWaveforms({required this.loadMedia}); + final AssetMediaLoader loadMedia; + final _runtime = CutdexRuntime(); + final _cache = <(String, int?), Future>{}; + Future _tail = Future.value(); + + Future load(AssetDocument asset) { + final key = (asset.location, asset.byteLength); + final cached = _cache.remove(key); + if (cached != null) { + _cache[key] = cached; + return cached; + } + if (_cache.length >= 16) _cache.remove(_cache.keys.first); + final future = _tail.then((_) async { + try { + final waveform = await loadMedia( + asset, + (media) => _runtime.waveform(WaveformRequest(media: media)), + ); + return TimelineWaveform( + sampleRate: waveform.sampleRate, + sourceStartSeconds: waveform.sourceStartSeconds, + frameCount: waveform.frameCount, + levels: List.unmodifiable([ + for (final level in waveform.levels) + TimelineWaveformLevel( + samplesPerBucket: level.samplesPerBucket, + channels: level.channels, + ), + ]), + ); + } catch (_) { + return null; + } + }); + _cache[key] = future; + _tail = future.then((_) {}); + return future; + } +} diff --git a/lib/integrations/runtime/media_waveforms.g.dart b/lib/integrations/runtime/media_waveforms.g.dart new file mode 100644 index 0000000..6ce36d2 --- /dev/null +++ b/lib/integrations/runtime/media_waveforms.g.dart @@ -0,0 +1,51 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'media_waveforms.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(mediaWaveforms) +final mediaWaveformsProvider = MediaWaveformsProvider._(); + +final class MediaWaveformsProvider + extends $FunctionalProvider + with $Provider { + MediaWaveformsProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'mediaWaveformsProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$mediaWaveformsHash(); + + @$internal + @override + $ProviderElement $createElement($ProviderPointer pointer) => + $ProviderElement(pointer); + + @override + MediaWaveforms create(Ref ref) { + return mediaWaveforms(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(MediaWaveforms value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$mediaWaveformsHash() => r'0523a0e7fc9f29c37c23d7c17d77a167294bde54'; diff --git a/lib/integrations/runtime/processing_configuration.dart b/lib/integrations/runtime/processing_configuration.dart new file mode 100644 index 0000000..618ec82 --- /dev/null +++ b/lib/integrations/runtime/processing_configuration.dart @@ -0,0 +1,178 @@ +import 'dart:io'; + +import 'package:cutdex_sdk/runtime/processing.dart'; +import 'package:path/path.dart' as p; + +/// App deployment configuration for non-realtime native processing. +final class ProcessingConfiguration { + const ProcessingConfiguration({ + required this.backend, + this.transcriptionModel, + this.translationModel, + this.vocalSeparationModel, + this.backgroundRemovalModel, + }); + + final CutdexProcessing backend; + final Uri? transcriptionModel; + final Uri? translationModel; + final Uri? vocalSeparationModel; + final Uri? backgroundRemovalModel; + + static String get _defaultResourcesRoot { + if (Platform.isMacOS) { + return p.join( + Platform.environment['HOME'] ?? '', + 'Documents', + 'Cutdex', + 'Resources', + ); + } + if (Platform.isWindows) { + return p.join( + Platform.environment['USERPROFILE'] ?? '', + 'Documents', + 'Cutdex', + 'Resources', + ); + } + return p.join( + Platform.environment['HOME'] ?? '', + 'Documents', + 'Cutdex', + 'Resources', + ); + } + + static String get _bundledRuntimeRoot { + final executable = File(Platform.resolvedExecutable); + if (Platform.isMacOS) { + return p.normalize( + p.join(executable.parent.path, '..', 'Resources', 'processing'), + ); + } + return p.join(executable.parent.path, 'processing'); + } + + static ProcessingConfiguration? configured({ + String? resourcesRoot, + DiagnosticSink? diagnostics, + }) { + const definedRoot = String.fromEnvironment('CUTDEX_PROCESSING_ROOT'); + final root = definedRoot.isNotEmpty + ? definedRoot + : Platform.environment['CUTDEX_PROCESSING_ROOT'] ?? _bundledRuntimeRoot; + final modelsRoot = p.join( + resourcesRoot ?? _defaultResourcesRoot, + 'Processing', + ); + final transcriptionPath = p.join( + modelsRoot, + 'Transcription', + 'whisper-turbo', + '1', + ); + final vocalPath = p.join( + modelsRoot, + 'VocalSeparation', + 'melband', + '1', + 'melband.pt', + ); + final translationPath = p.join( + modelsRoot, + 'Translation', + 'm2m100-418m', + '1', + ); + final backgroundRemovalPath = p.join( + modelsRoot, + 'BackgroundRemoval', + 'birefnet-matting', + '1', + 'model.onnx', + ); + return fromPaths( + root: root, + transcriptionPath: transcriptionPath, + vocalPath: vocalPath, + translationPath: translationPath, + backgroundRemovalPath: backgroundRemovalPath, + diagnostics: diagnostics, + ); + } + + /// Resolves each installed capability independently; absent files disable only that capability. + static ProcessingConfiguration? fromPaths({ + required String root, + required String transcriptionPath, + required String vocalPath, + required String translationPath, + String? backgroundRemovalPath, + DiagnosticSink? diagnostics, + }) { + if (!p.isAbsolute(root)) return null; + final exe = Platform.isWindows ? '.exe' : ''; + final executable = p.join(root, 'bin', 'cutdex-processing-worker$exe'); + final ffmpeg = p.join(root, 'bin', 'ffmpeg$exe'); + if (!File(executable).existsSync()) { + return null; + } + final asrWorker = p.join(root, 'workers', 'asr', 'cutdex-asr-worker$exe'); + final transcriptionModel = + p.isAbsolute(transcriptionPath) && + File(ffmpeg).existsSync() && + File(asrWorker).existsSync() && + File(p.join(transcriptionPath, 'ggml-model.bin')).existsSync() && + File(p.join(transcriptionPath, 'silero_vad.onnx')).existsSync() + ? Uri.directory(transcriptionPath) + : null; + final audioWorker = p.join( + root, + 'workers', + 'audio', + 'cutdex-audio-worker$exe', + ); + final m2m100Worker = p.join( + root, + 'workers', + 'translation', + 'cutdex-m2m100-worker$exe', + ); + final translationModel = + p.isAbsolute(translationPath) && + File(m2m100Worker).existsSync() && + File(p.join(translationPath, 'model.bin')).existsSync() && + File(p.join(translationPath, 'config.json')).existsSync() && + File(p.join(translationPath, 'shared_vocabulary.json')) + .existsSync() && + File(p.join(translationPath, 'sentencepiece.bpe.model')) + .existsSync() + ? Uri.directory(translationPath) + : null; + final vocalSeparationModel = + p.isAbsolute(vocalPath) && + File(ffmpeg).existsSync() && + File(audioWorker).existsSync() && + File(vocalPath).existsSync() + ? Uri.file(vocalPath) + : null; + final backgroundRemovalModel = + backgroundRemovalPath != null && + p.isAbsolute(backgroundRemovalPath) && + File(ffmpeg).existsSync() && + File(backgroundRemovalPath).existsSync() + ? Uri.file(backgroundRemovalPath) + : null; + return ProcessingConfiguration( + backend: CutdexProcessing.fromPackage( + Directory(root), + diagnostics: diagnostics, + ), + transcriptionModel: transcriptionModel, + translationModel: translationModel, + vocalSeparationModel: vocalSeparationModel, + backgroundRemovalModel: backgroundRemovalModel, + ); + } +} diff --git a/lib/integrations/runtime/processing_resource_repository.dart b/lib/integrations/runtime/processing_resource_repository.dart new file mode 100644 index 0000000..3019cfd --- /dev/null +++ b/lib/integrations/runtime/processing_resource_repository.dart @@ -0,0 +1,722 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:crypto/crypto.dart'; +import 'package:flutter/foundation.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:path/path.dart' as p; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import '../../persistence/app_settings_repositories.dart'; +import '../../errors/app_failure.dart'; +import '../app_failure_adapter.dart'; + +part 'processing_resource_repository.g.dart'; +part 'processing_resource_repository.freezed.dart'; + +enum ProcessingResourceState { notInstalled, downloading, installed, failed } + +enum ProcessingCapability { + transcription, + translation, + vocalSeparation, + backgroundRemoval, +} + +class ProcessingResourceCancelledException implements Exception { + const ProcessingResourceCancelledException(); +} + +@freezed +abstract class ProcessingResourceArtifact with _$ProcessingResourceArtifact { + const ProcessingResourceArtifact._(); + + const factory ProcessingResourceArtifact({ + required String path, + required Uri url, + required String sha256, + required int bytes, + }) = _ProcessingResourceArtifact; +} + +@freezed +abstract class ProcessingResourcePackage with _$ProcessingResourcePackage { + const ProcessingResourcePackage._(); + + const factory ProcessingResourcePackage({ + required ProcessingCapability capability, + required String id, + required String version, + required String name, + required String description, + required List artifacts, + }) = _ProcessingResourcePackage; + + int get bytes => + artifacts.fold(0, (total, artifact) => total + artifact.bytes); +} + +@freezed +abstract class ProcessingResourceInstall with _$ProcessingResourceInstall { + const ProcessingResourceInstall._(); + + const factory ProcessingResourceInstall({ + required ProcessingResourcePackage package, + required ProcessingResourceState state, + @Default(0) int downloadedBytes, + AppFailure? error, + }) = _ProcessingResourceInstall; + + double get progress => + package.bytes == 0 ? 0 : (downloadedBytes / package.bytes).clamp(0, 1); +} + +const _translationRevision = '18e406c615ef2991fa74d53734bf66b0a6b10cb4'; + +const _whisperRevision = '5359861c739e955e79d9a303bcbc70fb988958b1'; + +final defaultProcessingResourceCatalog = [ + ProcessingResourcePackage( + capability: ProcessingCapability.transcription, + id: 'whisper-turbo', + version: '1', + name: 'Whisper Large V3 Turbo', + description: '语音识别与字幕生成', + artifacts: [ + ProcessingResourceArtifact( + path: 'ggml-model.bin', + url: Uri.parse( + 'https://huggingface.co/ggerganov/whisper.cpp/resolve/' + '$_whisperRevision/ggml-large-v3-turbo-q5_0.bin', + ), + sha256: + '394221709cd5ad1f40c46e6031ca61bce88931e6e088c188294c6d5a55ffa7e2', + bytes: 574041195, + ), + ProcessingResourceArtifact( + path: 'silero_vad.onnx', + url: Uri.parse( + 'https://github.com/k2-fsa/sherpa-onnx/releases/download/' + 'asr-models/silero_vad.onnx', + ), + sha256: + '9e2449e1087496d8d4caba907f23e0bd3f78d91fa552479bb9c23ac09cbb1fd6', + bytes: 643854, + ), + ], + ), + ProcessingResourcePackage( + capability: ProcessingCapability.translation, + id: 'm2m100-418m', + version: '1', + name: 'M2M100 418M', + description: '字幕翻译', + artifacts: [ + ProcessingResourceArtifact( + path: 'config.json', + url: Uri.parse( + 'https://huggingface.co/gn64/M2M100_418M_CTranslate2/resolve/$_translationRevision/config.json', + ), + sha256: + '8f6496adfc930cbfecbe8281112197705c488fab47d34b4829b06d7f478909af', + bytes: 223, + ), + ProcessingResourceArtifact( + path: 'model.bin', + url: Uri.parse( + 'https://huggingface.co/gn64/M2M100_418M_CTranslate2/resolve/$_translationRevision/model.bin', + ), + sha256: + 'a1826980fc5c037e69c7ac94fcb56c03001a66f380eb71863cc0a3879e71421b', + bytes: 490667752, + ), + ProcessingResourceArtifact( + path: 'sentencepiece.bpe.model', + url: Uri.parse( + 'https://huggingface.co/gn64/M2M100_418M_CTranslate2/resolve/$_translationRevision/sentencepiece.bpe.model', + ), + sha256: + 'd8f7c76ed2a5e0822be39f0a4f95a55eb19c78f4593ce609e2edbc2aea4d380a', + bytes: 2423393, + ), + ProcessingResourceArtifact( + path: 'shared_vocabulary.json', + url: Uri.parse( + 'https://huggingface.co/gn64/M2M100_418M_CTranslate2/resolve/$_translationRevision/shared_vocabulary.json', + ), + sha256: + '7eb5d0ff184c6095c7c10f9911c0aea492250abd12854f9c3d787c64b1c6397e', + bytes: 2796509, + ), + ], + ), + ProcessingResourcePackage( + capability: ProcessingCapability.backgroundRemoval, + id: 'birefnet-matting', + version: '1', + name: 'BiRefNet Matting', + description: '图片与视频背景移除', + artifacts: [ + ProcessingResourceArtifact( + path: 'model.onnx', + url: Uri.parse( + 'https://github.com/ZhengPeng7/BiRefNet/releases/download/v1/' + 'BiRefNet-matting-epoch_100.onnx', + ), + sha256: + '6065d27c615ea27308f5b88598dd8db116eb07436c7a323ca40d13b2866c309e', + bytes: 972667742, + ), + ], + ), +]; + +@Riverpod(keepAlive: true) +FutureOr> processingResourceRepository( + Ref ref, +) async { + final resources = await ref + .watch(resourceLocationSettingsRepositoryProvider) + .load(); + final resourcesRoot = resources!; + final repository = ProcessingResourceRepository( + root: Directory(p.join(resourcesRoot, 'Processing')), + downloadsRoot: Directory(p.join(resourcesRoot, 'Downloads')), + ); + await repository.load(); + ref.onDispose(repository.dispose); + return repository; +} + +/// Owns optional resources required by processing capabilities. +/// Downloads never publish a partially installed +/// version: verified files are assembled in staging and the directory is then +/// atomically renamed into place. +final class ProcessingResourceRepository extends ChangeNotifier { + ProcessingResourceRepository({ + Directory? root, + this.downloadsRoot, + List? catalog, + }) : root = root ?? Directory(_defaultRoot()), + catalog = List.unmodifiable(catalog ?? defaultProcessingResourceCatalog); + + final Directory root; + final Directory? downloadsRoot; + final List catalog; + final Map _installs = {}; + final Set _cancelled = {}; + bool _loaded = false; + bool _disposed = false; + bool _subtitleDownloading = false; + bool _subtitleCancelled = false; + bool _subtitlePaused = false; + Set _subtitleAvailable = const {}; + Completer? _subtitleResume; + final Map _downloadClients = {}; + final Map _downloadRates = {}; + final Map> _pausedDownloads = {}; + + void _changed() { + if (!_disposed) notifyListeners(); + } + + @override + void dispose() { + if (_disposed) return; + _disposed = true; + _subtitleCancelled = true; + resumeSubtitleResources(); + _cancelled.addAll( + _installs.values + .where( + (install) => install.state == ProcessingResourceState.downloading, + ) + .map((install) => install.package.id), + ); + for (final id in _downloadClients.keys.toList()) { + _cancelled.add(id); + _pausedDownloads.remove(id)?.complete(); + _downloadClients[id]?.close(force: true); + } + super.dispose(); + } + + static const subtitleCapabilities = [ + ProcessingCapability.transcription, + ProcessingCapability.translation, + ]; + + bool get subtitlePaused => _subtitlePaused; + bool get subtitleDownloading => _subtitleDownloading; + int get subtitleDownloadBytesPerSecond => _subtitlePaused + ? 0 + : subtitleCapabilities.fold( + 0, + (total, capability) => total + downloadBytesPerSecondFor(capability), + ); + int downloadBytesPerSecondFor(ProcessingCapability capability) { + final package = packageFor(capability); + if (installFor(capability).state != ProcessingResourceState.downloading) { + return 0; + } + return _downloadRates[package.id]?.bytesPerSecond ?? 0; + } + + bool downloadPausedFor(ProcessingCapability capability) => + _pausedDownloads.containsKey(packageFor(capability).id); + + void pauseDownload(ProcessingCapability capability) { + final id = packageFor(capability).id; + if (installFor(capability).state != ProcessingResourceState.downloading || + _pausedDownloads.containsKey(id)) { + return; + } + _pausedDownloads[id] = Completer(); + _downloadRates[id]?.reset(); + _changed(); + } + + void resumeDownload(ProcessingCapability capability) { + final id = packageFor(capability).id; + final gate = _pausedDownloads.remove(id); + if (gate == null) return; + _downloadRates[id]?.reset(); + gate.complete(); + _changed(); + } + + Future _waitForDownloadResume(String packageId) async { + while (_pausedDownloads.containsKey(packageId)) { + await _pausedDownloads[packageId]!.future; + } + if (_cancelled.contains(packageId)) { + throw const ProcessingResourceCancelledException(); + } + } + + int get subtitleTotalBytes => subtitleCapabilities.fold( + 0, + (total, capability) => total + packageFor(capability).bytes, + ); + int get subtitleDownloadedBytes => subtitleCapabilities.fold(0, ( + total, + capability, + ) { + final install = installFor(capability); + return total + + (_subtitleAvailable.contains(capability) || + install.state == ProcessingResourceState.installed + ? install.package.bytes + : install.downloadedBytes.clamp(0, install.package.bytes).toInt()); + }); + + void pauseSubtitleResources() { + if (!_subtitleDownloading || _subtitlePaused) return; + _subtitlePaused = true; + for (final capability in subtitleCapabilities) { + _downloadRates[packageFor(capability).id]?.reset(); + } + _subtitleResume = Completer(); + _changed(); + } + + void resumeSubtitleResources() { + if (!_subtitlePaused) return; + _subtitlePaused = false; + for (final capability in subtitleCapabilities) { + _downloadRates[packageFor(capability).id]?.reset(); + } + _subtitleResume?.complete(); + _subtitleResume = null; + _changed(); + } + + Future _waitForSubtitleResume(String packageId) async { + if (!_subtitleDownloading || + !subtitleCapabilities.any( + (capability) => packageFor(capability).id == packageId, + )) { + return; + } + while (_subtitlePaused && !_subtitleCancelled) { + await _subtitleResume!.future; + } + if (_subtitleCancelled) { + throw const ProcessingResourceCancelledException(); + } + } + + /// Installs both subtitle resources with one byte-weighted progress value. + /// Already configured resources participate as completed bytes. + Future ensureSubtitleResources({ + Set available = const {}, + required void Function(ProcessingCapability stage, double progress) + onProgress, + }) async { + if (_subtitleDownloading) { + throw StateError('Subtitle download is already in progress'); + } + var stage = ProcessingCapability.transcription; + final total = subtitleTotalBytes; + _subtitleDownloading = true; + _subtitleCancelled = false; + _subtitlePaused = false; + _subtitleAvailable = Set.unmodifiable(available); + _changed(); + void report() { + final completed = subtitleDownloadedBytes; + var installed = true; + for (final capability in subtitleCapabilities) { + final install = installFor(capability); + final ready = + available.contains(capability) || + install.state == ProcessingResourceState.installed; + installed = installed && ready; + } + onProgress( + stage, + installed + ? 1.0 + : (total == 0 ? 0.0 : completed / total) + .clamp(0.0, 0.99) + .toDouble(), + ); + } + + try { + await load(); + addListener(report); + for (final capability in subtitleCapabilities) { + await _waitForSubtitleResume(packageFor(capability).id); + if (_subtitleCancelled) { + throw const ProcessingResourceCancelledException(); + } + if (available.contains(capability) || + installFor(capability).state == ProcessingResourceState.installed) { + continue; + } + stage = capability; + report(); + if (_subtitleCancelled) { + throw const ProcessingResourceCancelledException(); + } + await ensureAvailable(capability); + } + if (_subtitleCancelled) { + throw const ProcessingResourceCancelledException(); + } + report(); + } finally { + removeListener(report); + _subtitleDownloading = false; + _subtitleAvailable = const {}; + resumeSubtitleResources(); + _changed(); + } + } + + void cancelSubtitleResources() { + _subtitleCancelled = true; + resumeSubtitleResources(); + for (final capability in subtitleCapabilities) { + cancel(capability); + } + } + + List get installs => [ + for (final package in catalog) + _installs[package.id] ?? + ProcessingResourceInstall( + package: package, + state: ProcessingResourceState.notInstalled, + ), + ]; + + static String _defaultRoot() { + if (Platform.isMacOS) { + return p.join( + Platform.environment['HOME'] ?? '', + 'Library', + 'Application Support', + 'Cutdex', + 'models', + ); + } + if (Platform.isWindows) { + return p.join( + Platform.environment['LOCALAPPDATA'] ?? '', + 'Cutdex', + 'models', + ); + } + return p.join( + Platform.environment['XDG_DATA_HOME'] ?? + p.join(Platform.environment['HOME'] ?? '', '.local', 'share'), + 'cutdex', + 'models', + ); + } + + Directory directoryFor(ProcessingResourcePackage package) => Directory( + p.join( + root.path, + switch (package.capability) { + ProcessingCapability.transcription => 'Transcription', + ProcessingCapability.translation => 'Translation', + ProcessingCapability.vocalSeparation => 'VocalSeparation', + ProcessingCapability.backgroundRemoval => 'BackgroundRemoval', + }, + package.id, + package.version, + ), + ); + + ProcessingResourcePackage packageFor(ProcessingCapability capability) => + catalog.singleWhere((item) => item.capability == capability); + + ProcessingResourceInstall installFor(ProcessingCapability capability) { + final package = packageFor(capability); + return _installs[package.id] ?? + ProcessingResourceInstall( + package: package, + state: ProcessingResourceState.notInstalled, + ); + } + + Future load() async { + if (_loaded) return; + _loaded = true; + for (final package in catalog) { + final installed = await _isValidInstall(package); + _installs[package.id] = ProcessingResourceInstall( + package: package, + state: installed + ? ProcessingResourceState.installed + : ProcessingResourceState.notInstalled, + ); + } + _changed(); + } + + Future ensureAvailable(ProcessingCapability capability) async { + await load(); + final package = packageFor(capability); + final id = package.id; + if (_installs[id]?.state == ProcessingResourceState.installed) { + return directoryFor(package); + } + if (_installs[id]?.state == ProcessingResourceState.downloading) { + throw StateError('Resource download is already in progress'); + } + _cancelled.remove(id); + _set(package, ProcessingResourceState.downloading); + final destination = directoryFor(package); + final staging = downloadsRoot == null + ? Directory('${destination.path}.download') + : Directory( + p.join(downloadsRoot!.path, '${package.id}-${package.version}'), + ); + try { + if (await staging.exists()) await staging.delete(recursive: true); + await staging.create(recursive: true); + var completed = 0; + for (final artifact in package.artifacts) { + await _waitForSubtitleResume(id); + if (_cancelled.contains(id)) { + throw const ProcessingResourceCancelledException(); + } + final target = File(p.join(staging.path, artifact.path)); + await target.parent.create(recursive: true); + await _download(id, artifact, target, (received) { + _set( + package, + ProcessingResourceState.downloading, + downloadedBytes: completed + received, + ); + }); + completed += artifact.bytes; + } + if (_cancelled.contains(id)) { + throw const ProcessingResourceCancelledException(); + } + await File(p.join(staging.path, '.installed.json')).writeAsString( + jsonEncode({'id': package.id, 'version': package.version}), + flush: true, + ); + await destination.parent.create(recursive: true); + if (await destination.exists()) await destination.delete(recursive: true); + await staging.rename(destination.path); + _set( + package, + ProcessingResourceState.installed, + downloadedBytes: package.bytes, + ); + return destination; + } on ProcessingResourceCancelledException { + if (await staging.exists()) await staging.delete(recursive: true); + _set(package, ProcessingResourceState.notInstalled); + throw const ProcessingResourceCancelledException(); + } catch (error) { + if (await staging.exists()) await staging.delete(recursive: true); + if (_cancelled.contains(id)) { + _set(package, ProcessingResourceState.notInstalled); + throw const ProcessingResourceCancelledException(); + } + _set( + package, + ProcessingResourceState.failed, + error: appFailureFromError(error), + ); + rethrow; + } finally { + _pausedDownloads.remove(id)?.complete(); + _cancelled.remove(id); + } + } + + void cancel(ProcessingCapability capability) { + final id = packageFor(capability).id; + if (_subtitleDownloading && subtitleCapabilities.contains(capability)) { + _subtitleCancelled = true; + resumeSubtitleResources(); + } + _cancelled.add(id); + resumeDownload(capability); + _downloadClients[id]?.close(force: true); + } + + Future remove(ProcessingCapability capability) async { + await load(); + final package = packageFor(capability); + cancel(capability); + final directory = directoryFor(package); + if (await directory.exists()) await directory.delete(recursive: true); + _set(package, ProcessingResourceState.notInstalled); + } + + Future _isValidInstall(ProcessingResourcePackage package) async { + final directory = directoryFor(package); + final marker = File(p.join(directory.path, '.installed.json')); + if (!await marker.exists()) return false; + try { + final value = jsonDecode(await marker.readAsString()); + if (value is! Map || + value['id'] != package.id || + value['version'] != package.version) { + return false; + } + return package.artifacts.every( + (artifact) => File(p.join(directory.path, artifact.path)).existsSync(), + ); + } on FormatException { + return false; + } + } + + Future _download( + String packageId, + ProcessingResourceArtifact artifact, + File target, + ValueChanged onProgress, + ) async { + if (_disposed) throw const ProcessingResourceCancelledException(); + final client = HttpClient(); + _downloadClients[packageId] = client; + final rate = _DownloadRate(); + _downloadRates[packageId] = rate; + try { + await _waitForSubtitleResume(packageId); + await _waitForDownloadResume(packageId); + final request = await client.getUrl(artifact.url); + request.headers.set(HttpHeaders.userAgentHeader, 'Cutdex/1'); + final response = await request.close(); + if (response.statusCode < 200 || response.statusCode >= 300) { + throw AppException( + AppErrorCode.resourceDownloadHttpFailed, + httpStatusCode: response.statusCode, + diagnostic: artifact.url.toString(), + ); + } + final output = target.openWrite(); + final digestOutput = _DigestSink(); + final digestInput = sha256.startChunkedConversion(digestOutput); + var received = 0; + try { + await for (final chunk in response) { + await _waitForSubtitleResume(packageId); + await _waitForDownloadResume(packageId); + if (_cancelled.contains(packageId)) { + throw const ProcessingResourceCancelledException(); + } + digestInput.add(chunk); + output.add(chunk); + received += chunk.length; + rate.record(received); + onProgress(received); + } + } finally { + digestInput.close(); + await output.close(); + } + final actual = digestOutput.value.toString(); + if (received != artifact.bytes || actual != artifact.sha256) { + throw AppException(AppErrorCode.resourceChecksumFailed); + } + } finally { + _downloadRates.remove(packageId); + _downloadClients.remove(packageId); + client.close(force: true); + } + } + + void _set( + ProcessingResourcePackage package, + ProcessingResourceState state, { + int downloadedBytes = 0, + AppFailure? error, + }) { + _installs[package.id] = ProcessingResourceInstall( + package: package, + state: state, + downloadedBytes: downloadedBytes, + error: error, + ); + _changed(); + } +} + +final class _DownloadRate { + final Stopwatch _clock = Stopwatch()..start(); + int _sampleBytes = 0; + int _sampleMilliseconds = 0; + int _lastBytes = 0; + int bytesPerSecond = 0; + + void record(int receivedBytes) { + _lastBytes = receivedBytes; + final now = _clock.elapsedMilliseconds; + final elapsed = now - _sampleMilliseconds; + if (elapsed < 500) return; + bytesPerSecond = ((receivedBytes - _sampleBytes) * 1000 / elapsed).round(); + _sampleBytes = receivedBytes; + _sampleMilliseconds = now; + } + + void reset() { + _sampleBytes = _lastBytes; + _sampleMilliseconds = _clock.elapsedMilliseconds; + bytesPerSecond = 0; + } +} + +final class _DigestSink implements Sink { + Digest? _digest; + Digest get value => _digest ?? (throw StateError('Missing digest')); + + @override + void add(Digest data) => _digest = data; + + @override + void close() {} +} diff --git a/lib/integrations/runtime/processing_resource_repository.freezed.dart b/lib/integrations/runtime/processing_resource_repository.freezed.dart new file mode 100644 index 0000000..cd1c0a4 --- /dev/null +++ b/lib/integrations/runtime/processing_resource_repository.freezed.dart @@ -0,0 +1,1362 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'processing_resource_repository.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +T _$identity(T value) => value; + +/// @nodoc +mixin _$ProcessingResourceArtifact implements DiagnosticableTreeMixin { + String get path; + Uri get url; + String get sha256; + int get bytes; + + /// Create a copy of ProcessingResourceArtifact + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $ProcessingResourceArtifactCopyWith + get copyWith => + _$ProcessingResourceArtifactCopyWithImpl( + this as ProcessingResourceArtifact, + _$identity, + ); + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + final _this = this as ProcessingResourceArtifact; + properties + ..add(DiagnosticsProperty('type', 'ProcessingResourceArtifact')) + ..add(DiagnosticsProperty('path', _this.path)) + ..add(DiagnosticsProperty('url', _this.url)) + ..add(DiagnosticsProperty('sha256', _this.sha256)) + ..add(DiagnosticsProperty('bytes', _this.bytes)); + } + + @override + bool operator ==(Object other) { + final _this = this as ProcessingResourceArtifact; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is ProcessingResourceArtifact && + (identical(other.path, _this.path) || other.path == _this.path) && + (identical(other.url, _this.url) || other.url == _this.url) && + (identical(other.sha256, _this.sha256) || + other.sha256 == _this.sha256) && + (identical(other.bytes, _this.bytes) || + other.bytes == _this.bytes)); + } + + @override + int get hashCode { + final _this = this as ProcessingResourceArtifact; + return Object.hash( + runtimeType, + _this.path, + _this.url, + _this.sha256, + _this.bytes, + ); + } + + @override + String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { + final _this = this as ProcessingResourceArtifact; + return 'ProcessingResourceArtifact(path: ${_this.path}, url: ${_this.url}, sha256: ${_this.sha256}, bytes: ${_this.bytes})'; + } +} + +/// @nodoc +abstract mixin class $ProcessingResourceArtifactCopyWith<$Res> { + factory $ProcessingResourceArtifactCopyWith( + ProcessingResourceArtifact value, + $Res Function(ProcessingResourceArtifact) _then, + ) = _$ProcessingResourceArtifactCopyWithImpl; + @useResult + $Res call({String path, Uri url, String sha256, int bytes}); +} + +/// @nodoc +class _$ProcessingResourceArtifactCopyWithImpl<$Res> + implements $ProcessingResourceArtifactCopyWith<$Res> { + _$ProcessingResourceArtifactCopyWithImpl(this._self, this._then); + + final ProcessingResourceArtifact _self; + final $Res Function(ProcessingResourceArtifact) _then; + + /// Create a copy of ProcessingResourceArtifact + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? path = null, + Object? url = null, + Object? sha256 = null, + Object? bytes = null, + }) { + return _then( + ProcessingResourceArtifact( + path: null == path + ? _self.path + : path // ignore: cast_nullable_to_non_nullable + as String, + url: null == url + ? _self.url + : url // ignore: cast_nullable_to_non_nullable + as Uri, + sha256: null == sha256 + ? _self.sha256 + : sha256 // ignore: cast_nullable_to_non_nullable + as String, + bytes: null == bytes + ? _self.bytes + : bytes // ignore: cast_nullable_to_non_nullable + as int, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [ProcessingResourceArtifact]. +extension ProcessingResourceArtifactPatterns on ProcessingResourceArtifact { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_ProcessingResourceArtifact value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ProcessingResourceArtifact() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_ProcessingResourceArtifact value) $default, + ) { + final _that = this; + switch (_that) { + case _ProcessingResourceArtifact(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_ProcessingResourceArtifact value)? $default, + ) { + final _that = this; + switch (_that) { + case _ProcessingResourceArtifact() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function(String path, Uri url, String sha256, int bytes)? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ProcessingResourceArtifact() when $default != null: + return $default(_that.path, _that.url, _that.sha256, _that.bytes); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function(String path, Uri url, String sha256, int bytes) $default, + ) { + final _that = this; + switch (_that) { + case _ProcessingResourceArtifact(): + return $default(_that.path, _that.url, _that.sha256, _that.bytes); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function(String path, Uri url, String sha256, int bytes)? $default, + ) { + final _that = this; + switch (_that) { + case _ProcessingResourceArtifact() when $default != null: + return $default(_that.path, _that.url, _that.sha256, _that.bytes); + case _: + return null; + } + } +} + +/// @nodoc + +class _ProcessingResourceArtifact extends ProcessingResourceArtifact + with DiagnosticableTreeMixin { + const _ProcessingResourceArtifact({ + required this.path, + required this.url, + required this.sha256, + required this.bytes, + }) : super._(); + + @override + final String path; + @override + final Uri url; + @override + final String sha256; + @override + final int bytes; + + /// Create a copy of ProcessingResourceArtifact + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$ProcessingResourceArtifactCopyWith<_ProcessingResourceArtifact> + get copyWith => + __$ProcessingResourceArtifactCopyWithImpl<_ProcessingResourceArtifact>( + this, + _$identity, + ); + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + properties + ..add(DiagnosticsProperty('type', 'ProcessingResourceArtifact')) + ..add(DiagnosticsProperty('path', path)) + ..add(DiagnosticsProperty('url', url)) + ..add(DiagnosticsProperty('sha256', sha256)) + ..add(DiagnosticsProperty('bytes', bytes)); + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _ProcessingResourceArtifact && + (identical(other.path, path) || other.path == path) && + (identical(other.url, url) || other.url == url) && + (identical(other.sha256, sha256) || other.sha256 == sha256) && + (identical(other.bytes, bytes) || other.bytes == bytes)); + } + + @override + int get hashCode { + return Object.hash(runtimeType, path, url, sha256, bytes); + } + + @override + String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { + return 'ProcessingResourceArtifact(path: $path, url: $url, sha256: $sha256, bytes: $bytes)'; + } +} + +/// @nodoc +abstract mixin class _$ProcessingResourceArtifactCopyWith<$Res> + implements $ProcessingResourceArtifactCopyWith<$Res> { + factory _$ProcessingResourceArtifactCopyWith( + _ProcessingResourceArtifact value, + $Res Function(_ProcessingResourceArtifact) _then, + ) = __$ProcessingResourceArtifactCopyWithImpl; + @override + @useResult + $Res call({String path, Uri url, String sha256, int bytes}); +} + +/// @nodoc +class __$ProcessingResourceArtifactCopyWithImpl<$Res> + implements _$ProcessingResourceArtifactCopyWith<$Res> { + __$ProcessingResourceArtifactCopyWithImpl(this._self, this._then); + + final _ProcessingResourceArtifact _self; + final $Res Function(_ProcessingResourceArtifact) _then; + + /// Create a copy of ProcessingResourceArtifact + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? path = null, + Object? url = null, + Object? sha256 = null, + Object? bytes = null, + }) { + return _then( + _ProcessingResourceArtifact( + path: null == path + ? _self.path + : path // ignore: cast_nullable_to_non_nullable + as String, + url: null == url + ? _self.url + : url // ignore: cast_nullable_to_non_nullable + as Uri, + sha256: null == sha256 + ? _self.sha256 + : sha256 // ignore: cast_nullable_to_non_nullable + as String, + bytes: null == bytes + ? _self.bytes + : bytes // ignore: cast_nullable_to_non_nullable + as int, + ), + ); + } +} + +/// @nodoc +mixin _$ProcessingResourcePackage implements DiagnosticableTreeMixin { + ProcessingCapability get capability; + String get id; + String get version; + String get name; + String get description; + List get artifacts; + + /// Create a copy of ProcessingResourcePackage + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $ProcessingResourcePackageCopyWith get copyWith => + _$ProcessingResourcePackageCopyWithImpl( + this as ProcessingResourcePackage, + _$identity, + ); + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + final _this = this as ProcessingResourcePackage; + properties + ..add(DiagnosticsProperty('type', 'ProcessingResourcePackage')) + ..add(DiagnosticsProperty('capability', _this.capability)) + ..add(DiagnosticsProperty('id', _this.id)) + ..add(DiagnosticsProperty('version', _this.version)) + ..add(DiagnosticsProperty('name', _this.name)) + ..add(DiagnosticsProperty('description', _this.description)) + ..add(DiagnosticsProperty('artifacts', _this.artifacts)); + } + + @override + bool operator ==(Object other) { + final _this = this as ProcessingResourcePackage; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is ProcessingResourcePackage && + (identical(other.capability, _this.capability) || + other.capability == _this.capability) && + (identical(other.id, _this.id) || other.id == _this.id) && + (identical(other.version, _this.version) || + other.version == _this.version) && + (identical(other.name, _this.name) || other.name == _this.name) && + (identical(other.description, _this.description) || + other.description == _this.description) && + const DeepCollectionEquality().equals( + other.artifacts, + _this.artifacts, + )); + } + + @override + int get hashCode { + final _this = this as ProcessingResourcePackage; + return Object.hash( + runtimeType, + _this.capability, + _this.id, + _this.version, + _this.name, + _this.description, + const DeepCollectionEquality().hash(_this.artifacts), + ); + } + + @override + String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { + final _this = this as ProcessingResourcePackage; + return 'ProcessingResourcePackage(capability: ${_this.capability}, id: ${_this.id}, version: ${_this.version}, name: ${_this.name}, description: ${_this.description}, artifacts: ${_this.artifacts})'; + } +} + +/// @nodoc +abstract mixin class $ProcessingResourcePackageCopyWith<$Res> { + factory $ProcessingResourcePackageCopyWith( + ProcessingResourcePackage value, + $Res Function(ProcessingResourcePackage) _then, + ) = _$ProcessingResourcePackageCopyWithImpl; + @useResult + $Res call({ + ProcessingCapability capability, + String id, + String version, + String name, + String description, + List artifacts, + }); +} + +/// @nodoc +class _$ProcessingResourcePackageCopyWithImpl<$Res> + implements $ProcessingResourcePackageCopyWith<$Res> { + _$ProcessingResourcePackageCopyWithImpl(this._self, this._then); + + final ProcessingResourcePackage _self; + final $Res Function(ProcessingResourcePackage) _then; + + /// Create a copy of ProcessingResourcePackage + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? capability = null, + Object? id = null, + Object? version = null, + Object? name = null, + Object? description = null, + Object? artifacts = null, + }) { + return _then( + ProcessingResourcePackage( + capability: null == capability + ? _self.capability + : capability // ignore: cast_nullable_to_non_nullable + as ProcessingCapability, + id: null == id + ? _self.id + : id // ignore: cast_nullable_to_non_nullable + as String, + version: null == version + ? _self.version + : version // ignore: cast_nullable_to_non_nullable + as String, + name: null == name + ? _self.name + : name // ignore: cast_nullable_to_non_nullable + as String, + description: null == description + ? _self.description + : description // ignore: cast_nullable_to_non_nullable + as String, + artifacts: null == artifacts + ? _self.artifacts + : artifacts // ignore: cast_nullable_to_non_nullable + as List, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [ProcessingResourcePackage]. +extension ProcessingResourcePackagePatterns on ProcessingResourcePackage { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_ProcessingResourcePackage value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ProcessingResourcePackage() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_ProcessingResourcePackage value) $default, + ) { + final _that = this; + switch (_that) { + case _ProcessingResourcePackage(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_ProcessingResourcePackage value)? $default, + ) { + final _that = this; + switch (_that) { + case _ProcessingResourcePackage() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + ProcessingCapability capability, + String id, + String version, + String name, + String description, + List artifacts, + )? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ProcessingResourcePackage() when $default != null: + return $default( + _that.capability, + _that.id, + _that.version, + _that.name, + _that.description, + _that.artifacts, + ); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function( + ProcessingCapability capability, + String id, + String version, + String name, + String description, + List artifacts, + ) + $default, + ) { + final _that = this; + switch (_that) { + case _ProcessingResourcePackage(): + return $default( + _that.capability, + _that.id, + _that.version, + _that.name, + _that.description, + _that.artifacts, + ); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + ProcessingCapability capability, + String id, + String version, + String name, + String description, + List artifacts, + )? + $default, + ) { + final _that = this; + switch (_that) { + case _ProcessingResourcePackage() when $default != null: + return $default( + _that.capability, + _that.id, + _that.version, + _that.name, + _that.description, + _that.artifacts, + ); + case _: + return null; + } + } +} + +/// @nodoc + +class _ProcessingResourcePackage extends ProcessingResourcePackage + with DiagnosticableTreeMixin { + const _ProcessingResourcePackage({ + required this.capability, + required this.id, + required this.version, + required this.name, + required this.description, + required List artifacts, + }) : _artifacts = artifacts, + super._(); + + @override + final ProcessingCapability capability; + @override + final String id; + @override + final String version; + @override + final String name; + @override + final String description; + final List _artifacts; + @override + List get artifacts { + if (_artifacts is EqualUnmodifiableListView) return _artifacts; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_artifacts); + } + + /// Create a copy of ProcessingResourcePackage + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$ProcessingResourcePackageCopyWith<_ProcessingResourcePackage> + get copyWith => + __$ProcessingResourcePackageCopyWithImpl<_ProcessingResourcePackage>( + this, + _$identity, + ); + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + properties + ..add(DiagnosticsProperty('type', 'ProcessingResourcePackage')) + ..add(DiagnosticsProperty('capability', capability)) + ..add(DiagnosticsProperty('id', id)) + ..add(DiagnosticsProperty('version', version)) + ..add(DiagnosticsProperty('name', name)) + ..add(DiagnosticsProperty('description', description)) + ..add(DiagnosticsProperty('artifacts', artifacts)); + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _ProcessingResourcePackage && + (identical(other.capability, capability) || + other.capability == capability) && + (identical(other.id, id) || other.id == id) && + (identical(other.version, version) || other.version == version) && + (identical(other.name, name) || other.name == name) && + (identical(other.description, description) || + other.description == description) && + const DeepCollectionEquality().equals(other.artifacts, _artifacts)); + } + + @override + int get hashCode { + return Object.hash( + runtimeType, + capability, + id, + version, + name, + description, + const DeepCollectionEquality().hash(_artifacts), + ); + } + + @override + String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { + return 'ProcessingResourcePackage(capability: $capability, id: $id, version: $version, name: $name, description: $description, artifacts: $artifacts)'; + } +} + +/// @nodoc +abstract mixin class _$ProcessingResourcePackageCopyWith<$Res> + implements $ProcessingResourcePackageCopyWith<$Res> { + factory _$ProcessingResourcePackageCopyWith( + _ProcessingResourcePackage value, + $Res Function(_ProcessingResourcePackage) _then, + ) = __$ProcessingResourcePackageCopyWithImpl; + @override + @useResult + $Res call({ + ProcessingCapability capability, + String id, + String version, + String name, + String description, + List artifacts, + }); +} + +/// @nodoc +class __$ProcessingResourcePackageCopyWithImpl<$Res> + implements _$ProcessingResourcePackageCopyWith<$Res> { + __$ProcessingResourcePackageCopyWithImpl(this._self, this._then); + + final _ProcessingResourcePackage _self; + final $Res Function(_ProcessingResourcePackage) _then; + + /// Create a copy of ProcessingResourcePackage + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? capability = null, + Object? id = null, + Object? version = null, + Object? name = null, + Object? description = null, + Object? artifacts = null, + }) { + return _then( + _ProcessingResourcePackage( + capability: null == capability + ? _self.capability + : capability // ignore: cast_nullable_to_non_nullable + as ProcessingCapability, + id: null == id + ? _self.id + : id // ignore: cast_nullable_to_non_nullable + as String, + version: null == version + ? _self.version + : version // ignore: cast_nullable_to_non_nullable + as String, + name: null == name + ? _self.name + : name // ignore: cast_nullable_to_non_nullable + as String, + description: null == description + ? _self.description + : description // ignore: cast_nullable_to_non_nullable + as String, + artifacts: null == artifacts + ? _self._artifacts + : artifacts // ignore: cast_nullable_to_non_nullable + as List, + ), + ); + } +} + +/// @nodoc +mixin _$ProcessingResourceInstall implements DiagnosticableTreeMixin { + ProcessingResourcePackage get package; + ProcessingResourceState get state; + int get downloadedBytes; + AppFailure? get error; + + /// Create a copy of ProcessingResourceInstall + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $ProcessingResourceInstallCopyWith get copyWith => + _$ProcessingResourceInstallCopyWithImpl( + this as ProcessingResourceInstall, + _$identity, + ); + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + final _this = this as ProcessingResourceInstall; + properties + ..add(DiagnosticsProperty('type', 'ProcessingResourceInstall')) + ..add(DiagnosticsProperty('package', _this.package)) + ..add(DiagnosticsProperty('state', _this.state)) + ..add(DiagnosticsProperty('downloadedBytes', _this.downloadedBytes)) + ..add(DiagnosticsProperty('error', _this.error)); + } + + @override + bool operator ==(Object other) { + final _this = this as ProcessingResourceInstall; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is ProcessingResourceInstall && + (identical(other.package, _this.package) || + other.package == _this.package) && + (identical(other.state, _this.state) || + other.state == _this.state) && + (identical(other.downloadedBytes, _this.downloadedBytes) || + other.downloadedBytes == _this.downloadedBytes) && + (identical(other.error, _this.error) || + other.error == _this.error)); + } + + @override + int get hashCode { + final _this = this as ProcessingResourceInstall; + return Object.hash( + runtimeType, + _this.package, + _this.state, + _this.downloadedBytes, + _this.error, + ); + } + + @override + String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { + final _this = this as ProcessingResourceInstall; + return 'ProcessingResourceInstall(package: ${_this.package}, state: ${_this.state}, downloadedBytes: ${_this.downloadedBytes}, error: ${_this.error})'; + } +} + +/// @nodoc +abstract mixin class $ProcessingResourceInstallCopyWith<$Res> { + factory $ProcessingResourceInstallCopyWith( + ProcessingResourceInstall value, + $Res Function(ProcessingResourceInstall) _then, + ) = _$ProcessingResourceInstallCopyWithImpl; + @useResult + $Res call({ + ProcessingResourcePackage package, + ProcessingResourceState state, + int downloadedBytes, + AppFailure? error, + }); + + $ProcessingResourcePackageCopyWith<$Res> get package; +} + +/// @nodoc +class _$ProcessingResourceInstallCopyWithImpl<$Res> + implements $ProcessingResourceInstallCopyWith<$Res> { + _$ProcessingResourceInstallCopyWithImpl(this._self, this._then); + + final ProcessingResourceInstall _self; + final $Res Function(ProcessingResourceInstall) _then; + + /// Create a copy of ProcessingResourceInstall + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? package = null, + Object? state = null, + Object? downloadedBytes = null, + Object? error = freezed, + }) { + return _then( + ProcessingResourceInstall( + package: null == package + ? _self.package + : package // ignore: cast_nullable_to_non_nullable + as ProcessingResourcePackage, + state: null == state + ? _self.state + : state // ignore: cast_nullable_to_non_nullable + as ProcessingResourceState, + downloadedBytes: null == downloadedBytes + ? _self.downloadedBytes + : downloadedBytes // ignore: cast_nullable_to_non_nullable + as int, + error: freezed == error + ? _self.error + : error // ignore: cast_nullable_to_non_nullable + as AppFailure?, + ), + ); + } + + /// Create a copy of ProcessingResourceInstall + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $ProcessingResourcePackageCopyWith<$Res> get package { + return $ProcessingResourcePackageCopyWith<$Res>(_self.package, (value) { + return _then(_self.copyWith(package: value)); + }); + } +} + +/// Adds pattern-matching-related methods to [ProcessingResourceInstall]. +extension ProcessingResourceInstallPatterns on ProcessingResourceInstall { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_ProcessingResourceInstall value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ProcessingResourceInstall() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_ProcessingResourceInstall value) $default, + ) { + final _that = this; + switch (_that) { + case _ProcessingResourceInstall(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_ProcessingResourceInstall value)? $default, + ) { + final _that = this; + switch (_that) { + case _ProcessingResourceInstall() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + ProcessingResourcePackage package, + ProcessingResourceState state, + int downloadedBytes, + AppFailure? error, + )? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ProcessingResourceInstall() when $default != null: + return $default( + _that.package, + _that.state, + _that.downloadedBytes, + _that.error, + ); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function( + ProcessingResourcePackage package, + ProcessingResourceState state, + int downloadedBytes, + AppFailure? error, + ) + $default, + ) { + final _that = this; + switch (_that) { + case _ProcessingResourceInstall(): + return $default( + _that.package, + _that.state, + _that.downloadedBytes, + _that.error, + ); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + ProcessingResourcePackage package, + ProcessingResourceState state, + int downloadedBytes, + AppFailure? error, + )? + $default, + ) { + final _that = this; + switch (_that) { + case _ProcessingResourceInstall() when $default != null: + return $default( + _that.package, + _that.state, + _that.downloadedBytes, + _that.error, + ); + case _: + return null; + } + } +} + +/// @nodoc + +class _ProcessingResourceInstall extends ProcessingResourceInstall + with DiagnosticableTreeMixin { + const _ProcessingResourceInstall({ + required this.package, + required this.state, + this.downloadedBytes = 0, + this.error, + }) : super._(); + + @override + final ProcessingResourcePackage package; + @override + final ProcessingResourceState state; + @override + @JsonKey() + final int downloadedBytes; + @override + final AppFailure? error; + + /// Create a copy of ProcessingResourceInstall + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$ProcessingResourceInstallCopyWith<_ProcessingResourceInstall> + get copyWith => + __$ProcessingResourceInstallCopyWithImpl<_ProcessingResourceInstall>( + this, + _$identity, + ); + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + properties + ..add(DiagnosticsProperty('type', 'ProcessingResourceInstall')) + ..add(DiagnosticsProperty('package', package)) + ..add(DiagnosticsProperty('state', state)) + ..add(DiagnosticsProperty('downloadedBytes', downloadedBytes)) + ..add(DiagnosticsProperty('error', error)); + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _ProcessingResourceInstall && + (identical(other.package, package) || other.package == package) && + (identical(other.state, state) || other.state == state) && + (identical(other.downloadedBytes, downloadedBytes) || + other.downloadedBytes == downloadedBytes) && + (identical(other.error, error) || other.error == error)); + } + + @override + int get hashCode { + return Object.hash(runtimeType, package, state, downloadedBytes, error); + } + + @override + String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { + return 'ProcessingResourceInstall(package: $package, state: $state, downloadedBytes: $downloadedBytes, error: $error)'; + } +} + +/// @nodoc +abstract mixin class _$ProcessingResourceInstallCopyWith<$Res> + implements $ProcessingResourceInstallCopyWith<$Res> { + factory _$ProcessingResourceInstallCopyWith( + _ProcessingResourceInstall value, + $Res Function(_ProcessingResourceInstall) _then, + ) = __$ProcessingResourceInstallCopyWithImpl; + @override + @useResult + $Res call({ + ProcessingResourcePackage package, + ProcessingResourceState state, + int downloadedBytes, + AppFailure? error, + }); + + @override + $ProcessingResourcePackageCopyWith<$Res> get package; +} + +/// @nodoc +class __$ProcessingResourceInstallCopyWithImpl<$Res> + implements _$ProcessingResourceInstallCopyWith<$Res> { + __$ProcessingResourceInstallCopyWithImpl(this._self, this._then); + + final _ProcessingResourceInstall _self; + final $Res Function(_ProcessingResourceInstall) _then; + + /// Create a copy of ProcessingResourceInstall + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? package = null, + Object? state = null, + Object? downloadedBytes = null, + Object? error = freezed, + }) { + return _then( + _ProcessingResourceInstall( + package: null == package + ? _self.package + : package // ignore: cast_nullable_to_non_nullable + as ProcessingResourcePackage, + state: null == state + ? _self.state + : state // ignore: cast_nullable_to_non_nullable + as ProcessingResourceState, + downloadedBytes: null == downloadedBytes + ? _self.downloadedBytes + : downloadedBytes // ignore: cast_nullable_to_non_nullable + as int, + error: freezed == error + ? _self.error + : error // ignore: cast_nullable_to_non_nullable + as AppFailure?, + ), + ); + } + + /// Create a copy of ProcessingResourceInstall + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $ProcessingResourcePackageCopyWith<$Res> get package { + return $ProcessingResourcePackageCopyWith<$Res>(_self.package, (value) { + return _then(_self.copyWith(package: value)); + }); + } +} diff --git a/lib/integrations/runtime/processing_resource_repository.g.dart b/lib/integrations/runtime/processing_resource_repository.g.dart new file mode 100644 index 0000000..ec62acb --- /dev/null +++ b/lib/integrations/runtime/processing_resource_repository.g.dart @@ -0,0 +1,53 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'processing_resource_repository.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(processingResourceRepository) +final processingResourceRepositoryProvider = + ProcessingResourceRepositoryProvider._(); + +final class ProcessingResourceRepositoryProvider + extends + $FunctionalProvider< + AsyncValue>, + Raw, + FutureOr> + > + with + $FutureModifier>, + $FutureProvider> { + ProcessingResourceRepositoryProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'processingResourceRepositoryProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$processingResourceRepositoryHash(); + + @$internal + @override + $FutureProviderElement> $createElement( + $ProviderPointer pointer, + ) => $FutureProviderElement(pointer); + + @override + FutureOr> create(Ref ref) { + return processingResourceRepository(ref); + } +} + +String _$processingResourceRepositoryHash() => + r'e96db5dd36cde4d619d1bc1236be27591d3794e1'; diff --git a/lib/integrations/runtime/processing_resource_state.dart b/lib/integrations/runtime/processing_resource_state.dart new file mode 100644 index 0000000..0406ed6 --- /dev/null +++ b/lib/integrations/runtime/processing_resource_state.dart @@ -0,0 +1,78 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import 'processing_resource_repository.dart'; + +part 'processing_resource_state.g.dart'; +part 'processing_resource_state.freezed.dart'; + +@freezed +abstract class ProcessingResourcesSnapshot with _$ProcessingResourcesSnapshot { + const factory ProcessingResourcesSnapshot({ + @Default([]) List installs, + @Default({}) Set paused, + @Default({}) Map rates, + @Default(false) bool subtitleDownloading, + @Default(false) bool subtitlePaused, + @Default(0) int subtitleDownloadedBytes, + @Default(0) int subtitleTotalBytes, + @Default(0) int subtitleBytesPerSecond, + }) = _ProcessingResourcesSnapshot; +} + +/// Resource ownership stays in the repository; observers receive value snapshots. +@riverpod +class ProcessingResources extends _$ProcessingResources { + @override + ProcessingResourcesSnapshot build(ProcessingResourceRepository repository) { + void changed() { + if (ref.mounted) state = _snapshot(); + } + + repository.addListener(changed); + ref.onDispose(() => repository.removeListener(changed)); + return _snapshot(); + } + + ProcessingResourcesSnapshot _snapshot() => ProcessingResourcesSnapshot( + installs: List.of(repository.installs), + paused: { + for (final package in repository.catalog) + if (repository.downloadPausedFor(package.capability)) + package.capability, + }, + rates: { + for (final package in repository.catalog) + package.capability: repository.downloadBytesPerSecondFor( + package.capability, + ), + }, + subtitleDownloading: repository.subtitleDownloading, + subtitlePaused: repository.subtitlePaused, + subtitleDownloadedBytes: + repository.catalog.any( + (p) => p.capability == ProcessingCapability.transcription, + ) && + repository.catalog.any( + (p) => p.capability == ProcessingCapability.translation, + ) + ? repository.subtitleDownloadedBytes + : 0, + subtitleTotalBytes: repository.catalog + .where( + (p) => ProcessingResourceRepository.subtitleCapabilities.contains( + p.capability, + ), + ) + .fold(0, (bytes, p) => bytes + p.bytes), + subtitleBytesPerSecond: + repository.catalog.any( + (p) => p.capability == ProcessingCapability.transcription, + ) && + repository.catalog.any( + (p) => p.capability == ProcessingCapability.translation, + ) + ? repository.subtitleDownloadBytesPerSecond + : 0, + ); +} diff --git a/lib/integrations/runtime/processing_resource_state.freezed.dart b/lib/integrations/runtime/processing_resource_state.freezed.dart new file mode 100644 index 0000000..89bb6fe --- /dev/null +++ b/lib/integrations/runtime/processing_resource_state.freezed.dart @@ -0,0 +1,580 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'processing_resource_state.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +T _$identity(T value) => value; + +/// @nodoc +mixin _$ProcessingResourcesSnapshot { + List get installs; + Set get paused; + Map get rates; + bool get subtitleDownloading; + bool get subtitlePaused; + int get subtitleDownloadedBytes; + int get subtitleTotalBytes; + int get subtitleBytesPerSecond; + + /// Create a copy of ProcessingResourcesSnapshot + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $ProcessingResourcesSnapshotCopyWith + get copyWith => + _$ProcessingResourcesSnapshotCopyWithImpl( + this as ProcessingResourcesSnapshot, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as ProcessingResourcesSnapshot; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is ProcessingResourcesSnapshot && + const DeepCollectionEquality().equals( + other.installs, + _this.installs, + ) && + const DeepCollectionEquality().equals(other.paused, _this.paused) && + const DeepCollectionEquality().equals(other.rates, _this.rates) && + (identical(other.subtitleDownloading, _this.subtitleDownloading) || + other.subtitleDownloading == _this.subtitleDownloading) && + (identical(other.subtitlePaused, _this.subtitlePaused) || + other.subtitlePaused == _this.subtitlePaused) && + (identical( + other.subtitleDownloadedBytes, + _this.subtitleDownloadedBytes, + ) || + other.subtitleDownloadedBytes == + _this.subtitleDownloadedBytes) && + (identical(other.subtitleTotalBytes, _this.subtitleTotalBytes) || + other.subtitleTotalBytes == _this.subtitleTotalBytes) && + (identical( + other.subtitleBytesPerSecond, + _this.subtitleBytesPerSecond, + ) || + other.subtitleBytesPerSecond == _this.subtitleBytesPerSecond)); + } + + @override + int get hashCode { + final _this = this as ProcessingResourcesSnapshot; + return Object.hash( + runtimeType, + const DeepCollectionEquality().hash(_this.installs), + const DeepCollectionEquality().hash(_this.paused), + const DeepCollectionEquality().hash(_this.rates), + _this.subtitleDownloading, + _this.subtitlePaused, + _this.subtitleDownloadedBytes, + _this.subtitleTotalBytes, + _this.subtitleBytesPerSecond, + ); + } + + @override + String toString() { + final _this = this as ProcessingResourcesSnapshot; + return 'ProcessingResourcesSnapshot(installs: ${_this.installs}, paused: ${_this.paused}, rates: ${_this.rates}, subtitleDownloading: ${_this.subtitleDownloading}, subtitlePaused: ${_this.subtitlePaused}, subtitleDownloadedBytes: ${_this.subtitleDownloadedBytes}, subtitleTotalBytes: ${_this.subtitleTotalBytes}, subtitleBytesPerSecond: ${_this.subtitleBytesPerSecond})'; + } +} + +/// @nodoc +abstract mixin class $ProcessingResourcesSnapshotCopyWith<$Res> { + factory $ProcessingResourcesSnapshotCopyWith( + ProcessingResourcesSnapshot value, + $Res Function(ProcessingResourcesSnapshot) _then, + ) = _$ProcessingResourcesSnapshotCopyWithImpl; + @useResult + $Res call({ + List installs, + Set paused, + Map rates, + bool subtitleDownloading, + bool subtitlePaused, + int subtitleDownloadedBytes, + int subtitleTotalBytes, + int subtitleBytesPerSecond, + }); +} + +/// @nodoc +class _$ProcessingResourcesSnapshotCopyWithImpl<$Res> + implements $ProcessingResourcesSnapshotCopyWith<$Res> { + _$ProcessingResourcesSnapshotCopyWithImpl(this._self, this._then); + + final ProcessingResourcesSnapshot _self; + final $Res Function(ProcessingResourcesSnapshot) _then; + + /// Create a copy of ProcessingResourcesSnapshot + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? installs = null, + Object? paused = null, + Object? rates = null, + Object? subtitleDownloading = null, + Object? subtitlePaused = null, + Object? subtitleDownloadedBytes = null, + Object? subtitleTotalBytes = null, + Object? subtitleBytesPerSecond = null, + }) { + return _then( + ProcessingResourcesSnapshot( + installs: null == installs + ? _self.installs + : installs // ignore: cast_nullable_to_non_nullable + as List, + paused: null == paused + ? _self.paused + : paused // ignore: cast_nullable_to_non_nullable + as Set, + rates: null == rates + ? _self.rates + : rates // ignore: cast_nullable_to_non_nullable + as Map, + subtitleDownloading: null == subtitleDownloading + ? _self.subtitleDownloading + : subtitleDownloading // ignore: cast_nullable_to_non_nullable + as bool, + subtitlePaused: null == subtitlePaused + ? _self.subtitlePaused + : subtitlePaused // ignore: cast_nullable_to_non_nullable + as bool, + subtitleDownloadedBytes: null == subtitleDownloadedBytes + ? _self.subtitleDownloadedBytes + : subtitleDownloadedBytes // ignore: cast_nullable_to_non_nullable + as int, + subtitleTotalBytes: null == subtitleTotalBytes + ? _self.subtitleTotalBytes + : subtitleTotalBytes // ignore: cast_nullable_to_non_nullable + as int, + subtitleBytesPerSecond: null == subtitleBytesPerSecond + ? _self.subtitleBytesPerSecond + : subtitleBytesPerSecond // ignore: cast_nullable_to_non_nullable + as int, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [ProcessingResourcesSnapshot]. +extension ProcessingResourcesSnapshotPatterns on ProcessingResourcesSnapshot { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_ProcessingResourcesSnapshot value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ProcessingResourcesSnapshot() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_ProcessingResourcesSnapshot value) $default, + ) { + final _that = this; + switch (_that) { + case _ProcessingResourcesSnapshot(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_ProcessingResourcesSnapshot value)? $default, + ) { + final _that = this; + switch (_that) { + case _ProcessingResourcesSnapshot() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + List installs, + Set paused, + Map rates, + bool subtitleDownloading, + bool subtitlePaused, + int subtitleDownloadedBytes, + int subtitleTotalBytes, + int subtitleBytesPerSecond, + )? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ProcessingResourcesSnapshot() when $default != null: + return $default( + _that.installs, + _that.paused, + _that.rates, + _that.subtitleDownloading, + _that.subtitlePaused, + _that.subtitleDownloadedBytes, + _that.subtitleTotalBytes, + _that.subtitleBytesPerSecond, + ); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function( + List installs, + Set paused, + Map rates, + bool subtitleDownloading, + bool subtitlePaused, + int subtitleDownloadedBytes, + int subtitleTotalBytes, + int subtitleBytesPerSecond, + ) + $default, + ) { + final _that = this; + switch (_that) { + case _ProcessingResourcesSnapshot(): + return $default( + _that.installs, + _that.paused, + _that.rates, + _that.subtitleDownloading, + _that.subtitlePaused, + _that.subtitleDownloadedBytes, + _that.subtitleTotalBytes, + _that.subtitleBytesPerSecond, + ); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + List installs, + Set paused, + Map rates, + bool subtitleDownloading, + bool subtitlePaused, + int subtitleDownloadedBytes, + int subtitleTotalBytes, + int subtitleBytesPerSecond, + )? + $default, + ) { + final _that = this; + switch (_that) { + case _ProcessingResourcesSnapshot() when $default != null: + return $default( + _that.installs, + _that.paused, + _that.rates, + _that.subtitleDownloading, + _that.subtitlePaused, + _that.subtitleDownloadedBytes, + _that.subtitleTotalBytes, + _that.subtitleBytesPerSecond, + ); + case _: + return null; + } + } +} + +/// @nodoc + +class _ProcessingResourcesSnapshot implements ProcessingResourcesSnapshot { + const _ProcessingResourcesSnapshot({ + List installs = const [], + Set paused = const {}, + Map rates = const {}, + this.subtitleDownloading = false, + this.subtitlePaused = false, + this.subtitleDownloadedBytes = 0, + this.subtitleTotalBytes = 0, + this.subtitleBytesPerSecond = 0, + }) : _installs = installs, + _paused = paused, + _rates = rates; + + final List _installs; + @override + @JsonKey() + List get installs { + if (_installs is EqualUnmodifiableListView) return _installs; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_installs); + } + + final Set _paused; + @override + @JsonKey() + Set get paused { + if (_paused is EqualUnmodifiableSetView) return _paused; + // ignore: implicit_dynamic_type + return EqualUnmodifiableSetView(_paused); + } + + final Map _rates; + @override + @JsonKey() + Map get rates { + if (_rates is EqualUnmodifiableMapView) return _rates; + // ignore: implicit_dynamic_type + return EqualUnmodifiableMapView(_rates); + } + + @override + @JsonKey() + final bool subtitleDownloading; + @override + @JsonKey() + final bool subtitlePaused; + @override + @JsonKey() + final int subtitleDownloadedBytes; + @override + @JsonKey() + final int subtitleTotalBytes; + @override + @JsonKey() + final int subtitleBytesPerSecond; + + /// Create a copy of ProcessingResourcesSnapshot + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$ProcessingResourcesSnapshotCopyWith<_ProcessingResourcesSnapshot> + get copyWith => + __$ProcessingResourcesSnapshotCopyWithImpl<_ProcessingResourcesSnapshot>( + this, + _$identity, + ); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _ProcessingResourcesSnapshot && + const DeepCollectionEquality().equals(other.installs, _installs) && + const DeepCollectionEquality().equals(other.paused, _paused) && + const DeepCollectionEquality().equals(other.rates, _rates) && + (identical(other.subtitleDownloading, subtitleDownloading) || + other.subtitleDownloading == subtitleDownloading) && + (identical(other.subtitlePaused, subtitlePaused) || + other.subtitlePaused == subtitlePaused) && + (identical( + other.subtitleDownloadedBytes, + subtitleDownloadedBytes, + ) || + other.subtitleDownloadedBytes == subtitleDownloadedBytes) && + (identical(other.subtitleTotalBytes, subtitleTotalBytes) || + other.subtitleTotalBytes == subtitleTotalBytes) && + (identical(other.subtitleBytesPerSecond, subtitleBytesPerSecond) || + other.subtitleBytesPerSecond == subtitleBytesPerSecond)); + } + + @override + int get hashCode { + return Object.hash( + runtimeType, + const DeepCollectionEquality().hash(_installs), + const DeepCollectionEquality().hash(_paused), + const DeepCollectionEquality().hash(_rates), + subtitleDownloading, + subtitlePaused, + subtitleDownloadedBytes, + subtitleTotalBytes, + subtitleBytesPerSecond, + ); + } + + @override + String toString() { + return 'ProcessingResourcesSnapshot(installs: $installs, paused: $paused, rates: $rates, subtitleDownloading: $subtitleDownloading, subtitlePaused: $subtitlePaused, subtitleDownloadedBytes: $subtitleDownloadedBytes, subtitleTotalBytes: $subtitleTotalBytes, subtitleBytesPerSecond: $subtitleBytesPerSecond)'; + } +} + +/// @nodoc +abstract mixin class _$ProcessingResourcesSnapshotCopyWith<$Res> + implements $ProcessingResourcesSnapshotCopyWith<$Res> { + factory _$ProcessingResourcesSnapshotCopyWith( + _ProcessingResourcesSnapshot value, + $Res Function(_ProcessingResourcesSnapshot) _then, + ) = __$ProcessingResourcesSnapshotCopyWithImpl; + @override + @useResult + $Res call({ + List installs, + Set paused, + Map rates, + bool subtitleDownloading, + bool subtitlePaused, + int subtitleDownloadedBytes, + int subtitleTotalBytes, + int subtitleBytesPerSecond, + }); +} + +/// @nodoc +class __$ProcessingResourcesSnapshotCopyWithImpl<$Res> + implements _$ProcessingResourcesSnapshotCopyWith<$Res> { + __$ProcessingResourcesSnapshotCopyWithImpl(this._self, this._then); + + final _ProcessingResourcesSnapshot _self; + final $Res Function(_ProcessingResourcesSnapshot) _then; + + /// Create a copy of ProcessingResourcesSnapshot + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? installs = null, + Object? paused = null, + Object? rates = null, + Object? subtitleDownloading = null, + Object? subtitlePaused = null, + Object? subtitleDownloadedBytes = null, + Object? subtitleTotalBytes = null, + Object? subtitleBytesPerSecond = null, + }) { + return _then( + _ProcessingResourcesSnapshot( + installs: null == installs + ? _self._installs + : installs // ignore: cast_nullable_to_non_nullable + as List, + paused: null == paused + ? _self._paused + : paused // ignore: cast_nullable_to_non_nullable + as Set, + rates: null == rates + ? _self._rates + : rates // ignore: cast_nullable_to_non_nullable + as Map, + subtitleDownloading: null == subtitleDownloading + ? _self.subtitleDownloading + : subtitleDownloading // ignore: cast_nullable_to_non_nullable + as bool, + subtitlePaused: null == subtitlePaused + ? _self.subtitlePaused + : subtitlePaused // ignore: cast_nullable_to_non_nullable + as bool, + subtitleDownloadedBytes: null == subtitleDownloadedBytes + ? _self.subtitleDownloadedBytes + : subtitleDownloadedBytes // ignore: cast_nullable_to_non_nullable + as int, + subtitleTotalBytes: null == subtitleTotalBytes + ? _self.subtitleTotalBytes + : subtitleTotalBytes // ignore: cast_nullable_to_non_nullable + as int, + subtitleBytesPerSecond: null == subtitleBytesPerSecond + ? _self.subtitleBytesPerSecond + : subtitleBytesPerSecond // ignore: cast_nullable_to_non_nullable + as int, + ), + ); + } +} diff --git a/lib/integrations/runtime/processing_resource_state.g.dart b/lib/integrations/runtime/processing_resource_state.g.dart new file mode 100644 index 0000000..38b20ee --- /dev/null +++ b/lib/integrations/runtime/processing_resource_state.g.dart @@ -0,0 +1,124 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'processing_resource_state.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning +/// Resource ownership stays in the repository; observers receive value snapshots. + +@ProviderFor(ProcessingResources) +final processingResourcesProvider = ProcessingResourcesFamily._(); + +/// Resource ownership stays in the repository; observers receive value snapshots. +final class ProcessingResourcesProvider + extends + $NotifierProvider { + /// Resource ownership stays in the repository; observers receive value snapshots. + ProcessingResourcesProvider._({ + required ProcessingResourcesFamily super.from, + required ProcessingResourceRepository super.argument, + }) : super( + retry: null, + name: r'processingResourcesProvider', + isAutoDispose: true, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$processingResourcesHash(); + + @override + String toString() { + return r'processingResourcesProvider' + '' + '($argument)'; + } + + @$internal + @override + ProcessingResources create() => ProcessingResources(); + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(ProcessingResourcesSnapshot value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } + + @override + bool operator ==(Object other) { + return other is ProcessingResourcesProvider && other.argument == argument; + } + + @override + int get hashCode { + return argument.hashCode; + } +} + +String _$processingResourcesHash() => + r'd39d92ad2c74b9be524152b3e946e6f1b43de7b0'; + +/// Resource ownership stays in the repository; observers receive value snapshots. + +final class ProcessingResourcesFamily extends $Family + with + $ClassFamilyOverride< + ProcessingResources, + ProcessingResourcesSnapshot, + ProcessingResourcesSnapshot, + ProcessingResourcesSnapshot, + ProcessingResourceRepository + > { + ProcessingResourcesFamily._() + : super( + retry: null, + name: r'processingResourcesProvider', + dependencies: null, + $allTransitiveDependencies: null, + isAutoDispose: true, + ); + + /// Resource ownership stays in the repository; observers receive value snapshots. + + ProcessingResourcesProvider call(ProcessingResourceRepository repository) => + ProcessingResourcesProvider._(argument: repository, from: this); + + @override + String toString() => r'processingResourcesProvider'; +} + +/// Resource ownership stays in the repository; observers receive value snapshots. + +abstract class _$ProcessingResources + extends $Notifier { + late final _$args = ref.$arg as ProcessingResourceRepository; + ProcessingResourceRepository get repository => _$args; + + ProcessingResourcesSnapshot build(ProcessingResourceRepository repository); + @$mustCallSuper + @override + WhenComplete runBuild() { + final ref = + this.ref + as $Ref; + final element = + ref.element + as $ClassProviderElement< + AnyNotifier< + ProcessingResourcesSnapshot, + ProcessingResourcesSnapshot + >, + ProcessingResourcesSnapshot, + Object?, + Object? + >; + return element.handleCreate(ref, () => build(_$args)); + } +} diff --git a/lib/integrations/runtime/timeline_thumbnails.dart b/lib/integrations/runtime/timeline_thumbnails.dart new file mode 100644 index 0000000..53d27e5 --- /dev/null +++ b/lib/integrations/runtime/timeline_thumbnails.dart @@ -0,0 +1,487 @@ +import 'dart:async'; +import 'dart:math' as math; +import 'dart:ui' as ui; + +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline/engine.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:cutdex_sdk/timeline_ui.dart'; +import 'package:flutter/foundation.dart'; + +typedef _MediaKey = ({Uri uri, TrackSelection? trackSelection, bool isImage}); +typedef _FrameKey = ({ + Uri uri, + TrackSelection? trackSelection, + bool isImage, + int tick, + int maximumEdge, +}); +typedef _CachedFrame = ({_FrameKey key, ui.Image image}); + +/// One viewport's runtime requests and decoded-image cache; never project data. +/// Source URIs identify frames across provisional and imported asset IDs. +class RuntimeTimelineThumbnails extends ChangeNotifier + implements TimelineThumbnails { + RuntimeTimelineThumbnails({ + required this.resolveMedia, + this.resolveTrackSelection, + CutdexRuntime? runtime, + this.maximumEntries = 256, + this.maximumDecodedBytes = 64 * 1024 * 1024, + this.maximumConcurrent = 2, + this.maximumBatchSize = 4, + }) : _runtime = runtime ?? CutdexRuntime() { + if (maximumEntries <= 0 || + maximumDecodedBytes <= 0 || + maximumConcurrent <= 0 || + maximumBatchSize <= 0 || + maximumBatchSize > 128) { + throw ArgumentError('Thumbnail limits must be positive and bounded'); + } + } + + static const _resolutionTiers = [ + 64, + 128, + 192, + 256, + 384, + 512, + 768, + 1024, + 1536, + 2048, + ]; + + /// Selects the largest power-of-two source-tick interval covered by a tile. + static int samplingIntervalFor(int sourceSpanTicks) { + if (sourceSpanTicks <= 0) { + throw ArgumentError.value(sourceSpanTicks, 'sourceSpanTicks'); + } + return 1 << (sourceSpanTicks.bitLength - 1); + } + + /// Snaps nearby layout centers onto a cache-stable source-time grid. Bounds + /// describe the media asset, not its current edit window; an unknown upper + /// media boundary leaves the grid uncapped. + static int sampledTickFor({ + required int sourceTick, + required int sourceSpanTicks, + required int minimumTick, + required int? maximumTickExclusive, + }) { + if (sourceTick < 0 || + sourceSpanTicks <= 0 || + minimumTick < 0 || + (maximumTickExclusive != null && maximumTickExclusive <= minimumTick)) { + throw ArgumentError('Invalid thumbnail sampling range'); + } + final interval = samplingIntervalFor(sourceSpanTicks); + final desired = maximumTickExclusive == null + ? math.max(minimumTick, sourceTick) + : sourceTick.clamp(minimumTick, maximumTickExclusive - 1); + final lower = desired ~/ interval * interval; + final upper = lower + interval; + var sampled = desired - lower < upper - desired ? lower : upper; + if (sampled < minimumTick) return minimumTick; + if (maximumTickExclusive != null && sampled >= maximumTickExclusive) { + final lastGridTick = (maximumTickExclusive - 1) ~/ interval * interval; + sampled = lastGridTick >= minimumTick + ? lastGridTick + : maximumTickExclusive - 1; + } + return sampled; + } + + /// Quantizes painted device pixels so tiny layout changes reuse cache data. + static int maximumEdgeFor({ + required ui.Size logicalSize, + required double devicePixelRatio, + }) { + if (!logicalSize.width.isFinite || + !logicalSize.height.isFinite || + logicalSize.width <= 0 || + logicalSize.height <= 0 || + !devicePixelRatio.isFinite || + devicePixelRatio <= 0) { + throw ArgumentError( + 'Thumbnail paint geometry must be finite and positive', + ); + } + final requested = + (math.max(logicalSize.width, logicalSize.height) * devicePixelRatio) + .ceil(); + for (final tier in _resolutionTiers) { + if (requested <= tier) return tier; + } + return _resolutionTiers.last; + } + + final MediaReference? Function(PayloadRef) resolveMedia; + final TrackSelection? Function(PayloadRef)? resolveTrackSelection; + final CutdexRuntime _runtime; + final int maximumEntries; + final int maximumDecodedBytes; + final int maximumConcurrent; + final int maximumBatchSize; + final _cache = <_FrameKey, ui.Image?>{}; + final _mediaFrames = <_MediaKey, Set<_FrameKey>>{}; + + _MediaKey _mediaKey(_FrameKey key) => + (uri: key.uri, trackSelection: key.trackSelection, isImage: key.isImage); + final _aspectRatios = <_MediaKey, double>{}; + final _wanted = <_FrameKey>{}; + final _used = <_FrameKey>{}; + final _inFlight = <_FrameKey>{}; + var _decodedBytes = 0; + var _activeLoads = 0; + var _scheduled = false; + var _disposed = false; + + @override + void beginFrame() { + _wanted.clear(); + _used.clear(); + } + + @override + double? aspectRatioFor(ElementRecord element) { + if (_disposed || element.payloadRef == null) return null; + final media = resolveMedia(element.payloadRef!); + if (media == null) return null; + return _aspectRatios[( + uri: media.uri, + trackSelection: resolveTrackSelection?.call(element.payloadRef!), + isImage: media.isImage, + )]; + } + + @override + ui.Image? imageFor( + ElementRecord element, + int sourceTick, { + required int sourceSpanTicks, + required ui.Size logicalSize, + required double devicePixelRatio, + }) { + if (_disposed || + sourceTick < 0 || + sourceSpanTicks <= 0 || + element.sourceStart < 0 || + element.duration <= 0 || + element.payloadRef == null) { + return null; + } + final media = resolveMedia(element.payloadRef!); + if (media == null) return null; + final sampledTick = media.isImage + ? 0 + : sampledTickFor( + sourceTick: sourceTick, + sourceSpanTicks: sourceSpanTicks, + minimumTick: math.max(0, element.mediaStart ?? 0), + maximumTickExclusive: element.mediaStart == null + ? null + : element.mediaStart! + element.mediaDuration!, + ); + final key = ( + uri: media.uri, + trackSelection: resolveTrackSelection?.call(element.payloadRef!), + isImage: media.isImage, + tick: sampledTick, + maximumEdge: maximumEdgeFor( + logicalSize: logicalSize, + devicePixelRatio: devicePixelRatio, + ), + ); + final fallback = + _bestCached(key, touch: true) ?? + _nearestCached( + key, + maximumTickDistance: math.max( + sourceSpanTicks, + samplingIntervalFor(sourceSpanTicks), + ), + touch: true, + ); + if (!_wanted.contains(key) && _wanted.length >= maximumEntries) { + if (fallback != null) _used.add(fallback.key); + return fallback?.image; + } + _wanted.add(key); + if (fallback != null) _used.add(fallback.key); + return fallback?.image; + } + + @override + void endFrame() { + if (_disposed || _scheduled) return; + _scheduled = true; + scheduleMicrotask(() { + _scheduled = false; + _drain(); + }); + } + + void _drain() { + if (_disposed) return; + while (_activeLoads < maximumConcurrent) { + _FrameKey? seed; + for (final key in _wanted) { + if (_needsLoad(key)) { + seed = key; + break; + } + } + if (seed == null) return; + final batch = <_FrameKey>[]; + final mediaKey = _mediaKey(seed); + final firstForMedia = + !_mediaFrames.containsKey(mediaKey) && + !_inFlight.any((key) => _mediaKey(key) == mediaKey); + final batchLimit = firstForMedia ? 1 : maximumBatchSize; + for (final key in _wanted) { + if (batch.length >= batchLimit) break; + if (key.uri == seed.uri && + key.trackSelection == seed.trackSelection && + key.isImage == seed.isImage && + key.maximumEdge == seed.maximumEdge && + _needsLoad(key)) { + batch.add(key); + } + } + _inFlight.addAll(batch); + _activeLoads++; + unawaited(_loadBatch(batch)); + } + } + + bool _needsLoad(_FrameKey key) { + if (_inFlight.contains(key) || _cache.containsKey(key)) return false; + final cached = _bestCached(key); + return cached == null || cached.key.maximumEdge < key.maximumEdge; + } + + Future _loadBatch(List<_FrameKey> keys) async { + final decoded = <_FrameKey, ui.Image?>{}; + var aspectChanged = false; + var failed = false; + try { + final seed = keys.first; + final thumbnails = await _runtime.thumbnails( + ThumbnailBatchRequest( + media: MediaReference( + id: seed.uri.toString(), + uri: seed.uri, + isImage: seed.isImage, + ), + trackSelection: + seed.trackSelection ?? const TrackSelection.defaultTrack(), + times: [ + for (final key in keys) + MediaTime(key.tick, TimelineClock.ticksPerSecond), + ], + maximumWidth: seed.maximumEdge, + maximumHeight: seed.maximumEdge, + tolerance: MediaTime(1, 4), + quality: 0.72, + ), + ); + final decodeOrder = [ + for (var index = 0; index < keys.length; index++) + if (_wanted.contains(keys[index])) index, + for (var index = 0; index < keys.length; index++) + if (!_wanted.contains(keys[index])) index, + ]; + for (final index in decodeOrder) { + final key = keys[index]; + final thumbnail = thumbnails[index]; + if (_disposed) break; + aspectChanged = + _rememberAspect(key, thumbnail.width, thumbnail.height) || + aspectChanged; + try { + final codec = await ui.instantiateImageCodec(thumbnail.data); + try { + decoded[key] = (await codec.getNextFrame()).image; + } finally { + codec.dispose(); + } + } catch (_) { + decoded[key] = null; + } + } + } catch (_) { + failed = true; + } finally { + _inFlight.removeAll(keys); + _activeLoads--; + if (_disposed) { + for (final image in decoded.values) { + image?.dispose(); + } + } else { + var hasNewImage = false; + if (failed) { + for (final image in decoded.values) { + image?.dispose(); + } + for (final key in keys) { + if (_wanted.contains(key)) _store(key, null); + } + } else { + for (final entry in decoded.entries) { + _store(entry.key, entry.value); + if (_wanted.contains(entry.key) && entry.value != null) { + hasNewImage = true; + } + } + } + if (hasNewImage || aspectChanged) notifyListeners(); + _drain(); + } + } + } + + bool _rememberAspect(_FrameKey key, int width, int height) { + if (width <= 0 || height <= 0) return false; + final media = ( + uri: key.uri, + trackSelection: key.trackSelection, + isImage: key.isImage, + ); + final value = width / height; + final previous = _aspectRatios[media]; + if (previous != null && (previous - value).abs() < 0.0001) return false; + _aspectRatios[media] = value; + return true; + } + + _CachedFrame? _bestCached(_FrameKey desired, {bool touch = false}) { + final exact = _cache[desired]; + if (exact != null) { + if (touch) _touch(desired); + return (key: desired, image: exact); + } + _CachedFrame? adequate; + _CachedFrame? fallback; + for (final key in _mediaFrames[_mediaKey(desired)] ?? const <_FrameKey>{}) { + final image = _cache[key]; + if (image == null || + key.uri != desired.uri || + key.trackSelection != desired.trackSelection || + key.isImage != desired.isImage || + key.tick != desired.tick) { + continue; + } + final candidate = (key: key, image: image); + if (key.maximumEdge >= desired.maximumEdge) { + if (adequate == null || key.maximumEdge < adequate.key.maximumEdge) { + adequate = candidate; + } + } else if (fallback == null || + key.maximumEdge > fallback.key.maximumEdge) { + fallback = candidate; + } + } + final result = adequate ?? fallback; + if (touch && result != null) _touch(result.key); + return result; + } + + _CachedFrame? _nearestCached( + _FrameKey desired, { + required int maximumTickDistance, + bool touch = false, + }) { + _CachedFrame? result; + var bestDistance = maximumTickDistance + 1; + for (final key in _mediaFrames[_mediaKey(desired)] ?? const <_FrameKey>{}) { + final image = _cache[key]; + if (image == null || key.uri != desired.uri) { + continue; + } + if (key.trackSelection != desired.trackSelection || + key.isImage != desired.isImage) { + continue; + } + final distance = (key.tick - desired.tick).abs(); + if (distance > maximumTickDistance || distance > bestDistance) continue; + if (distance == bestDistance && + result != null && + key.maximumEdge <= result.key.maximumEdge) { + continue; + } + result = (key: key, image: image); + bestDistance = distance; + } + if (touch && result != null) _touch(result.key); + return result; + } + + void _store(_FrameKey key, ui.Image? image) { + if (_cache.containsKey(key)) { + final previous = _cache.remove(key); + if (previous != null) { + _decodedBytes -= _imageBytes(previous); + if (!identical(previous, image)) previous.dispose(); + } + } + _cache[key] = image; + (_mediaFrames[_mediaKey(key)] ??= <_FrameKey>{}).add(key); + if (image != null) _decodedBytes += _imageBytes(image); + _trimCache(); + } + + void _touch(_FrameKey key) { + if (!_cache.containsKey(key)) return; + final image = _cache.remove(key); + _cache[key] = image; + } + + void _trimCache() { + while ((_cache.length > maximumEntries || + _decodedBytes > maximumDecodedBytes) && + _cache.length > 1) { + _FrameKey? victim; + for (final key in _cache.keys) { + if (!_wanted.contains(key) && + !_used.contains(key) && + !_inFlight.contains(key)) { + victim = key; + break; + } + } + victim ??= _cache.keys.firstWhere( + (key) => !_inFlight.contains(key), + orElse: () => _cache.keys.first, + ); + final image = _cache.remove(victim); + final media = _mediaKey(victim); + final frames = _mediaFrames[media]!; + frames.remove(victim); + if (frames.isEmpty) _mediaFrames.remove(media); + if (image != null) { + _decodedBytes -= _imageBytes(image); + image.dispose(); + } + } + } + + int _imageBytes(ui.Image image) => image.width * image.height * 4; + + @override + void dispose() { + _disposed = true; + _wanted.clear(); + _used.clear(); + _aspectRatios.clear(); + for (final image in _cache.values) { + image?.dispose(); + } + _cache.clear(); + _mediaFrames.clear(); + _decodedBytes = 0; + super.dispose(); + } +} diff --git a/lib/integrations/runtime/timeline_waveforms.dart b/lib/integrations/runtime/timeline_waveforms.dart new file mode 100644 index 0000000..18e2d54 --- /dev/null +++ b/lib/integrations/runtime/timeline_waveforms.dart @@ -0,0 +1,203 @@ +import 'dart:async'; + +import 'package:cutdex_sdk/editor.dart' show ClipAudioGain; + +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline/engine.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:cutdex_sdk/timeline_ui.dart'; +import 'package:flutter/foundation.dart'; + +typedef _WaveformKey = ({String id, Uri uri, TrackSelection? trackSelection}); + +/// Source-level cache shared by clips on one timeline, independent of zoom. +class RuntimeTimelineWaveforms extends ChangeNotifier + implements TimelineWaveforms { + RuntimeTimelineWaveforms({ + required this.resolveMedia, + this.resolveTrackSelection, + this.resolveGain, + this.gainChanges, + CutdexRuntime? runtime, + this.maximumEntries = 16, + this.maximumConcurrent = 2, + }) : _runtime = runtime ?? CutdexRuntime() { + if (maximumEntries < 1 || maximumConcurrent < 1) { + throw ArgumentError('Waveform limits must be positive'); + } + gainChanges?.addListener(_gainChanged); + } + + final double Function(ElementRecord)? resolveGain; + final Listenable? gainChanges; + void _gainChanged() { + if (!_disposed) notifyListeners(); + } + + final MediaReference? Function(PayloadRef) resolveMedia; + final TrackSelection? Function(PayloadRef)? resolveTrackSelection; + final CutdexRuntime _runtime; + + /// Warm-cache target. Visible sources remain pinned until they leave the view. + final int maximumEntries; + final int maximumConcurrent; + final _cache = <_WaveformKey, TimelineWaveform?>{}; + final _wanted = <_WaveformKey>{}; + final _inFlight = <_WaveformKey>{}; + final _attempts = <_WaveformKey, int>{}; + final _retries = <_WaveformKey, Timer>{}; + Future? _supported; + var _scheduled = false; + var _disposed = false; + + @override + void beginFrame() => _wanted.clear(); + + @override + bool hasAudioFor(ElementRecord element) => + !_disposed && + element.payloadRef != null && + resolveMedia(element.payloadRef!) != null; + + @override + TimelineWaveform? waveformFor(ElementRecord element) { + if (_disposed || + element.payloadRef == null || + ClipAudioGain.isDetached(element)) { + return null; + } + final media = resolveMedia(element.payloadRef!); + if (media == null) return null; + final key = ( + id: media.id, + uri: media.uri, + trackSelection: resolveTrackSelection?.call(element.payloadRef!), + ); + _wanted.add(key); + if (!_cache.containsKey(key)) return null; + final value = _cache.remove(key); + _cache[key] = value; + if (value == null || resolveGain == null) return value; + return TimelineWaveform( + sampleRate: value.sampleRate, + sourceStartSeconds: value.sourceStartSeconds, + frameCount: value.frameCount, + levels: value.levels, + amplitudeScale: resolveGain!(element), + ); + } + + @override + void endFrame() { + if (_disposed || _scheduled) return; + _scheduled = true; + scheduleMicrotask(() { + _scheduled = false; + for (final key in _retries.keys.toList()) { + if (!_wanted.contains(key)) { + _retries.remove(key)!.cancel(); + _attempts.remove(key); + } + } + _trimCache(); + _drain(); + }); + } + + void _drain() { + if (_disposed) return; + for (final key in _wanted) { + if (_inFlight.length >= maximumConcurrent) break; + if (_cache.containsKey(key) || + _inFlight.contains(key) || + _retries.containsKey(key)) { + continue; + } + _inFlight.add(key); + unawaited(_load(key)); + } + } + + Future _load(_WaveformKey key) async { + TimelineWaveform? value; + final attempt = (_attempts[key] ?? 0) + 1; + _attempts[key] = attempt; + var retry = false; + try { + final supported = await (_supported ??= _checkSupport()); + if (supported && !_disposed) { + final result = await _runtime.waveform( + WaveformRequest( + media: MediaReference(id: key.id, uri: key.uri), + trackSelection: + key.trackSelection ?? const TrackSelection.defaultTrack(), + ), + ); + value = TimelineWaveform( + sampleRate: result.sampleRate, + sourceStartSeconds: result.sourceStartSeconds, + frameCount: result.frameCount, + levels: List.unmodifiable([ + for (final level in result.levels) + TimelineWaveformLevel( + samplesPerBucket: level.samplesPerBucket, + channels: level.channels, + ), + ]), + ); + } + } on RuntimeException catch (error) { + retry = error.retryable && attempt < 3; + } catch (_) { + // Permanent failures stay cached; malformed sources must not loop. + } finally { + _inFlight.remove(key); + if (!_disposed) { + if (retry && _wanted.contains(key)) { + _retries[key] = Timer(Duration(seconds: 1 << (attempt - 1)), () { + _retries.remove(key); + _drain(); + }); + } else { + _attempts.remove(key); + if (!retry) _cache[key] = value; + } + _trimCache(); + if (value != null && _wanted.contains(key)) notifyListeners(); + _drain(); + } + } + } + + Future _checkSupport() async { + try { + final capabilities = await _runtime.capabilities(); + return capabilities.query('media.waveform') == + CapabilityAvailability.available; + } catch (_) { + _supported = null; + rethrow; + } + } + + void _trimCache() { + for (final key in _cache.keys.toList()) { + if (_cache.length <= maximumEntries) break; + if (!_wanted.contains(key)) _cache.remove(key); + } + } + + @override + void dispose() { + _disposed = true; + gainChanges?.removeListener(_gainChanged); + _wanted.clear(); + _cache.clear(); + for (final timer in _retries.values) { + timer.cancel(); + } + _retries.clear(); + _attempts.clear(); + super.dispose(); + } +} diff --git a/lib/integrations/tool_workspace_registry.dart b/lib/integrations/tool_workspace_registry.dart new file mode 100644 index 0000000..c21ff48 --- /dev/null +++ b/lib/integrations/tool_workspace_registry.dart @@ -0,0 +1,65 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/tools.dart'; + +import 'editor_command_host.dart'; + +/// Owns the mutable workspace/dispatcher lifecycle without knowing any protocol. +class EditorToolRegistry { + EditorToolRegistry(EditorSession session) + : owner = session, + _session = session, + dynamicWorkspaces = false, + workspaces = Map.unmodifiable({ + for (final sequence in session.document.sequences) + jsonEncode([session.document.id, sequence.id.value]): editorToolsFor( + session, + sequence.id, + ), + }); + + EditorToolRegistry.application(EditorCommandHost host) + : owner = Object(), + dynamicWorkspaces = true, + workspaces = {'application': EditorToolDispatcher(host: host)}; + + final bool dynamicWorkspaces; + final Object owner; + final Map workspaces; + EditorSession? _session; + int _generation = 0; + + void attach(EditorSession? session, {String? projectId}) { + if (!dynamicWorkspaces || identical(_session, session)) return; + for (final id + in workspaces.keys.where((id) => id != 'application').toList()) { + unawaited(releaseEditorTools(_session!, workspaces.remove(id)!)); + } + _session = session; + if (session == null) return; + final generation = ++_generation; + for (final sequence in session.document.sequences) { + workspaces[jsonEncode([ + projectId, + session.document.id, + sequence.id.value, + generation, + ])] = editorToolsFor( + session, + sequence.id, + ); + } + } + + Future dispose() async { + for (final entry in workspaces.entries.toList()) { + if (_session != null && entry.key != 'application') { + await releaseEditorTools(_session!, entry.value); + } else { + await entry.value.dispose(); + } + } + } +} diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb new file mode 100644 index 0000000..771b73b --- /dev/null +++ b/lib/l10n/app_de.arb @@ -0,0 +1,889 @@ +{ + "projectsNone": "Keine Projekte", + "agentConversations": "Unterhaltungen", + "renameConversationTitle": "Chat umbenennen", + "renameConversationDescription": "Wähle einen kurzen, leicht erkennbaren Namen.", + "showMoreConversations": "Mehr anzeigen", + "showFewerConversations": "Weniger anzeigen", + "agentNewConversation": "Neue Unterhaltung", + "agentElapsedTime": "Dauer {duration}", + "agentConversationActions": "Unterhaltungsaktionen", + "agentMoveToTrash": "In den Papierkorb verschieben", + "agentTrash": "Papierkorb", + "agentRestore": "Wiederherstellen", + "agentEmptyTrash": "Papierkorb leeren", + "agentDeleteForever": "Dauerhaft löschen", + "agentConversationLocation": "Speicherort für Unterhaltungen", + "agentChooseExistingConversations": "Vorhandene Unterhaltungen auswählen", + "agentMoveConversations": "Unterhaltungen verschieben", + "agentLocationUnavailable": "Speicherort für Unterhaltungen nicht verfügbar", + "agentLocationBusy": "Warten Sie, bis laufende Unterhaltungen beendet sind", + "agentRelinkProvider": "Anbieter neu verknüpfen", + "@@locale": "de", + "settings": "Einstellungen", + "closeSettings": "Einstellungen schließen", + "general": "Allgemein", + "appearance": "Darstellung", + "theme": "Design", + "system": "Systemeinstellung", + "light": "Hell", + "dark": "Dunkel", + "saveAppearanceFailed": "Das Erscheinungsbild konnte nicht gespeichert werden. Bitte versuchen Sie es erneut.", + "loadAppearanceFailed": "Die Darstellungseinstellungen konnten nicht geladen werden. Bitte wählen Sie erneut ein Design aus.", + "cancel": "Abbrechen", + "save": "Speichern", + "create": "Erstellen", + "close": "Schließen", + "retry": "Erneut versuchen", + "name": "Name", + "enterName": "Geben Sie einen Namen ein", + "invalidName": "Namen dürfen keine Pfadtrennzeichen oder Steuerzeichen enthalten", + "projectName": "Projektname", + "newProject": "Neues Projekt", + "openProject": "Projekt öffnen", + "openProjectMore": "Weiteres Projekt öffnen", + "projects": "Projekte", + "projectsEmpty": "Keine Projekte", + "openingWorkspace": "Arbeitsbereich wird geöffnet…", + "loadProjectsFailed": "Projekte konnten nicht geladen werden", + "backToProjects": "Zurück zum Schnitt", + "timelines": "Timelines", + "timelineLimitReached": "Jedes Projekt kann maximal {count} Timelines enthalten.", + "timelineName": "Name der Timeline", + "defaultTimelineName": "Timeline {index}", + "newTimeline": "Neue Timeline", + "noTimelines": "Keine Timelines", + "activeTimeline": "Aktuelle Timeline", + "timelineUnavailable": "Timeline nicht verfügbar", + "projectNoTimelines": "Dieses Projekt enthält noch keine Timelines", + "createTimelineHint": "Erstellen Sie links unter „Timelines“ eine Timeline, um mit dem Schnitt zu beginnen.", + "createTimelineChat": "Erstellen Sie eine Timeline, um den Chat zu starten", + "editingFirstLayout": "Schnitt im Vordergrund", + "agentEditingLayout": "Agent und Schnitt", + "agentLayoutDescription": "Planen, zusammenarbeiten und ausführen", + "editingLayoutDescription": "Vorschau, schneiden und verfeinern", + "saveHere": "Hier speichern", + "selectDirectoryFailed": "Es konnte kein Verzeichnis ausgewählt werden. Überprüfen Sie die Systemberechtigungen.", + "operationFailed": "Der Vorgang ist fehlgeschlagen. Bitte versuchen Sie es erneut.", + "collapseSidebar": "Seitenleiste einklappen", + "expandSidebar": "Seitenleiste erweitern", + "expandEditor": "Schnittbereich öffnen", + "collapseProperties": "Eigenschaften reduzieren", + "expandProperties": "Eigenschaften erweitern", + "layout": "Layout", + "materials": "Medien", + "all": "Alle", + "video": "Video", + "audio": "Audio", + "image": "Bild", + "picture": "Bild", + "captions": "Untertitel", + "text": "Text", + "noMedia": "Keine Medien", + "mediaCategory": "Medienkategorie", + "captionTasks": "Untertitelaufgaben", + "listLayout": "Listenansicht", + "gridLayout": "Rasteransicht", + "addToTimeline": "Zur Timeline hinzufügen", + "rename": "Umbenennen", + "renameMedia": "Medien umbenennen", + "removeMedia": "Medien entfernen", + "remove": "Entfernen", + "revealFinder": "Im Finder anzeigen", + "revealFileManager": "Im Dateimanager anzeigen", + "dropToAdd": "Loslassen zum Hinzufügen", + "timelineDropToStart": "Medien hierher ziehen, um zu beginnen.", + "dragMediaHint": "Ziehen Sie Video, Audio oder Bilder hierher\nOriginaldateien bleiben an ihrem aktuellen Speicherort", + "transcribe": "Transkribieren", + "generateCaptions": "Untertitel erstellen", + "play": "Wiedergeben", + "pause": "Pause", + "retryPreview": "Vorschau erneut versuchen", + "canvasRatio": "Bildseitenverhältnis", + "noPreviewContent": "Kein Inhalt zur Vorschau auf der Timeline vorhanden", + "nativePreviewUnsupported": "Die native Vorschau ist auf dieser Plattform nicht verfügbar", + "canvasTransformFailed": "Die Leinwand konnte nicht transformiert werden. Bitte versuchen Sie es erneut.", + "undo": "Rückgängig", + "redo": "Wiederholen", + "deleteSelectedClips": "Ausgewählte Clips löschen", + "splitAtPlayhead": "Am Abspielkopf teilen", + "trimLeft": "Links kürzen", + "trimRight": "Rechts kürzen", + "trimLeftTooltip": "Links vom Abspielkopf entfernen, rechts behalten", + "trimRightTooltip": "Rechts vom Abspielkopf entfernen, links behalten", + "currentSequence": "Aktuelle Sequenz", + "projectProperties": "Projekteigenschaften", + "canvasSize": "Leinwandgröße", + "frameRate": "Bildrate", + "duration": "Dauer", + "totalDuration": "Gesamtdauer", + "clipDuration": "Clipdauer", + "seconds": "Sekunden", + "clip": "Clip", + "unnamedClip": "Unbenannter Clip", + "gap": "Lücke", + "compoundClip": "Zusammengesetzter Clip", + "textClip": "Textclip", + "pictureProperties": "Bild", + "position": "Position", + "rotation": "Drehung", + "scale": "Skalierung", + "size": "Größe", + "transform": "Transformation", + "resetPosition": "Position zurücksetzen", + "keepAspectRatio": "Seitenverhältnis sperren", + "alignment": "Ausrichtung", + "alignLeft": "Links ausrichten", + "alignRight": "Rechts ausrichten", + "alignTop": "Oben ausrichten", + "alignBottom": "Unten ausrichten", + "alignHorizontalCenter": "Horizontal zentrieren", + "alignVerticalCenter": "Vertikal zentrieren", + "volume": "Lautstärke", + "gain": "Verstärkung", + "mute": "Stummschalten", + "unmute": "Stummschaltung aufheben", + "resetVolume": "Lautstärke zurücksetzen", + "invalidGain": "Geben Sie einen Wert zwischen -90 und +12 ein", + "animation": "Animation", + "keyframes": "Keyframes", + "removeAllKeyframes": "Entfernen Sie alle Keyframes", + "linear": "Linear", + "easeIn": "Langsam beschleunigen", + "easeOut": "Langsam abbremsen", + "easeInOut": "Sanft beschleunigen und abbremsen", + "basic": "Grundlagen", + "mask": "Maske", + "addMask": "Maske hinzufügen", + "deleteMask": "Maske löschen", + "resetMask": "Maske zurücksetzen", + "enableMask": "Maske aktivieren", + "disableMask": "Maske deaktivieren", + "moveMaskUp": "Maske nach oben verschieben", + "moveMaskDown": "Maske nach unten verschieben", + "rectangle": "Rechteck", + "ellipse": "Ellipse", + "invert": "Invertieren", + "feather": "Weiche Kante", + "add": "Addieren", + "subtract": "Subtrahieren", + "intersect": "Schnittmenge", + "initialRegion": "Ausgangsbereich", + "none": "Keine", + "color": "Farbe", + "fontSize": "Schriftgröße", + "outlineWidth": "Konturstärke", + "outlineColor": "Konturfarbe", + "captionBaseline": "Untertitel-Grundlinie", + "content": "Text", + "start": "Start", + "time": "Zeit", + "speed": "Geschwindigkeit", + "speedSegmentCount": "{count} Geschwindigkeitssegmente", + "splitSpeedAtPlayhead": "Geschwindigkeit am Abspielkopf teilen", + "speedChange": "Geschwindigkeit", + "speedMode": "Geschwindigkeitsmodus", + "constantSpeed": "Konstante Geschwindigkeit", + "segmentedSpeed": "Segmentierte Geschwindigkeit", + "speedNotAvailable": "Geschwindigkeitskontrollen sind noch nicht verfügbar", + "custom": "Benutzerdefiniert", + "invalidNumber": "Ungültiger Wert", + "mediaUnavailable": "Medien nicht verfügbar", + "mediaMissing": "Fehlende Medien", + "mediaColorSpace": "Medienfarbraum", + "mediaColorInterpretation": "Interpretation der Medienfarbe", + "colorInfoNotLoaded": "Farbinformationen nicht geladen", + "unknownColorSpace": "Unbekannter Farbraum. Anzeige als Rec.709.", + "colorBackendUnsupported": "Das aktuelle Backend unterstützt keine Medienfarbinterpretation.", + "loadClipPropertiesFailed": "Clip-Eigenschaften konnten nicht gelesen werden", + "updatePictureFailed": "Bildeigenschaften konnten nicht aktualisiert werden", + "updateVolumeFailed": "Die Lautstärke konnte nicht aktualisiert werden", + "updateMaskFailed": "Maske konnte nicht aktualisiert werden", + "updateKeyframesFailed": "Keyframes konnten nicht aktualisiert werden", + "maskPreviewFailed": "Die Maskenvorschau konnte nicht vorbereitet werden", + "alignClipFailed": "Der Clip konnte nicht ausgerichtet werden. Warten Sie auf die Vorschau und versuchen Sie es dann erneut.", + "invalidTransform": "Die Skalierung muss 1 % bis 10.000 % betragen. Position und Winkel müssen gültige Zahlen sein.", + "editFailed": "Konnte nicht bearbeitet werden. Überprüfen Sie die Eingabe und den Zeitbereich.", + "addMediaFailed": "Medien konnten nicht hinzugefügt werden. Bitte versuchen Sie es erneut.", + "deleteCaption": "Untertitel löschen", + "mergeCaptions": "Untertitel zusammenführen", + "captionDeleted": "Untertitel gelöscht", + "captionChanged": "Die Untertitel haben sich geändert. Bitte versuchen Sie es erneut.", + "captionEditChanged": "Die Untertitel haben sich geändert. Bitte erneut bearbeiten.", + "assistantHint": "Beschreiben Sie Ihre Bearbeitungsidee", + "configureAgentHint": "Konfigurieren Sie den Agentendienst, um mit dem Chatten zu beginnen", + "agentRestartHint": "Konfigurieren Sie den Agentendienst und starten Sie dann die App neu.", + "replyInterrupted": "Antwort unterbrochen", + "replying": "Antwort wird erstellt…", + "stopReply": "Antwort stoppen", + "sendMessage": "Nachricht senden", + "addAttachment": "Anhang hinzufügen (noch nicht verfügbar)", + "replyFailed": "Antwort fehlgeschlagen. Überprüfen Sie die Verbindung oder versuchen Sie es später noch einmal.", + "mcpService": "MCP-Dienst", + "listenPort": "Port", + "accessToken": "Zugriffstoken", + "copyAccessToken": "Zugriffstoken kopieren", + "accessTokenCopied": "Zugriffstoken kopiert", + "loadMcpFailed": "Die MCP-Einstellungen konnten nicht geladen werden. Wiederholen", + "saveMcpFailed": "MCP-Einstellungen konnten nicht gespeichert werden. Bitte versuchen Sie es erneut.", + "retryStart": "Versuchen Sie es erneut", + "invalidPort": "Der Port muss zwischen 1 und 65535 liegen", + "loadingSettings": "Einstellungen werden geladen…", + "starting": "Wird gestartet…", + "stopping": "Wird gestoppt…", + "disabled": "Deaktiviert", + "running": "Aktiv", + "startFailed": "Start fehlgeschlagen", + "saved": "Gespeichert", + "unsaved": "Nicht gespeichert", + "saving": "Wird gespeichert…", + "pendingSave": "Speichern steht aus", + "notApplied": "Nicht angewendet", + "enable": "Aktivieren", + "disable": "Deaktivieren", + "type": "Typ", + "status": "Status", + "file": "Datei", + "unboundMedia": "Keine Medien zugeordnet", + "unboundAudio": "Keine Audiospur zugeordnet", + "vertical": "Vertikal", + "language": "Sprache", + "saveLanguageFailed": "Die Sprache konnte nicht gespeichert werden. Bitte versuchen Sie es erneut.", + "loadLanguageFailed": "Die Sprache konnte nicht geladen werden. Bitte wählen Sie erneut aus.", + "propertiesFirstLayout": "Eigenschaften zuerst", + "defaultLayout": "Standardlayout", + "separateVocals": "Gesang trennen", + "detachAudio": "Audio abtrennen", + "restoreAudio": "Audio wiederherstellen", + "audioDetached": "Audio abgetrennt", + "addAll": "Alle hinzufügen", + "preparingMedia": "Medien werden vorbereitet…", + "cancelling": "Wird abgebrochen…", + "cancelled": "Abgebrochen", + "interruptedTask": "Aufgabe unterbrochen. Starten Sie neu, um fortzufahren", + "auto": "Automatisch", + "autoDetect": "Automatisch erkennen", + "noTranslation": "Nicht übersetzen", + "sourceLanguage": "Ausgangssprache", + "translationLanguage": "Zielsprache", + "transcriptionNotConfigured": "Die Transkription ist nicht konfiguriert. Installieren Sie die Erkennungskomponente und das Whisper Turbo-Modell.", + "translationNotConfigured": "Die Untertitelübersetzung ist nicht konfiguriert. Sie können Untertitel in der Ausgangssprache generieren.", + "sourceLanguageUnknown": "Es konnte keine Ausgangssprache für die Übersetzung ermittelt werden.", + "startTranscriptionFailed": "Die Transkription konnte nicht gestartet werden. Überprüfen Sie die Medien oder warten Sie, bis die aktuelle Aufgabe abgeschlossen ist.", + "placeMediaFirst": "Platzieren Sie dieses Medium auf der Timeline, bevor Sie Untertitel anwenden.", + "placeTranslationMediaFirst": "Platzieren Sie die entsprechenden Medien auf der Timeline, bevor Sie übersetzte Untertitel anwenden.", + "selectTargetClip": "Wählen Sie den Zielclip aus", + "timelineChanged": "Die Zeitleiste hat sich geändert. Wählen Sie den Zielclip erneut aus.", + "transcriptionAccessFailed": "Transkription fehlgeschlagen: Auf Komponente, Modell oder Quellmedium kann nicht zugegriffen werden (notConfigured)", + "transcriptionNoAudio": "Transkription fehlgeschlagen: Kein erkennbares Audio im ausgewählten Medium oder Track (noAudio)", + "transcriptionInvalidResult": "Transkription fehlgeschlagen: Ungültige Untertiteldatei zurückgegeben (invalidResult)", + "transcriptionWorkerExited": "Transkription fehlgeschlagen: Erkennungskomponente wurde unerwartet beendet (workerExited)", + "transcriptionProcessingFailed": "Transkription fehlgeschlagen: native Verarbeitung fehlgeschlagen (processingFailed)", + "transcriptionFailed": "Die Transkription ist fehlgeschlagen. Überprüfen Sie Komponente, Modell, Audiospur und Dauer", + "transcribing": "Wird transkribiert…", + "captionsGenerated": "Untertitel erstellt", + "cancelTranscription": "Transkription abbrechen", + "applyCaptions": "Untertitel anwenden", + "preparingTranslation": "Übersetzung wird vorbereitet…", + "translatingCaptions": "Untertitel werden übersetzt…", + "cancellingTranslation": "Übersetzung wird abgebrochen…", + "translatedCaptionsGenerated": "Übersetzte Untertitel erstellt", + "translationCancelled": "Übersetzung abgebrochen", + "translationInterrupted": "Übersetzung unterbrochen", + "cancelTranslation": "Übersetzung abbrechen", + "editorServiceUnavailable": "Bearbeitungsdienst nicht verfügbar. Öffnen Sie das Projekt erneut.", + "mcpUnavailable": "MCP-Verbindung nicht verfügbar. Überprüfen Sie den lokalen Port und das Token.", + "openTimelineFailed": "Die Zeitleiste konnte nicht geöffnet werden", + "noTimelineSequence": "Diese Timeline enthält keine Sequenz.", + "waitingForProject": "Warten auf das Öffnen eines Projekts", + "hold": "Halten", + "noImportableFiles": "Keine importierbaren Dateien erhalten", + "virtualFilesUnsupported": "Ziehen Sie Originaldateien aus dem Dateimanager. Virtuelle Dateien werden noch nicht unterstützt.", + "editorSessionStartFailed": "Der Timeline-Editor konnte nicht geöffnet werden", + "previewStartFailed": "Die native Vorschau konnte nicht gestartet werden", + "previewInvalidTrack": "Die ausgewählte Audio- oder Videospur ist im Medium nicht vorhanden.", + "previewMissingBinding": "Medienbindungen fehlen. Diese Zeitleiste konnte nicht in der Vorschau angezeigt werden.", + "previewUnsupportedEdits": "Diese Zeitleiste enthält Bearbeitungen, die noch nicht von der Vorschau unterstützt werden.", + "previewUnsupportedConfiguration": "Diese Vorschaukonfiguration wird auf der aktuellen Plattform oder Systemversion nicht unterstützt.", + "previewHdrUnsupported": "HDR-Medien erfordern Tone Mapping für die SDR-Vorschau. Das aktuelle System oder die Vorschaukonfiguration unterstützt dies nicht.", + "previewAudioOutOfRange": "Der Audioclip überschreitet den Quellspurbereich und kann nicht in der Vorschau angezeigt werden.", + "previewResourceMissing": "Vorschaumedien sind nicht mehr vorhanden. Suchen Sie die Originaldatei erneut.", + "previewInvalidComposition": "Ungültige Videokompositionskonfiguration. Vorschau konnte nicht erstellt werden.", + "previewInvalidData": "Invalid preview data. Bitte versuchen Sie es erneut.", + "previewFailed": "Preview failed. Überprüfen Sie den Medienzugriff und versuchen Sie es erneut.", + "chatFailed": "Das Gespräch konnte nicht abgeschlossen werden. Überprüfen Sie die Dienstkonfiguration oder versuchen Sie es später erneut.", + "delete": "Löschen", + "pinTimeline": "Zeitleiste anheften", + "unpinTimeline": "Zeitleiste lösen", + "deleteTimelineConfirmation": "„{name}“ und den Bearbeitungsverlauf löschen? Dies kann nicht rückgängig gemacht werden.", + "@deleteTimelineConfirmation": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "processingFailed": "Verarbeitung fehlgeschlagen", + "noMatchingOptions": "Keine passenden Optionen", + "removeMediaConfirmation": "„{name}“ aus der Bibliothek entfernen? Vorhandene Clips, Verlauf und die Originaldatei bleiben erhalten.", + "@removeMediaConfirmation": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "mediaAdded": "{count} Medienreferenzen hinzugefügt", + "@mediaAdded": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "duplicatesSkipped": "Doppelte {count}-Dateien wurden übersprungen", + "@duplicatesSkipped": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mediaCount": "{count} Medienelemente", + "importMedia": "Importieren", + "@mediaCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "noMediaOfType": "Kein {type}-Medium", + "@noMediaOfType": { + "placeholders": { + "type": { + "type": "String" + } + } + }, + "captionsImported": "Importierte {count}-Untertitel", + "@captionsImported": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "editCaptionError": "Untertitel konnten nicht bearbeitet werden: {message}", + "@editCaptionError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "mcpStartError": "MCP konnte nicht gestartet werden: {message}", + "@mcpStartError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "manualColorSpace": "Manuell ausgewählt: {name}", + "@manualColorSpace": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "detectedColorSpace": "Erkannt: {name}", + "@detectedColorSpace": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "keyframeLabel": "{channel}-Keyframe", + "@keyframeLabel": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "maskMode": "Kombinationsmodus: {mode}", + "@maskMode": { + "placeholders": { + "mode": { + "type": "String" + } + } + }, + "keyframeCount": "{count} Keyframes", + "@keyframeCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "toggleKeyframe": "{channel}-Keyframe: {action}", + "@toggleKeyframe": { + "placeholders": { + "action": { + "type": "String" + }, + "channel": { + "type": "String" + } + } + }, + "previousKeyframe": "Vorheriger {channel}-Keyframe", + "@previousKeyframe": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "nextKeyframe": "Nächster {channel}-Keyframe", + "@nextKeyframe": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "keyframeSettings": "{channel}-Keyframe-Einstellungen", + "@keyframeSettings": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "selectedClipsHint": "{count} Clips ausgewählt\nWählen Sie einen Clip aus, um seine Eigenschaften anzuzeigen", + "@selectedClipsHint": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "transcriptionError": "Die Transkription ist fehlgeschlagen. Überprüfen Sie die Komponente, das Modell, die Audiospur und die Dauer ({code}).", + "@transcriptionError": { + "placeholders": { + "code": { + "type": "String" + } + } + }, + "captionsAdded": "{count}-Untertitel hinzugefügt. Bearbeiten Sie sie im Eigenschaftenfenster.", + "@captionsAdded": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "translatedCaptionsAdded": "{count} übersetzte Untertitel hinzugefügt. Bearbeiten Sie sie im Eigenschaftenfenster.", + "@translatedCaptionsAdded": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "applyCaptionsError": "Untertitel konnten nicht angewendet werden: {message}", + "@applyCaptionsError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "applyTranslatedCaptionsError": "Übersetzte Untertitel konnten nicht angewendet werden: {message}", + "@applyTranslatedCaptionsError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "recognizedCaptions": "{count} Untertitel erkannt", + "@recognizedCaptions": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "captionCount": "{count} Untertitel", + "@captionCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "translationFailed": "Übersetzung fehlgeschlagen: {message}", + "@translationFailed": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "translatedCaptionCount": "{count} Untertitel ({language})", + "@translatedCaptionCount": { + "placeholders": { + "count": { + "type": "int" + }, + "language": { + "type": "String" + } + } + }, + "previewParameterError": "Ungültige Vorschauparameter: {message}", + "@previewParameterError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "mediaOffline": "Medien offline oder nicht verfügbar: {names}", + "@mediaOffline": { + "placeholders": { + "names": { + "type": "String" + } + } + }, + "searchOptions": "Suche {label}…", + "@searchOptions": { + "placeholders": { + "label": { + "type": "String" + } + } + }, + "loadRecentProjectsFailed": "Aktuelle Bibliotheken konnten nicht geladen werden. Sie können eine Bibliothek weiterhin manuell öffnen.", + "projectAccessFailed": "Projekt nicht verfügbar", + "projectMissingDirectory": "Projekt nicht gefunden", + "recentProjectSaveFailed": "Die Bibliothek wurde geöffnet, aber der aktuelle Bibliothekseintrag konnte nicht gespeichert werden.", + "lastProjectSaveFailed": "Projekt geöffnet, aber der letzte Projektdatensatz konnte nicht gespeichert werden.", + "enterProjectName": "Geben Sie einen Projektnamen ein", + "projectSwitched": "Das Projekt hat sich geändert. Ziehen Sie das Medium erneut hinein.", + "notLocalMedia": "Dieses Medium ist keine lokale Datei", + "revealMediaFailed": "Medien konnten im Dateimanager nicht angezeigt werden", + "openMatchingProject": "Öffnen Sie zunächst das entsprechende Projekt", + "projectMismatch": "Die Bibliothek an diesem Standort stimmt nicht mit dem Datensatz überein. Wählen Sie es erneut mit Bibliothek öffnen aus.", + "openProjectFirst": "Öffnen Sie zunächst eine Bibliothek", + "localFilesOnly": "Ziehen Sie lokale Dateien aus dem Dateimanager", + "foldersUnsupported": "Wählen Sie Dateien aus. Das Ziehen von Ordnern wird noch nicht unterstützt.", + "mediaImportCancelled": "Medienimport abgebrochen", + "fileAccessFailed": "Die Datei fehlt oder ist nicht lesbar. Überprüfen Sie den Standort und die Berechtigungen", + "registerMediaFailed": "Medien konnten nicht registriert werden. Bitte versuchen Sie es erneut", + "mediaNoLongerExists": "Medien gibt es nicht mehr", + "mediaNoTracks": "Das Medium verfügt über keine verwendbaren Video- oder Audiospuren", + "invalidMediaDuration": "Ungültige Mediendauer", + "mediaInfoUnsupported": "Das Lesen von Medieninformationen wird auf dieser Plattform noch nicht unterstützt", + "mediaInfoFailed": "Medieninformationen konnten nicht gelesen werden. Überprüfen Sie die Datei- und Zugriffsberechtigungen", + "saveTimelineFailed": "Die Zeitleiste konnte nicht gespeichert werden. Versuchen Sie es erneut. Nicht gespeicherte Änderungen bleiben in dieser Sitzung bestehen.", + "addKeyframeAction": "Hinzufügen", + "backgroundTasks": "Hintergrundaufgaben", + "noBackgroundTasks": "Keine Hintergrundaufgaben", + "retryTask": "Erneut versuchen", + "applyOriginalCaptions": "Originaluntertitel anwenden", + "applyTranslatedCaptions": "Übersetzte Untertitel anwenden", + "subtitleTaskStarted": "Untertitelaufgabe gestartet", + "fitTimeline": "Gesamte Zeitleiste einpassen", + "modify": "Modify", + "projectSettings": "Project settings", + "projectSettingsDescription": "Change project output settings while keeping clip timing and speed.", + "projectColorSpace": "Color space", + "projectWidth": "Width (px)", + "projectHeight": "Height (px)", + "projectResolutionInvalid": "Enter a whole number from 1 to 16384", + "previewFullscreen": "Vollbildvorschau", + "exitPreviewFullscreen": "Vollbild verlassen", + "previewGoToStart": "Zum Anfang", + "previewPreviousFrame": "Vorheriges Bild", + "previewNextFrame": "Nächstes Bild", + "softwareUpdates": "Softwareupdates", + "checkForUpdates": "Nach Updates suchen", + "automaticallyCheckUpdates": "Automatisch nach Updates suchen", + "updatesUnavailable": "Updates sind in diesem Build nicht verfügbar.", + "updateCheckFailed": "Updates konnten nicht geprüft werden. Bitte erneut versuchen.", + "agentSettings": "Agent", + "agentSaveSettingsFailed": "Die Agent-Einstellungen konnten nicht gespeichert werden.", + "agentDeleteProviderTitle": "Anbieter löschen?", + "agentDeleteProviderDescription": "„{providerName}“ und der gespeicherte API-Schlüssel werden von diesem Gerät entfernt.", + "agentProviderRequired": "Fügen Sie einen Anbieter hinzu, bevor Sie den Assistenten aktivieren.", + "agentUseSelectedModel": "Neue Agent-Anfragen verwenden das ausgewählte Modell.", + "agentEnable": "Agent aktivieren", + "agentDefaultModel": "Standardmodell", + "agentConfigureModel": "Modelle konfigurieren", + "agentSelectModel": "Modell auswählen", + "agentModelUnavailable": "Das Modell dieser Unterhaltung ist nicht verfügbar. Wählen Sie ein anderes Modell für eine neue Unterhaltung.", + "agentModelChangeSession": "Beim Wechseln des Modells wird eine neue Agent-Sitzung gestartet.", + "agentCustomProviders": "Benutzerdefinierte Anbieter", + "agentProviderStorageDescription": "Anbietermetadaten werden lokal gespeichert. API-Schlüssel werden im Anmeldedatenspeicher des Systems aufbewahrt.", + "agentAddProvider": "Anbieter hinzufügen", + "agentBackToProviders": "Zurück zu den Anbietern", + "agentLoadSettingsFailed": "Agent-Einstellungen konnten nicht geladen werden. Erneut versuchen", + "agentEnableProvider": "Provider aktivieren", + "agentEditProvider": "Anbieter bearbeiten", + "agentDeleteProvider": "Anbieter löschen", + "agentModelIdsUnique": "Modell-IDs müssen eindeutig sein.", + "agentEditProviderTitle": "Anbieter bearbeiten", + "agentProviderEndpointDescription": "Konfigurieren Sie einen OpenAI-kompatiblen Chat-Completions-Endpunkt.", + "agentSaveProvider": "Anbieter speichern", + "agentProviderConfiguration": "Provider-Konfiguration", + "agentAuthenticationAndModels": "Authentifizierung und Modelle", + "agentApiType": "API-Typ", + "agentOpenAiChatCompletions": "OpenAI Completions", + "agentBaseUrl": "Basis-URL", + "agentApiKey": "API-Schlüssel", + "agentProviderNameHint": "Mein Anbieter", + "agentApiKeyOptional": "Optional für Endpunkte, die keine Authentifizierung erfordern.", + "agentApiKeyKeep": "Leer lassen, um den gespeicherten Schlüssel beizubehalten.", + "agentOptional": "Optional", + "agentApiKeyOneLine": "Der API-Schlüssel muss einzeilig sein.", + "agentRemoveSavedApiKey": "Gespeicherten API-Schlüssel entfernen", + "agentModels": "Modelle", + "agentAddModel": "Modell hinzufügen", + "agentRequiredField": "Dieses Feld ist erforderlich.", + "agentInvalidBaseUrl": "Geben Sie eine HTTP(S)-Basis-URL ohne Anmeldedaten, Abfrage oder Fragment ein.", + "agentModelId": "Modell-ID", + "agentContextWindow": "Kontextfenster", + "agentMaxOutputTokens": "Maximale Ausgabe", + "agentMaxOutputBelowContext": "Muss kleiner als das Kontextfenster sein.", + "agentDeleteModel": "Modell löschen", + "agentPositiveInteger": "Geben Sie eine positive Ganzzahl ein.", + "agentConfigurationReadFailed": "Die Agent-Konfiguration konnte nicht gelesen werden. Prüfen Sie die Einstellungen und versuchen Sie es erneut.", + "agentConfigurationRequired": "Konfigurieren und aktivieren Sie zuerst den Agent in den Einstellungen.", + "agentSessionRestoreFailed": "Die Agent-Sitzung konnte nicht wiederhergestellt werden. Versuchen Sie es später erneut.", + "select": "Auswählen", + "projectLocation": "Projektspeicherort", + "projectLocationNotSet": "Nicht festgelegt", + "resourceLocation": "Ressourcenspeicherort", + "resourceLocationNotSet": "Nicht festgelegt", + "loadProjectLocationFailed": "Der Projektspeicherort konnte nicht geladen werden.", + "saveProjectLocationFailed": "Der Projektspeicherort konnte nicht gespeichert werden.", + "loadResourceLocationFailed": "Der Ressourcenspeicherort konnte nicht geladen werden.", + "saveResourceLocationFailed": "Der Ressourcenspeicherort konnte nicht gespeichert werden.", + "downloadAndContinue": "Herunterladen und fortfahren", + "downloadInBackground": "Im Hintergrund herunterladen", + "downloadingResource": "Wird heruntergeladen…", + "processingResourceDownloadFailed": "Die Ressource für die Spracherkennung konnte nicht heruntergeladen werden. Versuchen Sie es erneut.", + "transcriptionResourceRequired": "Zum Erstellen von Untertiteln muss zuerst ein Spracherkennungsmodell heruntergeladen werden.", + "removeBackground": "Hintergrund entfernen", + "startBackgroundRemoval": "Hintergrund entfernen", + "backgroundRemovalResourceRequired": "Für die Hintergrundentfernung ist ein lokales Modell erforderlich. Nach dem Download startet sie automatisch.", + "backgroundRemovalDownloadTask": "Ressource zur Hintergrundentfernung herunterladen", + "backgroundRemovalResourceName": "Modell zur Hintergrundentfernung", + "backgroundRemovalTaskStarted": "Hintergrundentfernung gestartet", + "backgroundRemovalApplying": "Clip-Medium wird ersetzt", + "backgroundRemovalComplete": "Hintergrundentfernung abgeschlossen", + "backgroundRemovalFailed": "Hintergrundentfernung fehlgeschlagen", + "backgroundRemovalDestructiveHint": "Das erzeugte transparente Medium ersetzt diesen Clip. Mit Rückgängig können Sie den ursprünglichen Clip wiederherstellen.", + "startBackgroundRemovalFailed": "Die Hintergrundentfernung konnte nicht gestartet werden. Prüfen Sie das Medium oder warten Sie, bis die aktuelle Verarbeitung abgeschlossen ist.", + "agentContextBudgetExceeded": "Das Eingabebudget reicht für Systemanweisungen, Werkzeuge und Nachricht nicht aus. Kontextfenster vergrößern oder maximale Ausgabe reduzieren.", + "agentAuthenticationFailed": "Authentifizierung fehlgeschlagen. API Key und Berechtigungen prüfen.", + "agentConnectionFailed": "Verbindung fehlgeschlagen oder Zeitlimit überschritten. Base URL und Netzwerk prüfen.", + "agentProtocolFailed": "Die Antwort passt nicht zum gewählten API-Typ oder der Stream ist unvollständig.", + "agentContextBudgetTooSmall": "Mehr Eingaberaum für Systemanweisungen reservieren. Kontextfenster vergrößern oder maximale Ausgabe reduzieren.", + "agentCompacting": "Kontext aufbereiten…", + "agentEditing": "Bearbeiten…", + "agentVerifying": "Ergebnisse prüfen…", + "agentTurnLimitReached": "Diese Aufgabe hat das Ausführungslimit erreicht. Änderungen wurden gespeichert. Sende „Weiter“, um fortzufahren.", + "agentRecoveryRequired": "Das vorherige Ergebnis ist unbestätigt. Fortsetzen prüft gespeicherte Belege; unbestätigte Änderungen werden nicht wiederholt.", + "agentExportReplyFailed": "Video erfolgreich exportiert. Die Zusammenfassung ist fehlgeschlagen. Erneut versuchen, ohne Bearbeitung oder Export zu wiederholen.", + "agentRetrySummary": "Zusammenfassung wiederholen", + "agentResumeTask": "Aufgabe fortsetzen", + "agentTaskInterrupted": "Die Aufgabe wurde unterbrochen. Vom gespeicherten Stand fortsetzen.", + "downloadSubtitleModel": "Untertitelmodell herunterladen", + "downloadModelAction": "Herunterladen", + "subtitleEngineUnavailable": "Das Modell ist installiert, aber die Untertitel-Engine konnte nicht starten. Reparieren Sie die Engine; das Modell muss nicht erneut heruntergeladen werden.", + "backgroundTaskDetails": "Aufgabendetails", + "backgroundTaskFailed": "Fehlgeschlagen", + "backgroundTaskCompleted": "Abgeschlossen", + "captionWrapLines": "Untertitel umbrechen", + "captionSingleLine": "Untertitel einzeilig anzeigen", + "noMatchingCaptions": "Keine passenden Untertitel", + "subtitleResourcesRequired": "Diese Ressourcen werden für Untertitel benötigt. Nach dem Download beginnt die Erstellung automatisch.", + "subtitleResourcesDownloadSize": "Herunterzuladen: {size}", + "pauseDownload": "Pausieren", + "resumeDownload": "Fortsetzen", + "downloadPaused": "Pausiert", + "cancelResourceDownloadTitle": "Download abbrechen?", + "cancelResourceDownloadMessage": "Der Download wird beendet. Der Fortschritt der aktuellen Ressource kann verloren gehen.", + "continueDownload": "Download fortsetzen", + "cancelDownload": "Download abbrechen", + "speechResourceStage": "Spracherkennungsressource", + "translationResourceStage": "Übersetzungsressource", + "subtitleResourceDownloadTask": "Sprach- und Übersetzungsressourcen herunterladen", + "downloadingSpeechModel": "Sprachmodell wird heruntergeladen", + "downloadingTranslationModel": "Übersetzungsmodell wird heruntergeladen", + "selectProject": "Projekt auswählen", + "searchProjects": "Projekte suchen", + "noMatchingProjects": "Keine passenden Projekte", + "projectLocationMissing": "Der Ordner ist nicht vorhanden. Er wird beim Erstellen eines Projekts angelegt.", + "projectLocationUnavailable": "Der Projektspeicherort ist nicht verfügbar. Verbinden Sie das Laufwerk oder prüfen Sie das Netzwerk und versuchen Sie es erneut, oder ändern Sie den Speicherort.", + "projectLocationNotWritable": "Der Projektspeicherort ist nicht beschreibbar. Prüfen Sie die Berechtigungen oder ändern Sie den Speicherort.", + "projectLocationCreateFailed": "Der Projektordner konnte nicht erstellt oder beschrieben werden. Prüfen Sie die Berechtigungen oder ändern Sie den Speicherort.", + "removeProjectFromSidebar": "Aus der Seitenleiste entfernen", + "projectRemoved": "Projekt entfernt. Lokale Dateien und Unterhaltungen bleiben erhalten.", + "agentNoConversations": "Noch keine Unterhaltungen", + "collapseProject": "Projekt einklappen", + "expandProject": "Projekt ausklappen", + "agentDeleteConfirmation": "„{title}“ und alle Nachrichten endgültig löschen? Dies kann nicht rückgängig gemacht werden. Lokale Projektdateien sind nicht betroffen.", + "agentEmptyTrashConfirmation": "Alle Unterhaltungen im Papierkorb endgültig löschen? Dies kann nicht rückgängig gemacht werden. Lokale Projektdateien sind nicht betroffen.", + "checkingForUpdates": "Suche nach Updates…", + "appIsUpToDate": "Die App ist aktuell.", + "downloadingUpdate": "Update wird heruntergeladen: {progress}%", + "updateAvailable": "Version {version} ist verfügbar.", + "downloadUpdate": "Update herunterladen", + "restartToUpdate": "Für Update neu starten", + "updateOperationFailed": "Update fehlgeschlagen. Aktive Aufgaben abschließen und erneut versuchen.", + "windowMinimize": "Minimieren", + "windowMaximize": "Maximieren", + "windowRestore": "Wiederherstellen", + "workspaceAgent": "Assistent", + "workspaceCut": "Schnitt", + "noAvailableOptions": "Keine Optionen verfügbar", + "composerReferenceInvalid": "Ein Verweis ist nicht mehr gültig. Öffnen Sie sein Projekt oder entfernen Sie ihn.", + "durationSeconds": "{seconds} s", + "durationMinutesSeconds": "{minutes} min {seconds} s", + "projectNameInvalid": "Ungültiger Projektname", + "projectLocationDefaultUnavailable": "Der Standard-Projektordner ist nicht zugänglich. Wählen Sie ihn in den Einstellungen erneut aus.", + "chooseProjectLocation": "Wählen Sie zuerst einen Projektordner in den Einstellungen.", + "untitledTimeline": "Unbenannte Timeline", + "primarySequence": "Hauptsequenz", + "primaryStoryline": "Haupthandlung", + "projectSessionClosed": "Die Projektsitzung wurde geschlossen. Öffnen Sie das Projekt erneut.", + "timelineSessionClosed": "Die Timeline-Sitzung wurde geschlossen. Öffnen Sie die Timeline erneut.", + "timelineMissing": "Die Timeline existiert nicht oder wurde gelöscht.", + "timelineInUse": "Die Timeline wird verwendet und kann noch nicht gelöscht werden.", + "timelineHasBackgroundTasks": "Beenden Sie die Hintergrundaufgaben der Timeline, bevor Sie sie löschen.", + "timelineRequired": "Ein Projekt muss mindestens eine Timeline behalten.", + "mediaReadFailed": "Medium konnte nicht gelesen werden", + "mediaImportFailed": "Medium konnte nicht importiert werden", + "unsupportedMediaType": "Es können nur Video-, Audio- und Bilddateien importiert werden.", + "mediaNoVideoTracks": "Das Medium hat keine verwendbare Videospur", + "mediaDurationOutOfRange": "Die Mediendauer überschreitet den Timeline-Bereich", + "resourceDownloadHttpFailed": "Download fehlgeschlagen (HTTP {statusCode})", + "resourceChecksumFailed": "Die Modelldatei konnte nicht überprüft werden. Laden Sie die Ressource erneut herunter.", + "subtitleLanguageAf": "Afrikaans", + "subtitleLanguageAm": "Amharisch", + "subtitleLanguageAr": "Arabisch", + "subtitleLanguageAst": "Asturisch", + "subtitleLanguageAz": "Aserbaidschanisch", + "subtitleLanguageBa": "Baschkirisch", + "subtitleLanguageBe": "Belarussisch", + "subtitleLanguageBg": "Bulgarisch", + "subtitleLanguageBn": "Bengalisch", + "subtitleLanguageBr": "Bretonisch", + "subtitleLanguageBs": "Bosnisch", + "subtitleLanguageCa": "Katalanisch", + "subtitleLanguageCeb": "Cebuano", + "subtitleLanguageCs": "Tschechisch", + "subtitleLanguageCy": "Walisisch", + "subtitleLanguageDa": "Dänisch", + "subtitleLanguageDe": "Deutsch", + "subtitleLanguageEl": "Griechisch", + "subtitleLanguageEn": "Englisch", + "subtitleLanguageEs": "Spanisch", + "subtitleLanguageEt": "Estnisch", + "subtitleLanguageFa": "Persisch", + "subtitleLanguageFf": "Ful", + "subtitleLanguageFi": "Finnisch", + "subtitleLanguageFr": "Französisch", + "subtitleLanguageFy": "Westfriesisch", + "subtitleLanguageGa": "Irisch", + "subtitleLanguageGd": "Gälisch (Schottland)", + "subtitleLanguageGl": "Galicisch", + "subtitleLanguageGu": "Gujarati", + "subtitleLanguageHa": "Haussa", + "subtitleLanguageHe": "Hebräisch", + "subtitleLanguageHi": "Hindi", + "subtitleLanguageHr": "Kroatisch", + "subtitleLanguageHt": "Haiti-Kreolisch", + "subtitleLanguageHu": "Ungarisch", + "subtitleLanguageHy": "Armenisch", + "subtitleLanguageId": "Indonesisch", + "subtitleLanguageIg": "Igbo", + "subtitleLanguageIlo": "Ilokano", + "subtitleLanguageIs": "Isländisch", + "subtitleLanguageIt": "Italienisch", + "subtitleLanguageJa": "Japanisch", + "subtitleLanguageJv": "Javanisch", + "subtitleLanguageKa": "Georgisch", + "subtitleLanguageKk": "Kasachisch", + "subtitleLanguageKm": "Khmer", + "subtitleLanguageKn": "Kannada", + "subtitleLanguageKo": "Koreanisch", + "subtitleLanguageLb": "Luxemburgisch", + "subtitleLanguageLg": "Ganda", + "subtitleLanguageLn": "Lingala", + "subtitleLanguageLo": "Laotisch", + "subtitleLanguageLt": "Litauisch", + "subtitleLanguageLv": "Lettisch", + "subtitleLanguageMg": "Malagasy", + "subtitleLanguageMk": "Mazedonisch", + "subtitleLanguageMl": "Malayalam", + "subtitleLanguageMn": "Mongolisch", + "subtitleLanguageMr": "Marathi", + "subtitleLanguageMs": "Malaiisch", + "subtitleLanguageMy": "Birmanisch", + "subtitleLanguageNe": "Nepalesisch", + "subtitleLanguageNl": "Niederländisch", + "subtitleLanguageNo": "Norwegisch", + "subtitleLanguageNs": "Nord-Sotho", + "subtitleLanguageOc": "Okzitanisch", + "subtitleLanguageOr": "Oriya", + "subtitleLanguagePa": "Punjabi", + "subtitleLanguagePl": "Polnisch", + "subtitleLanguagePs": "Paschtu", + "subtitleLanguagePt": "Portugiesisch", + "subtitleLanguageRo": "Rumänisch", + "subtitleLanguageRu": "Russisch", + "subtitleLanguageSd": "Sindhi", + "subtitleLanguageSi": "Singhalesisch", + "subtitleLanguageSk": "Slowakisch", + "subtitleLanguageSl": "Slowenisch", + "subtitleLanguageSo": "Somali", + "subtitleLanguageSq": "Albanisch", + "subtitleLanguageSr": "Serbisch", + "subtitleLanguageSs": "Swazi", + "subtitleLanguageSu": "Sundanesisch", + "subtitleLanguageSv": "Schwedisch", + "subtitleLanguageSw": "Suaheli", + "subtitleLanguageTa": "Tamil", + "subtitleLanguageTh": "Thailändisch", + "subtitleLanguageTl": "Tagalog", + "subtitleLanguageTn": "Tswana", + "subtitleLanguageTr": "Türkisch", + "subtitleLanguageUk": "Ukrainisch", + "subtitleLanguageUr": "Urdu", + "subtitleLanguageUz": "Usbekisch", + "subtitleLanguageVi": "Vietnamesisch", + "subtitleLanguageWo": "Wolof", + "subtitleLanguageXh": "Xhosa", + "subtitleLanguageYi": "Jiddisch", + "subtitleLanguageYo": "Yoruba", + "subtitleLanguageYue": "Kantonesisch", + "subtitleLanguageZh": "Chinesisch", + "subtitleLanguageZu": "Zulu", + "linearRec2020": "Lineares Rec.2020", + "diagnostics": "Diagnose", + "exportDiagnostics": "Diagnosepaket exportieren", + "exportDiagnosticsFailed": "Die Diagnose konnte nicht exportiert werden. Bitte erneut versuchen.", + "exportDiagnosticsSucceeded": "Diagnosepaket gespeichert." +} diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb new file mode 100644 index 0000000..1a53fce --- /dev/null +++ b/lib/l10n/app_en.arb @@ -0,0 +1,1342 @@ +{ + "selectProject": "Select project", + "searchProjects": "Search projects", + "noMatchingProjects": "No matching projects", + "projectsNone": "No projects yet", + "projectLocationMissing": "The folder does not exist. It will be created when you create a project.", + "projectLocationUnavailable": "The project save location is unavailable. Connect the disk or check the network and retry, or change the location.", + "projectLocationNotWritable": "The project save location is not writable. Check permissions or change the location.", + "projectLocationCreateFailed": "Could not create or write to the project save folder. Check permissions or change the location.", + "removeProjectFromSidebar": "Remove from sidebar", + "projectRemoved": "Project removed. Local files and conversations are preserved.", + "agentNoConversations": "No conversations yet", + "renameConversationTitle": "Rename chat", + "renameConversationDescription": "Keep it short and easy to recognize.", + "collapseProject": "Collapse project", + "expandProject": "Expand project", + "agentDeleteConfirmation": "Permanently delete “{title}” and all its messages? This cannot be undone. Local project files will not be affected.", + "agentEmptyTrashConfirmation": "Permanently delete all conversations in Trash? This cannot be undone. Local project files will not be affected.", + "@agentDeleteConfirmation": { + "placeholders": { + "title": { + "type": "String" + } + } + }, + "agentConversations": "Conversations", + "showMoreConversations": "Show more", + "showFewerConversations": "Show fewer", + "agentNewConversation": "New conversation", + "agentElapsedTime": "Took {duration}", + "@agentElapsedTime": {"placeholders": {"duration": {"type": "String"}}}, + "agentConversationActions": "Conversation actions", + "agentMoveToTrash": "Move to Trash", + "agentTrash": "Trash", + "agentRestore": "Restore", + "agentEmptyTrash": "Empty Trash", + "agentDeleteForever": "Delete permanently", + "agentConversationLocation": "Conversation location", + "agentChooseExistingConversations": "Choose existing conversations", + "agentMoveConversations": "Move conversations", + "agentLocationUnavailable": "Conversation location is unavailable", + "agentLocationBusy": "Finish current conversations before moving files", + "agentRelinkProvider": "Relink provider", + "@@locale": "en", + "settings": "Settings", + "closeSettings": "Close settings", + "general": "General", + "appearance": "Appearance", + "theme": "Theme", + "system": "System default", + "light": "Light", + "dark": "Dark", + "saveAppearanceFailed": "Could not save appearance. Please try again.", + "loadAppearanceFailed": "Could not load appearance. Please select a theme again.", + "cancel": "Cancel", + "save": "Save", + "create": "Create", + "close": "Close", + "retry": "Retry", + "select": "Select", + "name": "Name", + "enterName": "Enter a name", + "invalidName": "Names cannot contain path separators or control characters", + "projects": "Projects", + "projectName": "Project name", + "projectLocation": "Project save location", + "projectLocationNotSet": "Not set", + "loadProjectLocationFailed": "Could not load the project save location.", + "saveProjectLocationFailed": "Could not save the project save location.", + "resourceLocation": "Resource storage location", + "resourceLocationNotSet": "Not set", + "loadResourceLocationFailed": "Could not load the resource storage location.", + "saveResourceLocationFailed": "Could not save the resource storage location.", + "transcriptionResourceRequired": "Generating subtitles requires downloading a speech recognition model first.", + "downloadAndContinue": "Download and continue", + "downloadingResource": "Downloading…", + "downloadInBackground": "Download in background", + "processingResourceDownloadFailed": "Could not download the speech recognition resource. Please try again.", + "newProject": "New project", + "openProject": "Open project", + "openProjectMore": "Open project…", + "saveHere": "Save here", + "selectDirectoryFailed": "Could not select a directory. Check system permissions.", + "openingWorkspace": "Opening workspace…", + "loadProjectsFailed": "Could not load projects", + "projectsEmpty": "Create or open a project to start editing.", + "backToProjects": "Back to editing", + "timelines": "Timelines", + "timelineLimitReached": "Each project can contain up to {count} timelines.", + "@timelineLimitReached": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "timelineName": "Timeline name", + "defaultTimelineName": "Timeline {index}", + "@defaultTimelineName": { + "description": "Default name assigned to a newly created timeline.", + "placeholders": { + "index": { + "type": "int" + } + } + }, + "newTimeline": "New timeline", + "noTimelines": "No timelines", + "activeTimeline": "Current timeline", + "timelineUnavailable": "Timeline unavailable", + "projectNoTimelines": "This project has no timelines yet", + "createTimelineHint": "Create a timeline in the Timelines section on the left to start editing.", + "createTimelineChat": "Create a timeline to start chatting", + "operationFailed": "Operation failed. Please try again.", + "collapseSidebar": "Collapse sidebar", + "expandSidebar": "Expand sidebar", + "expandEditor": "Expand editing area", + "collapseProperties": "Collapse properties", + "expandProperties": "Expand properties", + "layout": "Layout", + "editingFirstLayout": "Editing first", + "agentEditingLayout": "Agent + editing", + "agentLayoutDescription": "Plan, collaborate, and execute", + "editingLayoutDescription": "Preview, edit, and refine", + "materials": "Media", + "all": "All", + "video": "Video", + "audio": "Audio", + "image": "Image", + "picture": "Image", + "captions": "Captions", + "text": "Text", + "noMedia": "No media", + "mediaCategory": "Media category", + "captionTasks": "Caption tasks", + "listLayout": "List view", + "gridLayout": "Grid view", + "addToTimeline": "Add to timeline", + "rename": "Rename", + "renameMedia": "Rename media", + "removeMedia": "Remove media", + "remove": "Remove", + "revealFinder": "Show in Finder", + "revealFileManager": "Show in file manager", + "dropToAdd": "Release to add", + "timelineDropToStart": "Drag media here to get started.", + "dragMediaHint": "Drag video, audio, or images here\nOriginal files stay in their current location", + "transcribe": "Transcribe", + "generateCaptions": "Generate captions", + "play": "Play", + "pause": "Pause", + "retryPreview": "Retry preview", + "canvasRatio": "Canvas aspect ratio", + "noPreviewContent": "No content to preview on the timeline", + "nativePreviewUnsupported": "Native preview is unavailable on this platform", + "canvasTransformFailed": "Could not transform the canvas. Please try again.", + "undo": "Undo", + "redo": "Redo", + "deleteSelectedClips": "Delete selected clips", + "splitAtPlayhead": "Split at playhead", + "trimLeft": "Trim left", + "trimRight": "Trim right", + "trimLeftTooltip": "Trim away the left of the playhead, keeping the right", + "trimRightTooltip": "Trim away the right of the playhead, keeping the left", + "currentSequence": "Current sequence", + "projectProperties": "Project properties", + "canvasSize": "Canvas size", + "frameRate": "Frame rate", + "duration": "Duration", + "totalDuration": "Total duration", + "clipDuration": "Clip duration", + "seconds": "seconds", + "clip": "Clip", + "unnamedClip": "Unnamed clip", + "gap": "Gap", + "compoundClip": "Compound clip", + "textClip": "Text clip", + "pictureProperties": "Picture", + "position": "Position", + "rotation": "Rotation", + "scale": "Scale", + "size": "Size", + "transform": "Transform", + "resetPosition": "Reset position", + "keepAspectRatio": "Lock aspect ratio", + "alignment": "Alignment", + "alignLeft": "Align left", + "alignRight": "Align right", + "alignTop": "Align top", + "alignBottom": "Align bottom", + "alignHorizontalCenter": "Center horizontally", + "alignVerticalCenter": "Center vertically", + "volume": "Volume", + "gain": "Gain", + "mute": "Mute", + "unmute": "Unmute", + "resetVolume": "Reset volume", + "invalidGain": "Enter a value between -90 and +12", + "animation": "Animation", + "keyframes": "Keyframes", + "removeAllKeyframes": "Remove all keyframes", + "linear": "Linear", + "easeIn": "Ease in", + "easeOut": "Ease out", + "easeInOut": "Ease in and out", + "basic": "Basic", + "mask": "Mask", + "addMask": "Add mask", + "deleteMask": "Delete mask", + "resetMask": "Reset mask", + "enableMask": "Enable mask", + "disableMask": "Disable mask", + "moveMaskUp": "Move mask up", + "moveMaskDown": "Move mask down", + "rectangle": "Rectangle", + "ellipse": "Ellipse", + "invert": "Invert", + "feather": "Feather", + "add": "Add", + "subtract": "Subtract", + "intersect": "Intersect", + "initialRegion": "Initial region", + "none": "None", + "color": "Color", + "fontSize": "Font size", + "outlineWidth": "Outline width", + "outlineColor": "Outline color", + "captionBaseline": "Caption baseline", + "content": "Text", + "start": "Start", + "time": "Time", + "speed": "Speed", + "speedSegmentCount": "{count} speed segments", + "@speedSegmentCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "splitSpeedAtPlayhead": "Split speed at playhead", + "speedChange": "Speed", + "speedMode": "Speed mode", + "constantSpeed": "Constant speed", + "segmentedSpeed": "Segmented speed", + "speedNotAvailable": "Speed controls are not available yet", + "custom": "Custom", + "invalidNumber": "Invalid value", + "mediaUnavailable": "Media unavailable", + "mediaMissing": "Missing media", + "mediaColorSpace": "Media color space", + "mediaColorInterpretation": "Media color interpretation", + "colorInfoNotLoaded": "Color information not loaded", + "unknownColorSpace": "Unknown color space. Displaying as Rec.709.", + "colorBackendUnsupported": "The current backend does not support media color interpretation.", + "loadClipPropertiesFailed": "Could not read clip properties", + "updatePictureFailed": "Could not update picture properties", + "updateVolumeFailed": "Could not update volume", + "updateMaskFailed": "Could not update mask", + "updateKeyframesFailed": "Could not update keyframes", + "maskPreviewFailed": "Could not prepare mask preview", + "alignClipFailed": "Could not align the clip. Wait for the preview, then try again.", + "invalidTransform": "Scale must be 1%–10000%. Position and angle must be valid numbers.", + "editFailed": "Could not edit. Check the input and time range.", + "addMediaFailed": "Could not add media. Please try again.", + "deleteCaption": "Delete caption", + "mergeCaptions": "Merge captions", + "captionDeleted": "Caption deleted", + "captionChanged": "Captions have changed. Please try again.", + "captionEditChanged": "Captions have changed. Please edit again.", + "assistantHint": "Describe your editing idea", + "configureAgentHint": "Configure the agent service to start chatting", + "agentRestartHint": "Configure the agent service, then restart the app.", + "replyInterrupted": "Response interrupted", + "replying": "Responding…", + "stopReply": "Stop response", + "sendMessage": "Send message", + "addAttachment": "Add attachment (not available yet)", + "replyFailed": "Response failed. Check the connection or try again later.", + "mcpService": "MCP service", + "listenPort": "Port", + "accessToken": "Access token", + "copyAccessToken": "Copy access token", + "accessTokenCopied": "Access token copied", + "loadMcpFailed": "Could not load MCP settings. Retry", + "saveMcpFailed": "Could not save MCP settings. Please try again.", + "retryStart": "Retry starting", + "invalidPort": "Port must be between 1 and 65535", + "loadingSettings": "Loading settings…", + "starting": "Starting…", + "stopping": "Stopping…", + "disabled": "Disabled", + "running": "Running", + "startFailed": "Failed to start", + "saved": "Saved", + "unsaved": "Unsaved", + "saving": "Saving…", + "pendingSave": "Pending save", + "notApplied": "Not applied", + "enable": "Enable", + "disable": "Disable", + "type": "Type", + "status": "Status", + "file": "File", + "unboundMedia": "No media bound", + "unboundAudio": "No audio track bound", + "vertical": "Vertical", + "language": "Language", + "saveLanguageFailed": "Could not save language. Please try again.", + "loadLanguageFailed": "Could not load language. Please select again.", + "propertiesFirstLayout": "Properties first", + "defaultLayout": "Default layout", + "separateVocals": "Separate vocals", + "detachAudio": "Detach audio", + "restoreAudio": "Restore audio", + "audioDetached": "Audio detached", + "addAll": "Add all", + "preparingMedia": "Preparing media…", + "cancelling": "Cancelling…", + "cancelled": "Cancelled", + "interruptedTask": "Task interrupted. Restart to continue", + "auto": "Automatic", + "autoDetect": "Auto detect", + "noTranslation": "No translation", + "sourceLanguage": "Source language", + "translationLanguage": "Translation language", + "transcriptionNotConfigured": "Transcription is not configured. Install the recognition component and Whisper Turbo model.", + "translationNotConfigured": "Caption translation is not configured. You can generate captions in the source language.", + "sourceLanguageUnknown": "Could not determine a source language for translation.", + "startTranscriptionFailed": "Could not start transcription. Check media or wait for the current task to finish.", + "placeMediaFirst": "Place this media on the timeline before applying captions.", + "placeTranslationMediaFirst": "Place the corresponding media on the timeline before applying translated captions.", + "selectTargetClip": "Select target clip", + "timelineChanged": "The timeline has changed. Select the target clip again.", + "transcriptionAccessFailed": "Transcription failed: component, model, or source media inaccessible (notConfigured)", + "transcriptionNoAudio": "Transcription failed: no recognizable audio in the selected media or track (noAudio)", + "transcriptionInvalidResult": "Transcription failed: invalid caption file returned (invalidResult)", + "transcriptionWorkerExited": "Transcription failed: recognition component exited unexpectedly (workerExited)", + "transcriptionProcessingFailed": "Transcription failed: native processing failed (processingFailed)", + "transcriptionFailed": "Transcription failed. Check the component, model, audio track, and duration", + "transcribing": "Transcribing…", + "captionsGenerated": "Captions generated", + "cancelTranscription": "Cancel transcription", + "applyCaptions": "Apply captions", + "preparingTranslation": "Preparing translation…", + "translatingCaptions": "Translating captions…", + "cancellingTranslation": "Cancelling translation…", + "translatedCaptionsGenerated": "Translated captions generated", + "translationCancelled": "Translation cancelled", + "translationInterrupted": "Translation interrupted", + "cancelTranslation": "Cancel translation", + "editorServiceUnavailable": "Editing service unavailable. Reopen the project.", + "mcpUnavailable": "MCP connection unavailable. Check the local port and token.", + "openTimelineFailed": "Could not open the timeline", + "noTimelineSequence": "This timeline has no sequence", + "waitingForProject": "Waiting for a project to open", + "hold": "Hold", + "noImportableFiles": "No importable files received", + "virtualFilesUnsupported": "Drag original files from the file manager. Virtual files are not supported yet.", + "editorSessionStartFailed": "Could not open the timeline editor", + "previewStartFailed": "Could not start native preview", + "previewInvalidTrack": "The selected audio or video track does not exist in the media.", + "previewMissingBinding": "Media bindings are missing. Could not preview this timeline.", + "previewUnsupportedEdits": "This timeline contains edits that are not yet supported by preview.", + "previewUnsupportedConfiguration": "This preview configuration is not supported on the current platform or system version.", + "previewHdrUnsupported": "HDR media requires tone mapping for SDR preview. The current system or preview configuration does not support it.", + "previewAudioOutOfRange": "The audio clip exceeds the source track range and cannot be previewed.", + "previewResourceMissing": "Preview media no longer exists. Locate the original file again.", + "previewInvalidComposition": "Invalid video composition configuration. Could not create preview.", + "previewInvalidData": "Invalid preview data. Please try again.", + "previewFailed": "Preview failed. Check media access and try again.", + "chatFailed": "Could not complete the conversation. Check the service configuration or try again later.", + "delete": "Delete", + "pinTimeline": "Pin timeline", + "unpinTimeline": "Unpin timeline", + "deleteTimelineConfirmation": "Delete “{name}” and its edit history? This cannot be undone.", + "@deleteTimelineConfirmation": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "processingFailed": "Processing failed", + "noMatchingOptions": "No matching options", + "removeMediaConfirmation": "Remove “{name}” from the project? Existing clips, history, and the original file will be kept.", + "@removeMediaConfirmation": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "mediaAdded": "Added {count} media references", + "@mediaAdded": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "duplicatesSkipped": "Skipped {count} duplicate files", + "@duplicatesSkipped": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mediaCount": "{count} media items", + "@mediaCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "importMedia": "Import", + "noMediaOfType": "No {type} media", + "@noMediaOfType": { + "placeholders": { + "type": { + "type": "String" + } + } + }, + "captionsImported": "Imported {count} captions", + "@captionsImported": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "editCaptionError": "Could not edit captions: {message}", + "@editCaptionError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "mcpStartError": "Could not start MCP: {message}", + "@mcpStartError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "manualColorSpace": "Manually selected: {name}", + "@manualColorSpace": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "detectedColorSpace": "Detected: {name}", + "@detectedColorSpace": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "keyframeLabel": "{channel} keyframe", + "@keyframeLabel": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "maskMode": "Combination mode: {mode}", + "@maskMode": { + "placeholders": { + "mode": { + "type": "String" + } + } + }, + "keyframeCount": "{count} keyframes", + "@keyframeCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "toggleKeyframe": "{action} {channel} keyframe", + "@toggleKeyframe": { + "placeholders": { + "action": { + "type": "String" + }, + "channel": { + "type": "String" + } + } + }, + "previousKeyframe": "Previous {channel} keyframe", + "@previousKeyframe": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "nextKeyframe": "Next {channel} keyframe", + "@nextKeyframe": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "keyframeSettings": "{channel} keyframe settings", + "@keyframeSettings": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "selectedClipsHint": "{count} clips selected\nSelect one clip to view its properties", + "@selectedClipsHint": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "transcriptionError": "Transcription failed. Check the component, model, audio track, and duration ({code})", + "@transcriptionError": { + "placeholders": { + "code": { + "type": "String" + } + } + }, + "captionsAdded": "Added {count} captions. Edit them in the properties panel.", + "@captionsAdded": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "translatedCaptionsAdded": "Added {count} translated captions. Edit them in the properties panel.", + "@translatedCaptionsAdded": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "applyCaptionsError": "Could not apply captions: {message}", + "@applyCaptionsError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "applyTranslatedCaptionsError": "Could not apply translated captions: {message}", + "@applyTranslatedCaptionsError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "recognizedCaptions": "Recognized {count} captions", + "@recognizedCaptions": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "captionCount": "{count} captions", + "@captionCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "translationFailed": "Translation failed: {message}", + "@translationFailed": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "translatedCaptionCount": "{count} {language} captions", + "@translatedCaptionCount": { + "placeholders": { + "count": { + "type": "int" + }, + "language": { + "type": "String" + } + } + }, + "previewParameterError": "Invalid preview parameters: {message}", + "@previewParameterError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "mediaOffline": "Media offline or unavailable: {names}", + "@mediaOffline": { + "placeholders": { + "names": { + "type": "String" + } + } + }, + "searchOptions": "Search {label}…", + "@searchOptions": { + "placeholders": { + "label": { + "type": "String" + } + } + }, + "loadRecentProjectsFailed": "Could not load recent projects. You can still open a project manually.", + "projectAccessFailed": "Project unavailable", + "projectMissingDirectory": "Project not found", + "recentProjectSaveFailed": "Project opened, but the recent project record could not be saved.", + "lastProjectSaveFailed": "Project opened, but the last project record could not be saved.", + "enterProjectName": "Enter a project name", + "projectSwitched": "The project has changed. Drag the media in again.", + "notLocalMedia": "This media is not a local file", + "revealMediaFailed": "Could not show media in the file manager", + "openMatchingProject": "Open the corresponding project first", + "projectMismatch": "The project at this location does not match the record. Select it again with Open project.", + "openProjectFirst": "Open a project first", + "localFilesOnly": "Drag local files from the file manager", + "foldersUnsupported": "Select files. Dragging folders is not supported yet.", + "mediaImportCancelled": "Media import cancelled", + "fileAccessFailed": "The file is missing or unreadable. Check its location and permissions", + "registerMediaFailed": "Could not register media. Please try again", + "mediaNoLongerExists": "Media no longer exists", + "mediaNoTracks": "Media has no usable video or audio tracks", + "invalidMediaDuration": "Invalid media duration", + "mediaInfoUnsupported": "Reading media information is not supported on this platform yet", + "mediaInfoFailed": "Could not read media information. Check the file and access permissions", + "saveTimelineFailed": "Could not save the timeline. Try again. Unsaved edits remain in this session.", + "addKeyframeAction": "Add", + "backgroundTasks": "Background tasks", + "noBackgroundTasks": "No background tasks", + "retryTask": "Retry", + "applyOriginalCaptions": "Apply original captions", + "applyTranslatedCaptions": "Apply translated captions", + "subtitleTaskStarted": "Subtitle task started", + "fitTimeline": "Fit entire timeline", + "modify": "Modify", + "projectSettings": "Project settings", + "projectSettingsDescription": "Change project output settings while keeping clip timing and speed.", + "projectColorSpace": "Color space", + "projectWidth": "Width (px)", + "projectHeight": "Height (px)", + "projectResolutionInvalid": "Enter a whole number from 1 to 16384", + "previewFullscreen": "Fullscreen preview", + "exitPreviewFullscreen": "Exit fullscreen", + "previewGoToStart": "Go to start", + "previewPreviousFrame": "Previous frame", + "previewNextFrame": "Next frame", + "softwareUpdates": "Software updates", + "checkForUpdates": "Check for updates", + "automaticallyCheckUpdates": "Automatically check for updates", + "updatesUnavailable": "Updates are unavailable in this build.", + "updateCheckFailed": "Could not check for updates. Please try again.", + "removeBackground": "Remove background", + "startBackgroundRemoval": "Remove background", + "backgroundRemovalResourceRequired": "Background removal needs a local model. It starts automatically after download.", + "backgroundRemovalDownloadTask": "Download background removal resource", + "backgroundRemovalResourceName": "Background removal model", + "backgroundRemovalDestructiveHint": "The generated transparent media will replace this clip. You can still use Undo to restore the original clip.", + "backgroundRemovalTaskStarted": "Background removal started", + "startBackgroundRemovalFailed": "Could not start background removal. Check the media or wait for the current processing task.", + "backgroundRemovalComplete": "Background removal complete", + "backgroundRemovalApplying": "Replacing clip media", + "backgroundRemovalFailed": "Background removal failed", + "agentSettings": "Agent", + "agentSaveSettingsFailed": "Could not save Agent settings.", + "agentDeleteProviderTitle": "Delete provider?", + "agentDeleteProviderDescription": "“{providerName}” and its saved API key will be removed from this device.", + "@agentDeleteProviderDescription": { + "placeholders": { + "providerName": { + "type": "String" + } + } + }, + "agentProviderRequired": "Add a provider before enabling the assistant.", + "agentUseSelectedModel": "Use the selected model for new Agent requests.", + "agentEnable": "Enable Agent", + "agentDefaultModel": "Default model", + "agentConfigureModel": "Configure models", + "agentSelectModel": "Select model", + "agentModelUnavailable": "The model for this conversation is unavailable. Select another model to start a new conversation.", + "agentModelChangeSession": "Changing the model starts a new Agent session.", + "agentCustomProviders": "Custom providers", + "agentProviderStorageDescription": "Provider metadata is stored locally. API keys are kept in the system credential store.", + "agentAddProvider": "Add provider", + "agentBackToProviders": "Back to providers", + "agentLoadSettingsFailed": "Could not load Agent settings. Retry", + "agentEnableProvider": "Enable provider", + "agentEditProvider": "Edit provider", + "agentDeleteProvider": "Delete provider", + "agentModelIdsUnique": "Model IDs must be unique.", + "agentEditProviderTitle": "Edit provider", + "agentProviderEndpointDescription": "Configure an OpenAI-compatible Chat Completions endpoint.", + "agentSaveProvider": "Save provider", + "agentProviderConfiguration": "Provider configuration", + "agentAuthenticationAndModels": "Authentication & models", + "agentApiType": "API type", + "agentOpenAiChatCompletions": "OpenAI Completions", + "agentBaseUrl": "Base URL", + "agentApiKey": "API key", + "agentProviderNameHint": "My provider", + "agentApiKeyOptional": "Optional for endpoints that do not require authentication.", + "agentApiKeyKeep": "Leave blank to keep the saved key.", + "agentOptional": "Optional", + "agentApiKeyOneLine": "The API key must be one line.", + "agentRemoveSavedApiKey": "Remove saved API key", + "agentModels": "Models", + "agentAddModel": "Add model", + "agentRequiredField": "This field is required.", + "agentInvalidBaseUrl": "Enter an HTTP(S) base URL without credentials, query, or fragment.", + "agentModelId": "Model ID", + "agentContextWindow": "Context window", + "agentMaxOutputTokens": "Max output", + "agentMaxOutputBelowContext": "Must be below context.", + "agentDeleteModel": "Delete model", + "agentPositiveInteger": "Use a positive integer.", + "agentConfigurationReadFailed": "Could not read the Agent configuration. Check settings and try again.", + "agentConfigurationRequired": "Configure and enable Agent in Settings first.", + "agentSessionRestoreFailed": "Could not restore the Agent session. Try again later.", + "agentContextBudgetExceeded": "Input budget is too small for the system instructions, tools and message. Increase the context window or reduce maximum output tokens.", + "agentAuthenticationFailed": "Authentication failed. Check the Provider API key and permissions.", + "agentConnectionFailed": "Could not connect to the model service, or the request timed out. Check the Base URL and network.", + "agentProtocolFailed": "The service response does not match the selected API type, or the response stream is incomplete.", + "agentContextBudgetTooSmall": "Reserve more input space for system instructions. Increase the context window or reduce maximum output tokens.", + "agentCompacting": "Organizing context…", + "agentEditing": "Editing…", + "agentVerifying": "Checking results…", + "agentTurnLimitReached": "This task reached its execution limit. Edits have been saved. Send “Continue” to resume.", + "agentRecoveryRequired": "The previous operation is unconfirmed. Continue to check saved receipts; unconfirmed edits will not be repeated.", + "agentExportReplyFailed": "Video exported successfully. The summary reply failed. Retry the summary without repeating edits or export.", + "agentRetrySummary": "Retry summary", + "agentResumeTask": "Continue task", + "agentTaskInterrupted": "This task was interrupted. Continue from its saved progress.", + "downloadSubtitleModel": "Download subtitle model", + "downloadModelAction": "Download", + "subtitleEngineUnavailable": "The model is installed, but the subtitle engine could not start. Repair the processing engine; the model does not need to be downloaded again.", + "backgroundTaskDetails": "Task details", + "backgroundTaskFailed": "Failed", + "backgroundTaskCompleted": "Completed", + "captionWrapLines": "Wrap subtitle text", + "captionSingleLine": "Show subtitles on one line", + "noMatchingCaptions": "No matching subtitles", + "subtitleResourcesRequired": "These resources are needed for subtitles. Generation starts automatically after download.", + "subtitleResourcesDownloadSize": "To download: {size}", + "pauseDownload": "Pause", + "resumeDownload": "Resume", + "downloadPaused": "Paused", + "@subtitleResourcesDownloadSize": { + "placeholders": {"size": {"type": "String"}} + }, + "cancelResourceDownloadTitle": "Cancel download?", + "cancelResourceDownloadMessage": "The download will stop. Progress on the current resource may be lost.", + "continueDownload": "Continue downloading", + "cancelDownload": "Cancel download", + "speechResourceStage": "Speech recognition resource", + "translationResourceStage": "Translation resource", + "subtitleResourceDownloadTask": "Download speech and translation resources", + "downloadingSpeechModel": "Downloading speech model", + "downloadingTranslationModel": "Downloading translation model", + "checkingForUpdates": "Checking for updates…", + "appIsUpToDate": "You are up to date.", + "downloadingUpdate": "Downloading update: {progress}%", + "updateAvailable": "Version {version} is available.", + "downloadUpdate": "Download update", + "restartToUpdate": "Restart to update", + "updateOperationFailed": "Could not update. Finish active tasks and try again.", + "@downloadingUpdate": { + "placeholders": { + "progress": { + "type": "int" + } + } + }, + "@updateAvailable": { + "placeholders": { + "version": { + "type": "String" + } + } + }, + "windowMinimize": "Minimize", + "windowMaximize": "Maximize", + "windowRestore": "Restore", + "workspaceAgent": "Agent", + "workspaceCut": "Cut", + "noAvailableOptions": "No options available", + "composerReferenceInvalid": "A reference is no longer valid. Return to its project or remove it.", + "durationSeconds": "{seconds}s", + "durationMinutesSeconds": "{minutes}m {seconds}s", + "projectNameInvalid": "Invalid project name", + "projectLocationDefaultUnavailable": "Could not access the default project location. Select it again in Settings.", + "chooseProjectLocation": "Select a project save location in Settings first.", + "untitledTimeline": "Untitled timeline", + "primarySequence": "Main sequence", + "primaryStoryline": "Main storyline", + "projectSessionClosed": "The project session has closed. Reopen the project.", + "timelineSessionClosed": "The timeline session has closed. Reopen the timeline.", + "timelineMissing": "The timeline does not exist or has been deleted.", + "timelineInUse": "The timeline is in use and cannot be deleted yet.", + "timelineHasBackgroundTasks": "Finish the timeline’s background tasks before deleting it.", + "timelineRequired": "A project must keep at least one timeline.", + "mediaReadFailed": "Could not read media", + "mediaImportFailed": "Could not import media", + "unsupportedMediaType": "Only video, audio, and image files can be imported.", + "mediaNoVideoTracks": "Media has no usable video track", + "mediaDurationOutOfRange": "Media duration exceeds the timeline range", + "resourceDownloadHttpFailed": "Download failed (HTTP {statusCode})", + "resourceChecksumFailed": "Model file verification failed. Download the resource again.", + "subtitleLanguageAf": "Afrikaans", + "subtitleLanguageAm": "Amharic", + "subtitleLanguageAr": "Arabic", + "subtitleLanguageAst": "Asturian", + "subtitleLanguageAz": "Azerbaijani", + "subtitleLanguageBa": "Bashkir", + "subtitleLanguageBe": "Belarusian", + "subtitleLanguageBg": "Bulgarian", + "subtitleLanguageBn": "Bangla", + "subtitleLanguageBr": "Breton", + "subtitleLanguageBs": "Bosnian", + "subtitleLanguageCa": "Catalan", + "subtitleLanguageCeb": "Cebuano", + "subtitleLanguageCs": "Czech", + "subtitleLanguageCy": "Welsh", + "subtitleLanguageDa": "Danish", + "subtitleLanguageDe": "German", + "subtitleLanguageEl": "Greek", + "subtitleLanguageEn": "English", + "subtitleLanguageEs": "Spanish", + "subtitleLanguageEt": "Estonian", + "subtitleLanguageFa": "Persian", + "subtitleLanguageFf": "Fula", + "subtitleLanguageFi": "Finnish", + "subtitleLanguageFr": "French", + "subtitleLanguageFy": "Western Frisian", + "subtitleLanguageGa": "Irish", + "subtitleLanguageGd": "Scottish Gaelic", + "subtitleLanguageGl": "Galician", + "subtitleLanguageGu": "Gujarati", + "subtitleLanguageHa": "Hausa", + "subtitleLanguageHe": "Hebrew", + "subtitleLanguageHi": "Hindi", + "subtitleLanguageHr": "Croatian", + "subtitleLanguageHt": "Haitian Creole", + "subtitleLanguageHu": "Hungarian", + "subtitleLanguageHy": "Armenian", + "subtitleLanguageId": "Indonesian", + "subtitleLanguageIg": "Igbo", + "subtitleLanguageIlo": "Iloko", + "subtitleLanguageIs": "Icelandic", + "subtitleLanguageIt": "Italian", + "subtitleLanguageJa": "Japanese", + "subtitleLanguageJv": "Javanese", + "subtitleLanguageKa": "Georgian", + "subtitleLanguageKk": "Kazakh", + "subtitleLanguageKm": "Khmer", + "subtitleLanguageKn": "Kannada", + "subtitleLanguageKo": "Korean", + "subtitleLanguageLb": "Luxembourgish", + "subtitleLanguageLg": "Ganda", + "subtitleLanguageLn": "Lingala", + "subtitleLanguageLo": "Lao", + "subtitleLanguageLt": "Lithuanian", + "subtitleLanguageLv": "Latvian", + "subtitleLanguageMg": "Malagasy", + "subtitleLanguageMk": "Macedonian", + "subtitleLanguageMl": "Malayalam", + "subtitleLanguageMn": "Mongolian", + "subtitleLanguageMr": "Marathi", + "subtitleLanguageMs": "Malay", + "subtitleLanguageMy": "Burmese", + "subtitleLanguageNe": "Nepali", + "subtitleLanguageNl": "Dutch", + "subtitleLanguageNo": "Norwegian", + "subtitleLanguageNs": "Northern Sotho", + "subtitleLanguageOc": "Occitan", + "subtitleLanguageOr": "Odia", + "subtitleLanguagePa": "Punjabi", + "subtitleLanguagePl": "Polish", + "subtitleLanguagePs": "Pashto", + "subtitleLanguagePt": "Portuguese", + "subtitleLanguageRo": "Romanian", + "subtitleLanguageRu": "Russian", + "subtitleLanguageSd": "Sindhi", + "subtitleLanguageSi": "Sinhala", + "subtitleLanguageSk": "Slovak", + "subtitleLanguageSl": "Slovenian", + "subtitleLanguageSo": "Somali", + "subtitleLanguageSq": "Albanian", + "subtitleLanguageSr": "Serbian", + "subtitleLanguageSs": "Swati", + "subtitleLanguageSu": "Sundanese", + "subtitleLanguageSv": "Swedish", + "subtitleLanguageSw": "Swahili", + "subtitleLanguageTa": "Tamil", + "subtitleLanguageTh": "Thai", + "subtitleLanguageTl": "Tagalog", + "subtitleLanguageTn": "Tswana", + "subtitleLanguageTr": "Turkish", + "subtitleLanguageUk": "Ukrainian", + "subtitleLanguageUr": "Urdu", + "subtitleLanguageUz": "Uzbek", + "subtitleLanguageVi": "Vietnamese", + "subtitleLanguageWo": "Wolof", + "subtitleLanguageXh": "Xhosa", + "subtitleLanguageYi": "Yiddish", + "subtitleLanguageYo": "Yoruba", + "subtitleLanguageYue": "Cantonese", + "subtitleLanguageZh": "Chinese", + "subtitleLanguageZu": "Zulu", + "@workspaceAgent": { + "description": "Localized workspaceAgent shown in the Cutdex interface." + }, + "@workspaceCut": { + "description": "Localized workspaceCut shown in the Cutdex interface." + }, + "@noAvailableOptions": { + "description": "Localized noAvailableOptions shown in the Cutdex interface." + }, + "@composerReferenceInvalid": { + "description": "Localized composerReferenceInvalid shown in the Cutdex interface." + }, + "@durationSeconds": { + "description": "Localized durationSeconds shown in the Cutdex interface.", + "placeholders": { + "seconds": { + "type": "int" + } + } + }, + "@durationMinutesSeconds": { + "description": "Localized durationMinutesSeconds shown in the Cutdex interface.", + "placeholders": { + "minutes": { + "type": "int" + }, + "seconds": { + "type": "int" + } + } + }, + "@projectNameInvalid": { + "description": "Localized projectNameInvalid shown in the Cutdex interface." + }, + "@projectLocationDefaultUnavailable": { + "description": "Localized projectLocationDefaultUnavailable shown in the Cutdex interface." + }, + "@chooseProjectLocation": { + "description": "Localized chooseProjectLocation shown in the Cutdex interface." + }, + "@untitledTimeline": { + "description": "Localized untitledTimeline shown in the Cutdex interface." + }, + "@primarySequence": { + "description": "Localized primarySequence shown in the Cutdex interface." + }, + "@primaryStoryline": { + "description": "Localized primaryStoryline shown in the Cutdex interface." + }, + "@projectSessionClosed": { + "description": "Localized projectSessionClosed shown in the Cutdex interface." + }, + "@timelineSessionClosed": { + "description": "Localized timelineSessionClosed shown in the Cutdex interface." + }, + "@timelineMissing": { + "description": "Localized timelineMissing shown in the Cutdex interface." + }, + "@timelineInUse": { + "description": "Localized timelineInUse shown in the Cutdex interface." + }, + "@timelineHasBackgroundTasks": { + "description": "Localized timelineHasBackgroundTasks shown in the Cutdex interface." + }, + "@timelineRequired": { + "description": "Localized timelineRequired shown in the Cutdex interface." + }, + "@mediaReadFailed": { + "description": "Localized mediaReadFailed shown in the Cutdex interface." + }, + "@mediaImportFailed": { + "description": "Localized mediaImportFailed shown in the Cutdex interface." + }, + "@unsupportedMediaType": { + "description": "Localized unsupportedMediaType shown in the Cutdex interface." + }, + "@mediaNoVideoTracks": { + "description": "Localized mediaNoVideoTracks shown in the Cutdex interface." + }, + "@mediaDurationOutOfRange": { + "description": "Localized mediaDurationOutOfRange shown in the Cutdex interface." + }, + "@resourceDownloadHttpFailed": { + "description": "Localized resourceDownloadHttpFailed shown in the Cutdex interface.", + "placeholders": { + "statusCode": { + "type": "String" + } + } + }, + "@resourceChecksumFailed": { + "description": "Localized resourceChecksumFailed shown in the Cutdex interface." + }, + "@subtitleLanguageAf": { + "description": "Display name of subtitle language af (Unicode locale data)." + }, + "@subtitleLanguageAm": { + "description": "Display name of subtitle language am (Unicode locale data)." + }, + "@subtitleLanguageAr": { + "description": "Display name of subtitle language ar (Unicode locale data)." + }, + "@subtitleLanguageAst": { + "description": "Display name of subtitle language ast (Unicode locale data)." + }, + "@subtitleLanguageAz": { + "description": "Display name of subtitle language az (Unicode locale data)." + }, + "@subtitleLanguageBa": { + "description": "Display name of subtitle language ba (Unicode locale data)." + }, + "@subtitleLanguageBe": { + "description": "Display name of subtitle language be (Unicode locale data)." + }, + "@subtitleLanguageBg": { + "description": "Display name of subtitle language bg (Unicode locale data)." + }, + "@subtitleLanguageBn": { + "description": "Display name of subtitle language bn (Unicode locale data)." + }, + "@subtitleLanguageBr": { + "description": "Display name of subtitle language br (Unicode locale data)." + }, + "@subtitleLanguageBs": { + "description": "Display name of subtitle language bs (Unicode locale data)." + }, + "@subtitleLanguageCa": { + "description": "Display name of subtitle language ca (Unicode locale data)." + }, + "@subtitleLanguageCeb": { + "description": "Display name of subtitle language ceb (Unicode locale data)." + }, + "@subtitleLanguageCs": { + "description": "Display name of subtitle language cs (Unicode locale data)." + }, + "@subtitleLanguageCy": { + "description": "Display name of subtitle language cy (Unicode locale data)." + }, + "@subtitleLanguageDa": { + "description": "Display name of subtitle language da (Unicode locale data)." + }, + "@subtitleLanguageDe": { + "description": "Display name of subtitle language de (Unicode locale data)." + }, + "@subtitleLanguageEl": { + "description": "Display name of subtitle language el (Unicode locale data)." + }, + "@subtitleLanguageEn": { + "description": "Display name of subtitle language en (Unicode locale data)." + }, + "@subtitleLanguageEs": { + "description": "Display name of subtitle language es (Unicode locale data)." + }, + "@subtitleLanguageEt": { + "description": "Display name of subtitle language et (Unicode locale data)." + }, + "@subtitleLanguageFa": { + "description": "Display name of subtitle language fa (Unicode locale data)." + }, + "@subtitleLanguageFf": { + "description": "Display name of subtitle language ff (Unicode locale data)." + }, + "@subtitleLanguageFi": { + "description": "Display name of subtitle language fi (Unicode locale data)." + }, + "@subtitleLanguageFr": { + "description": "Display name of subtitle language fr (Unicode locale data)." + }, + "@subtitleLanguageFy": { + "description": "Display name of subtitle language fy (Unicode locale data)." + }, + "@subtitleLanguageGa": { + "description": "Display name of subtitle language ga (Unicode locale data)." + }, + "@subtitleLanguageGd": { + "description": "Display name of subtitle language gd (Unicode locale data)." + }, + "@subtitleLanguageGl": { + "description": "Display name of subtitle language gl (Unicode locale data)." + }, + "@subtitleLanguageGu": { + "description": "Display name of subtitle language gu (Unicode locale data)." + }, + "@subtitleLanguageHa": { + "description": "Display name of subtitle language ha (Unicode locale data)." + }, + "@subtitleLanguageHe": { + "description": "Display name of subtitle language he (Unicode locale data)." + }, + "@subtitleLanguageHi": { + "description": "Display name of subtitle language hi (Unicode locale data)." + }, + "@subtitleLanguageHr": { + "description": "Display name of subtitle language hr (Unicode locale data)." + }, + "@subtitleLanguageHt": { + "description": "Display name of subtitle language ht (Unicode locale data)." + }, + "@subtitleLanguageHu": { + "description": "Display name of subtitle language hu (Unicode locale data)." + }, + "@subtitleLanguageHy": { + "description": "Display name of subtitle language hy (Unicode locale data)." + }, + "@subtitleLanguageId": { + "description": "Display name of subtitle language id (Unicode locale data)." + }, + "@subtitleLanguageIg": { + "description": "Display name of subtitle language ig (Unicode locale data)." + }, + "@subtitleLanguageIlo": { + "description": "Display name of subtitle language ilo (Unicode locale data)." + }, + "@subtitleLanguageIs": { + "description": "Display name of subtitle language is (Unicode locale data)." + }, + "@subtitleLanguageIt": { + "description": "Display name of subtitle language it (Unicode locale data)." + }, + "@subtitleLanguageJa": { + "description": "Display name of subtitle language ja (Unicode locale data)." + }, + "@subtitleLanguageJv": { + "description": "Display name of subtitle language jv (Unicode locale data)." + }, + "@subtitleLanguageKa": { + "description": "Display name of subtitle language ka (Unicode locale data)." + }, + "@subtitleLanguageKk": { + "description": "Display name of subtitle language kk (Unicode locale data)." + }, + "@subtitleLanguageKm": { + "description": "Display name of subtitle language km (Unicode locale data)." + }, + "@subtitleLanguageKn": { + "description": "Display name of subtitle language kn (Unicode locale data)." + }, + "@subtitleLanguageKo": { + "description": "Display name of subtitle language ko (Unicode locale data)." + }, + "@subtitleLanguageLb": { + "description": "Display name of subtitle language lb (Unicode locale data)." + }, + "@subtitleLanguageLg": { + "description": "Display name of subtitle language lg (Unicode locale data)." + }, + "@subtitleLanguageLn": { + "description": "Display name of subtitle language ln (Unicode locale data)." + }, + "@subtitleLanguageLo": { + "description": "Display name of subtitle language lo (Unicode locale data)." + }, + "@subtitleLanguageLt": { + "description": "Display name of subtitle language lt (Unicode locale data)." + }, + "@subtitleLanguageLv": { + "description": "Display name of subtitle language lv (Unicode locale data)." + }, + "@subtitleLanguageMg": { + "description": "Display name of subtitle language mg (Unicode locale data)." + }, + "@subtitleLanguageMk": { + "description": "Display name of subtitle language mk (Unicode locale data)." + }, + "@subtitleLanguageMl": { + "description": "Display name of subtitle language ml (Unicode locale data)." + }, + "@subtitleLanguageMn": { + "description": "Display name of subtitle language mn (Unicode locale data)." + }, + "@subtitleLanguageMr": { + "description": "Display name of subtitle language mr (Unicode locale data)." + }, + "@subtitleLanguageMs": { + "description": "Display name of subtitle language ms (Unicode locale data)." + }, + "@subtitleLanguageMy": { + "description": "Display name of subtitle language my (Unicode locale data)." + }, + "@subtitleLanguageNe": { + "description": "Display name of subtitle language ne (Unicode locale data)." + }, + "@subtitleLanguageNl": { + "description": "Display name of subtitle language nl (Unicode locale data)." + }, + "@subtitleLanguageNo": { + "description": "Display name of subtitle language no (Unicode locale data)." + }, + "@subtitleLanguageNs": { + "description": "Display name of subtitle language ns (Unicode locale data)." + }, + "@subtitleLanguageOc": { + "description": "Display name of subtitle language oc (Unicode locale data)." + }, + "@subtitleLanguageOr": { + "description": "Display name of subtitle language or (Unicode locale data)." + }, + "@subtitleLanguagePa": { + "description": "Display name of subtitle language pa (Unicode locale data)." + }, + "@subtitleLanguagePl": { + "description": "Display name of subtitle language pl (Unicode locale data)." + }, + "@subtitleLanguagePs": { + "description": "Display name of subtitle language ps (Unicode locale data)." + }, + "@subtitleLanguagePt": { + "description": "Display name of subtitle language pt (Unicode locale data)." + }, + "@subtitleLanguageRo": { + "description": "Display name of subtitle language ro (Unicode locale data)." + }, + "@subtitleLanguageRu": { + "description": "Display name of subtitle language ru (Unicode locale data)." + }, + "@subtitleLanguageSd": { + "description": "Display name of subtitle language sd (Unicode locale data)." + }, + "@subtitleLanguageSi": { + "description": "Display name of subtitle language si (Unicode locale data)." + }, + "@subtitleLanguageSk": { + "description": "Display name of subtitle language sk (Unicode locale data)." + }, + "@subtitleLanguageSl": { + "description": "Display name of subtitle language sl (Unicode locale data)." + }, + "@subtitleLanguageSo": { + "description": "Display name of subtitle language so (Unicode locale data)." + }, + "@subtitleLanguageSq": { + "description": "Display name of subtitle language sq (Unicode locale data)." + }, + "@subtitleLanguageSr": { + "description": "Display name of subtitle language sr (Unicode locale data)." + }, + "@subtitleLanguageSs": { + "description": "Display name of subtitle language ss (Unicode locale data)." + }, + "@subtitleLanguageSu": { + "description": "Display name of subtitle language su (Unicode locale data)." + }, + "@subtitleLanguageSv": { + "description": "Display name of subtitle language sv (Unicode locale data)." + }, + "@subtitleLanguageSw": { + "description": "Display name of subtitle language sw (Unicode locale data)." + }, + "@subtitleLanguageTa": { + "description": "Display name of subtitle language ta (Unicode locale data)." + }, + "@subtitleLanguageTh": { + "description": "Display name of subtitle language th (Unicode locale data)." + }, + "@subtitleLanguageTl": { + "description": "Display name of subtitle language tl (Unicode locale data)." + }, + "@subtitleLanguageTn": { + "description": "Display name of subtitle language tn (Unicode locale data)." + }, + "@subtitleLanguageTr": { + "description": "Display name of subtitle language tr (Unicode locale data)." + }, + "@subtitleLanguageUk": { + "description": "Display name of subtitle language uk (Unicode locale data)." + }, + "@subtitleLanguageUr": { + "description": "Display name of subtitle language ur (Unicode locale data)." + }, + "@subtitleLanguageUz": { + "description": "Display name of subtitle language uz (Unicode locale data)." + }, + "@subtitleLanguageVi": { + "description": "Display name of subtitle language vi (Unicode locale data)." + }, + "@subtitleLanguageWo": { + "description": "Display name of subtitle language wo (Unicode locale data)." + }, + "@subtitleLanguageXh": { + "description": "Display name of subtitle language xh (Unicode locale data)." + }, + "@subtitleLanguageYi": { + "description": "Display name of subtitle language yi (Unicode locale data)." + }, + "@subtitleLanguageYo": { + "description": "Display name of subtitle language yo (Unicode locale data)." + }, + "@subtitleLanguageYue": { + "description": "Display name of subtitle language yue (Unicode locale data)." + }, + "@subtitleLanguageZh": { + "description": "Display name of subtitle language zh (Unicode locale data)." + }, + "@subtitleLanguageZu": { + "description": "Display name of subtitle language zu (Unicode locale data)." + }, + "linearRec2020": "Linear Rec.2020", + "@linearRec2020": { + "description": "Linear-light Rec.2020 color interpretation. Keep Rec.2020 unchanged." + }, + "diagnostics": "Diagnostics", + "exportDiagnostics": "Export diagnostic package", + "exportDiagnosticsFailed": "Could not export diagnostics. Please try again.", + "exportDiagnosticsSucceeded": "Diagnostic package saved." +} diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb new file mode 100644 index 0000000..559f15f --- /dev/null +++ b/lib/l10n/app_es.arb @@ -0,0 +1,889 @@ +{ + "projectsNone": "No hay proyectos", + "agentConversations": "Conversaciones", + "renameConversationTitle": "Renombrar chat", + "renameConversationDescription": "Usa un nombre breve y fácil de reconocer.", + "showMoreConversations": "Mostrar más", + "showFewerConversations": "Mostrar menos", + "agentNewConversation": "Nueva conversación", + "agentElapsedTime": "Duración {duration}", + "agentConversationActions": "Acciones de conversación", + "agentMoveToTrash": "Mover a la papelera", + "agentTrash": "Papelera", + "agentRestore": "Restaurar", + "agentEmptyTrash": "Vaciar papelera", + "agentDeleteForever": "Eliminar permanentemente", + "agentConversationLocation": "Ubicación de conversaciones", + "agentChooseExistingConversations": "Elegir conversaciones existentes", + "agentMoveConversations": "Mover conversaciones", + "agentLocationUnavailable": "La ubicación de conversaciones no está disponible", + "agentLocationBusy": "Espera a que terminen las conversaciones activas", + "agentRelinkProvider": "Volver a vincular proveedor", + "@@locale": "es", + "settings": "Ajustes", + "closeSettings": "Cerrar configuración", + "general": "General", + "appearance": "Apariencia", + "theme": "Tema", + "system": "Seguir el sistema", + "light": "Claro", + "dark": "Oscuro", + "saveAppearanceFailed": "No se pudo salvar la apariencia. Por favor inténtalo de nuevo.", + "loadAppearanceFailed": "No se pudo cargar la apariencia. Por favor seleccione un tema nuevamente.", + "cancel": "Cancelar", + "save": "Guardar", + "create": "Crear", + "close": "Cerrar", + "retry": "Reintentar", + "name": "Nombre", + "enterName": "Introduce un nombre", + "invalidName": "Los nombres no pueden contener separadores de ruta ni caracteres de control.", + "projectName": "Nombre del proyecto", + "newProject": "Nuevo proyecto", + "openProject": "Abrir proyecto", + "openProjectMore": "Abrir otro proyecto", + "projects": "Proyectos", + "projectsEmpty": "No hay proyectos", + "openingWorkspace": "Abriendo el espacio de trabajo…", + "loadProjectsFailed": "No se pudieron cargar los proyectos", + "backToProjects": "Volver a la edición", + "timelines": "Líneas de tiempo", + "timelineLimitReached": "Cada proyecto puede contener hasta {count} líneas de tiempo.", + "timelineName": "Nombre de la línea de tiempo", + "defaultTimelineName": "Línea de tiempo {index}", + "newTimeline": "Nueva línea de tiempo", + "noTimelines": "No hay líneas de tiempo", + "activeTimeline": "Línea de tiempo actual", + "timelineUnavailable": "Línea de tiempo no disponible", + "projectNoTimelines": "Este proyecto aún no tiene líneas de tiempo", + "createTimelineHint": "Crea una línea de tiempo en la sección «Líneas de tiempo» de la izquierda para empezar a editar.", + "createTimelineChat": "Crea una línea de tiempo para iniciar el chat", + "editingFirstLayout": "Edición prioritaria", + "agentEditingLayout": "Agente y edición", + "agentLayoutDescription": "Planificar, colaborar y ejecutar", + "editingLayoutDescription": "Previsualizar, editar y ajustar", + "saveHere": "Guardar aquí", + "selectDirectoryFailed": "No se pudo seleccionar un directorio. Verifique los permisos del sistema.", + "operationFailed": "La operación falló. Por favor inténtalo de nuevo.", + "collapseSidebar": "Contraer barra lateral", + "expandSidebar": "Expandir barra lateral", + "expandEditor": "Expandir área de edición", + "collapseProperties": "Contraer propiedades", + "expandProperties": "Expandir propiedades", + "layout": "Diseño", + "materials": "Medios", + "all": "Todos", + "video": "Video", + "audio": "Audio", + "image": "Imagen", + "picture": "Imagen", + "captions": "Subtítulos", + "text": "Texto", + "noMedia": "Sin medios", + "mediaCategory": "Categoría de medios", + "captionTasks": "Tareas de subtítulos", + "listLayout": "Vista de lista", + "gridLayout": "Vista de cuadrícula", + "addToTimeline": "Añadir a la línea de tiempo", + "rename": "Cambiar nombre", + "renameMedia": "Cambiar nombre del medio", + "removeMedia": "Quitar medio", + "remove": "Quitar", + "revealFinder": "Mostrar en Finder", + "revealFileManager": "Mostrar en el gestor de archivos", + "dropToAdd": "Suelta para añadir", + "timelineDropToStart": "Arrastra contenido multimedia aquí para empezar.", + "dragMediaHint": "Arrastra vídeo, audio o imágenes aquí\nLos archivos originales permanecen en su ubicación actual", + "transcribe": "Transcribir", + "generateCaptions": "Generar subtítulos", + "play": "Reproducir", + "pause": "Pausar", + "retryPreview": "Reintentar vista previa", + "canvasRatio": "Relación de aspecto", + "noPreviewContent": "No hay contenido para obtener una vista previa en la línea de tiempo.", + "nativePreviewUnsupported": "La vista previa nativa no está disponible en esta plataforma", + "canvasTransformFailed": "No se pudo transformar el lienzo. Por favor inténtalo de nuevo.", + "undo": "Deshacer", + "redo": "Rehacer", + "deleteSelectedClips": "Eliminar clips seleccionados", + "splitAtPlayhead": "Dividir en el cabezal de reproducción", + "trimLeft": "Recortar izquierda", + "trimRight": "Recortar derecha", + "trimLeftTooltip": "Eliminar a la izquierda del cabezal y conservar la derecha", + "trimRightTooltip": "Eliminar a la derecha del cabezal y conservar la izquierda", + "currentSequence": "Secuencia actual", + "projectProperties": "Propiedades del proyecto", + "canvasSize": "Tamaño del lienzo", + "frameRate": "Tasa de fotogramas", + "duration": "Duración", + "totalDuration": "Duración total", + "clipDuration": "Duración del clip", + "seconds": "segundos", + "clip": "Clip", + "unnamedClip": "Clip sin nombre", + "gap": "Espacio vacío", + "compoundClip": "Clip compuesto", + "textClip": "Clip de texto", + "pictureProperties": "Imagen", + "position": "Posición", + "rotation": "Rotación", + "scale": "Escala", + "size": "Tamaño", + "transform": "Transformación", + "resetPosition": "Restablecer posición", + "keepAspectRatio": "Bloquear relación de aspecto", + "alignment": "Alineación", + "alignLeft": "Alinear a la izquierda", + "alignRight": "Alinear a la derecha", + "alignTop": "Alinear arriba", + "alignBottom": "Alinear abajo", + "alignHorizontalCenter": "Centrar horizontalmente", + "alignVerticalCenter": "Centrar verticalmente", + "volume": "Volumen", + "gain": "Ganancia", + "mute": "Silenciar", + "unmute": "Activar sonido", + "resetVolume": "Restablecer volumen", + "invalidGain": "Introduzca un valor entre -90 y +12", + "animation": "Animación", + "keyframes": "Fotogramas clave", + "removeAllKeyframes": "Eliminar todos los fotogramas clave", + "linear": "Lineal", + "easeIn": "Entrada suave", + "easeOut": "Salida suave", + "easeInOut": "Entrada y salida suaves", + "basic": "Básico", + "mask": "Máscara", + "addMask": "Agregar máscara", + "deleteMask": "Eliminar máscara", + "resetMask": "Restablecer máscara", + "enableMask": "Habilitar máscara", + "disableMask": "Desactivar máscara", + "moveMaskUp": "Mover máscara hacia arriba", + "moveMaskDown": "Mover máscara hacia abajo", + "rectangle": "Rectángulo", + "ellipse": "Elipse", + "invert": "Invertir", + "feather": "Desvanecimiento", + "add": "Sumar", + "subtract": "Restar", + "intersect": "Intersección", + "initialRegion": "Región inicial", + "none": "Ninguno", + "color": "Color", + "fontSize": "Tamaño de fuente", + "outlineWidth": "Grosor del contorno", + "outlineColor": "Color del contorno", + "captionBaseline": "Línea base de subtítulos", + "content": "Texto", + "start": "Inicio", + "time": "Tiempo", + "speed": "Velocidad", + "speedSegmentCount": "{count} segmentos de velocidad", + "splitSpeedAtPlayhead": "Dividir velocidad en el cabezal", + "speedChange": "Velocidad", + "speedMode": "Modo de velocidad", + "constantSpeed": "Velocidad constante", + "segmentedSpeed": "Velocidad segmentada", + "speedNotAvailable": "Los controles de velocidad aún no están disponibles", + "custom": "Personalizado", + "invalidNumber": "Valor no válido", + "mediaUnavailable": "Medios no disponibles", + "mediaMissing": "Medios faltantes", + "mediaColorSpace": "Espacio de color de medios", + "mediaColorInterpretation": "Interpretación del color de los medios.", + "colorInfoNotLoaded": "Información de color no cargada", + "unknownColorSpace": "Espacio de color desconocido. Mostrando como Rec.709.", + "colorBackendUnsupported": "El backend actual no admite la interpretación del color de los medios.", + "loadClipPropertiesFailed": "No se pudieron leer las propiedades del clip", + "updatePictureFailed": "No se pudieron actualizar las propiedades de la imagen", + "updateVolumeFailed": "No se pudo actualizar el volumen", + "updateMaskFailed": "No se pudo actualizar la máscara", + "updateKeyframesFailed": "No se pudieron actualizar los fotogramas clave", + "maskPreviewFailed": "No se pudo preparar la vista previa de la máscara", + "alignClipFailed": "No se pudo alinear el clip. Espere la vista previa y vuelva a intentarlo.", + "invalidTransform": "La escala debe ser del 1% al 10000%. La posición y el ángulo deben ser números válidos.", + "editFailed": "No se pudo editar. Verifique la entrada y el rango de tiempo.", + "addMediaFailed": "No se pudieron agregar medios. Por favor inténtalo de nuevo.", + "deleteCaption": "Eliminar subtítulo", + "mergeCaptions": "Combinar subtítulos", + "captionDeleted": "Subtítulo eliminado", + "captionChanged": "Los subtítulos han cambiado. Por favor inténtalo de nuevo.", + "captionEditChanged": "Los subtítulos han cambiado. Por favor edite nuevamente.", + "assistantHint": "Describe tu idea de edición", + "configureAgentHint": "Configurar el servicio de agente para comenzar a chatear", + "agentRestartHint": "Configure el servicio del agente y luego reinicie la aplicación.", + "replyInterrupted": "Respuesta interrumpida", + "replying": "Respondiendo…", + "stopReply": "Detener respuesta", + "sendMessage": "Enviar mensaje", + "addAttachment": "Agregar archivo adjunto (aún no disponible)", + "replyFailed": "La respuesta falló. Verifique la conexión o vuelva a intentarlo más tarde.", + "mcpService": "servicio MCP", + "listenPort": "Puerto", + "accessToken": "token de acceso", + "copyAccessToken": "Copiar token de acceso", + "accessTokenCopied": "Token de acceso copiado", + "loadMcpFailed": "No se pudo cargar la configuración de MCP. Rever", + "saveMcpFailed": "No se pudo guardar la configuración de MCP. Por favor inténtalo de nuevo.", + "retryStart": "Reintentar inicio", + "invalidPort": "El puerto debe estar entre 1 y 65535", + "loadingSettings": "Cargando ajustes…", + "starting": "Iniciando…", + "stopping": "Deteniendo…", + "disabled": "Desactivado", + "running": "En ejecución", + "startFailed": "No se pudo iniciar", + "saved": "Guardado", + "unsaved": "No guardado", + "saving": "Guardando…", + "pendingSave": "Pendiente de guardar", + "notApplied": "No aplicado", + "enable": "Activar", + "disable": "Desactivar", + "type": "Tipo", + "status": "Estado", + "file": "Archivo", + "unboundMedia": "Sin medio asociado", + "unboundAudio": "Sin pista de audio asociada", + "vertical": "Vertical", + "language": "Idioma", + "saveLanguageFailed": "No se pudo guardar el idioma. Por favor inténtalo de nuevo.", + "loadLanguageFailed": "No se pudo cargar el idioma. Por favor seleccione nuevamente.", + "propertiesFirstLayout": "Propiedades primero", + "defaultLayout": "Diseño predeterminado", + "separateVocals": "Separar voces", + "detachAudio": "Separar audio", + "restoreAudio": "Restaurar audio", + "audioDetached": "Audio separado", + "addAll": "Añadir todo", + "preparingMedia": "Preparando medios…", + "cancelling": "Cancelando…", + "cancelled": "Cancelado", + "interruptedTask": "Tarea interrumpida. Reiniciar para continuar", + "auto": "Automático", + "autoDetect": "Detección automática", + "noTranslation": "No traducir", + "sourceLanguage": "Idioma de origen", + "translationLanguage": "Idioma de destino", + "transcriptionNotConfigured": "La transcripción no está configurada. Instale el componente de reconocimiento y el modelo Whisper Turbo.", + "translationNotConfigured": "La traducción de subtítulos no está configurada. Puede generar subtítulos en el idioma de origen.", + "sourceLanguageUnknown": "No se pudo determinar un idioma de origen para la traducción.", + "startTranscriptionFailed": "No se pudo iniciar la transcripción. Verifique los medios o espere a que finalice la tarea actual.", + "placeMediaFirst": "Coloque este medio en la línea de tiempo antes de aplicar subtítulos.", + "placeTranslationMediaFirst": "Coloque los medios correspondientes en la línea de tiempo antes de aplicar subtítulos traducidos.", + "selectTargetClip": "Seleccionar clip de destino", + "timelineChanged": "La línea de tiempo ha cambiado. Seleccione el clip de destino nuevamente.", + "transcriptionAccessFailed": "Error de transcripción: componente, modelo o medio de origen inaccesible (notConfigured)", + "transcriptionNoAudio": "Error de transcripción: no hay audio reconocible en el medio o pista seleccionada (noAudio)", + "transcriptionInvalidResult": "Error de transcripción: se devolvió un archivo de subtítulos no válido (invalidResult)", + "transcriptionWorkerExited": "Error de transcripción: el componente de reconocimiento salió inesperadamente (workerExited)", + "transcriptionProcessingFailed": "Error de transcripción: error en el procesamiento nativo (processingFailed)", + "transcriptionFailed": "La transcripción falló. Verifique el componente, modelo, pista de audio y duración.", + "transcribing": "Transcribiendo…", + "captionsGenerated": "Subtítulos generados", + "cancelTranscription": "Cancelar transcripción", + "applyCaptions": "Aplicar subtítulos", + "preparingTranslation": "Preparando traducción…", + "translatingCaptions": "Traduciendo subtítulos…", + "cancellingTranslation": "Cancelando traducción…", + "translatedCaptionsGenerated": "Subtítulos traducidos generados", + "translationCancelled": "Traducción cancelada", + "translationInterrupted": "Traducción interrumpida", + "cancelTranslation": "Cancelar traducción", + "editorServiceUnavailable": "Servicio de edición no disponible. Vuelva a abrir el proyecto.", + "mcpUnavailable": "Conexión MCP no disponible. Verifique el puerto local y el token.", + "openTimelineFailed": "No se pudo abrir la línea de tiempo", + "noTimelineSequence": "Esta línea de tiempo no tiene ninguna secuencia.", + "waitingForProject": "Esperando a que se abra un proyecto", + "hold": "Mantener", + "noImportableFiles": "No se han recibido archivos importables", + "virtualFilesUnsupported": "Arrastre los archivos originales desde el administrador de archivos. Los archivos virtuales aún no son compatibles.", + "editorSessionStartFailed": "No se pudo abrir el editor de la línea de tiempo", + "previewStartFailed": "No se pudo iniciar la vista previa nativa", + "previewInvalidTrack": "La pista de audio o vídeo seleccionada no existe en el medio.", + "previewMissingBinding": "Faltan enlaces de medios. No se pudo obtener una vista previa de esta línea de tiempo.", + "previewUnsupportedEdits": "Esta línea de tiempo contiene ediciones que aún no son compatibles con la vista previa.", + "previewUnsupportedConfiguration": "Esta configuración de vista previa no es compatible con la plataforma o versión actual del sistema.", + "previewHdrUnsupported": "Los medios HDR requieren mapeo de tonos para la vista previa SDR. El sistema actual o la configuración de vista previa no lo admiten.", + "previewAudioOutOfRange": "El clip de audio excede el rango de pistas de origen y no se puede obtener una vista previa.", + "previewResourceMissing": "Los medios de vista previa ya no existen. Localice el archivo original nuevamente.", + "previewInvalidComposition": "Configuración de composición de vídeo no válida. No se pudo crear una vista previa.", + "previewInvalidData": "Datos de vista previa no válidos. Por favor inténtalo de nuevo.", + "previewFailed": "La vista previa falló. Verifique el acceso a los medios e inténtelo nuevamente.", + "chatFailed": "No se pudo completar la conversación. Verifique la configuración del servicio o vuelva a intentarlo más tarde.", + "delete": "Eliminar", + "pinTimeline": "Fijar línea de tiempo", + "unpinTimeline": "Desfijar línea de tiempo", + "deleteTimelineConfirmation": "¿Eliminar «{name}» y su historial de edición? Esta acción no se puede deshacer.", + "@deleteTimelineConfirmation": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "processingFailed": "Error de procesamiento", + "noMatchingOptions": "No hay opciones coincidentes", + "removeMediaConfirmation": "¿Eliminar “{name}” de la biblioteca? Se conservarán los clips existentes, el historial y el archivo original.", + "@removeMediaConfirmation": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "mediaAdded": "Se añadieron {count} referencias de medios", + "@mediaAdded": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "duplicatesSkipped": "Archivos duplicados {count} omitidos", + "@duplicatesSkipped": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mediaCount": "{count} medios", + "importMedia": "Importar", + "@mediaCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "noMediaOfType": "Sin medios {type}", + "@noMediaOfType": { + "placeholders": { + "type": { + "type": "String" + } + } + }, + "captionsImported": "Subtítulos {count} importados", + "@captionsImported": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "editCaptionError": "No se pudieron editar los subtítulos: {message}", + "@editCaptionError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "mcpStartError": "No se pudo iniciar MCP: {message}", + "@mcpStartError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "manualColorSpace": "Seleccionado manualmente: {name}", + "@manualColorSpace": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "detectedColorSpace": "Detectado: {name}", + "@detectedColorSpace": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "keyframeLabel": "Fotograma clave de {channel}", + "@keyframeLabel": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "maskMode": "Modo de combinación: {mode}", + "@maskMode": { + "placeholders": { + "mode": { + "type": "String" + } + } + }, + "keyframeCount": "{count} fotogramas clave", + "@keyframeCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "toggleKeyframe": "{action} fotograma clave de {channel}", + "@toggleKeyframe": { + "placeholders": { + "action": { + "type": "String" + }, + "channel": { + "type": "String" + } + } + }, + "previousKeyframe": "Fotograma clave anterior de {channel}", + "@previousKeyframe": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "nextKeyframe": "Siguiente fotograma clave de {channel}", + "@nextKeyframe": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "keyframeSettings": "Ajustes de fotogramas clave de {channel}", + "@keyframeSettings": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "selectedClipsHint": "Clips {count} seleccionados\nSeleccione un clip para ver sus propiedades", + "@selectedClipsHint": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "transcriptionError": "La transcripción falló. Verifique el componente, modelo, pista de audio y duración ({code})", + "@transcriptionError": { + "placeholders": { + "code": { + "type": "String" + } + } + }, + "captionsAdded": "Se agregaron subtítulos {count}. Edítalos en el panel de propiedades.", + "@captionsAdded": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "translatedCaptionsAdded": "Se agregaron subtítulos traducidos {count}. Edítalos en el panel de propiedades.", + "@translatedCaptionsAdded": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "applyCaptionsError": "No se pudieron aplicar subtítulos: {message}", + "@applyCaptionsError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "applyTranslatedCaptionsError": "No se pudieron aplicar subtítulos traducidos: {message}", + "@applyTranslatedCaptionsError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "recognizedCaptions": "{count} subtítulos reconocidos", + "@recognizedCaptions": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "captionCount": "{count} subtítulos", + "@captionCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "translationFailed": "Error de traducción: {message}", + "@translationFailed": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "translatedCaptionCount": "{count} subtítulos en {language}", + "@translatedCaptionCount": { + "placeholders": { + "count": { + "type": "int" + }, + "language": { + "type": "String" + } + } + }, + "previewParameterError": "Parámetros de vista previa no válidos: {message}", + "@previewParameterError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "mediaOffline": "Medios sin conexión o no disponibles: {names}", + "@mediaOffline": { + "placeholders": { + "names": { + "type": "String" + } + } + }, + "searchOptions": "Buscar {label}…", + "@searchOptions": { + "placeholders": { + "label": { + "type": "String" + } + } + }, + "loadRecentProjectsFailed": "No se pudieron cargar bibliotecas recientes. Aún puedes abrir una biblioteca manualmente.", + "projectAccessFailed": "Proyecto no disponible", + "projectMissingDirectory": "Proyecto no encontrado", + "recentProjectSaveFailed": "La biblioteca se abrió, pero no se pudo guardar el registro reciente de la biblioteca.", + "lastProjectSaveFailed": "El proyecto se abrió, pero no se pudo guardar el último registro del proyecto.", + "enterProjectName": "Introduzca un nombre de proyecto", + "projectSwitched": "El proyecto ha cambiado. Arrastre los medios nuevamente.", + "notLocalMedia": "Este medio no es un archivo local.", + "revealMediaFailed": "No se pudieron mostrar los medios en el administrador de archivos", + "openMatchingProject": "Abra primero el proyecto correspondiente", + "projectMismatch": "La biblioteca en esta ubicación no coincide con el registro. Selecciónelo nuevamente con Abrir biblioteca.", + "openProjectFirst": "Abra una biblioteca primero", + "localFilesOnly": "Arrastre archivos locales desde el administrador de archivos", + "foldersUnsupported": "Seleccionar archivos. Aún no se admite arrastrar carpetas.", + "mediaImportCancelled": "Importación de medios cancelada", + "fileAccessFailed": "El archivo falta o es ilegible. Comprueba su ubicación y permisos.", + "registerMediaFailed": "No se pudieron registrar los medios. Por favor inténtalo de nuevo", + "mediaNoLongerExists": "Los medios ya no existen.", + "mediaNoTracks": "Los medios no tienen pistas de audio o video utilizables.", + "invalidMediaDuration": "Duración de medios no válida", + "mediaInfoUnsupported": "La lectura de información multimedia aún no es compatible con esta plataforma", + "mediaInfoFailed": "No se pudo leer la información de los medios. Comprueba el archivo y los permisos de acceso.", + "saveTimelineFailed": "No se pudo guardar la línea de tiempo. Intentar otra vez. Las ediciones no guardadas permanecen en esta sesión.", + "addKeyframeAction": "Añadir", + "backgroundTasks": "Tareas en segundo plano", + "noBackgroundTasks": "No hay tareas en segundo plano", + "retryTask": "Reintentar", + "applyOriginalCaptions": "Aplicar subtítulos originales", + "applyTranslatedCaptions": "Aplicar subtítulos traducidos", + "subtitleTaskStarted": "Tarea de subtítulos iniciada", + "fitTimeline": "Ajustar toda la línea de tiempo", + "modify": "Modify", + "projectSettings": "Project settings", + "projectSettingsDescription": "Change project output settings while keeping clip timing and speed.", + "projectColorSpace": "Color space", + "projectWidth": "Width (px)", + "projectHeight": "Height (px)", + "projectResolutionInvalid": "Enter a whole number from 1 to 16384", + "previewFullscreen": "Vista previa a pantalla completa", + "exitPreviewFullscreen": "Salir de pantalla completa", + "previewGoToStart": "Ir al inicio", + "previewPreviousFrame": "Fotograma anterior", + "previewNextFrame": "Fotograma siguiente", + "softwareUpdates": "Actualizaciones", + "checkForUpdates": "Buscar actualizaciones", + "automaticallyCheckUpdates": "Buscar actualizaciones automáticamente", + "updatesUnavailable": "Este paquete no ofrece actualizaciones.", + "updateCheckFailed": "No se pudieron buscar actualizaciones. Inténtalo de nuevo.", + "agentSettings": "Agente", + "agentSaveSettingsFailed": "No se pudo guardar la configuración del agente.", + "agentDeleteProviderTitle": "¿Eliminar proveedor?", + "agentDeleteProviderDescription": "“{providerName}” y su clave de API guardada se eliminarán de este dispositivo.", + "agentProviderRequired": "Añade un proveedor antes de activar el asistente.", + "agentUseSelectedModel": "Las nuevas solicitudes del agente usarán el modelo seleccionado.", + "agentEnable": "Activar agente", + "agentDefaultModel": "Modelo predeterminado", + "agentConfigureModel": "Configurar modelos", + "agentSelectModel": "Seleccionar modelo", + "agentModelUnavailable": "El modelo de esta conversación no está disponible. Selecciona otro modelo para iniciar una nueva conversación.", + "agentModelChangeSession": "Al cambiar el modelo se inicia una nueva sesión del agente.", + "agentCustomProviders": "Proveedores personalizados", + "agentProviderStorageDescription": "Los metadatos del proveedor se guardan localmente. Las claves de API se conservan en el almacén de credenciales del sistema.", + "agentAddProvider": "Añadir proveedor", + "agentBackToProviders": "Volver a proveedores", + "agentLoadSettingsFailed": "No se pudo cargar la configuración del agente. Reintentar", + "agentEnableProvider": "Activar proveedor", + "agentEditProvider": "Editar proveedor", + "agentDeleteProvider": "Eliminar proveedor", + "agentModelIdsUnique": "Los ID de modelo deben ser únicos.", + "agentEditProviderTitle": "Editar proveedor", + "agentProviderEndpointDescription": "Configura un endpoint de Chat Completions compatible con OpenAI.", + "agentSaveProvider": "Guardar proveedor", + "agentProviderConfiguration": "Configuración del proveedor", + "agentAuthenticationAndModels": "Autenticación y modelos", + "agentApiType": "Tipo de API", + "agentOpenAiChatCompletions": "OpenAI Completions", + "agentBaseUrl": "URL base", + "agentApiKey": "Clave de API", + "agentProviderNameHint": "Mi proveedor", + "agentApiKeyOptional": "Opcional para endpoints que no requieren autenticación.", + "agentApiKeyKeep": "Déjalo en blanco para conservar la clave guardada.", + "agentOptional": "Opcional", + "agentApiKeyOneLine": "La clave de API debe ocupar una sola línea.", + "agentRemoveSavedApiKey": "Eliminar clave de API guardada", + "agentModels": "Modelos", + "agentAddModel": "Añadir modelo", + "agentRequiredField": "Este campo es obligatorio.", + "agentInvalidBaseUrl": "Introduce una URL base HTTP(S) sin credenciales, consulta ni fragmento.", + "agentModelId": "ID de modelo", + "agentContextWindow": "Ventana de contexto", + "agentMaxOutputTokens": "Salida máxima", + "agentMaxOutputBelowContext": "Debe ser menor que la ventana de contexto.", + "agentDeleteModel": "Eliminar modelo", + "agentPositiveInteger": "Introduce un número entero positivo.", + "agentConfigurationReadFailed": "No se pudo leer la configuración del agente. Revisa los ajustes e inténtalo de nuevo.", + "agentConfigurationRequired": "Primero configura y activa el agente en Ajustes.", + "agentSessionRestoreFailed": "No se pudo restaurar la sesión del agente. Inténtalo de nuevo más tarde.", + "select": "Seleccionar", + "projectLocation": "Ubicación de guardado de proyectos", + "projectLocationNotSet": "Sin configurar", + "resourceLocation": "Ubicación de almacenamiento de recursos", + "resourceLocationNotSet": "Sin configurar", + "loadProjectLocationFailed": "No se pudo cargar la ubicación de guardado de proyectos.", + "saveProjectLocationFailed": "No se pudo guardar la ubicación de proyectos.", + "loadResourceLocationFailed": "No se pudo cargar la ubicación de almacenamiento de recursos.", + "saveResourceLocationFailed": "No se pudo guardar la ubicación de recursos.", + "downloadAndContinue": "Descargar y continuar", + "downloadInBackground": "Descargar en segundo plano", + "downloadingResource": "Descargando…", + "processingResourceDownloadFailed": "No se pudo descargar el recurso de reconocimiento de voz. Inténtalo de nuevo.", + "transcriptionResourceRequired": "Para generar subtítulos, primero debes descargar un modelo de reconocimiento de voz.", + "removeBackground": "Eliminar fondo", + "startBackgroundRemoval": "Eliminar fondo", + "backgroundRemovalResourceRequired": "La eliminación de fondo necesita un modelo local. Comenzará automáticamente después de la descarga.", + "backgroundRemovalDownloadTask": "Descargar recurso de eliminación de fondo", + "backgroundRemovalResourceName": "Modelo de eliminación de fondo", + "backgroundRemovalTaskStarted": "Eliminación de fondo iniciada", + "backgroundRemovalApplying": "Reemplazando el contenido del clip", + "backgroundRemovalComplete": "Eliminación de fondo completada", + "backgroundRemovalFailed": "Error al eliminar el fondo", + "backgroundRemovalDestructiveHint": "El contenido transparente generado reemplazará este clip. Puedes usar Deshacer para restaurar el clip original.", + "startBackgroundRemovalFailed": "No se pudo iniciar la eliminación de fondo. Comprueba el contenido o espera a que termine la tarea de procesamiento actual.", + "agentContextBudgetExceeded": "El presupuesto de entrada no alcanza para las instrucciones, herramientas y mensaje. Amplía el contexto o reduce la salida máxima.", + "agentAuthenticationFailed": "Error de autenticación. Comprueba la API Key y los permisos.", + "agentConnectionFailed": "Error de conexión o tiempo de espera agotado. Comprueba la Base URL y la red.", + "agentProtocolFailed": "La respuesta no coincide con el tipo de API elegido o el flujo está incompleto.", + "agentContextBudgetTooSmall": "Reserva más espacio para las instrucciones. Amplía el contexto o reduce la salida máxima.", + "agentCompacting": "Organizando el contexto…", + "agentEditing": "Editando…", + "agentVerifying": "Comprobando resultados…", + "agentTurnLimitReached": "La tarea alcanzó su límite de ejecución. Los cambios se han guardado. Envía «Continuar» para reanudar.", + "agentRecoveryRequired": "El resultado anterior no está confirmado. Continúa para verificar los registros guardados; no se repetirán cambios no confirmados.", + "agentExportReplyFailed": "Vídeo exportado. Falló la respuesta de resumen. Puedes reintentar el resumen sin repetir la edición ni la exportación.", + "agentRetrySummary": "Reintentar resumen", + "agentResumeTask": "Continuar tarea", + "agentTaskInterrupted": "La tarea se interrumpió. Continúa desde el progreso guardado.", + "downloadSubtitleModel": "Descargar modelo de subtítulos", + "downloadModelAction": "Descargar", + "subtitleEngineUnavailable": "El modelo está instalado, pero el motor de subtítulos no pudo iniciarse. Repara el motor; no es necesario volver a descargar el modelo.", + "backgroundTaskDetails": "Detalles de la tarea", + "backgroundTaskFailed": "Error", + "backgroundTaskCompleted": "Completado", + "captionWrapLines": "Ajustar texto de subtítulos", + "captionSingleLine": "Mostrar subtítulos en una línea", + "noMatchingCaptions": "No hay subtítulos coincidentes", + "subtitleResourcesRequired": "Estos recursos son necesarios para los subtítulos. La generación comenzará automáticamente al terminar la descarga.", + "subtitleResourcesDownloadSize": "Por descargar: {size}", + "pauseDownload": "Pausar", + "resumeDownload": "Reanudar", + "downloadPaused": "En pausa", + "cancelResourceDownloadTitle": "¿Cancelar la descarga?", + "cancelResourceDownloadMessage": "La descarga se detendrá. Es posible que se pierda el progreso del recurso actual.", + "continueDownload": "Continuar descarga", + "cancelDownload": "Cancelar descarga", + "speechResourceStage": "Recurso de reconocimiento de voz", + "translationResourceStage": "Recurso de traducción", + "subtitleResourceDownloadTask": "Descargar recursos de voz y traducción", + "downloadingSpeechModel": "Descargando modelo de voz", + "downloadingTranslationModel": "Descargando modelo de traducción", + "selectProject": "Seleccionar proyecto", + "searchProjects": "Buscar proyectos", + "noMatchingProjects": "No hay proyectos coincidentes", + "projectLocationMissing": "La carpeta no existe. Se creará al crear un proyecto.", + "projectLocationUnavailable": "La ubicación de guardado no está disponible. Conecta el disco o comprueba la red y vuelve a intentarlo, o cambia la ubicación.", + "projectLocationNotWritable": "No se puede escribir en la ubicación de guardado. Comprueba los permisos o cambia la ubicación.", + "projectLocationCreateFailed": "No se pudo crear la carpeta del proyecto o escribir en ella. Comprueba los permisos o cambia la ubicación.", + "removeProjectFromSidebar": "Quitar de la barra lateral", + "projectRemoved": "Proyecto eliminado de la lista. Se conservan los archivos locales y las conversaciones.", + "agentNoConversations": "Aún no hay conversaciones", + "collapseProject": "Contraer proyecto", + "expandProject": "Expandir proyecto", + "agentDeleteConfirmation": "¿Eliminar permanentemente «{title}» y todos sus mensajes? Esta acción no se puede deshacer. Los archivos locales del proyecto no se verán afectados.", + "agentEmptyTrashConfirmation": "¿Eliminar permanentemente todas las conversaciones de la papelera? Esta acción no se puede deshacer. Los archivos locales del proyecto no se verán afectados.", + "checkingForUpdates": "Buscando actualizaciones…", + "appIsUpToDate": "La aplicación está actualizada.", + "downloadingUpdate": "Descargando actualización: {progress}%", + "updateAvailable": "La versión {version} está disponible.", + "downloadUpdate": "Descargar actualización", + "restartToUpdate": "Reiniciar y actualizar", + "updateOperationFailed": "No se pudo actualizar. Termina las tareas activas e inténtalo de nuevo.", + "windowMinimize": "Minimizar", + "windowMaximize": "Maximizar", + "windowRestore": "Restaurar", + "workspaceAgent": "Asistente", + "workspaceCut": "Edición", + "noAvailableOptions": "No hay opciones disponibles", + "composerReferenceInvalid": "Una referencia ya no es válida. Vuelve a su proyecto o elimínala.", + "durationSeconds": "{seconds} s", + "durationMinutesSeconds": "{minutes} min {seconds} s", + "projectNameInvalid": "Nombre de proyecto no válido", + "projectLocationDefaultUnavailable": "No se puede acceder a la ubicación predeterminada de los proyectos. Vuelve a seleccionarla en Ajustes.", + "chooseProjectLocation": "Selecciona primero una ubicación para guardar proyectos en Ajustes.", + "untitledTimeline": "Línea de tiempo sin título", + "primarySequence": "Secuencia principal", + "primaryStoryline": "Línea principal", + "projectSessionClosed": "La sesión del proyecto se ha cerrado. Abre el proyecto de nuevo.", + "timelineSessionClosed": "La sesión de la línea de tiempo se ha cerrado. Ábrela de nuevo.", + "timelineMissing": "La línea de tiempo no existe o se ha eliminado.", + "timelineInUse": "La línea de tiempo está en uso y aún no se puede eliminar.", + "timelineHasBackgroundTasks": "Finaliza las tareas en segundo plano de la línea de tiempo antes de eliminarla.", + "timelineRequired": "Un proyecto debe conservar al menos una línea de tiempo.", + "mediaReadFailed": "No se pudo leer el medio", + "mediaImportFailed": "No se pudo importar el medio", + "unsupportedMediaType": "Solo se pueden importar archivos de vídeo, audio e imagen.", + "mediaNoVideoTracks": "El medio no tiene ninguna pista de vídeo utilizable", + "mediaDurationOutOfRange": "La duración del medio supera el rango de la línea de tiempo", + "resourceDownloadHttpFailed": "Error de descarga (HTTP {statusCode})", + "resourceChecksumFailed": "Error al verificar el archivo del modelo. Descarga el recurso de nuevo.", + "subtitleLanguageAf": "afrikáans", + "subtitleLanguageAm": "amárico", + "subtitleLanguageAr": "árabe", + "subtitleLanguageAst": "asturiano", + "subtitleLanguageAz": "azerbaiyano", + "subtitleLanguageBa": "baskir", + "subtitleLanguageBe": "bielorruso", + "subtitleLanguageBg": "búlgaro", + "subtitleLanguageBn": "bengalí", + "subtitleLanguageBr": "bretón", + "subtitleLanguageBs": "bosnio", + "subtitleLanguageCa": "catalán", + "subtitleLanguageCeb": "cebuano", + "subtitleLanguageCs": "checo", + "subtitleLanguageCy": "galés", + "subtitleLanguageDa": "danés", + "subtitleLanguageDe": "alemán", + "subtitleLanguageEl": "griego", + "subtitleLanguageEn": "inglés", + "subtitleLanguageEs": "español", + "subtitleLanguageEt": "estonio", + "subtitleLanguageFa": "persa", + "subtitleLanguageFf": "fula", + "subtitleLanguageFi": "finés", + "subtitleLanguageFr": "francés", + "subtitleLanguageFy": "frisón occidental", + "subtitleLanguageGa": "irlandés", + "subtitleLanguageGd": "gaélico escocés", + "subtitleLanguageGl": "gallego", + "subtitleLanguageGu": "guyaratí", + "subtitleLanguageHa": "hausa", + "subtitleLanguageHe": "hebreo", + "subtitleLanguageHi": "hindi", + "subtitleLanguageHr": "croata", + "subtitleLanguageHt": "criollo haitiano", + "subtitleLanguageHu": "húngaro", + "subtitleLanguageHy": "armenio", + "subtitleLanguageId": "indonesio", + "subtitleLanguageIg": "igbo", + "subtitleLanguageIlo": "ilocano", + "subtitleLanguageIs": "islandés", + "subtitleLanguageIt": "italiano", + "subtitleLanguageJa": "japonés", + "subtitleLanguageJv": "javanés", + "subtitleLanguageKa": "georgiano", + "subtitleLanguageKk": "kazajo", + "subtitleLanguageKm": "jemer", + "subtitleLanguageKn": "canarés", + "subtitleLanguageKo": "coreano", + "subtitleLanguageLb": "luxemburgués", + "subtitleLanguageLg": "ganda", + "subtitleLanguageLn": "lingala", + "subtitleLanguageLo": "lao", + "subtitleLanguageLt": "lituano", + "subtitleLanguageLv": "letón", + "subtitleLanguageMg": "malgache", + "subtitleLanguageMk": "macedonio", + "subtitleLanguageMl": "malayálam", + "subtitleLanguageMn": "mongol", + "subtitleLanguageMr": "maratí", + "subtitleLanguageMs": "malayo", + "subtitleLanguageMy": "birmano", + "subtitleLanguageNe": "nepalí", + "subtitleLanguageNl": "neerlandés", + "subtitleLanguageNo": "noruego", + "subtitleLanguageNs": "sotho septentrional", + "subtitleLanguageOc": "occitano", + "subtitleLanguageOr": "oriya", + "subtitleLanguagePa": "panyabí", + "subtitleLanguagePl": "polaco", + "subtitleLanguagePs": "pastún", + "subtitleLanguagePt": "portugués", + "subtitleLanguageRo": "rumano", + "subtitleLanguageRu": "ruso", + "subtitleLanguageSd": "sindi", + "subtitleLanguageSi": "cingalés", + "subtitleLanguageSk": "eslovaco", + "subtitleLanguageSl": "esloveno", + "subtitleLanguageSo": "somalí", + "subtitleLanguageSq": "albanés", + "subtitleLanguageSr": "serbio", + "subtitleLanguageSs": "suazi", + "subtitleLanguageSu": "sundanés", + "subtitleLanguageSv": "sueco", + "subtitleLanguageSw": "suajili", + "subtitleLanguageTa": "tamil", + "subtitleLanguageTh": "tailandés", + "subtitleLanguageTl": "tagalo", + "subtitleLanguageTn": "setsuana", + "subtitleLanguageTr": "turco", + "subtitleLanguageUk": "ucraniano", + "subtitleLanguageUr": "urdu", + "subtitleLanguageUz": "uzbeko", + "subtitleLanguageVi": "vietnamita", + "subtitleLanguageWo": "wólof", + "subtitleLanguageXh": "xhosa", + "subtitleLanguageYi": "yidis", + "subtitleLanguageYo": "yoruba", + "subtitleLanguageYue": "cantonés", + "subtitleLanguageZh": "chino", + "subtitleLanguageZu": "zulú", + "linearRec2020": "Rec.2020 lineal", + "diagnostics": "Diagnóstico", + "exportDiagnostics": "Exportar paquete de diagnóstico", + "exportDiagnosticsFailed": "No se pudo exportar el diagnóstico. Inténtalo de nuevo.", + "exportDiagnosticsSucceeded": "Paquete de diagnóstico guardado." +} diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb new file mode 100644 index 0000000..a61fb0d --- /dev/null +++ b/lib/l10n/app_fr.arb @@ -0,0 +1,889 @@ +{ + "projectsNone": "Aucun projet", + "agentConversations": "Conversations", + "renameConversationTitle": "Renommer la discussion", + "renameConversationDescription": "Choisissez un nom court et facile à reconnaître.", + "showMoreConversations": "Afficher plus", + "showFewerConversations": "Afficher moins", + "agentNewConversation": "Nouvelle conversation", + "agentElapsedTime": "Durée {duration}", + "agentConversationActions": "Actions de la conversation", + "agentMoveToTrash": "Déplacer vers la corbeille", + "agentTrash": "Corbeille", + "agentRestore": "Restaurer", + "agentEmptyTrash": "Vider la corbeille", + "agentDeleteForever": "Supprimer définitivement", + "agentConversationLocation": "Emplacement des conversations", + "agentChooseExistingConversations": "Choisir des conversations existantes", + "agentMoveConversations": "Déplacer les conversations", + "agentLocationUnavailable": "Emplacement des conversations indisponible", + "agentLocationBusy": "Attendez la fin des conversations en cours", + "agentRelinkProvider": "Réassocier le fournisseur", + "@@locale": "fr", + "settings": "Paramètres", + "closeSettings": "Fermer les paramètres", + "general": "Général", + "appearance": "Apparence", + "theme": "Thème", + "system": "Suivre le système", + "light": "Clair", + "dark": "Sombre", + "saveAppearanceFailed": "Impossible de sauvegarder l'apparence. Veuillez réessayer.", + "loadAppearanceFailed": "Impossible de charger l'apparence. Veuillez sélectionner à nouveau un thème.", + "cancel": "Annuler", + "save": "Enregistrer", + "create": "Créer", + "close": "Fermer", + "retry": "Réessayer", + "name": "Nom", + "enterName": "Entrez un nom", + "invalidName": "Les noms ne peuvent pas contenir de séparateurs de chemin ni de caractères de contrôle", + "projectName": "Nom du projet", + "newProject": "Nouveau projet", + "openProject": "Ouvrir un projet", + "openProjectMore": "Ouvrir un autre projet", + "projects": "Projets", + "projectsEmpty": "Aucun projet", + "openingWorkspace": "Ouverture de l’espace de travail…", + "loadProjectsFailed": "Impossible de charger les projets", + "backToProjects": "Retour au montage", + "timelines": "Timelines", + "timelineLimitReached": "Chaque projet peut contenir jusqu’à {count} timelines.", + "timelineName": "Nom de la timeline", + "defaultTimelineName": "Timeline {index}", + "newTimeline": "Nouvelle timeline", + "noTimelines": "Aucune timeline", + "activeTimeline": "Timeline actuelle", + "timelineUnavailable": "Timeline indisponible", + "projectNoTimelines": "Ce projet ne contient aucune timeline", + "createTimelineHint": "Créez une timeline dans la section « Timelines » à gauche pour commencer le montage.", + "createTimelineChat": "Créez une timeline pour commencer à discuter", + "editingFirstLayout": "Montage prioritaire", + "agentEditingLayout": "Agent et montage", + "agentLayoutDescription": "Planifier, collaborer et exécuter", + "editingLayoutDescription": "Prévisualiser, monter et affiner", + "saveHere": "Enregistrer ici", + "selectDirectoryFailed": "Impossible de sélectionner un répertoire. Vérifiez les autorisations du système.", + "operationFailed": "L'opération a échoué. Veuillez réessayer.", + "collapseSidebar": "Réduire la barre latérale", + "expandSidebar": "Développer la barre latérale", + "expandEditor": "Développer la zone de montage", + "collapseProperties": "Réduire les propriétés", + "expandProperties": "Développer les propriétés", + "layout": "Disposition", + "materials": "Médias", + "all": "Tous", + "video": "Vidéo", + "audio": "Audio", + "image": "Image", + "picture": "Image", + "captions": "Sous-titres", + "text": "Texte", + "noMedia": "Aucun média", + "mediaCategory": "Catégorie de médias", + "captionTasks": "Tâches de sous-titrage", + "listLayout": "Vue en liste", + "gridLayout": "Vue grille", + "addToTimeline": "Ajouter à la timeline", + "rename": "Renommer", + "renameMedia": "Renommer le média", + "removeMedia": "Retirer le média", + "remove": "Retirer", + "revealFinder": "Afficher dans le Finder", + "revealFileManager": "Afficher dans le gestionnaire de fichiers", + "dropToAdd": "Relâcher pour ajouter", + "timelineDropToStart": "Faites glisser des médias ici pour commencer.", + "dragMediaHint": "Faites glisser la vidéo, l'audio ou les images ici\nLes fichiers originaux restent à leur emplacement actuel", + "transcribe": "Transcrire", + "generateCaptions": "Générer des sous-titres", + "play": "Lire", + "pause": "Pause", + "retryPreview": "Réessayer l'aperçu", + "canvasRatio": "Rapport d’image", + "noPreviewContent": "Aucun contenu à prévisualiser sur la timeline", + "nativePreviewUnsupported": "L'aperçu natif n'est pas disponible sur cette plateforme", + "canvasTransformFailed": "Impossible de transformer la toile. Veuillez réessayer.", + "undo": "Annuler", + "redo": "Rétablir", + "deleteSelectedClips": "Supprimer les clips sélectionnés", + "splitAtPlayhead": "Diviser au niveau de la tête de lecture", + "trimLeft": "Rogner à gauche", + "trimRight": "Rogner à droite", + "trimLeftTooltip": "Supprimer à gauche de la tête de lecture et conserver la droite", + "trimRightTooltip": "Supprimer à droite de la tête de lecture et conserver la gauche", + "currentSequence": "Séquence actuelle", + "projectProperties": "Propriétés du projet", + "canvasSize": "Taille du canevas", + "frameRate": "Fréquence d’images", + "duration": "Durée", + "totalDuration": "Durée totale", + "clipDuration": "Durée du clip", + "seconds": "secondes", + "clip": "Clip", + "unnamedClip": "Clip sans nom", + "gap": "Intervalle", + "compoundClip": "Clip composé", + "textClip": "Clip de texte", + "pictureProperties": "Image", + "position": "Position", + "rotation": "Rotation", + "scale": "Échelle", + "size": "Taille", + "transform": "Transformation", + "resetPosition": "Réinitialiser la position", + "keepAspectRatio": "Verrouiller le rapport hauteur/largeur", + "alignment": "Alignement", + "alignLeft": "Aligner à gauche", + "alignRight": "Aligner à droite", + "alignTop": "Aligner en haut", + "alignBottom": "Aligner en bas", + "alignHorizontalCenter": "Centrer horizontalement", + "alignVerticalCenter": "Centrer verticalement", + "volume": "Volume", + "gain": "Gain", + "mute": "Couper le son", + "unmute": "Activer le son", + "resetVolume": "Réinitialiser le volume", + "invalidGain": "Saisissez une valeur comprise entre -90 et +12", + "animation": "Animation", + "keyframes": "Images clés", + "removeAllKeyframes": "Supprimer toutes les images clés", + "linear": "Linéaire", + "easeIn": "Accélération progressive", + "easeOut": "Décélération progressive", + "easeInOut": "Accélération et décélération", + "basic": "Général", + "mask": "Masque", + "addMask": "Ajouter un masque", + "deleteMask": "Supprimer le masque", + "resetMask": "Réinitialiser le masque", + "enableMask": "Activer le masque", + "disableMask": "Désactiver le masque", + "moveMaskUp": "Déplacer le masque vers le haut", + "moveMaskDown": "Descendre le masque", + "rectangle": "Rectangle", + "ellipse": "Ellipse", + "invert": "Inverser", + "feather": "Contour progressif", + "add": "Addition", + "subtract": "Soustraction", + "intersect": "Intersection", + "initialRegion": "Région initiale", + "none": "Aucun", + "color": "Couleur", + "fontSize": "Taille de la police", + "outlineWidth": "Épaisseur du contour", + "outlineColor": "Couleur du contour", + "captionBaseline": "Ligne de base des sous-titres", + "content": "Texte", + "start": "Début", + "time": "Temps", + "speed": "Vitesse", + "speedSegmentCount": "{count} segments de vitesse", + "splitSpeedAtPlayhead": "Scinder la vitesse à la tête de lecture", + "speedChange": "Vitesse", + "speedMode": "Mode de vitesse", + "constantSpeed": "Vitesse constante", + "segmentedSpeed": "Vitesse segmentée", + "speedNotAvailable": "Les contrôles de vitesse ne sont pas encore disponibles", + "custom": "Personnalisé", + "invalidNumber": "Valeur invalide", + "mediaUnavailable": "Médias indisponibles", + "mediaMissing": "Média manquant", + "mediaColorSpace": "Espace colorimétrique des médias", + "mediaColorInterpretation": "Interprétation des couleurs des médias", + "colorInfoNotLoaded": "Les informations de couleur ne sont pas chargées", + "unknownColorSpace": "Espace colorimétrique inconnu. Affichage sous forme de Rec.709.", + "colorBackendUnsupported": "Le backend actuel ne prend pas en charge l’interprétation des couleurs du support.", + "loadClipPropertiesFailed": "Impossible de lire les propriétés du clip", + "updatePictureFailed": "Impossible de mettre à jour les propriétés de l'image", + "updateVolumeFailed": "Impossible de mettre à jour le volume", + "updateMaskFailed": "Impossible de mettre à jour le masque", + "updateKeyframesFailed": "Impossible de mettre à jour les images clés", + "maskPreviewFailed": "Impossible de préparer l'aperçu du masque", + "alignClipFailed": "Impossible d'aligner le clip. Attendez l'aperçu, puis réessayez.", + "invalidTransform": "L'échelle doit être comprise entre 1 % et 10 000 %. La position et l'angle doivent être des nombres valides.", + "editFailed": "Impossible de modifier. Vérifiez l'entrée et la plage horaire.", + "addMediaFailed": "Impossible d'ajouter des médias. Veuillez réessayer.", + "deleteCaption": "Supprimer le sous-titre", + "mergeCaptions": "Fusionner les sous-titres", + "captionDeleted": "Sous-titre supprimé", + "captionChanged": "Les sous-titres ont changé. Veuillez réessayer.", + "captionEditChanged": "Les sous-titres ont changé. Veuillez modifier à nouveau.", + "assistantHint": "Décrivez votre idée d'édition", + "configureAgentHint": "Configurer le service d'agent pour commencer à discuter", + "agentRestartHint": "Configurez le service d'agent, puis redémarrez l'application.", + "replyInterrupted": "Réponse interrompue", + "replying": "Réponse en cours…", + "stopReply": "Arrêter la réponse", + "sendMessage": "Envoyer un message", + "addAttachment": "Ajouter une pièce jointe (pas encore disponible)", + "replyFailed": "La réponse a échoué. Vérifiez la connexion ou réessayez plus tard.", + "mcpService": "Service MCP", + "listenPort": "Port", + "accessToken": "Jeton d'accès", + "copyAccessToken": "Copier le jeton d'accès", + "accessTokenCopied": "Jeton d'accès copié", + "loadMcpFailed": "Impossible de charger les paramètres MCP. Réessayer", + "saveMcpFailed": "Impossible d'enregistrer les paramètres MCP. Veuillez réessayer.", + "retryStart": "Réessayez de démarrer", + "invalidPort": "Le port doit être compris entre 1 et 65535", + "loadingSettings": "Chargement des paramètres…", + "starting": "Démarrage…", + "stopping": "Arrêt…", + "disabled": "Désactivé", + "running": "En cours d’exécution", + "startFailed": "Échec du démarrage", + "saved": "Enregistré", + "unsaved": "Non enregistré", + "saving": "Enregistrement…", + "pendingSave": "En attente de sauvegarde", + "notApplied": "Non appliqué", + "enable": "Activer", + "disable": "Désactiver", + "type": "Type", + "status": "Statut", + "file": "Fichier", + "unboundMedia": "Aucun média associé", + "unboundAudio": "Aucune piste audio associée", + "vertical": "Vertical", + "language": "Langue", + "saveLanguageFailed": "Impossible d'enregistrer la langue. Veuillez réessayer.", + "loadLanguageFailed": "Impossible de charger la langue. Veuillez sélectionner à nouveau.", + "propertiesFirstLayout": "Les propriétés d'abord", + "defaultLayout": "Disposition par défaut", + "separateVocals": "Séparer la voix", + "detachAudio": "Détacher l’audio", + "restoreAudio": "Restaurer l’audio", + "audioDetached": "Audio détaché", + "addAll": "Tout ajouter", + "preparingMedia": "Préparation des médias…", + "cancelling": "Annulation…", + "cancelled": "Annulé", + "interruptedTask": "Tâche interrompue. Redémarrez pour continuer", + "auto": "Automatique", + "autoDetect": "Détection automatique", + "noTranslation": "Ne pas traduire", + "sourceLanguage": "Langue source", + "translationLanguage": "Langue cible", + "transcriptionNotConfigured": "La transcription n'est pas configurée. Installez le composant de reconnaissance et le modèle Whisper Turbo.", + "translationNotConfigured": "La traduction des sous-titres n'est pas configurée. Vous pouvez générer des sous-titres dans la langue source.", + "sourceLanguageUnknown": "Impossible de déterminer une langue source pour la traduction.", + "startTranscriptionFailed": "Impossible de démarrer la transcription. Vérifiez les médias ou attendez la fin de la tâche en cours.", + "placeMediaFirst": "Placez ce média sur la timeline avant d'appliquer des sous-titres.", + "placeTranslationMediaFirst": "Placez le média correspondant sur la timeline avant d'appliquer les sous-titres traduits.", + "selectTargetClip": "Sélectionner le clip cible", + "timelineChanged": "La chronologie a changé. Sélectionnez à nouveau le clip cible.", + "transcriptionAccessFailed": "Échec de la transcription : composant, modèle ou média source inaccessible (notConfigured)", + "transcriptionNoAudio": "Échec de la transcription : aucun son reconnaissable dans le média ou la piste sélectionné (noAudio)", + "transcriptionInvalidResult": "Échec de la transcription : fichier de sous-titre non valide renvoyé (invalidResult)", + "transcriptionWorkerExited": "Échec de la transcription : le composant de reconnaissance s'est arrêté de manière inattendue (workerExited)", + "transcriptionProcessingFailed": "Échec de la transcription : échec du traitement natif (processingFailed)", + "transcriptionFailed": "La transcription a échoué. Vérifiez le composant, le modèle, la piste audio et la durée", + "transcribing": "Transcription…", + "captionsGenerated": "Sous-titres générés", + "cancelTranscription": "Annuler la transcription", + "applyCaptions": "Appliquer les sous-titres", + "preparingTranslation": "Préparation de la traduction…", + "translatingCaptions": "Traduction des sous-titres…", + "cancellingTranslation": "Annulation de la traduction…", + "translatedCaptionsGenerated": "Sous-titres traduits générés", + "translationCancelled": "Traduction annulée", + "translationInterrupted": "Traduction interrompue", + "cancelTranslation": "Annuler la traduction", + "editorServiceUnavailable": "Service d'édition indisponible. Rouvrez le projet.", + "mcpUnavailable": "Connexion MCP indisponible. Vérifiez le port local et le jeton.", + "openTimelineFailed": "Impossible d'ouvrir la chronologie", + "noTimelineSequence": "Cette timeline ne contient aucune séquence.", + "waitingForProject": "En attente d'ouverture d'un projet", + "hold": "Maintien", + "noImportableFiles": "Aucun fichier importable reçu", + "virtualFilesUnsupported": "Faites glisser les fichiers originaux depuis le gestionnaire de fichiers. Les fichiers virtuels ne sont pas encore pris en charge.", + "editorSessionStartFailed": "Impossible d’ouvrir l’éditeur de timeline", + "previewStartFailed": "Impossible de démarrer l'aperçu natif", + "previewInvalidTrack": "La piste audio ou vidéo sélectionnée n'existe pas dans le média.", + "previewMissingBinding": "Les liaisons multimédias sont manquantes. Impossible de prévisualiser cette chronologie.", + "previewUnsupportedEdits": "Cette chronologie contient des modifications qui ne sont pas encore prises en charge par l'aperçu.", + "previewUnsupportedConfiguration": "Cette configuration d'aperçu n'est pas prise en charge sur la plateforme ou la version actuelle du système.", + "previewHdrUnsupported": "Les médias HDR nécessitent un mappage de tons pour l'aperçu SDR. Le système actuel ou la configuration d'aperçu ne le prend pas en charge.", + "previewAudioOutOfRange": "Le clip audio dépasse la plage de la piste source et ne peut pas être prévisualisé.", + "previewResourceMissing": "Le média de prévisualisation n'existe plus. Localisez à nouveau le fichier d'origine.", + "previewInvalidComposition": "Configuration de composition vidéo non valide. Impossible de créer un aperçu.", + "previewInvalidData": "Données d'aperçu non valides. Veuillez réessayer.", + "previewFailed": "L'aperçu a échoué. Vérifiez l'accès aux médias et réessayez.", + "chatFailed": "Impossible de terminer la conversation. Vérifiez la configuration du service ou réessayez plus tard.", + "delete": "Supprimer", + "pinTimeline": "Épingler la timeline", + "unpinTimeline": "Désépingler la timeline", + "deleteTimelineConfirmation": "Supprimer « {name} » et son historique de modification ? Cette action est irréversible.", + "@deleteTimelineConfirmation": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "processingFailed": "Échec du traitement", + "noMatchingOptions": "Aucune option correspondante", + "removeMediaConfirmation": "Supprimer « {name} » de la bibliothèque ? Les clips existants, l'historique et le fichier original seront conservés.", + "@removeMediaConfirmation": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "mediaAdded": "{count} références de médias ajoutées", + "@mediaAdded": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "duplicatesSkipped": "Fichiers en double {count} ignorés", + "@duplicatesSkipped": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mediaCount": "{count} médias", + "importMedia": "Importer", + "@mediaCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "noMediaOfType": "Aucun support {type}", + "@noMediaOfType": { + "placeholders": { + "type": { + "type": "String" + } + } + }, + "captionsImported": "Sous-titres {count} importées", + "@captionsImported": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "editCaptionError": "Impossible de modifier les sous-titres : {message}", + "@editCaptionError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "mcpStartError": "Impossible de démarrer MCP : {message}", + "@mcpStartError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "manualColorSpace": "Sélectionné manuellement : {name}", + "@manualColorSpace": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "detectedColorSpace": "Détecté : {name}", + "@detectedColorSpace": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "keyframeLabel": "Image clé de {channel}", + "@keyframeLabel": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "maskMode": "Mode combiné : {mode}", + "@maskMode": { + "placeholders": { + "mode": { + "type": "String" + } + } + }, + "keyframeCount": "{count} images clés", + "@keyframeCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "toggleKeyframe": "{action} une image clé de {channel}", + "@toggleKeyframe": { + "placeholders": { + "action": { + "type": "String" + }, + "channel": { + "type": "String" + } + } + }, + "previousKeyframe": "Image clé précédente de {channel}", + "@previousKeyframe": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "nextKeyframe": "Image clé suivante de {channel}", + "@nextKeyframe": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "keyframeSettings": "Réglages des images clés de {channel}", + "@keyframeSettings": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "selectedClipsHint": "Clips {count} sélectionnés\nSélectionnez un clip pour afficher ses propriétés", + "@selectedClipsHint": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "transcriptionError": "La transcription a échoué. Vérifiez le composant, le modèle, la piste audio et la durée ({code})", + "@transcriptionError": { + "placeholders": { + "code": { + "type": "String" + } + } + }, + "captionsAdded": "Ajout des sous-titres {count}. Modifiez-les dans le panneau des propriétés.", + "@captionsAdded": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "translatedCaptionsAdded": "Ajout des sous-titres traduits {count}. Modifiez-les dans le panneau des propriétés.", + "@translatedCaptionsAdded": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "applyCaptionsError": "Impossible d'appliquer les sous-titres : {message}", + "@applyCaptionsError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "applyTranslatedCaptionsError": "Impossible d'appliquer les sous-titres traduits : {message}", + "@applyTranslatedCaptionsError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "recognizedCaptions": "{count} sous-titres reconnus", + "@recognizedCaptions": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "captionCount": "{count} sous-titres", + "@captionCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "translationFailed": "Échec de la traduction : {message}", + "@translationFailed": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "translatedCaptionCount": "{count} sous-titres en {language}", + "@translatedCaptionCount": { + "placeholders": { + "count": { + "type": "int" + }, + "language": { + "type": "String" + } + } + }, + "previewParameterError": "Paramètres d'aperçu non valides : {message}", + "@previewParameterError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "mediaOffline": "Média hors ligne ou indisponible : {names}", + "@mediaOffline": { + "placeholders": { + "names": { + "type": "String" + } + } + }, + "searchOptions": "Rechercher {label}…", + "@searchOptions": { + "placeholders": { + "label": { + "type": "String" + } + } + }, + "loadRecentProjectsFailed": "Impossible de charger les bibliothèques récentes. Vous pouvez toujours ouvrir une bibliothèque manuellement.", + "projectAccessFailed": "Projet indisponible", + "projectMissingDirectory": "Projet introuvable", + "recentProjectSaveFailed": "Bibliothèque ouverte, mais l'enregistrement récent de la bibliothèque n'a pas pu être enregistré.", + "lastProjectSaveFailed": "Projet ouvert, mais le dernier enregistrement du projet n'a pas pu être enregistré.", + "enterProjectName": "Entrez un nom de projet", + "projectSwitched": "Le projet a changé. Faites glisser à nouveau le média.", + "notLocalMedia": "Ce média n'est pas un fichier local", + "revealMediaFailed": "Impossible d'afficher les médias dans le gestionnaire de fichiers", + "openMatchingProject": "Ouvrez d'abord le projet correspondant", + "projectMismatch": "La bibliothèque à cet emplacement ne correspond pas à la notice. Sélectionnez-le à nouveau avec Ouvrir la bibliothèque.", + "openProjectFirst": "Ouvrez d'abord une bibliothèque", + "localFilesOnly": "Faites glisser les fichiers locaux depuis le gestionnaire de fichiers", + "foldersUnsupported": "Sélectionnez les fichiers. Le déplacement de dossiers n'est pas encore pris en charge.", + "mediaImportCancelled": "Importation multimédia annulée", + "fileAccessFailed": "Le fichier est manquant ou illisible. Vérifiez son emplacement et ses autorisations", + "registerMediaFailed": "Impossible d'enregistrer le média. Veuillez réessayer", + "mediaNoLongerExists": "Les médias n'existent plus", + "mediaNoTracks": "Le média n'a aucune piste vidéo ou audio utilisable", + "invalidMediaDuration": "Durée du média invalide", + "mediaInfoUnsupported": "La lecture des informations multimédias n'est pas encore prise en charge sur cette plate-forme", + "mediaInfoFailed": "Impossible de lire les informations multimédias. Vérifiez le fichier et les autorisations d'accès", + "saveTimelineFailed": "Impossible d'enregistrer la chronologie. Essayer à nouveau. Les modifications non enregistrées restent dans cette session.", + "addKeyframeAction": "Ajouter", + "backgroundTasks": "Tâches en arrière-plan", + "noBackgroundTasks": "Aucune tâche en arrière-plan", + "retryTask": "Réessayer", + "applyOriginalCaptions": "Appliquer les sous-titres originaux", + "applyTranslatedCaptions": "Appliquer les sous-titres traduits", + "subtitleTaskStarted": "Tâche de sous-titres démarrée", + "fitTimeline": "Afficher toute la chronologie", + "modify": "Modify", + "projectSettings": "Project settings", + "projectSettingsDescription": "Change project output settings while keeping clip timing and speed.", + "projectColorSpace": "Color space", + "projectWidth": "Width (px)", + "projectHeight": "Height (px)", + "projectResolutionInvalid": "Enter a whole number from 1 to 16384", + "previewFullscreen": "Aperçu plein écran", + "exitPreviewFullscreen": "Quitter le plein écran", + "previewGoToStart": "Aller au début", + "previewPreviousFrame": "Image précédente", + "previewNextFrame": "Image suivante", + "softwareUpdates": "Mises à jour", + "checkForUpdates": "Rechercher des mises à jour", + "automaticallyCheckUpdates": "Rechercher automatiquement les mises à jour", + "updatesUnavailable": "Les mises à jour sont indisponibles pour cette version.", + "updateCheckFailed": "Impossible de rechercher les mises à jour. Réessayez.", + "agentSettings": "Agent", + "agentSaveSettingsFailed": "Impossible d’enregistrer les réglages de l’Agent.", + "agentDeleteProviderTitle": "Supprimer le fournisseur ?", + "agentDeleteProviderDescription": "« {providerName} » et sa clé API enregistrée seront supprimés de cet appareil.", + "agentProviderRequired": "Ajoutez un fournisseur avant d’activer l’assistant.", + "agentUseSelectedModel": "Les nouvelles requêtes de l’Agent utiliseront le modèle sélectionné.", + "agentEnable": "Activer l’Agent", + "agentDefaultModel": "Modèle par défaut", + "agentConfigureModel": "Configurer les modèles", + "agentSelectModel": "Choisir un modèle", + "agentModelUnavailable": "Le modèle de cette conversation est indisponible. Choisissez un autre modèle pour démarrer une nouvelle conversation.", + "agentModelChangeSession": "Changer de modèle démarre une nouvelle session de l’Agent.", + "agentCustomProviders": "Fournisseurs personnalisés", + "agentProviderStorageDescription": "Les métadonnées du fournisseur sont stockées localement. Les clés API sont conservées dans le gestionnaire d’identifiants du système.", + "agentAddProvider": "Ajouter un fournisseur", + "agentBackToProviders": "Retour aux fournisseurs", + "agentLoadSettingsFailed": "Impossible de charger les réglages de l’Agent. Réessayer", + "agentEnableProvider": "Activer le fournisseur", + "agentEditProvider": "Modifier le fournisseur", + "agentDeleteProvider": "Supprimer le fournisseur", + "agentModelIdsUnique": "Les identifiants de modèle doivent être uniques.", + "agentEditProviderTitle": "Modifier le fournisseur", + "agentProviderEndpointDescription": "Configurez un endpoint Chat Completions compatible avec OpenAI.", + "agentSaveProvider": "Enregistrer le fournisseur", + "agentProviderConfiguration": "Configuration du fournisseur", + "agentAuthenticationAndModels": "Authentification et modèles", + "agentApiType": "Type d’API", + "agentOpenAiChatCompletions": "OpenAI Completions", + "agentBaseUrl": "URL de base", + "agentApiKey": "Clé API", + "agentProviderNameHint": "Mon fournisseur", + "agentApiKeyOptional": "Facultatif pour les endpoints qui ne nécessitent pas d’authentification.", + "agentApiKeyKeep": "Laissez ce champ vide pour conserver la clé enregistrée.", + "agentOptional": "Facultatif", + "agentApiKeyOneLine": "La clé API doit tenir sur une seule ligne.", + "agentRemoveSavedApiKey": "Supprimer la clé API enregistrée", + "agentModels": "Modèles", + "agentAddModel": "Ajouter un modèle", + "agentRequiredField": "Ce champ est obligatoire.", + "agentInvalidBaseUrl": "Saisissez une URL de base HTTP(S) sans identifiants, requête ni fragment.", + "agentModelId": "Identifiant du modèle", + "agentContextWindow": "Fenêtre de contexte", + "agentMaxOutputTokens": "Sortie maximale", + "agentMaxOutputBelowContext": "Doit être inférieur à la fenêtre de contexte.", + "agentDeleteModel": "Supprimer le modèle", + "agentPositiveInteger": "Saisissez un entier positif.", + "agentConfigurationReadFailed": "Impossible de lire la configuration de l’Agent. Vérifiez les réglages et réessayez.", + "agentConfigurationRequired": "Configurez et activez d’abord l’Agent dans les réglages.", + "agentSessionRestoreFailed": "Impossible de restaurer la session de l’Agent. Réessayez plus tard.", + "select": "Sélectionner", + "projectLocation": "Emplacement d’enregistrement des projets", + "projectLocationNotSet": "Non défini", + "resourceLocation": "Emplacement de stockage des ressources", + "resourceLocationNotSet": "Non défini", + "loadProjectLocationFailed": "Impossible de charger l’emplacement d’enregistrement des projets.", + "saveProjectLocationFailed": "Impossible d’enregistrer l’emplacement des projets.", + "loadResourceLocationFailed": "Impossible de charger l’emplacement de stockage des ressources.", + "saveResourceLocationFailed": "Impossible d’enregistrer l’emplacement des ressources.", + "downloadAndContinue": "Télécharger et continuer", + "downloadInBackground": "Télécharger en arrière-plan", + "downloadingResource": "Téléchargement…", + "processingResourceDownloadFailed": "Impossible de télécharger la ressource de reconnaissance vocale. Réessayez.", + "transcriptionResourceRequired": "Pour générer des sous-titres, vous devez d’abord télécharger un modèle de reconnaissance vocale.", + "removeBackground": "Supprimer l’arrière-plan", + "startBackgroundRemoval": "Supprimer l’arrière-plan", + "backgroundRemovalResourceRequired": "La suppression de l’arrière-plan nécessite un modèle local. Elle démarre automatiquement après le téléchargement.", + "backgroundRemovalDownloadTask": "Télécharger la ressource de suppression d’arrière-plan", + "backgroundRemovalResourceName": "Modèle de suppression d’arrière-plan", + "backgroundRemovalTaskStarted": "Suppression de l’arrière-plan démarrée", + "backgroundRemovalApplying": "Remplacement du média du clip", + "backgroundRemovalComplete": "Suppression de l’arrière-plan terminée", + "backgroundRemovalFailed": "Échec de la suppression de l’arrière-plan", + "backgroundRemovalDestructiveHint": "Le média transparent généré remplacera ce clip. Vous pouvez utiliser Annuler pour restaurer le clip d’origine.", + "startBackgroundRemovalFailed": "Impossible de démarrer la suppression de l’arrière-plan. Vérifiez le média ou attendez la fin de la tâche de traitement en cours.", + "agentContextBudgetExceeded": "Le budget d’entrée ne suffit pas pour les instructions, outils et message. Augmentez le contexte ou réduisez la sortie maximale.", + "agentAuthenticationFailed": "Échec de l’authentification. Vérifiez la clé API et les autorisations.", + "agentConnectionFailed": "Connexion impossible ou délai dépassé. Vérifiez la Base URL et le réseau.", + "agentProtocolFailed": "La réponse ne correspond pas au type d’API choisi ou le flux est incomplet.", + "agentContextBudgetTooSmall": "Réservez plus d’espace pour les instructions système. Augmentez le contexte ou réduisez la sortie maximale.", + "agentCompacting": "Organisation du contexte…", + "agentEditing": "Modification en cours…", + "agentVerifying": "Vérification des résultats…", + "agentTurnLimitReached": "La tâche a atteint sa limite d’exécution. Les modifications sont enregistrées. Envoyez « Continuer » pour reprendre.", + "agentRecoveryRequired": "Le résultat précédent est incertain. Reprenez pour vérifier les opérations enregistrées ; les modifications non confirmées ne seront pas répétées.", + "agentExportReplyFailed": "Vidéo exportée. La réponse récapitulative a échoué. Réessayez le résumé sans répéter le montage ni l’exportation.", + "agentRetrySummary": "Réessayer le résumé", + "agentResumeTask": "Reprendre la tâche", + "agentTaskInterrupted": "La tâche a été interrompue. Reprenez depuis la progression enregistrée.", + "downloadSubtitleModel": "Télécharger le modèle de sous-titres", + "downloadModelAction": "Télécharger", + "subtitleEngineUnavailable": "Le modèle est installé, mais le moteur de sous-titres n’a pas pu démarrer. Réparez le moteur ; il n’est pas nécessaire de télécharger à nouveau le modèle.", + "backgroundTaskDetails": "Détails de la tâche", + "backgroundTaskFailed": "Échec", + "backgroundTaskCompleted": "Terminé", + "captionWrapLines": "Renvoyer les sous-titres à la ligne", + "captionSingleLine": "Afficher les sous-titres sur une ligne", + "noMatchingCaptions": "Aucun sous-titre correspondant", + "subtitleResourcesRequired": "Ces ressources sont nécessaires aux sous-titres. La génération démarrera automatiquement après le téléchargement.", + "subtitleResourcesDownloadSize": "À télécharger : {size}", + "pauseDownload": "Suspendre", + "resumeDownload": "Reprendre", + "downloadPaused": "En pause", + "cancelResourceDownloadTitle": "Annuler le téléchargement ?", + "cancelResourceDownloadMessage": "Le téléchargement s’arrêtera. La progression de la ressource en cours peut être perdue.", + "continueDownload": "Continuer le téléchargement", + "cancelDownload": "Annuler le téléchargement", + "speechResourceStage": "Ressource de reconnaissance vocale", + "translationResourceStage": "Ressource de traduction", + "subtitleResourceDownloadTask": "Télécharger les ressources vocales et de traduction", + "downloadingSpeechModel": "Téléchargement du modèle vocal", + "downloadingTranslationModel": "Téléchargement du modèle de traduction", + "selectProject": "Sélectionner un projet", + "searchProjects": "Rechercher des projets", + "noMatchingProjects": "Aucun projet correspondant", + "projectLocationMissing": "Le dossier n’existe pas. Il sera créé lors de la création d’un projet.", + "projectLocationUnavailable": "L’emplacement de sauvegarde est indisponible. Connectez le disque ou vérifiez le réseau et réessayez, ou changez d’emplacement.", + "projectLocationNotWritable": "L’emplacement de sauvegarde n’est pas accessible en écriture. Vérifiez les autorisations ou changez d’emplacement.", + "projectLocationCreateFailed": "Impossible de créer le dossier de sauvegarde ou d’y écrire. Vérifiez les autorisations ou changez d’emplacement.", + "removeProjectFromSidebar": "Retirer de la barre latérale", + "projectRemoved": "Projet retiré. Les fichiers locaux et les conversations sont conservés.", + "agentNoConversations": "Aucune conversation pour le moment", + "collapseProject": "Réduire le projet", + "expandProject": "Développer le projet", + "agentDeleteConfirmation": "Supprimer définitivement « {title} » et tous ses messages ? Cette action est irréversible. Les fichiers locaux du projet ne seront pas affectés.", + "agentEmptyTrashConfirmation": "Supprimer définitivement toutes les conversations de la corbeille ? Cette action est irréversible. Les fichiers locaux du projet ne seront pas affectés.", + "checkingForUpdates": "Recherche de mises à jour…", + "appIsUpToDate": "L’application est à jour.", + "downloadingUpdate": "Téléchargement : {progress} %", + "updateAvailable": "La version {version} est disponible.", + "downloadUpdate": "Télécharger la mise à jour", + "restartToUpdate": "Redémarrer et mettre à jour", + "updateOperationFailed": "Mise à jour impossible. Terminez les tâches en cours et réessayez.", + "windowMinimize": "Réduire", + "windowMaximize": "Agrandir", + "windowRestore": "Restaurer", + "workspaceAgent": "Assistant", + "workspaceCut": "Montage", + "noAvailableOptions": "Aucune option disponible", + "composerReferenceInvalid": "Une référence est devenue invalide. Revenez à son projet ou supprimez-la.", + "durationSeconds": "{seconds} s", + "durationMinutesSeconds": "{minutes} min {seconds} s", + "projectNameInvalid": "Nom de projet invalide", + "projectLocationDefaultUnavailable": "Impossible d’accéder à l’emplacement par défaut des projets. Sélectionnez-le à nouveau dans les paramètres.", + "chooseProjectLocation": "Sélectionnez d’abord un emplacement de sauvegarde des projets dans les paramètres.", + "untitledTimeline": "Timeline sans titre", + "primarySequence": "Séquence principale", + "primaryStoryline": "Scénario principal", + "projectSessionClosed": "La session du projet est fermée. Rouvrez le projet.", + "timelineSessionClosed": "La session de la timeline est fermée. Rouvrez la timeline.", + "timelineMissing": "La timeline n’existe pas ou a été supprimée.", + "timelineInUse": "La timeline est utilisée et ne peut pas encore être supprimée.", + "timelineHasBackgroundTasks": "Terminez les tâches en arrière-plan de la timeline avant de la supprimer.", + "timelineRequired": "Un projet doit conserver au moins une timeline.", + "mediaReadFailed": "Impossible de lire le média", + "mediaImportFailed": "Impossible d’importer le média", + "unsupportedMediaType": "Seuls les fichiers vidéo, audio et image peuvent être importés.", + "mediaNoVideoTracks": "Le média ne contient aucune piste vidéo utilisable", + "mediaDurationOutOfRange": "La durée du média dépasse la plage de la timeline", + "resourceDownloadHttpFailed": "Échec du téléchargement (HTTP {statusCode})", + "resourceChecksumFailed": "La vérification du modèle a échoué. Téléchargez à nouveau la ressource.", + "subtitleLanguageAf": "afrikaans", + "subtitleLanguageAm": "amharique", + "subtitleLanguageAr": "arabe", + "subtitleLanguageAst": "asturien", + "subtitleLanguageAz": "azerbaïdjanais", + "subtitleLanguageBa": "bachkir", + "subtitleLanguageBe": "biélorusse", + "subtitleLanguageBg": "bulgare", + "subtitleLanguageBn": "bengali", + "subtitleLanguageBr": "breton", + "subtitleLanguageBs": "bosniaque", + "subtitleLanguageCa": "catalan", + "subtitleLanguageCeb": "cebuano", + "subtitleLanguageCs": "tchèque", + "subtitleLanguageCy": "gallois", + "subtitleLanguageDa": "danois", + "subtitleLanguageDe": "allemand", + "subtitleLanguageEl": "grec", + "subtitleLanguageEn": "anglais", + "subtitleLanguageEs": "espagnol", + "subtitleLanguageEt": "estonien", + "subtitleLanguageFa": "persan", + "subtitleLanguageFf": "peul", + "subtitleLanguageFi": "finnois", + "subtitleLanguageFr": "français", + "subtitleLanguageFy": "frison occidental", + "subtitleLanguageGa": "irlandais", + "subtitleLanguageGd": "gaélique écossais", + "subtitleLanguageGl": "galicien", + "subtitleLanguageGu": "goudjarati", + "subtitleLanguageHa": "haoussa", + "subtitleLanguageHe": "hébreu", + "subtitleLanguageHi": "hindi", + "subtitleLanguageHr": "croate", + "subtitleLanguageHt": "créole haïtien", + "subtitleLanguageHu": "hongrois", + "subtitleLanguageHy": "arménien", + "subtitleLanguageId": "indonésien", + "subtitleLanguageIg": "igbo", + "subtitleLanguageIlo": "ilocano", + "subtitleLanguageIs": "islandais", + "subtitleLanguageIt": "italien", + "subtitleLanguageJa": "japonais", + "subtitleLanguageJv": "javanais", + "subtitleLanguageKa": "géorgien", + "subtitleLanguageKk": "kazakh", + "subtitleLanguageKm": "khmer", + "subtitleLanguageKn": "kannada", + "subtitleLanguageKo": "coréen", + "subtitleLanguageLb": "luxembourgeois", + "subtitleLanguageLg": "ganda", + "subtitleLanguageLn": "lingala", + "subtitleLanguageLo": "lao", + "subtitleLanguageLt": "lituanien", + "subtitleLanguageLv": "letton", + "subtitleLanguageMg": "malgache", + "subtitleLanguageMk": "macédonien", + "subtitleLanguageMl": "malayalam", + "subtitleLanguageMn": "mongol", + "subtitleLanguageMr": "marathi", + "subtitleLanguageMs": "malais", + "subtitleLanguageMy": "birman", + "subtitleLanguageNe": "népalais", + "subtitleLanguageNl": "néerlandais", + "subtitleLanguageNo": "norvégien", + "subtitleLanguageNs": "sotho du Nord", + "subtitleLanguageOc": "occitan", + "subtitleLanguageOr": "odia", + "subtitleLanguagePa": "pendjabi", + "subtitleLanguagePl": "polonais", + "subtitleLanguagePs": "pachto", + "subtitleLanguagePt": "portugais", + "subtitleLanguageRo": "roumain", + "subtitleLanguageRu": "russe", + "subtitleLanguageSd": "sindhi", + "subtitleLanguageSi": "cingalais", + "subtitleLanguageSk": "slovaque", + "subtitleLanguageSl": "slovène", + "subtitleLanguageSo": "somali", + "subtitleLanguageSq": "albanais", + "subtitleLanguageSr": "serbe", + "subtitleLanguageSs": "swati", + "subtitleLanguageSu": "soundanais", + "subtitleLanguageSv": "suédois", + "subtitleLanguageSw": "swahili", + "subtitleLanguageTa": "tamoul", + "subtitleLanguageTh": "thaï", + "subtitleLanguageTl": "tagalog", + "subtitleLanguageTn": "tswana", + "subtitleLanguageTr": "turc", + "subtitleLanguageUk": "ukrainien", + "subtitleLanguageUr": "ourdou", + "subtitleLanguageUz": "ouzbek", + "subtitleLanguageVi": "vietnamien", + "subtitleLanguageWo": "wolof", + "subtitleLanguageXh": "xhosa", + "subtitleLanguageYi": "yiddish", + "subtitleLanguageYo": "yoruba", + "subtitleLanguageYue": "cantonais", + "subtitleLanguageZh": "chinois", + "subtitleLanguageZu": "zoulou", + "linearRec2020": "Rec.2020 linéaire", + "diagnostics": "Diagnostic", + "exportDiagnostics": "Exporter le diagnostic", + "exportDiagnosticsFailed": "Impossible d’exporter le diagnostic. Réessayez.", + "exportDiagnosticsSucceeded": "Diagnostic enregistré." +} diff --git a/lib/l10n/app_it.arb b/lib/l10n/app_it.arb new file mode 100644 index 0000000..ae5aec9 --- /dev/null +++ b/lib/l10n/app_it.arb @@ -0,0 +1,889 @@ +{ + "projectsNone": "Nessun progetto", + "agentConversations": "Conversazioni", + "renameConversationTitle": "Rinomina chat", + "renameConversationDescription": "Usa un nome breve e facile da riconoscere.", + "showMoreConversations": "Mostra altro", + "showFewerConversations": "Mostra meno", + "agentNewConversation": "Nuova conversazione", + "agentElapsedTime": "Durata {duration}", + "agentConversationActions": "Azioni della conversazione", + "agentMoveToTrash": "Sposta nel cestino", + "agentTrash": "Cestino", + "agentRestore": "Ripristina", + "agentEmptyTrash": "Svuota cestino", + "agentDeleteForever": "Elimina definitivamente", + "agentConversationLocation": "Posizione delle conversazioni", + "agentChooseExistingConversations": "Scegli conversazioni esistenti", + "agentMoveConversations": "Sposta conversazioni", + "agentLocationUnavailable": "Posizione delle conversazioni non disponibile", + "agentLocationBusy": "Attendi la fine delle conversazioni attive", + "agentRelinkProvider": "Ricollega provider", + "@@locale": "it", + "settings": "Impostazioni", + "closeSettings": "Chiudi le impostazioni", + "general": "Generale", + "appearance": "Aspetto", + "theme": "Tema", + "system": "Segui il sistema", + "light": "Chiaro", + "dark": "Scuro", + "saveAppearanceFailed": "Impossibile salvare l'aspetto. Per favore riprova.", + "loadAppearanceFailed": "Impossibile caricare l'aspetto. Seleziona di nuovo un tema.", + "cancel": "Annulla", + "save": "Salva", + "create": "Crea", + "close": "Chiudi", + "retry": "Riprova", + "name": "Nome", + "enterName": "Inserisci un nome", + "invalidName": "I nomi non possono contenere separatori di percorso o caratteri di controllo", + "projectName": "Nome del progetto", + "newProject": "Nuovo progetto", + "openProject": "Apri progetto", + "openProjectMore": "Apri un altro progetto", + "projects": "Progetti", + "projectsEmpty": "Nessun progetto", + "openingWorkspace": "Apertura dell’area di lavoro…", + "loadProjectsFailed": "Impossibile caricare i progetti", + "backToProjects": "Torna al montaggio", + "timelines": "Timeline", + "timelineLimitReached": "Ogni progetto può contenere fino a {count} timeline.", + "timelineName": "Nome della timeline", + "defaultTimelineName": "Timeline {index}", + "newTimeline": "Nuova timeline", + "noTimelines": "Nessuna timeline", + "activeTimeline": "Timeline corrente", + "timelineUnavailable": "Timeline non disponibile", + "projectNoTimelines": "Questo progetto non contiene ancora timeline", + "createTimelineHint": "Crea una timeline nella sezione “Timeline” a sinistra per iniziare il montaggio.", + "createTimelineChat": "Crea una timeline per iniziare la chat", + "editingFirstLayout": "Priorità al montaggio", + "agentEditingLayout": "Agente e montaggio", + "agentLayoutDescription": "Pianifica, collabora ed esegui", + "editingLayoutDescription": "Anteprima, montaggio e rifinitura", + "saveHere": "Salva qui", + "selectDirectoryFailed": "Impossibile selezionare una directory. Controlla i permessi di sistema.", + "operationFailed": "Operazione fallita. Per favore riprova.", + "collapseSidebar": "Comprimi la barra laterale", + "expandSidebar": "Espandi la barra laterale", + "expandEditor": "Espandi area di montaggio", + "collapseProperties": "Comprimi proprietà", + "expandProperties": "Espandi proprietà", + "layout": "Layout", + "materials": "Media", + "all": "Tutti", + "video": "Video", + "audio": "Audio", + "image": "Immagine", + "picture": "Immagine", + "captions": "Sottotitoli", + "text": "Testo", + "noMedia": "Nessun media", + "mediaCategory": "Categoria media", + "captionTasks": "Attività sottotitoli", + "listLayout": "Visualizzazione elenco", + "gridLayout": "Visualizzazione griglia", + "addToTimeline": "Aggiungi alla timeline", + "rename": "Rinomina", + "renameMedia": "Rinomina media", + "removeMedia": "Rimuovi media", + "remove": "Rimuovi", + "revealFinder": "Mostra nel Finder", + "revealFileManager": "Mostra nel gestore file", + "dropToAdd": "Rilascia per aggiungere", + "timelineDropToStart": "Trascina qui i contenuti multimediali per iniziare.", + "dragMediaHint": "Trascina qui video, audio o immagini\nI file originali rimangono nella posizione corrente", + "transcribe": "Trascrivi", + "generateCaptions": "Genera sottotitoli", + "play": "Riproduci", + "pause": "Pausa", + "retryPreview": "Riprova l'anteprima", + "canvasRatio": "Rapporto d'aspetto", + "noPreviewContent": "Nessun contenuto da visualizzare in anteprima sulla timeline", + "nativePreviewUnsupported": "L'anteprima nativa non è disponibile su questa piattaforma", + "canvasTransformFailed": "Impossibile trasformare la tela. Per favore riprova.", + "undo": "Annulla", + "redo": "Ripristina", + "deleteSelectedClips": "Elimina i clip selezionati", + "splitAtPlayhead": "Dividi in playhead", + "trimLeft": "Taglia a sinistra", + "trimRight": "Taglia a destra", + "trimLeftTooltip": "Rimuovi a sinistra della testina e conserva la destra", + "trimRightTooltip": "Rimuovi a destra della testina e conserva la sinistra", + "currentSequence": "Sequenza corrente", + "projectProperties": "Proprietà del progetto", + "canvasSize": "Dimensioni del canvas", + "frameRate": "Frequenza fotogrammi", + "duration": "Durata", + "totalDuration": "Durata totale", + "clipDuration": "Durata della clip", + "seconds": "secondi", + "clip": "Clip", + "unnamedClip": "Clip senza nome", + "gap": "Spazio vuoto", + "compoundClip": "Clip composta", + "textClip": "Clip di testo", + "pictureProperties": "Immagine", + "position": "Posizione", + "rotation": "Rotazione", + "scale": "Scala", + "size": "Dimensioni", + "transform": "Trasformazione", + "resetPosition": "Ripristina posizione", + "keepAspectRatio": "Blocca le proporzioni", + "alignment": "Allineamento", + "alignLeft": "Allinea a sinistra", + "alignRight": "Allinea a destra", + "alignTop": "Allinea in alto", + "alignBottom": "Allinea il fondo", + "alignHorizontalCenter": "Centra orizzontalmente", + "alignVerticalCenter": "Centra verticalmente", + "volume": "Volume", + "gain": "Guadagno", + "mute": "Disattiva audio", + "unmute": "Riattiva audio", + "resetVolume": "Reimposta il volume", + "invalidGain": "Immettere un valore compreso tra -90 e +12", + "animation": "Animazione", + "keyframes": "Fotogrammi chiave", + "removeAllKeyframes": "Rimuovi tutti i fotogrammi chiave", + "linear": "Lineare", + "easeIn": "Accelerazione graduale", + "easeOut": "Decelerazione graduale", + "easeInOut": "Accelerazione e decelerazione graduali", + "basic": "Base", + "mask": "Maschera", + "addMask": "Aggiungi maschera", + "deleteMask": "Elimina maschera", + "resetMask": "Reimposta la maschera", + "enableMask": "Abilita maschera", + "disableMask": "Disabilita maschera", + "moveMaskUp": "Sposta la maschera verso l'alto", + "moveMaskDown": "Sposta la maschera verso il basso", + "rectangle": "Rettangolo", + "ellipse": "Ellisse", + "invert": "Inverti", + "feather": "Sfumatura", + "add": "Somma", + "subtract": "Sottrazione", + "intersect": "Intersezione", + "initialRegion": "Area iniziale", + "none": "Nessuno", + "color": "Colore", + "fontSize": "Dimensione del carattere", + "outlineWidth": "Spessore contorno", + "outlineColor": "Colore contorno", + "captionBaseline": "Linea di base sottotitoli", + "content": "Testo", + "start": "Inizio", + "time": "Tempo", + "speed": "Velocità", + "speedSegmentCount": "{count} segmenti di velocità", + "splitSpeedAtPlayhead": "Dividi velocità sulla testina", + "speedChange": "Velocità", + "speedMode": "Modalità velocità", + "constantSpeed": "Velocità costante", + "segmentedSpeed": "Velocità segmentata", + "speedNotAvailable": "I controlli di velocità non sono ancora disponibili", + "custom": "Personalizzato", + "invalidNumber": "Valore non valido", + "mediaUnavailable": "Supporto non disponibile", + "mediaMissing": "Media mancanti", + "mediaColorSpace": "Spazio colore multimediale", + "mediaColorInterpretation": "Interpretazione del colore dei media", + "colorInfoNotLoaded": "Informazioni sul colore non caricate", + "unknownColorSpace": "Spazio colore sconosciuto. Visualizzato come Rec.709.", + "colorBackendUnsupported": "Il backend attuale non supporta l'interpretazione del colore dei media.", + "loadClipPropertiesFailed": "Impossibile leggere le proprietà della clip", + "updatePictureFailed": "Impossibile aggiornare le proprietà dell'immagine", + "updateVolumeFailed": "Impossibile aggiornare il volume", + "updateMaskFailed": "Impossibile aggiornare la maschera", + "updateKeyframesFailed": "Impossibile aggiornare i fotogrammi chiave", + "maskPreviewFailed": "Impossibile preparare l'anteprima della maschera", + "alignClipFailed": "Impossibile allineare la clip. Attendi l'anteprima, quindi riprova.", + "invalidTransform": "La scala deve essere compresa tra 1% e 10.000%. La posizione e l'angolo devono essere numeri validi.", + "editFailed": "Impossibile modificare. Controllare l'input e l'intervallo di tempo.", + "addMediaFailed": "Impossibile aggiungere contenuti multimediali. Per favore riprova.", + "deleteCaption": "Elimina sottotitolo", + "mergeCaptions": "Unisci sottotitoli", + "captionDeleted": "Sottotitolo eliminato", + "captionChanged": "Le sottotitoli sono cambiate. Per favore riprova.", + "captionEditChanged": "Le sottotitoli sono cambiate. Per favore modifica di nuovo.", + "assistantHint": "Descrivi la tua idea di editing", + "configureAgentHint": "Configura il servizio dell'agente per iniziare a chattare", + "agentRestartHint": "Configura il servizio dell'agente, quindi riavvia l'app.", + "replyInterrupted": "Risposta interrotta", + "replying": "Risposta in corso…", + "stopReply": "Interrompi risposta", + "sendMessage": "Invia messaggio", + "addAttachment": "Aggiungi allegato (non ancora disponibile)", + "replyFailed": "La risposta non è riuscita. Controlla la connessione o riprova più tardi.", + "mcpService": "Servizio MCP", + "listenPort": "Porta", + "accessToken": "Token di accesso", + "copyAccessToken": "Copia token di accesso", + "accessTokenCopied": "Token di accesso copiato", + "loadMcpFailed": "Impossibile caricare le impostazioni MCP. Riprova", + "saveMcpFailed": "Impossibile salvare le impostazioni MCP. Per favore riprova.", + "retryStart": "Riprovare ad avviare", + "invalidPort": "La porta deve essere compresa tra 1 e 65535", + "loadingSettings": "Caricamento impostazioni…", + "starting": "Avvio…", + "stopping": "Arresto…", + "disabled": "Disattivato", + "running": "In esecuzione", + "startFailed": "Impossibile avviare", + "saved": "Salvato", + "unsaved": "Non salvato", + "saving": "Salvataggio…", + "pendingSave": "Salvataggio in sospeso", + "notApplied": "Non applicato", + "enable": "Attiva", + "disable": "Disattiva", + "type": "Tipo", + "status": "Stato", + "file": "File", + "unboundMedia": "Nessun media associato", + "unboundAudio": "Nessuna traccia audio associata", + "vertical": "Verticale", + "language": "Lingua", + "saveLanguageFailed": "Impossibile salvare la lingua. Per favore riprova.", + "loadLanguageFailed": "Impossibile caricare la lingua. Seleziona di nuovo.", + "propertiesFirstLayout": "Prima le proprietà", + "defaultLayout": "Disposizione predefinita", + "separateVocals": "Separa voce", + "detachAudio": "Separa audio", + "restoreAudio": "Ripristina audio", + "audioDetached": "Audio separato", + "addAll": "Aggiungi tutto", + "preparingMedia": "Preparazione media…", + "cancelling": "Annullamento…", + "cancelled": "Annullato", + "interruptedTask": "Compito interrotto. Ricomincia per continuare", + "auto": "Automatico", + "autoDetect": "Rilevamento automatico", + "noTranslation": "Non tradurre", + "sourceLanguage": "Lingua di origine", + "translationLanguage": "Lingua di destinazione", + "transcriptionNotConfigured": "La trascrizione non è configurata. Installa il componente di riconoscimento e il modello Whisper Turbo.", + "translationNotConfigured": "La traduzione dei sottotitoli non è configurata. Puoi generare sottotitoli nella lingua di origine.", + "sourceLanguageUnknown": "Impossibile determinare una lingua di origine per la traduzione.", + "startTranscriptionFailed": "Impossibile avviare la trascrizione. Controlla il supporto o attendi il completamento dell'attività corrente.", + "placeMediaFirst": "Posiziona questo supporto sulla timeline prima di applicare i sottotitoli.", + "placeTranslationMediaFirst": "Posiziona i media corrispondenti sulla timeline prima di applicare i sottotitoli tradotti.", + "selectTargetClip": "Seleziona la clip di destinazione", + "timelineChanged": "La sequenza temporale è cambiata. Seleziona nuovamente la clip di destinazione.", + "transcriptionAccessFailed": "Trascrizione non riuscita: componente, modello o supporto di origine inaccessibile (notConfigured)", + "transcriptionNoAudio": "Trascrizione non riuscita: nessun audio riconoscibile nel supporto o nella traccia selezionata (noAudio)", + "transcriptionInvalidResult": "Trascrizione non riuscita: restituito un file di sottotitoli non valido (invalidResult)", + "transcriptionWorkerExited": "Trascrizione non riuscita: il componente di riconoscimento è terminato in modo imprevisto (workerExited)", + "transcriptionProcessingFailed": "Trascrizione non riuscita: elaborazione nativa non riuscita (processingFailed)", + "transcriptionFailed": "La trascrizione non è riuscita. Controlla il componente, il modello, la traccia audio e la durata", + "transcribing": "Trascrizione…", + "captionsGenerated": "Sottotitoli generati", + "cancelTranscription": "Annulla trascrizione", + "applyCaptions": "Applica sottotitoli", + "preparingTranslation": "Preparazione traduzione…", + "translatingCaptions": "Traduzione sottotitoli…", + "cancellingTranslation": "Annullamento traduzione…", + "translatedCaptionsGenerated": "Sottotitoli tradotti generati", + "translationCancelled": "Traduzione annullata", + "translationInterrupted": "Traduzione interrotta", + "cancelTranslation": "Annulla traduzione", + "editorServiceUnavailable": "Servizio di modifica non disponibile. Riaprire il progetto.", + "mcpUnavailable": "Connessione MCP non disponibile. Controlla la porta locale e il token.", + "openTimelineFailed": "Impossibile aprire la sequenza temporale", + "noTimelineSequence": "Questa timeline non contiene sequenze.", + "waitingForProject": "In attesa dell'apertura di un progetto", + "hold": "Mantieni", + "noImportableFiles": "Nessun file importabile ricevuto", + "virtualFilesUnsupported": "Trascina i file originali dal file manager. I file virtuali non sono ancora supportati.", + "editorSessionStartFailed": "Impossibile aprire l’editor della timeline", + "previewStartFailed": "Impossibile avviare l'anteprima nativa", + "previewInvalidTrack": "La traccia audio o video selezionata non esiste nel media.", + "previewMissingBinding": "Mancano i collegamenti multimediali. Impossibile visualizzare l'anteprima di questa sequenza temporale.", + "previewUnsupportedEdits": "Questa sequenza temporale contiene modifiche che non sono ancora supportate dall'anteprima.", + "previewUnsupportedConfiguration": "Questa configurazione di anteprima non è supportata sulla piattaforma o sulla versione del sistema corrente.", + "previewHdrUnsupported": "I contenuti multimediali HDR richiedono la mappatura dei toni per l'anteprima SDR. Il sistema attuale o la configurazione di anteprima non lo supportano.", + "previewAudioOutOfRange": "La clip audio supera l'intervallo della traccia sorgente e non è possibile visualizzarne l'anteprima.", + "previewResourceMissing": "Il supporto di anteprima non esiste più. Individua nuovamente il file originale.", + "previewInvalidComposition": "Configurazione della composizione video non valida. Impossibile creare l'anteprima.", + "previewInvalidData": "Dati di anteprima non validi. Per favore riprova.", + "previewFailed": "Anteprima non riuscita. Controlla l'accesso ai contenuti multimediali e riprova.", + "chatFailed": "Impossibile completare la conversazione. Controlla la configurazione del servizio o riprova più tardi.", + "delete": "Elimina", + "pinTimeline": "Fissa timeline", + "unpinTimeline": "Rimuovi timeline fissata", + "deleteTimelineConfirmation": "Eliminare «{name}» e la cronologia delle modifiche? Questa azione non può essere annullata.", + "@deleteTimelineConfirmation": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "processingFailed": "Elaborazione non riuscita", + "noMatchingOptions": "Nessuna opzione corrispondente", + "removeMediaConfirmation": "Rimuovere \"{name}\" dalla libreria? I clip esistenti, la cronologia e il file originale verranno conservati.", + "@removeMediaConfirmation": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "mediaAdded": "Aggiunti {count} riferimenti ai media", + "@mediaAdded": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "duplicatesSkipped": "File duplicati {count} saltati", + "@duplicatesSkipped": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mediaCount": "{count} elementi multimediali", + "importMedia": "Importa", + "@mediaCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "noMediaOfType": "Nessun supporto {type}", + "@noMediaOfType": { + "placeholders": { + "type": { + "type": "String" + } + } + }, + "captionsImported": "Sottotitoli {count} importate", + "@captionsImported": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "editCaptionError": "Impossibile modificare i sottotitoli: {message}", + "@editCaptionError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "mcpStartError": "Impossibile avviare MCP: {message}", + "@mcpStartError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "manualColorSpace": "Selezionato manualmente: {name}", + "@manualColorSpace": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "detectedColorSpace": "Rilevato: {name}", + "@detectedColorSpace": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "keyframeLabel": "Fotogramma chiave di {channel}", + "@keyframeLabel": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "maskMode": "Modalità combinata: {mode}", + "@maskMode": { + "placeholders": { + "mode": { + "type": "String" + } + } + }, + "keyframeCount": "{count} fotogrammi chiave", + "@keyframeCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "toggleKeyframe": "{action} fotogramma chiave di {channel}", + "@toggleKeyframe": { + "placeholders": { + "action": { + "type": "String" + }, + "channel": { + "type": "String" + } + } + }, + "previousKeyframe": "Fotogramma chiave precedente di {channel}", + "@previousKeyframe": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "nextKeyframe": "Fotogramma chiave successivo di {channel}", + "@nextKeyframe": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "keyframeSettings": "Impostazioni fotogrammi chiave di {channel}", + "@keyframeSettings": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "selectedClipsHint": "Clip {count} selezionate\nSeleziona una clip per visualizzarne le proprietà", + "@selectedClipsHint": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "transcriptionError": "La trascrizione non è riuscita. Controlla il componente, il modello, la traccia audio e la durata ({code})", + "@transcriptionError": { + "placeholders": { + "code": { + "type": "String" + } + } + }, + "captionsAdded": "Aggiunte sottotitoli {count}. Modificali nel pannello delle proprietà.", + "@captionsAdded": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "translatedCaptionsAdded": "Aggiunti i sottotitoli tradotti {count}. Modificali nel pannello delle proprietà.", + "@translatedCaptionsAdded": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "applyCaptionsError": "Impossibile applicare i sottotitoli: {message}", + "@applyCaptionsError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "applyTranslatedCaptionsError": "Impossibile applicare i sottotitoli tradotti: {message}", + "@applyTranslatedCaptionsError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "recognizedCaptions": "{count} sottotitoli riconosciuti", + "@recognizedCaptions": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "captionCount": "{count} sottotitoli", + "@captionCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "translationFailed": "Traduzione non riuscita: {message}", + "@translationFailed": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "translatedCaptionCount": "{count} sottotitoli in {language}", + "@translatedCaptionCount": { + "placeholders": { + "count": { + "type": "int" + }, + "language": { + "type": "String" + } + } + }, + "previewParameterError": "Parametri di anteprima non validi: {message}", + "@previewParameterError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "mediaOffline": "File multimediali offline o non disponibili: {names}", + "@mediaOffline": { + "placeholders": { + "names": { + "type": "String" + } + } + }, + "searchOptions": "Cerca {label}…", + "@searchOptions": { + "placeholders": { + "label": { + "type": "String" + } + } + }, + "loadRecentProjectsFailed": "Impossibile caricare le librerie recenti. È comunque possibile aprire una libreria manualmente.", + "projectAccessFailed": "Progetto non disponibile", + "projectMissingDirectory": "Progetto non trovato", + "recentProjectSaveFailed": "Libreria aperta, ma non è stato possibile salvare il record recente della libreria.", + "lastProjectSaveFailed": "Progetto aperto, ma non è stato possibile salvare l'ultimo record del progetto.", + "enterProjectName": "Inserisci un nome per il progetto", + "projectSwitched": "Il progetto è cambiato. Trascina nuovamente il supporto.", + "notLocalMedia": "Questo supporto non è un file locale", + "revealMediaFailed": "Impossibile mostrare i media nel file manager", + "openMatchingProject": "Apri prima il progetto corrispondente", + "projectMismatch": "La libreria in questa posizione non corrisponde al record. Selezionalo di nuovo con Apri libreria.", + "openProjectFirst": "Apri prima una libreria", + "localFilesOnly": "Trascina i file locali dal file manager", + "foldersUnsupported": "Seleziona i file. Il trascinamento delle cartelle non è ancora supportato.", + "mediaImportCancelled": "Importazione multimediale annullata", + "fileAccessFailed": "Il file è mancante o illeggibile. Controlla la sua posizione e le autorizzazioni", + "registerMediaFailed": "Impossibile registrare il supporto. Per favore riprova", + "mediaNoLongerExists": "I media non esistono più", + "mediaNoTracks": "I contenuti multimediali non dispongono di tracce video o audio utilizzabili", + "invalidMediaDuration": "Durata multimediale non valida", + "mediaInfoUnsupported": "La lettura delle informazioni multimediali non è ancora supportata su questa piattaforma", + "mediaInfoFailed": "Impossibile leggere le informazioni dei media. Controlla il file e i permessi di accesso", + "saveTimelineFailed": "Impossibile salvare la sequenza temporale. Riprova. Le modifiche non salvate rimangono in questa sessione.", + "addKeyframeAction": "Aggiungi", + "backgroundTasks": "Attività in background", + "noBackgroundTasks": "Nessuna attività in background", + "retryTask": "Riprova", + "applyOriginalCaptions": "Applica sottotitoli originali", + "applyTranslatedCaptions": "Applica sottotitoli tradotti", + "subtitleTaskStarted": "Attività dei sottotitoli avviata", + "fitTimeline": "Adatta intera timeline", + "modify": "Modify", + "projectSettings": "Project settings", + "projectSettingsDescription": "Change project output settings while keeping clip timing and speed.", + "projectColorSpace": "Color space", + "projectWidth": "Width (px)", + "projectHeight": "Height (px)", + "projectResolutionInvalid": "Enter a whole number from 1 to 16384", + "previewFullscreen": "Anteprima a schermo intero", + "exitPreviewFullscreen": "Esci da schermo intero", + "previewGoToStart": "Vai all’inizio", + "previewPreviousFrame": "Fotogramma precedente", + "previewNextFrame": "Fotogramma successivo", + "softwareUpdates": "Aggiornamenti", + "checkForUpdates": "Cerca aggiornamenti", + "automaticallyCheckUpdates": "Cerca aggiornamenti automaticamente", + "updatesUnavailable": "Aggiornamenti non disponibili per questa build.", + "updateCheckFailed": "Impossibile cercare aggiornamenti. Riprova.", + "agentSettings": "Agent", + "agentSaveSettingsFailed": "Impossibile salvare le impostazioni dell’Agent.", + "agentDeleteProviderTitle": "Eliminare il provider?", + "agentDeleteProviderDescription": "“{providerName}” e la relativa chiave API salvata verranno rimossi da questo dispositivo.", + "agentProviderRequired": "Aggiungi un provider prima di attivare l’assistente.", + "agentUseSelectedModel": "Le nuove richieste dell’Agent useranno il modello selezionato.", + "agentEnable": "Attiva Agent", + "agentDefaultModel": "Modello predefinito", + "agentConfigureModel": "Configura modelli", + "agentSelectModel": "Seleziona modello", + "agentModelUnavailable": "Il modello di questa conversazione non è disponibile. Seleziona un altro modello per iniziare una nuova conversazione.", + "agentModelChangeSession": "La modifica del modello avvia una nuova sessione dell’Agent.", + "agentCustomProviders": "Provider personalizzati", + "agentProviderStorageDescription": "I metadati del provider vengono salvati localmente. Le chiavi API vengono conservate nell’archivio credenziali di sistema.", + "agentAddProvider": "Aggiungi provider", + "agentBackToProviders": "Torna ai provider", + "agentLoadSettingsFailed": "Impossibile caricare le impostazioni dell’Agent. Riprova", + "agentEnableProvider": "Abilita provider", + "agentEditProvider": "Modifica provider", + "agentDeleteProvider": "Elimina provider", + "agentModelIdsUnique": "Gli ID modello devono essere univoci.", + "agentEditProviderTitle": "Modifica provider", + "agentProviderEndpointDescription": "Configura un endpoint Chat Completions compatibile con OpenAI.", + "agentSaveProvider": "Salva provider", + "agentProviderConfiguration": "Configurazione del provider", + "agentAuthenticationAndModels": "Autenticazione e modelli", + "agentApiType": "Tipo di API", + "agentOpenAiChatCompletions": "OpenAI Completions", + "agentBaseUrl": "URL di base", + "agentApiKey": "Chiave API", + "agentProviderNameHint": "Il mio provider", + "agentApiKeyOptional": "Facoltativa per gli endpoint che non richiedono autenticazione.", + "agentApiKeyKeep": "Lascia vuoto per mantenere la chiave salvata.", + "agentOptional": "Facoltativo", + "agentApiKeyOneLine": "La chiave API deve essere su una sola riga.", + "agentRemoveSavedApiKey": "Rimuovi la chiave API salvata", + "agentModels": "Modelli", + "agentAddModel": "Aggiungi modello", + "agentRequiredField": "Questo campo è obbligatorio.", + "agentInvalidBaseUrl": "Inserisci un URL di base HTTP(S) senza credenziali, query o frammento.", + "agentModelId": "ID modello", + "agentContextWindow": "Finestra di contesto", + "agentMaxOutputTokens": "Output massimo", + "agentMaxOutputBelowContext": "Deve essere inferiore alla finestra di contesto.", + "agentDeleteModel": "Elimina modello", + "agentPositiveInteger": "Inserisci un numero intero positivo.", + "agentConfigurationReadFailed": "Impossibile leggere la configurazione dell’Agent. Controlla le impostazioni e riprova.", + "agentConfigurationRequired": "Prima configura e attiva l’Agent nelle Impostazioni.", + "agentSessionRestoreFailed": "Impossibile ripristinare la sessione dell’Agent. Riprova più tardi.", + "select": "Seleziona", + "projectLocation": "Posizione di salvataggio dei progetti", + "projectLocationNotSet": "Non impostata", + "resourceLocation": "Posizione di archiviazione delle risorse", + "resourceLocationNotSet": "Non impostata", + "loadProjectLocationFailed": "Impossibile caricare la posizione di salvataggio dei progetti.", + "saveProjectLocationFailed": "Impossibile salvare la posizione dei progetti.", + "loadResourceLocationFailed": "Impossibile caricare la posizione di archiviazione delle risorse.", + "saveResourceLocationFailed": "Impossibile salvare la posizione delle risorse.", + "downloadAndContinue": "Scarica e continua", + "downloadInBackground": "Scarica in background", + "downloadingResource": "Download in corso…", + "processingResourceDownloadFailed": "Impossibile scaricare la risorsa di riconoscimento vocale. Riprova.", + "transcriptionResourceRequired": "Per generare i sottotitoli, devi prima scaricare un modello di riconoscimento vocale.", + "removeBackground": "Rimuovi sfondo", + "startBackgroundRemoval": "Rimuovi sfondo", + "backgroundRemovalResourceRequired": "La rimozione dello sfondo richiede un modello locale. Si avvia automaticamente dopo il download.", + "backgroundRemovalDownloadTask": "Scarica la risorsa per la rimozione dello sfondo", + "backgroundRemovalResourceName": "Modello di rimozione dello sfondo", + "backgroundRemovalTaskStarted": "Rimozione dello sfondo avviata", + "backgroundRemovalApplying": "Sostituzione del contenuto del clip", + "backgroundRemovalComplete": "Rimozione dello sfondo completata", + "backgroundRemovalFailed": "Rimozione dello sfondo non riuscita", + "backgroundRemovalDestructiveHint": "Il contenuto trasparente generato sostituirà questo clip. Puoi usare Annulla per ripristinare il clip originale.", + "startBackgroundRemovalFailed": "Impossibile avviare la rimozione dello sfondo. Controlla il contenuto o attendi il completamento dell’elaborazione corrente.", + "agentContextBudgetExceeded": "Spazio di input insufficiente per istruzioni, strumenti e messaggio. Aumenta il contesto o riduci l’output massimo.", + "agentAuthenticationFailed": "Autenticazione non riuscita. Controlla API Key e autorizzazioni.", + "agentConnectionFailed": "Connessione non riuscita o scaduta. Controlla Base URL e rete.", + "agentProtocolFailed": "La risposta non corrisponde al tipo API scelto o il flusso è incompleto.", + "agentContextBudgetTooSmall": "Riserva più spazio per le istruzioni. Aumenta il contesto o riduci l’output massimo.", + "agentCompacting": "Organizzazione del contesto…", + "agentEditing": "Modifica in corso…", + "agentVerifying": "Verifica dei risultati…", + "agentTurnLimitReached": "La procedura ha raggiunto il limite di esecuzione. Le modifiche sono state salvate. Invia «Continua» per riprendere.", + "agentRecoveryRequired": "Il risultato precedente non è confermato. Riprendi per verificare i dati salvati; le modifiche non confermate non verranno ripetute.", + "agentExportReplyFailed": "Video esportato. La risposta di riepilogo non è riuscita. Riprova senza ripetere modifiche o esportazione.", + "agentRetrySummary": "Riprova riepilogo", + "agentResumeTask": "Riprendi attività", + "agentTaskInterrupted": "L’attività è stata interrotta. Riprendi dai progressi salvati.", + "downloadSubtitleModel": "Scarica il modello per i sottotitoli", + "downloadModelAction": "Scarica", + "subtitleEngineUnavailable": "Il modello è installato, ma il motore dei sottotitoli non si è avviato. Ripara il motore; non occorre scaricare nuovamente il modello.", + "backgroundTaskDetails": "Dettagli attività", + "backgroundTaskFailed": "Non riuscita", + "backgroundTaskCompleted": "Completata", + "captionWrapLines": "A capo automatico dei sottotitoli", + "captionSingleLine": "Mostra sottotitoli su una riga", + "noMatchingCaptions": "Nessun sottotitolo corrispondente", + "subtitleResourcesRequired": "Queste risorse sono necessarie per i sottotitoli. La generazione inizierà automaticamente dopo il download.", + "subtitleResourcesDownloadSize": "Da scaricare: {size}", + "pauseDownload": "Pausa", + "resumeDownload": "Riprendi", + "downloadPaused": "In pausa", + "cancelResourceDownloadTitle": "Annullare il download?", + "cancelResourceDownloadMessage": "Il download si interromperà. I progressi della risorsa corrente potrebbero andare persi.", + "continueDownload": "Continua il download", + "cancelDownload": "Annulla il download", + "speechResourceStage": "Risorsa di riconoscimento vocale", + "translationResourceStage": "Risorsa di traduzione", + "subtitleResourceDownloadTask": "Scarica risorse vocali e di traduzione", + "downloadingSpeechModel": "Download del modello vocale", + "downloadingTranslationModel": "Download del modello di traduzione", + "selectProject": "Seleziona progetto", + "searchProjects": "Cerca progetti", + "noMatchingProjects": "Nessun progetto corrispondente", + "projectLocationMissing": "La cartella non esiste. Verrà creata quando crei un progetto.", + "projectLocationUnavailable": "La posizione di salvataggio non è disponibile. Collega il disco o controlla la rete e riprova, oppure cambia posizione.", + "projectLocationNotWritable": "La posizione di salvataggio non è scrivibile. Controlla le autorizzazioni o cambia posizione.", + "projectLocationCreateFailed": "Impossibile creare la cartella del progetto o scrivervi. Controlla le autorizzazioni o cambia posizione.", + "removeProjectFromSidebar": "Rimuovi dalla barra laterale", + "projectRemoved": "Progetto rimosso. I file locali e le conversazioni sono conservati.", + "agentNoConversations": "Nessuna conversazione", + "collapseProject": "Comprimi progetto", + "expandProject": "Espandi progetto", + "agentDeleteConfirmation": "Eliminare definitivamente “{title}” e tutti i suoi messaggi? Questa azione non può essere annullata. I file locali del progetto non saranno modificati.", + "agentEmptyTrashConfirmation": "Eliminare definitivamente tutte le conversazioni nel cestino? Questa azione non può essere annullata. I file locali del progetto non saranno modificati.", + "checkingForUpdates": "Ricerca aggiornamenti…", + "appIsUpToDate": "L’app è aggiornata.", + "downloadingUpdate": "Download aggiornamento: {progress}%", + "updateAvailable": "È disponibile la versione {version}.", + "downloadUpdate": "Scarica aggiornamento", + "restartToUpdate": "Riavvia e aggiorna", + "updateOperationFailed": "Aggiornamento non riuscito. Completa le attività in corso e riprova.", + "windowMinimize": "Riduci a icona", + "windowMaximize": "Ingrandisci", + "windowRestore": "Ripristina", + "workspaceAgent": "Assistente", + "workspaceCut": "Montaggio", + "noAvailableOptions": "Nessuna opzione disponibile", + "composerReferenceInvalid": "Un riferimento non è più valido. Torna al suo progetto o rimuovilo.", + "durationSeconds": "{seconds} s", + "durationMinutesSeconds": "{minutes} min {seconds} s", + "projectNameInvalid": "Nome del progetto non valido", + "projectLocationDefaultUnavailable": "Impossibile accedere alla posizione predefinita dei progetti. Selezionala di nuovo nelle impostazioni.", + "chooseProjectLocation": "Seleziona prima una posizione di salvataggio dei progetti nelle impostazioni.", + "untitledTimeline": "Timeline senza titolo", + "primarySequence": "Sequenza principale", + "primaryStoryline": "Linea principale", + "projectSessionClosed": "La sessione del progetto è chiusa. Riapri il progetto.", + "timelineSessionClosed": "La sessione della timeline è chiusa. Riapri la timeline.", + "timelineMissing": "La timeline non esiste o è stata eliminata.", + "timelineInUse": "La timeline è in uso e non può ancora essere eliminata.", + "timelineHasBackgroundTasks": "Completa le attività in background della timeline prima di eliminarla.", + "timelineRequired": "Un progetto deve mantenere almeno una timeline.", + "mediaReadFailed": "Impossibile leggere il file multimediale", + "mediaImportFailed": "Impossibile importare il file multimediale", + "unsupportedMediaType": "È possibile importare solo file video, audio e immagini.", + "mediaNoVideoTracks": "Il file multimediale non contiene una traccia video utilizzabile", + "mediaDurationOutOfRange": "La durata del file multimediale supera l’intervallo della timeline", + "resourceDownloadHttpFailed": "Download non riuscito (HTTP {statusCode})", + "resourceChecksumFailed": "Verifica del file del modello non riuscita. Scarica di nuovo la risorsa.", + "subtitleLanguageAf": "afrikaans", + "subtitleLanguageAm": "amarico", + "subtitleLanguageAr": "arabo", + "subtitleLanguageAst": "asturiano", + "subtitleLanguageAz": "azerbaigiano", + "subtitleLanguageBa": "baschiro", + "subtitleLanguageBe": "bielorusso", + "subtitleLanguageBg": "bulgaro", + "subtitleLanguageBn": "bengalese", + "subtitleLanguageBr": "bretone", + "subtitleLanguageBs": "bosniaco", + "subtitleLanguageCa": "catalano", + "subtitleLanguageCeb": "cebuano", + "subtitleLanguageCs": "ceco", + "subtitleLanguageCy": "gallese", + "subtitleLanguageDa": "danese", + "subtitleLanguageDe": "tedesco", + "subtitleLanguageEl": "greco", + "subtitleLanguageEn": "inglese", + "subtitleLanguageEs": "spagnolo", + "subtitleLanguageEt": "estone", + "subtitleLanguageFa": "persiano", + "subtitleLanguageFf": "fulah", + "subtitleLanguageFi": "finlandese", + "subtitleLanguageFr": "francese", + "subtitleLanguageFy": "frisone occidentale", + "subtitleLanguageGa": "irlandese", + "subtitleLanguageGd": "gaelico scozzese", + "subtitleLanguageGl": "galiziano", + "subtitleLanguageGu": "gujarati", + "subtitleLanguageHa": "hausa", + "subtitleLanguageHe": "ebraico", + "subtitleLanguageHi": "hindi", + "subtitleLanguageHr": "croato", + "subtitleLanguageHt": "creolo haitiano", + "subtitleLanguageHu": "ungherese", + "subtitleLanguageHy": "armeno", + "subtitleLanguageId": "indonesiano", + "subtitleLanguageIg": "igbo", + "subtitleLanguageIlo": "ilocano", + "subtitleLanguageIs": "islandese", + "subtitleLanguageIt": "italiano", + "subtitleLanguageJa": "giapponese", + "subtitleLanguageJv": "giavanese", + "subtitleLanguageKa": "georgiano", + "subtitleLanguageKk": "kazako", + "subtitleLanguageKm": "khmer", + "subtitleLanguageKn": "kannada", + "subtitleLanguageKo": "coreano", + "subtitleLanguageLb": "lussemburghese", + "subtitleLanguageLg": "ganda", + "subtitleLanguageLn": "lingala", + "subtitleLanguageLo": "lao", + "subtitleLanguageLt": "lituano", + "subtitleLanguageLv": "lettone", + "subtitleLanguageMg": "malgascio", + "subtitleLanguageMk": "macedone", + "subtitleLanguageMl": "malayalam", + "subtitleLanguageMn": "mongolo", + "subtitleLanguageMr": "marathi", + "subtitleLanguageMs": "malese", + "subtitleLanguageMy": "birmano", + "subtitleLanguageNe": "nepalese", + "subtitleLanguageNl": "olandese", + "subtitleLanguageNo": "norvegese", + "subtitleLanguageNs": "sotho del nord", + "subtitleLanguageOc": "occitano", + "subtitleLanguageOr": "odia", + "subtitleLanguagePa": "punjabi", + "subtitleLanguagePl": "polacco", + "subtitleLanguagePs": "pashto", + "subtitleLanguagePt": "portoghese", + "subtitleLanguageRo": "rumeno", + "subtitleLanguageRu": "russo", + "subtitleLanguageSd": "sindhi", + "subtitleLanguageSi": "singalese", + "subtitleLanguageSk": "slovacco", + "subtitleLanguageSl": "sloveno", + "subtitleLanguageSo": "somalo", + "subtitleLanguageSq": "albanese", + "subtitleLanguageSr": "serbo", + "subtitleLanguageSs": "swati", + "subtitleLanguageSu": "sundanese", + "subtitleLanguageSv": "svedese", + "subtitleLanguageSw": "swahili", + "subtitleLanguageTa": "tamil", + "subtitleLanguageTh": "thailandese", + "subtitleLanguageTl": "tagalog", + "subtitleLanguageTn": "tswana", + "subtitleLanguageTr": "turco", + "subtitleLanguageUk": "ucraino", + "subtitleLanguageUr": "urdu", + "subtitleLanguageUz": "uzbeco", + "subtitleLanguageVi": "vietnamita", + "subtitleLanguageWo": "wolof", + "subtitleLanguageXh": "xhosa", + "subtitleLanguageYi": "yiddish", + "subtitleLanguageYo": "yoruba", + "subtitleLanguageYue": "cantonese", + "subtitleLanguageZh": "cinese", + "subtitleLanguageZu": "zulu", + "linearRec2020": "Rec.2020 lineare", + "diagnostics": "Diagnostica", + "exportDiagnostics": "Esporta pacchetto diagnostico", + "exportDiagnosticsFailed": "Impossibile esportare la diagnostica. Riprova.", + "exportDiagnosticsSucceeded": "Pacchetto diagnostico salvato." +} diff --git a/lib/l10n/app_ja.arb b/lib/l10n/app_ja.arb new file mode 100644 index 0000000..7923634 --- /dev/null +++ b/lib/l10n/app_ja.arb @@ -0,0 +1,889 @@ +{ + "projectsNone": "プロジェクトがありません", + "agentConversations": "会話", + "renameConversationTitle": "チャットの名前を変更", + "renameConversationDescription": "短く分かりやすい名前にしてください。", + "showMoreConversations": "さらに表示", + "showFewerConversations": "表示を減らす", + "agentNewConversation": "新しい会話", + "agentElapsedTime": "所要時間 {duration}", + "agentConversationActions": "会話の操作", + "agentMoveToTrash": "ゴミ箱に移動", + "agentTrash": "ゴミ箱", + "agentRestore": "復元", + "agentEmptyTrash": "ゴミ箱を空にする", + "agentDeleteForever": "完全に削除", + "agentConversationLocation": "会話の保存先", + "agentChooseExistingConversations": "既存の会話を選択", + "agentMoveConversations": "会話を移動", + "agentLocationUnavailable": "会話の保存先を利用できません", + "agentLocationBusy": "実行中の会話が終了してから移動してください", + "agentRelinkProvider": "プロバイダーを再関連付け", + "@@locale": "ja", + "settings": "設定", + "closeSettings": "設定を閉じる", + "general": "一般", + "appearance": "外観", + "theme": "テーマ", + "system": "システムに合わせる", + "light": "ライト", + "dark": "ダーク", + "saveAppearanceFailed": "外観を保存できませんでした。もう一度試してください。", + "loadAppearanceFailed": "外観を読み込めませんでした。テーマを再度選択してください。", + "cancel": "キャンセル", + "save": "保存", + "create": "作成", + "close": "閉じる", + "retry": "再試行", + "name": "名前", + "enterName": "名前を入力してください", + "invalidName": "名前にパス区切り文字や制御文字を含めることはできません", + "projectName": "プロジェクト名", + "newProject": "新規プロジェクト", + "openProject": "プロジェクトを開く", + "openProjectMore": "別のプロジェクトを開く", + "projects": "プロジェクト", + "projectsEmpty": "プロジェクトがありません", + "openingWorkspace": "ワークスペースを開いています…", + "loadProjectsFailed": "プロジェクトを読み込めませんでした", + "backToProjects": "編集に戻る", + "timelines": "タイムライン", + "timelineLimitReached": "1つのプロジェクトに作成できるタイムラインは最大{count}件です。", + "timelineName": "タイムライン名", + "defaultTimelineName": "タイムライン {index}", + "newTimeline": "新規タイムライン", + "noTimelines": "タイムラインがありません", + "activeTimeline": "現在のタイムライン", + "timelineUnavailable": "タイムラインを利用できません", + "projectNoTimelines": "このプロジェクトにはタイムラインがありません", + "createTimelineHint": "左側の「タイムライン」から新しいタイムラインを作成して編集を開始します。", + "createTimelineChat": "タイムラインを作成するとチャットを開始できます", + "editingFirstLayout": "編集優先", + "agentEditingLayout": "エージェントと編集", + "agentLayoutDescription": "計画、共同作業、実行", + "editingLayoutDescription": "プレビュー、編集、調整", + "saveHere": "ここに保存", + "selectDirectoryFailed": "ディレクトリを選択できませんでした。システム権限を確認してください。", + "operationFailed": "操作が失敗しました。もう一度試してください。", + "collapseSidebar": "サイドバーを折りたたむ", + "expandSidebar": "サイドバーを展開する", + "expandEditor": "編集エリアを展開", + "collapseProperties": "プロパティを折りたたむ", + "expandProperties": "プロパティを展開する", + "layout": "レイアウト", + "materials": "メディア", + "all": "すべて", + "video": "ビデオ", + "audio": "オーディオ", + "image": "画像", + "picture": "画像", + "captions": "字幕", + "text": "文章", + "noMedia": "メディアがありません", + "mediaCategory": "メディアの種類", + "captionTasks": "字幕タスク", + "listLayout": "リストビュー", + "gridLayout": "グリッドビュー", + "addToTimeline": "タイムラインに追加", + "rename": "名前を変更", + "renameMedia": "メディアの名前を変更", + "removeMedia": "メディアを削除", + "remove": "削除", + "revealFinder": "Finderで表示", + "revealFileManager": "ファイルマネージャーで表示", + "dropToAdd": "離して追加", + "timelineDropToStart": "メディアをここにドラッグして開始します。", + "dragMediaHint": "ビデオ、オーディオ、または画像をここにドラッグします\n元のファイルは現在の場所に残ります", + "transcribe": "文字起こし", + "generateCaptions": "字幕を生成", + "play": "再生", + "pause": "一時停止", + "retryPreview": "プレビューを再試行する", + "canvasRatio": "キャンバスの縦横比", + "noPreviewContent": "タイムラインにプレビューするコンテンツがありません", + "nativePreviewUnsupported": "このプラットフォームではネイティブ プレビューを利用できません", + "canvasTransformFailed": "キャンバスを変形できませんでした。もう一度試してください。", + "undo": "元に戻す", + "redo": "やり直す", + "deleteSelectedClips": "選択したクリップを削除します", + "splitAtPlayhead": "再生ヘッドで分割", + "trimLeft": "左側をトリム", + "trimRight": "右側をトリム", + "trimLeftTooltip": "再生ヘッドの左側を削除し、右側を保持", + "trimRightTooltip": "再生ヘッドの右側を削除し、左側を保持", + "currentSequence": "現在のシーケンス", + "projectProperties": "プロジェクトのプロパティ", + "canvasSize": "キャンバスサイズ", + "frameRate": "フレームレート", + "duration": "間隔", + "totalDuration": "合計期間", + "clipDuration": "クリップの長さ", + "seconds": "秒", + "clip": "クリップ", + "unnamedClip": "名称未設定のクリップ", + "gap": "ギャップ", + "compoundClip": "複合クリップ", + "textClip": "テキストクリップ", + "pictureProperties": "映像", + "position": "位置", + "rotation": "回転", + "scale": "拡大縮小", + "size": "サイズ", + "transform": "変形", + "resetPosition": "位置をリセット", + "keepAspectRatio": "アスペクト比をロックする", + "alignment": "配置", + "alignLeft": "左揃え", + "alignRight": "右揃え", + "alignTop": "上揃え", + "alignBottom": "下揃え", + "alignHorizontalCenter": "水平方向に中央揃え", + "alignVerticalCenter": "垂直方向に中央揃え", + "volume": "音量", + "gain": "ゲイン", + "mute": "ミュート", + "unmute": "ミュート解除", + "resetVolume": "音量をリセットする", + "invalidGain": "-90 ~ +12 の値を入力してください", + "animation": "アニメーション", + "keyframes": "キーフレーム", + "removeAllKeyframes": "すべてのキーフレームを削除します", + "linear": "リニア", + "easeIn": "イーズイン", + "easeOut": "イーズアウト", + "easeInOut": "イーズインアウト", + "basic": "基本", + "mask": "マスク", + "addMask": "マスクの追加", + "deleteMask": "マスクの削除", + "resetMask": "マスクをリセット", + "enableMask": "マスクを有効にする", + "disableMask": "マスクを無効にする", + "moveMaskUp": "マスクを上に移動します", + "moveMaskDown": "マスクを下に移動します", + "rectangle": "長方形", + "ellipse": "楕円", + "invert": "反転", + "feather": "ぼかし", + "add": "加算", + "subtract": "減算", + "intersect": "交差", + "initialRegion": "初期領域", + "none": "なし", + "color": "色", + "fontSize": "フォントサイズ", + "outlineWidth": "縁取りの幅", + "outlineColor": "縁取りの色", + "captionBaseline": "字幕のベースライン", + "content": "テキスト", + "start": "開始", + "time": "時間", + "speed": "スピード", + "speedSegmentCount": "速度区間:{count}", + "splitSpeedAtPlayhead": "再生ヘッドで速度を分割", + "speedChange": "スピード", + "speedMode": "速度モード", + "constantSpeed": "一定速度", + "segmentedSpeed": "分割速度", + "speedNotAvailable": "速度制御はまだ利用できません", + "custom": "カスタム", + "invalidNumber": "無効な値", + "mediaUnavailable": "メディアが利用できません", + "mediaMissing": "メディアが見つかりません", + "mediaColorSpace": "メディアの色空間", + "mediaColorInterpretation": "メディアの色の解釈", + "colorInfoNotLoaded": "カラー情報が読み込まれていません", + "unknownColorSpace": "不明な色空間。 Rec.709として表示されます。", + "colorBackendUnsupported": "現在のバックエンドはメディアの色の解釈をサポートしていません。", + "loadClipPropertiesFailed": "クリップのプロパティを読み取れませんでした", + "updatePictureFailed": "画像のプロパティを更新できませんでした", + "updateVolumeFailed": "ボリュームを更新できませんでした", + "updateMaskFailed": "マスクを更新できませんでした", + "updateKeyframesFailed": "キーフレームを更新できませんでした", + "maskPreviewFailed": "マスクのプレビューを準備できませんでした", + "alignClipFailed": "クリップを位置合わせできませんでした。プレビューが表示されるまで待ってから、もう一度試してください。", + "invalidTransform": "スケールは 1% ~ 10000% である必要があります。位置と角度は有効な数値でなければなりません。", + "editFailed": "編集できませんでした。入力と時間範囲を確認してください。", + "addMediaFailed": "メディアを追加できませんでした。もう一度試してください。", + "deleteCaption": "字幕を削除", + "mergeCaptions": "字幕を結合", + "captionDeleted": "字幕を削除しました", + "captionChanged": "字幕が変更されました。もう一度試してください。", + "captionEditChanged": "字幕が変更されました。再度編集してください。", + "assistantHint": "編集のアイデアを説明してください", + "configureAgentHint": "チャットを開始するようにエージェント サービスを構成する", + "agentRestartHint": "エージェント サービスを構成し、アプリを再起動します。", + "replyInterrupted": "応答が中断されました", + "replying": "応答中…", + "stopReply": "応答を停止", + "sendMessage": "メッセージを送信", + "addAttachment": "添付ファイルを追加します (まだ利用できません)", + "replyFailed": "応答に失敗しました。接続を確認するか、後でもう一度試してください。", + "mcpService": "MCPサービス", + "listenPort": "ポート", + "accessToken": "アクセストークン", + "copyAccessToken": "アクセストークンをコピーする", + "accessTokenCopied": "アクセストークンがコピーされました", + "loadMcpFailed": "MCP 設定をロードできませんでした。リトライ", + "saveMcpFailed": "MCP設定を保存できませんでした。もう一度試してください。", + "retryStart": "リトライスタート", + "invalidPort": "ポートは 1 ~ 65535 でなければなりません", + "loadingSettings": "設定を読み込み中…", + "starting": "起動中…", + "stopping": "停止中…", + "disabled": "無効", + "running": "実行中", + "startFailed": "開始に失敗しました", + "saved": "保存済み", + "unsaved": "未保存", + "saving": "保存中…", + "pendingSave": "保存保留中", + "notApplied": "未適用", + "enable": "有効にする", + "disable": "無効にする", + "type": "種類", + "status": "状態", + "file": "ファイル", + "unboundMedia": "メディア未設定", + "unboundAudio": "音声トラック未設定", + "vertical": "垂直", + "language": "言語", + "saveLanguageFailed": "言語を保存できませんでした。もう一度試してください。", + "loadLanguageFailed": "言語をロードできませんでした。再度選択してください。", + "propertiesFirstLayout": "最初にプロパティ", + "defaultLayout": "デフォルトのレイアウト", + "separateVocals": "ボーカルを分離", + "detachAudio": "音声を分離", + "restoreAudio": "音声を復元", + "audioDetached": "音声は分離済みです", + "addAll": "すべて追加", + "preparingMedia": "メディアを準備中…", + "cancelling": "キャンセル中…", + "cancelled": "キャンセル済み", + "interruptedTask": "タスクが中断されました。続行するには再起動してください", + "auto": "自動", + "autoDetect": "自動検出", + "noTranslation": "翻訳しない", + "sourceLanguage": "元の言語", + "translationLanguage": "翻訳先の言語", + "transcriptionNotConfigured": "文字起こしが設定されていません。認識コンポーネントと Whisper Turbo モデルをインストールします。", + "translationNotConfigured": "字幕翻訳が設定されていません。ソース言語で字幕を生成できます。", + "sourceLanguageUnknown": "翻訳のソース言語を決定できませんでした。", + "startTranscriptionFailed": "文字起こしを開始できませんでした。メディアを確認するか、現在のタスクが完了するまで待ちます。", + "placeMediaFirst": "字幕を適用する前に、このメディアをタイムライン上に配置します。", + "placeTranslationMediaFirst": "翻訳された字幕を適用する前に、対応するメディアをタイムライン上に配置します。", + "selectTargetClip": "ターゲットクリップを選択", + "timelineChanged": "タイムラインが変わりました。対象のクリップを再度選択してください。", + "transcriptionAccessFailed": "転写に失敗しました: コンポーネント、モデル、またはソース メディアにアクセスできません (notConfigured)", + "transcriptionNoAudio": "文字起こしに失敗しました: 選択したメディアまたはトラックに認識可能な音声がありません (noAudio)", + "transcriptionInvalidResult": "文字起こしに失敗しました: 無効な字幕 ファイルが返されました (invalidResult)", + "transcriptionWorkerExited": "転写に失敗しました: 認識コンポーネントが予期せず終了しました (workerExited)", + "transcriptionProcessingFailed": "転写に失敗しました: ネイティブ処理に失敗しました (processingFailed)", + "transcriptionFailed": "転写に失敗しました。コンポーネント、モデル、オーディオトラック、およびデュレーションを確認してください", + "transcribing": "文字起こし中…", + "captionsGenerated": "字幕を生成しました", + "cancelTranscription": "文字起こしをキャンセル", + "applyCaptions": "字幕を適用", + "preparingTranslation": "翻訳を準備中…", + "translatingCaptions": "字幕を翻訳中…", + "cancellingTranslation": "翻訳をキャンセル中…", + "translatedCaptionsGenerated": "翻訳字幕を生成しました", + "translationCancelled": "翻訳をキャンセルしました", + "translationInterrupted": "翻訳が中断されました", + "cancelTranslation": "翻訳をキャンセル", + "editorServiceUnavailable": "編集サービスは利用できません。プロジェクトを再度開きます。", + "mcpUnavailable": "MCP 接続が利用できません。ローカルポートとトークンを確認してください。", + "openTimelineFailed": "タイムラインを開けませんでした", + "noTimelineSequence": "このタイムラインにはシーケンスがありません。", + "waitingForProject": "プロジェクトが開くのを待っています", + "hold": "ホールド", + "noImportableFiles": "インポート可能なファイルを受信しませんでした", + "virtualFilesUnsupported": "ファイルマネージャーから元のファイルをドラッグします。仮想ファイルはまだサポートされていません。", + "editorSessionStartFailed": "タイムラインエディターを開けませんでした", + "previewStartFailed": "ネイティブ プレビューを開始できませんでした", + "previewInvalidTrack": "選択したオーディオまたはビデオ トラックがメディアに存在しません。", + "previewMissingBinding": "メディア バインディングがありません。このタイムラインをプレビューできませんでした。", + "previewUnsupportedEdits": "このタイムラインには、プレビューでまだ​​サポートされていない編集が含まれています。", + "previewUnsupportedConfiguration": "このプレビュー構成は、現在のプラットフォームまたはシステム バージョンではサポートされていません。", + "previewHdrUnsupported": "HDR メディアには、SDR プレビュー用のトーン マッピングが必要です。現在のシステムまたはプレビュー構成はこれをサポートしていません。", + "previewAudioOutOfRange": "オーディオ クリップはソース トラックの範囲を超えているため、プレビューできません。", + "previewResourceMissing": "プレビュー メディアは存在しません。元のファイルを再度見つけます。", + "previewInvalidComposition": "ビデオ構成設定が無効です。プレビューを作成できませんでした。", + "previewInvalidData": "無効なプレビュー データです。もう一度試してください。", + "previewFailed": "プレビューに失敗しました。メディアアクセスを確認して、再試行してください。", + "chatFailed": "会話を完了できませんでした。サービス構成を確認するか、後で再試行してください。", + "delete": "削除", + "pinTimeline": "タイムラインをピン留め", + "unpinTimeline": "ピン留めを解除", + "deleteTimelineConfirmation": "「{name}」と編集履歴を削除しますか?この操作は元に戻せません。", + "@deleteTimelineConfirmation": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "processingFailed": "処理に失敗しました", + "noMatchingOptions": "一致する項目がありません", + "removeMediaConfirmation": "「{name}」をライブラリから削除しますか?既存のクリップ、履歴、元のファイルは保持されます。", + "@removeMediaConfirmation": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "mediaAdded": "メディア参照を{count}件追加しました", + "@mediaAdded": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "duplicatesSkipped": "{count} 重複ファイルをスキップしました", + "@duplicatesSkipped": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mediaCount": "メディア{count}件", + "importMedia": "読み込む", + "@mediaCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "noMediaOfType": "{type} メディアがありません", + "@noMediaOfType": { + "placeholders": { + "type": { + "type": "String" + } + } + }, + "captionsImported": "インポートされた {count} 字幕", + "@captionsImported": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "editCaptionError": "字幕を編集できませんでした: {message}", + "@editCaptionError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "mcpStartError": "MCP を開始できませんでした: {message}", + "@mcpStartError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "manualColorSpace": "手動で選択: {name}", + "@manualColorSpace": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "detectedColorSpace": "検出されました: {name}", + "@detectedColorSpace": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "keyframeLabel": "{channel}のキーフレーム", + "@keyframeLabel": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "maskMode": "組み合わせモード: {mode}", + "@maskMode": { + "placeholders": { + "mode": { + "type": "String" + } + } + }, + "keyframeCount": "キーフレーム{count}個", + "@keyframeCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "toggleKeyframe": "{channel}のキーフレームを{action}", + "@toggleKeyframe": { + "placeholders": { + "action": { + "type": "String" + }, + "channel": { + "type": "String" + } + } + }, + "previousKeyframe": "前の{channel}キーフレーム", + "@previousKeyframe": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "nextKeyframe": "次の{channel}キーフレーム", + "@nextKeyframe": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "keyframeSettings": "{channel}のキーフレーム設定", + "@keyframeSettings": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "selectedClipsHint": "{count} クリップが選択されました\nクリップを 1 つ選択してそのプロパティを表示します", + "@selectedClipsHint": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "transcriptionError": "転写に失敗しました。コンポーネント、モデル、オーディオ トラック、およびデュレーションを確認します ({code})", + "@transcriptionError": { + "placeholders": { + "code": { + "type": "String" + } + } + }, + "captionsAdded": "{count} 字幕を追加しました。プロパティ パネルで編集します。", + "@captionsAdded": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "translatedCaptionsAdded": "{count} 翻訳字幕を追加しました。プロパティ パネルで編集します。", + "@translatedCaptionsAdded": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "applyCaptionsError": "字幕を適用できませんでした: {message}", + "@applyCaptionsError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "applyTranslatedCaptionsError": "翻訳された字幕を適用できませんでした: {message}", + "@applyTranslatedCaptionsError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "recognizedCaptions": "字幕を{count}件認識しました", + "@recognizedCaptions": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "captionCount": "字幕{count}件", + "@captionCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "translationFailed": "翻訳に失敗しました: {message}", + "@translationFailed": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "translatedCaptionCount": "{language}の字幕{count}件", + "@translatedCaptionCount": { + "placeholders": { + "count": { + "type": "int" + }, + "language": { + "type": "String" + } + } + }, + "previewParameterError": "無効なプレビューパラメータ: {message}", + "@previewParameterError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "mediaOffline": "メディアがオフラインまたは利用不可: {names}", + "@mediaOffline": { + "placeholders": { + "names": { + "type": "String" + } + } + }, + "searchOptions": "{label}を検索…", + "@searchOptions": { + "placeholders": { + "label": { + "type": "String" + } + } + }, + "loadRecentProjectsFailed": "最近のライブラリをロードできませんでした。ライブラリを手動で開くこともできます。", + "projectAccessFailed": "プロジェクトを利用できません", + "projectMissingDirectory": "プロジェクトが見つかりません", + "recentProjectSaveFailed": "ライブラリは開きましたが、最近のライブラリ レコードを保存できませんでした。", + "lastProjectSaveFailed": "プロジェクトは開きましたが、最後のプロジェクト レコードを保存できませんでした。", + "enterProjectName": "プロジェクト名を入力してください", + "projectSwitched": "プロジェクトが変更されました。メディアを再度ドラッグします。", + "notLocalMedia": "このメディアはローカル ファイルではありません", + "revealMediaFailed": "ファイルマネージャーでメディアを表示できませんでした", + "openMatchingProject": "まず対応するプロジェクトを開きます", + "projectMismatch": "この場所のライブラリはレコードと一致しません。 「ライブラリを開く」で再度選択します。", + "openProjectFirst": "まずライブラリを開いてください", + "localFilesOnly": "ファイルマネージャーからローカルファイルをドラッグ", + "foldersUnsupported": "ファイルを選択します。フォルダーのドラッグはまだサポートされていません。", + "mediaImportCancelled": "メディアのインポートがキャンセルされました", + "fileAccessFailed": "ファイルが見つからないか、読み取ることができません。場所と権限を確認してください", + "registerMediaFailed": "メディアを登録できませんでした。もう一度試してください", + "mediaNoLongerExists": "メディアはもう存在しません", + "mediaNoTracks": "メディアに使用可能なビデオまたはオーディオ トラックがありません", + "invalidMediaDuration": "メディアの長さが無効です", + "mediaInfoUnsupported": "このプラットフォームではメディア情報の読み取りがまだサポートされていません", + "mediaInfoFailed": "メディア情報を読み取れませんでした。ファイルとアクセス許可を確認してください", + "saveTimelineFailed": "タイムラインを保存できませんでした。もう一度やり直してください。保存されていない編集内容はこのセッションに残ります。", + "addKeyframeAction": "追加", + "backgroundTasks": "バックグラウンドタスク", + "noBackgroundTasks": "バックグラウンドタスクはありません", + "retryTask": "再試行", + "applyOriginalCaptions": "原文字幕を適用", + "applyTranslatedCaptions": "翻訳字幕を適用", + "subtitleTaskStarted": "字幕タスクを開始しました", + "fitTimeline": "タイムライン全体を表示", + "modify": "Modify", + "projectSettings": "Project settings", + "projectSettingsDescription": "Change project output settings while keeping clip timing and speed.", + "projectColorSpace": "Color space", + "projectWidth": "Width (px)", + "projectHeight": "Height (px)", + "projectResolutionInvalid": "Enter a whole number from 1 to 16384", + "previewFullscreen": "全画面プレビュー", + "exitPreviewFullscreen": "全画面表示を終了", + "previewGoToStart": "先頭へ移動", + "previewPreviousFrame": "前のフレーム", + "previewNextFrame": "次のフレーム", + "softwareUpdates": "ソフトウェア更新", + "checkForUpdates": "更新を確認", + "automaticallyCheckUpdates": "更新を自動的に確認", + "updatesUnavailable": "このビルドでは更新を利用できません。", + "updateCheckFailed": "更新を確認できませんでした。もう一度お試しください。", + "agentSettings": "Agent", + "agentSaveSettingsFailed": "Agent設定を保存できませんでした。", + "agentDeleteProviderTitle": "プロバイダーを削除しますか?", + "agentDeleteProviderDescription": "「{providerName}」と保存済みのAPIキーがこのデバイスから削除されます。", + "agentProviderRequired": "アシスタントを有効にする前にプロバイダーを追加してください。", + "agentUseSelectedModel": "新しいAgentリクエストには選択したモデルが使用されます。", + "agentEnable": "Agentを有効にする", + "agentDefaultModel": "デフォルトモデル", + "agentConfigureModel": "モデルを設定", + "agentSelectModel": "モデルを選択", + "agentModelUnavailable": "この会話のモデルは利用できません。別のモデルを選択して新しい会話を開始してください。", + "agentModelChangeSession": "モデルを変更すると、新しいAgentセッションが開始されます。", + "agentCustomProviders": "カスタムプロバイダー", + "agentProviderStorageDescription": "プロバイダーのメタデータはローカルに保存されます。APIキーはシステムの資格情報ストアに保管されます。", + "agentAddProvider": "プロバイダーを追加", + "agentBackToProviders": "プロバイダー一覧に戻る", + "agentLoadSettingsFailed": "Agent設定を読み込めませんでした。再試行", + "agentEnableProvider": "Provider を有効にする", + "agentEditProvider": "プロバイダーを編集", + "agentDeleteProvider": "プロバイダーを削除", + "agentModelIdsUnique": "モデルIDは一意である必要があります。", + "agentEditProviderTitle": "プロバイダーを編集", + "agentProviderEndpointDescription": "OpenAI互換のChat Completionsエンドポイントを設定します。", + "agentSaveProvider": "プロバイダーを保存", + "agentProviderConfiguration": "Provider 設定", + "agentAuthenticationAndModels": "認証とモデル", + "agentApiType": "APIタイプ", + "agentOpenAiChatCompletions": "OpenAI Completions", + "agentBaseUrl": "ベースURL", + "agentApiKey": "APIキー", + "agentProviderNameHint": "マイプロバイダー", + "agentApiKeyOptional": "認証を必要としないエンドポイントでは省略できます。", + "agentApiKeyKeep": "保存済みのキーを保持する場合は空欄にしてください。", + "agentOptional": "任意", + "agentApiKeyOneLine": "APIキーは1行で入力してください。", + "agentRemoveSavedApiKey": "保存済みのAPIキーを削除", + "agentModels": "モデル", + "agentAddModel": "モデルを追加", + "agentRequiredField": "この項目は必須です。", + "agentInvalidBaseUrl": "資格情報、クエリ、フラグメントを含まないHTTP(S)ベースURLを入力してください。", + "agentModelId": "モデルID", + "agentContextWindow": "コンテキストウィンドウ", + "agentMaxOutputTokens": "最大出力", + "agentMaxOutputBelowContext": "コンテキストウィンドウより小さい値を指定してください。", + "agentDeleteModel": "モデルを削除", + "agentPositiveInteger": "正の整数を入力してください。", + "agentConfigurationReadFailed": "Agent設定を読み込めませんでした。設定を確認してもう一度お試しください。", + "agentConfigurationRequired": "先に設定でAgentを構成して有効にしてください。", + "agentSessionRestoreFailed": "Agentセッションを復元できませんでした。しばらくしてからもう一度お試しください。", + "select": "選択", + "projectLocation": "プロジェクトの保存先", + "projectLocationNotSet": "未設定", + "resourceLocation": "リソースの保存先", + "resourceLocationNotSet": "未設定", + "loadProjectLocationFailed": "プロジェクトの保存先を読み込めませんでした。", + "saveProjectLocationFailed": "プロジェクトの保存先を保存できませんでした。", + "loadResourceLocationFailed": "リソースの保存先を読み込めませんでした。", + "saveResourceLocationFailed": "リソースの保存先を保存できませんでした。", + "downloadAndContinue": "ダウンロードして続行", + "downloadInBackground": "バックグラウンドでダウンロード", + "downloadingResource": "ダウンロード中…", + "processingResourceDownloadFailed": "音声認識リソースをダウンロードできませんでした。もう一度お試しください。", + "transcriptionResourceRequired": "字幕を生成するには、まず音声認識モデルをダウンロードする必要があります。", + "removeBackground": "背景を削除", + "startBackgroundRemoval": "背景を削除", + "backgroundRemovalResourceRequired": "背景削除にはローカルモデルが必要です。ダウンロード後に自動で開始します。", + "backgroundRemovalDownloadTask": "背景削除リソースをダウンロード", + "backgroundRemovalResourceName": "背景削除モデル", + "backgroundRemovalTaskStarted": "背景削除を開始しました", + "backgroundRemovalApplying": "クリップのメディアを置き換えています", + "backgroundRemovalComplete": "背景削除が完了しました", + "backgroundRemovalFailed": "背景削除に失敗しました", + "backgroundRemovalDestructiveHint": "生成された透過メディアでこのクリップを置き換えます。元に戻すを使用して元のクリップを復元できます。", + "startBackgroundRemovalFailed": "背景削除を開始できませんでした。メディアを確認するか、現在の処理タスクが完了するまでお待ちください。", + "agentContextBudgetExceeded": "システム指示、ツール、メッセージに必要な入力容量が不足しています。コンテキストを増やすか最大出力を減らしてください。", + "agentAuthenticationFailed": "認証に失敗しました。API Key と権限を確認してください。", + "agentConnectionFailed": "接続に失敗したかタイムアウトしました。Base URL とネットワークを確認してください。", + "agentProtocolFailed": "応答が選択した API タイプと一致しないか、ストリームが不完全です。", + "agentContextBudgetTooSmall": "システム指示用の入力容量を確保してください。コンテキストを増やすか最大出力を減らしてください。", + "agentCompacting": "コンテキストを整理中…", + "agentEditing": "編集中…", + "agentVerifying": "結果を確認中…", + "agentTurnLimitReached": "実行回数の上限に達しました。編集内容は保存されています。「続けて」と送信すると再開します。", + "agentRecoveryRequired": "前回の操作結果は未確認です。続行して保存済みの記録を確認できます。未確認の編集は繰り返しません。", + "agentExportReplyFailed": "動画は書き出し済みですが、要約の返信に失敗しました。編集や書き出しを繰り返さず要約を再試行できます。", + "agentRetrySummary": "要約を再試行", + "agentResumeTask": "タスクを続行", + "agentTaskInterrupted": "タスクが中断されました。保存済みの進行状況から続行できます。", + "downloadSubtitleModel": "字幕モデルをダウンロード", + "downloadModelAction": "ダウンロード", + "subtitleEngineUnavailable": "モデルはインストール済みですが、字幕処理エンジンを起動できませんでした。エンジンを修復してください。モデルの再ダウンロードは不要です。", + "backgroundTaskDetails": "タスクの詳細", + "backgroundTaskFailed": "失敗", + "backgroundTaskCompleted": "完了", + "captionWrapLines": "字幕を折り返して表示", + "captionSingleLine": "字幕を1行で表示", + "noMatchingCaptions": "一致する字幕がありません", + "subtitleResourcesRequired": "字幕の生成に必要なリソースです。ダウンロード後、自動的に生成を開始します。", + "subtitleResourcesDownloadSize": "ダウンロード容量: {size}", + "pauseDownload": "一時停止", + "resumeDownload": "再開", + "downloadPaused": "一時停止中", + "cancelResourceDownloadTitle": "ダウンロードをキャンセルしますか?", + "cancelResourceDownloadMessage": "ダウンロードを停止します。現在のリソースの進行状況は失われる場合があります。", + "continueDownload": "ダウンロードを続ける", + "cancelDownload": "ダウンロードをキャンセル", + "speechResourceStage": "音声認識リソース", + "translationResourceStage": "翻訳リソース", + "subtitleResourceDownloadTask": "音声・翻訳リソースをダウンロード", + "downloadingSpeechModel": "音声モデルをダウンロード中", + "downloadingTranslationModel": "翻訳モデルをダウンロード中", + "selectProject": "プロジェクトを選択", + "searchProjects": "プロジェクトを検索", + "noMatchingProjects": "一致するプロジェクトがありません", + "projectLocationMissing": "フォルダが存在しません。プロジェクト作成時に作成されます。", + "projectLocationUnavailable": "プロジェクトの保存先を利用できません。ディスクやネットワークを確認して再試行するか、保存先を変更してください。", + "projectLocationNotWritable": "プロジェクトの保存先に書き込めません。アクセス権を確認するか、保存先を変更してください。", + "projectLocationCreateFailed": "プロジェクト保存フォルダの作成または書き込みに失敗しました。アクセス権を確認するか、保存先を変更してください。", + "removeProjectFromSidebar": "サイドバーから削除", + "projectRemoved": "プロジェクトを一覧から削除しました。ローカルファイルと会話は保持されます。", + "agentNoConversations": "まだ会話がありません", + "collapseProject": "プロジェクトを折りたたむ", + "expandProject": "プロジェクトを展開", + "agentDeleteConfirmation": "「{title}」とすべてのメッセージを完全に削除しますか?この操作は取り消せません。ローカルのプロジェクトファイルには影響しません。", + "agentEmptyTrashConfirmation": "ゴミ箱内のすべての会話を完全に削除しますか?この操作は取り消せません。ローカルのプロジェクトファイルには影響しません。", + "checkingForUpdates": "更新を確認中…", + "appIsUpToDate": "最新バージョンです。", + "downloadingUpdate": "更新をダウンロード中:{progress}%", + "updateAvailable": "バージョン {version} が利用可能です。", + "downloadUpdate": "更新をダウンロード", + "restartToUpdate": "再起動して更新", + "updateOperationFailed": "更新できませんでした。実行中のタスクを完了してから再試行してください。", + "windowMinimize": "最小化", + "windowMaximize": "最大化", + "windowRestore": "元に戻す", + "workspaceAgent": "アシスタント", + "workspaceCut": "編集", + "noAvailableOptions": "利用できる項目がありません", + "composerReferenceInvalid": "参照が無効です。元のプロジェクトに戻るか、参照を削除してください。", + "durationSeconds": "{seconds}秒", + "durationMinutesSeconds": "{minutes}分{seconds}秒", + "projectNameInvalid": "プロジェクト名が無効です", + "projectLocationDefaultUnavailable": "既定のプロジェクト保存先にアクセスできません。設定で選び直してください。", + "chooseProjectLocation": "先に設定でプロジェクトの保存先を選択してください。", + "untitledTimeline": "無題のタイムライン", + "primarySequence": "メインシーケンス", + "primaryStoryline": "メインストーリーライン", + "projectSessionClosed": "プロジェクトのセッションが終了しました。開き直してください。", + "timelineSessionClosed": "タイムラインのセッションが終了しました。開き直してください。", + "timelineMissing": "タイムラインが存在しないか、削除されています。", + "timelineInUse": "タイムラインは使用中のため削除できません。", + "timelineHasBackgroundTasks": "削除する前にタイムラインのバックグラウンドタスクを完了してください。", + "timelineRequired": "プロジェクトには少なくとも1つのタイムラインが必要です。", + "mediaReadFailed": "メディアを読み込めませんでした", + "mediaImportFailed": "メディアを読み込めませんでした", + "unsupportedMediaType": "動画、音声、画像ファイルのみ読み込めます。", + "mediaNoVideoTracks": "メディアに利用できる映像トラックがありません", + "mediaDurationOutOfRange": "メディアの長さがタイムラインの範囲を超えています", + "resourceDownloadHttpFailed": "ダウンロードに失敗しました(HTTP {statusCode})", + "resourceChecksumFailed": "モデルファイルの検証に失敗しました。リソースを再ダウンロードしてください。", + "subtitleLanguageAf": "アフリカーンス語", + "subtitleLanguageAm": "アムハラ語", + "subtitleLanguageAr": "アラビア語", + "subtitleLanguageAst": "アストゥリアス語", + "subtitleLanguageAz": "アゼルバイジャン語", + "subtitleLanguageBa": "バシキール語", + "subtitleLanguageBe": "ベラルーシ語", + "subtitleLanguageBg": "ブルガリア語", + "subtitleLanguageBn": "ベンガル語", + "subtitleLanguageBr": "ブルトン語", + "subtitleLanguageBs": "ボスニア語", + "subtitleLanguageCa": "カタロニア語", + "subtitleLanguageCeb": "セブアノ語", + "subtitleLanguageCs": "チェコ語", + "subtitleLanguageCy": "ウェールズ語", + "subtitleLanguageDa": "デンマーク語", + "subtitleLanguageDe": "ドイツ語", + "subtitleLanguageEl": "ギリシャ語", + "subtitleLanguageEn": "英語", + "subtitleLanguageEs": "スペイン語", + "subtitleLanguageEt": "エストニア語", + "subtitleLanguageFa": "ペルシア語", + "subtitleLanguageFf": "フラ語", + "subtitleLanguageFi": "フィンランド語", + "subtitleLanguageFr": "フランス語", + "subtitleLanguageFy": "西フリジア語", + "subtitleLanguageGa": "アイルランド語", + "subtitleLanguageGd": "スコットランド・ゲール語", + "subtitleLanguageGl": "ガリシア語", + "subtitleLanguageGu": "グジャラート語", + "subtitleLanguageHa": "ハウサ語", + "subtitleLanguageHe": "ヘブライ語", + "subtitleLanguageHi": "ヒンディー語", + "subtitleLanguageHr": "クロアチア語", + "subtitleLanguageHt": "ハイチ・クレオール語", + "subtitleLanguageHu": "ハンガリー語", + "subtitleLanguageHy": "アルメニア語", + "subtitleLanguageId": "インドネシア語", + "subtitleLanguageIg": "イボ語", + "subtitleLanguageIlo": "イロカノ語", + "subtitleLanguageIs": "アイスランド語", + "subtitleLanguageIt": "イタリア語", + "subtitleLanguageJa": "日本語", + "subtitleLanguageJv": "ジャワ語", + "subtitleLanguageKa": "ジョージア語", + "subtitleLanguageKk": "カザフ語", + "subtitleLanguageKm": "クメール語", + "subtitleLanguageKn": "カンナダ語", + "subtitleLanguageKo": "韓国語", + "subtitleLanguageLb": "ルクセンブルク語", + "subtitleLanguageLg": "ガンダ語", + "subtitleLanguageLn": "リンガラ語", + "subtitleLanguageLo": "ラオ語", + "subtitleLanguageLt": "リトアニア語", + "subtitleLanguageLv": "ラトビア語", + "subtitleLanguageMg": "マダガスカル語", + "subtitleLanguageMk": "マケドニア語", + "subtitleLanguageMl": "マラヤーラム語", + "subtitleLanguageMn": "モンゴル語", + "subtitleLanguageMr": "マラーティー語", + "subtitleLanguageMs": "マレー語", + "subtitleLanguageMy": "ミャンマー語", + "subtitleLanguageNe": "ネパール語", + "subtitleLanguageNl": "オランダ語", + "subtitleLanguageNo": "ノルウェー語", + "subtitleLanguageNs": "北部ソト語", + "subtitleLanguageOc": "オック語", + "subtitleLanguageOr": "オディア語", + "subtitleLanguagePa": "パンジャブ語", + "subtitleLanguagePl": "ポーランド語", + "subtitleLanguagePs": "パシュトゥー語", + "subtitleLanguagePt": "ポルトガル語", + "subtitleLanguageRo": "ルーマニア語", + "subtitleLanguageRu": "ロシア語", + "subtitleLanguageSd": "シンド語", + "subtitleLanguageSi": "シンハラ語", + "subtitleLanguageSk": "スロバキア語", + "subtitleLanguageSl": "スロベニア語", + "subtitleLanguageSo": "ソマリ語", + "subtitleLanguageSq": "アルバニア語", + "subtitleLanguageSr": "セルビア語", + "subtitleLanguageSs": "スワジ語", + "subtitleLanguageSu": "スンダ語", + "subtitleLanguageSv": "スウェーデン語", + "subtitleLanguageSw": "スワヒリ語", + "subtitleLanguageTa": "タミル語", + "subtitleLanguageTh": "タイ語", + "subtitleLanguageTl": "タガログ語", + "subtitleLanguageTn": "ツワナ語", + "subtitleLanguageTr": "トルコ語", + "subtitleLanguageUk": "ウクライナ語", + "subtitleLanguageUr": "ウルドゥー語", + "subtitleLanguageUz": "ウズベク語", + "subtitleLanguageVi": "ベトナム語", + "subtitleLanguageWo": "ウォロフ語", + "subtitleLanguageXh": "コサ語", + "subtitleLanguageYi": "イディッシュ語", + "subtitleLanguageYo": "ヨルバ語", + "subtitleLanguageYue": "広東語", + "subtitleLanguageZh": "中国語", + "subtitleLanguageZu": "ズールー語", + "linearRec2020": "リニア Rec.2020", + "diagnostics": "診断", + "exportDiagnostics": "診断パッケージをエクスポート", + "exportDiagnosticsFailed": "診断をエクスポートできませんでした。もう一度お試しください。", + "exportDiagnosticsSucceeded": "診断パッケージを保存しました。" +} diff --git a/lib/l10n/app_ko.arb b/lib/l10n/app_ko.arb new file mode 100644 index 0000000..a1af81b --- /dev/null +++ b/lib/l10n/app_ko.arb @@ -0,0 +1,889 @@ +{ + "projectsNone": "프로젝트가 없습니다", + "agentConversations": "대화", + "renameConversationTitle": "채팅 이름 변경", + "renameConversationDescription": "짧고 알아보기 쉬운 이름을 사용하세요.", + "showMoreConversations": "더 보기", + "showFewerConversations": "접기", + "agentNewConversation": "새 대화", + "agentElapsedTime": "소요 시간 {duration}", + "agentConversationActions": "대화 작업", + "agentMoveToTrash": "휴지통으로 이동", + "agentTrash": "휴지통", + "agentRestore": "복원", + "agentEmptyTrash": "휴지통 비우기", + "agentDeleteForever": "영구 삭제", + "agentConversationLocation": "대화 저장 위치", + "agentChooseExistingConversations": "기존 대화 선택", + "agentMoveConversations": "대화 이동", + "agentLocationUnavailable": "대화 저장 위치를 사용할 수 없습니다", + "agentLocationBusy": "실행 중인 대화가 끝난 후 이동하세요", + "agentRelinkProvider": "제공자 다시 연결", + "@@locale": "ko", + "settings": "설정", + "closeSettings": "설정 닫기", + "general": "일반", + "appearance": "외관", + "theme": "테마", + "system": "시스템 설정 따르기", + "light": "라이트", + "dark": "다크", + "saveAppearanceFailed": "외모를 저장할 수 없습니다. 다시 시도해 주세요.", + "loadAppearanceFailed": "화면 설정을 불러올 수 없습니다. 테마를 다시 선택해 주세요.", + "cancel": "취소", + "save": "저장", + "create": "만들기", + "close": "닫기", + "retry": "다시 시도", + "name": "이름", + "enterName": "이름을 입력하세요", + "invalidName": "이름에는 경로 구분 기호나 제어 문자를 포함할 수 없습니다.", + "projectName": "프로젝트 이름", + "newProject": "새 프로젝트", + "openProject": "프로젝트 열기", + "openProjectMore": "다른 프로젝트 열기", + "projects": "프로젝트", + "projectsEmpty": "프로젝트가 없습니다", + "openingWorkspace": "작업 공간을 여는 중…", + "loadProjectsFailed": "프로젝트를 불러오지 못했습니다", + "backToProjects": "편집으로 돌아가기", + "timelines": "타임라인", + "timelineLimitReached": "프로젝트마다 타임라인을 최대 {count}개까지 만들 수 있습니다.", + "timelineName": "타임라인 이름", + "defaultTimelineName": "타임라인 {index}", + "newTimeline": "새 타임라인", + "noTimelines": "타임라인이 없습니다", + "activeTimeline": "현재 타임라인", + "timelineUnavailable": "타임라인을 사용할 수 없습니다", + "projectNoTimelines": "이 프로젝트에는 타임라인이 없습니다", + "createTimelineHint": "왼쪽의 ‘타임라인’에서 새 타임라인을 만들어 편집을 시작하세요.", + "createTimelineChat": "타임라인을 만들면 채팅을 시작할 수 있습니다", + "editingFirstLayout": "편집 우선", + "agentEditingLayout": "에이전트와 편집", + "agentLayoutDescription": "계획, 협업 및 실행", + "editingLayoutDescription": "미리보기, 편집 및 다듬기", + "saveHere": "여기에 저장", + "selectDirectoryFailed": "디렉터리를 선택할 수 없습니다. 시스템 권한을 확인하세요.", + "operationFailed": "작업이 실패했습니다. 다시 시도해 주세요.", + "collapseSidebar": "사이드바 접기", + "expandSidebar": "사이드바 확장", + "expandEditor": "편집 영역 펼치기", + "collapseProperties": "속성 축소", + "expandProperties": "속성 확장", + "layout": "레이아웃", + "materials": "미디어", + "all": "전체", + "video": "동영상", + "audio": "오디오", + "image": "영상", + "picture": "영상", + "captions": "자막", + "text": "텍스트", + "noMedia": "미디어 없음", + "mediaCategory": "미디어 분류", + "captionTasks": "자막 작업", + "listLayout": "목록 보기", + "gridLayout": "그리드 보기", + "addToTimeline": "타임라인에 추가", + "rename": "이름 바꾸기", + "renameMedia": "미디어 이름 바꾸기", + "removeMedia": "미디어 제거", + "remove": "제거", + "revealFinder": "Finder에서 보기", + "revealFileManager": "파일 관리자에서 보기", + "dropToAdd": "놓으면 추가됩니다", + "timelineDropToStart": "시작하려면 미디어를 여기로 드래그하세요.", + "dragMediaHint": "비디오, 오디오, 이미지를 여기로 드래그하세요.\n원본 파일은 현재 위치에 유지됩니다.", + "transcribe": "음성 받아쓰기", + "generateCaptions": "자막 생성", + "play": "재생", + "pause": "일시 정지", + "retryPreview": "미리보기 재시도", + "canvasRatio": "캔버스 종횡비", + "noPreviewContent": "타임라인에서 미리 볼 콘텐츠가 없습니다.", + "nativePreviewUnsupported": "이 플랫폼에서는 기본 미리보기를 사용할 수 없습니다.", + "canvasTransformFailed": "캔버스를 변환할 수 없습니다. 다시 시도해 주세요.", + "undo": "실행 취소", + "redo": "다시 실행", + "deleteSelectedClips": "선택한 클립 삭제", + "splitAtPlayhead": "플레이헤드에서 분할", + "trimLeft": "왼쪽 자르기", + "trimRight": "오른쪽 자르기", + "trimLeftTooltip": "재생 헤드 왼쪽을 제거하고 오른쪽 유지", + "trimRightTooltip": "재생 헤드 오른쪽을 제거하고 왼쪽 유지", + "currentSequence": "현재 시퀀스", + "projectProperties": "프로젝트 속성", + "canvasSize": "캔버스 크기", + "frameRate": "프레임 속도", + "duration": "지속", + "totalDuration": "총 기간", + "clipDuration": "클립 길이", + "seconds": "초", + "clip": "클립", + "unnamedClip": "이름 없는 클립", + "gap": "간격", + "compoundClip": "복합 클립", + "textClip": "텍스트 클립", + "pictureProperties": "영상", + "position": "위치", + "rotation": "회전", + "scale": "배율", + "size": "크기", + "transform": "변환", + "resetPosition": "위치 초기화", + "keepAspectRatio": "가로 세로 비율 잠금", + "alignment": "정렬", + "alignLeft": "왼쪽 정렬", + "alignRight": "오른쪽 정렬", + "alignTop": "상단 정렬", + "alignBottom": "하단 정렬", + "alignHorizontalCenter": "가로 가운데 정렬", + "alignVerticalCenter": "세로 가운데 정렬", + "volume": "볼륨", + "gain": "게인", + "mute": "음소거", + "unmute": "음소거 해제", + "resetVolume": "볼륨 재설정", + "invalidGain": "-90에서 +12 사이의 값을 입력하세요.", + "animation": "애니메이션", + "keyframes": "키프레임", + "removeAllKeyframes": "모든 키프레임 제거", + "linear": "선형", + "easeIn": "서서히 가속", + "easeOut": "서서히 감속", + "easeInOut": "서서히 가속 및 감속", + "basic": "기본", + "mask": "마스크", + "addMask": "마스크 추가", + "deleteMask": "마스크 삭제", + "resetMask": "마스크 재설정", + "enableMask": "마스크 활성화", + "disableMask": "마스크 비활성화", + "moveMaskUp": "마스크를 위로 이동", + "moveMaskDown": "마스크를 아래로 이동", + "rectangle": "사각형", + "ellipse": "타원", + "invert": "반전", + "feather": "페더", + "add": "더하기", + "subtract": "빼기", + "intersect": "교차", + "initialRegion": "초기 영역", + "none": "없음", + "color": "색상", + "fontSize": "글꼴 크기", + "outlineWidth": "외곽선 두께", + "outlineColor": "외곽선 색상", + "captionBaseline": "자막 기준선", + "content": "텍스트", + "start": "시작", + "time": "시간", + "speed": "속도", + "speedSegmentCount": "속도 구간 {count}개", + "splitSpeedAtPlayhead": "재생 헤드에서 속도 분할", + "speedChange": "속도", + "speedMode": "속도 모드", + "constantSpeed": "일정한 속도", + "segmentedSpeed": "분할 속도", + "speedNotAvailable": "속도 제어는 아직 사용할 수 없습니다.", + "custom": "사용자 지정", + "invalidNumber": "잘못된 값", + "mediaUnavailable": "미디어를 사용할 수 없음", + "mediaMissing": "미디어 누락", + "mediaColorSpace": "미디어 색 공간", + "mediaColorInterpretation": "미디어 색상 해석", + "colorInfoNotLoaded": "색상 정보가 로드되지 않았습니다.", + "unknownColorSpace": "알 수 없는 색상 공간입니다. Rec.709로 표시됩니다.", + "colorBackendUnsupported": "현재 백엔드는 미디어 색상 해석을 지원하지 않습니다.", + "loadClipPropertiesFailed": "클립 속성을 읽을 수 없습니다.", + "updatePictureFailed": "사진 속성을 업데이트할 수 없습니다.", + "updateVolumeFailed": "볼륨을 업데이트할 수 없습니다.", + "updateMaskFailed": "마스크를 업데이트할 수 없습니다.", + "updateKeyframesFailed": "키프레임을 업데이트할 수 없습니다.", + "maskPreviewFailed": "마스크 미리보기를 준비할 수 없습니다.", + "alignClipFailed": "클립을 정렬할 수 없습니다. 미리보기를 기다린 후 다시 시도해 보세요.", + "invalidTransform": "배율은 1%~10000%여야 합니다. 위치와 각도는 유효한 숫자여야 합니다.", + "editFailed": "편집할 수 없습니다. 입력 및 시간 범위를 확인하세요.", + "addMediaFailed": "미디어를 추가할 수 없습니다. 다시 시도해 주세요.", + "deleteCaption": "자막 삭제", + "mergeCaptions": "자막 병합", + "captionDeleted": "자막이 삭제되었습니다", + "captionChanged": "자막이 변경되었습니다. 다시 시도해 주세요.", + "captionEditChanged": "자막이 변경되었습니다. 다시 수정해 주세요.", + "assistantHint": "편집 아이디어를 설명해주세요", + "configureAgentHint": "채팅을 시작하도록 에이전트 서비스 구성", + "agentRestartHint": "에이전트 서비스를 구성한 후 앱을 다시 시작하세요.", + "replyInterrupted": "응답이 중단되었습니다.", + "replying": "응답 중…", + "stopReply": "응답 중지", + "sendMessage": "메시지 보내기", + "addAttachment": "첨부파일 추가(아직 사용할 수 없음)", + "replyFailed": "응답에 실패했습니다. 연결을 확인하거나 나중에 다시 시도하세요.", + "mcpService": "MCP 서비스", + "listenPort": "포트", + "accessToken": "액세스 토큰", + "copyAccessToken": "액세스 토큰 복사", + "accessTokenCopied": "액세스 토큰이 복사되었습니다.", + "loadMcpFailed": "MCP 설정을 로드할 수 없습니다. 다시 해 보다", + "saveMcpFailed": "MCP 설정을 저장할 수 없습니다. 다시 시도해 주세요.", + "retryStart": "다시 시작해 보세요.", + "invalidPort": "포트는 1에서 65535 사이여야 합니다.", + "loadingSettings": "설정 불러오는 중…", + "starting": "시작 중…", + "stopping": "중지 중…", + "disabled": "비활성화됨", + "running": "실행 중", + "startFailed": "시작하지 못했습니다.", + "saved": "저장됨", + "unsaved": "저장되지 않음", + "saving": "저장 중…", + "pendingSave": "저장 대기 중", + "notApplied": "적용되지 않음", + "enable": "활성화", + "disable": "비활성화", + "type": "유형", + "status": "상태", + "file": "파일", + "unboundMedia": "연결된 미디어 없음", + "unboundAudio": "연결된 오디오 트랙 없음", + "vertical": "세로", + "language": "언어", + "saveLanguageFailed": "언어를 저장할 수 없습니다. 다시 시도해 주세요.", + "loadLanguageFailed": "언어를 로드할 수 없습니다. 다시 선택해 주세요.", + "propertiesFirstLayout": "속성 우선", + "defaultLayout": "기본 레이아웃", + "separateVocals": "보컬 분리", + "detachAudio": "오디오 분리", + "restoreAudio": "오디오 복원", + "audioDetached": "오디오가 분리되었습니다", + "addAll": "모두 추가", + "preparingMedia": "미디어 준비 중…", + "cancelling": "취소 중…", + "cancelled": "취소됨", + "interruptedTask": "작업이 중단되었습니다. 계속하려면 다시 시작하세요.", + "auto": "자동", + "autoDetect": "자동 감지", + "noTranslation": "번역 안 함", + "sourceLanguage": "원본 언어", + "translationLanguage": "번역 언어", + "transcriptionNotConfigured": "전사가 구성되지 않았습니다. 인식 구성요소와 Whisper Turbo 모델을 설치합니다.", + "translationNotConfigured": "자막 번역이 구성되지 않았습니다. 소스 언어로 자막을 생성할 수 있습니다.", + "sourceLanguageUnknown": "번역할 소스 언어를 결정할 수 없습니다.", + "startTranscriptionFailed": "스크립트 작성을 시작할 수 없습니다. 미디어를 확인하거나 현재 작업이 완료될 때까지 기다리세요.", + "placeMediaFirst": "자막을 적용하기 전에 이 미디어를 타임라인에 배치하세요.", + "placeTranslationMediaFirst": "번역된 자막을 적용하기 전에 해당 미디어를 타임라인에 배치하세요.", + "selectTargetClip": "대상 클립 선택", + "timelineChanged": "타임라인이 변경되었습니다. 대상 클립을 다시 선택하십시오.", + "transcriptionAccessFailed": "기록 실패: 구성 요소, 모델 또는 소스 미디어에 액세스할 수 없음(notConfigured)", + "transcriptionNoAudio": "녹음 실패: 선택한 미디어 또는 트랙에서 인식할 수 있는 오디오가 없습니다(noAudio).", + "transcriptionInvalidResult": "스크립트 작성 실패: 잘못된 자막 파일이 반환되었습니다(invalidResult).", + "transcriptionWorkerExited": "기록 실패: 인식 구성 요소가 예기치 않게 종료되었습니다(workerExited).", + "transcriptionProcessingFailed": "전사 실패: 기본 처리 실패(processingFailed)", + "transcriptionFailed": "전사에 실패했습니다. 구성 요소, 모델, 오디오 트랙 및 지속 시간을 확인하세요.", + "transcribing": "받아쓰는 중…", + "captionsGenerated": "자막이 생성되었습니다", + "cancelTranscription": "받아쓰기 취소", + "applyCaptions": "자막 적용", + "preparingTranslation": "번역 준비 중…", + "translatingCaptions": "자막 번역 중…", + "cancellingTranslation": "번역 취소 중…", + "translatedCaptionsGenerated": "번역 자막이 생성되었습니다", + "translationCancelled": "번역이 취소되었습니다", + "translationInterrupted": "번역이 중단되었습니다", + "cancelTranslation": "번역 취소", + "editorServiceUnavailable": "편집 서비스를 이용할 수 없습니다. 프로젝트를 다시 엽니다.", + "mcpUnavailable": "MCP 연결을 사용할 수 없습니다. 로컬 포트와 토큰을 확인하세요.", + "openTimelineFailed": "타임라인을 열 수 없습니다.", + "noTimelineSequence": "이 타임라인에는 시퀀스가 없습니다.", + "waitingForProject": "프로젝트가 열리기를 기다리는 중", + "hold": "유지", + "noImportableFiles": "가져올 수 있는 파일이 수신되지 않았습니다.", + "virtualFilesUnsupported": "파일 관리자에서 원본 파일을 드래그하세요. 가상 파일은 아직 지원되지 않습니다.", + "editorSessionStartFailed": "타임라인 편집기를 열 수 없습니다", + "previewStartFailed": "기본 미리보기를 시작할 수 없습니다.", + "previewInvalidTrack": "선택한 오디오 또는 비디오 트랙이 미디어에 존재하지 않습니다.", + "previewMissingBinding": "미디어 바인딩이 누락되었습니다. 이 타임라인을 미리 볼 수 없습니다.", + "previewUnsupportedEdits": "이 타임라인에는 아직 미리보기에서 지원되지 않는 수정사항이 포함되어 있습니다.", + "previewUnsupportedConfiguration": "이 미리보기 구성은 현재 플랫폼 또는 시스템 버전에서 지원되지 않습니다.", + "previewHdrUnsupported": "HDR 미디어에는 SDR 미리 보기를 위한 톤 매핑이 필요합니다. 현재 시스템이나 미리보기 구성에서는 이를 지원하지 않습니다.", + "previewAudioOutOfRange": "오디오 클립이 소스 트랙 범위를 초과하여 미리 볼 수 없습니다.", + "previewResourceMissing": "미리보기 미디어가 더 이상 존재하지 않습니다. 원본 파일을 다시 찾으세요.", + "previewInvalidComposition": "동영상 구성 구성이 잘못되었습니다. 미리보기를 만들 수 없습니다.", + "previewInvalidData": "미리보기 데이터가 잘못되었습니다. 다시 시도해 주세요.", + "previewFailed": "미리보기에 실패했습니다. 미디어 액세스를 확인하고 다시 시도하세요.", + "chatFailed": "대화를 완료할 수 없습니다. 서비스 구성을 확인하거나 나중에 다시 시도하세요.", + "delete": "삭제", + "pinTimeline": "타임라인 고정", + "unpinTimeline": "타임라인 고정 해제", + "deleteTimelineConfirmation": "“{name}” 및 편집 기록을 삭제할까요? 이 작업은 되돌릴 수 없습니다.", + "@deleteTimelineConfirmation": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "processingFailed": "처리 실패", + "noMatchingOptions": "일치하는 옵션 없음", + "removeMediaConfirmation": "라이브러리에서 “{name}”를 제거하시겠습니까? 기존 클립, 히스토리, 원본 파일은 그대로 유지됩니다.", + "@removeMediaConfirmation": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "mediaAdded": "미디어 참조 {count}개가 추가되었습니다", + "@mediaAdded": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "duplicatesSkipped": "{count} 중복 파일을 건너뛰었습니다.", + "@duplicatesSkipped": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mediaCount": "미디어 {count}개", + "importMedia": "가져오기", + "@mediaCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "noMediaOfType": "{type} 미디어 없음", + "@noMediaOfType": { + "placeholders": { + "type": { + "type": "String" + } + } + }, + "captionsImported": "가져온 {count} 자막", + "@captionsImported": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "editCaptionError": "자막을 편집할 수 없습니다: {message}", + "@editCaptionError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "mcpStartError": "MCP를 시작할 수 없습니다: {message}", + "@mcpStartError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "manualColorSpace": "수동 선택: {name}", + "@manualColorSpace": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "detectedColorSpace": "감지됨: {name}", + "@detectedColorSpace": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "keyframeLabel": "{channel} 키프레임", + "@keyframeLabel": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "maskMode": "조합 모드: {mode}", + "@maskMode": { + "placeholders": { + "mode": { + "type": "String" + } + } + }, + "keyframeCount": "키프레임 {count}개", + "@keyframeCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "toggleKeyframe": "{channel} 키프레임 {action}", + "@toggleKeyframe": { + "placeholders": { + "action": { + "type": "String" + }, + "channel": { + "type": "String" + } + } + }, + "previousKeyframe": "이전 {channel} 키프레임", + "@previousKeyframe": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "nextKeyframe": "다음 {channel} 키프레임", + "@nextKeyframe": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "keyframeSettings": "{channel} 키프레임 설정", + "@keyframeSettings": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "selectedClipsHint": "{count} 클립이 선택됨\n해당 속성을 보려면 클립 하나를 선택하세요.", + "@selectedClipsHint": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "transcriptionError": "전사에 실패했습니다. 구성 요소, 모델, 오디오 트랙 및 지속 시간 확인({code})", + "@transcriptionError": { + "placeholders": { + "code": { + "type": "String" + } + } + }, + "captionsAdded": "{count} 자막을 추가했습니다. 속성 패널에서 편집하세요.", + "@captionsAdded": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "translatedCaptionsAdded": "{count} 번역된 자막을 추가했습니다. 속성 패널에서 편집하세요.", + "@translatedCaptionsAdded": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "applyCaptionsError": "자막을 적용할 수 없습니다: {message}", + "@applyCaptionsError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "applyTranslatedCaptionsError": "번역된 자막을 적용할 수 없습니다: {message}", + "@applyTranslatedCaptionsError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "recognizedCaptions": "자막 {count}개 인식됨", + "@recognizedCaptions": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "captionCount": "자막 {count}개", + "@captionCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "translationFailed": "번역 실패: {message}", + "@translationFailed": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "translatedCaptionCount": "{language} 자막 {count}개", + "@translatedCaptionCount": { + "placeholders": { + "count": { + "type": "int" + }, + "language": { + "type": "String" + } + } + }, + "previewParameterError": "잘못된 미리보기 매개변수: {message}", + "@previewParameterError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "mediaOffline": "미디어가 오프라인이거나 사용할 수 없음: {names}", + "@mediaOffline": { + "placeholders": { + "names": { + "type": "String" + } + } + }, + "searchOptions": "{label} 검색…", + "@searchOptions": { + "placeholders": { + "label": { + "type": "String" + } + } + }, + "loadRecentProjectsFailed": "최근 라이브러리를 로드할 수 없습니다. 여전히 수동으로 라이브러리를 열 수 있습니다.", + "projectAccessFailed": "프로젝트를 사용할 수 없음", + "projectMissingDirectory": "프로젝트를 찾을 수 없음", + "recentProjectSaveFailed": "라이브러리가 열렸지만 최근 라이브러리 기록을 저장할 수 없습니다.", + "lastProjectSaveFailed": "프로젝트가 열렸지만 마지막 프로젝트 기록을 저장할 수 없습니다.", + "enterProjectName": "프로젝트 이름을 입력하세요.", + "projectSwitched": "프로젝트가 변경되었습니다. 미디어를 다시 드래그하세요.", + "notLocalMedia": "이 미디어는 로컬 파일이 아닙니다.", + "revealMediaFailed": "파일 관리자에 미디어를 표시할 수 없습니다.", + "openMatchingProject": "먼저 해당 프로젝트를 엽니다.", + "projectMismatch": "이 위치에 있는 라이브러리는 기록과 일치하지 않습니다. 라이브러리 열기로 다시 선택하세요.", + "openProjectFirst": "먼저 라이브러리를 열어보세요", + "localFilesOnly": "파일 관리자에서 로컬 파일 드래그", + "foldersUnsupported": "파일을 선택합니다. 폴더 드래그는 아직 지원되지 않습니다.", + "mediaImportCancelled": "미디어 가져오기가 취소되었습니다.", + "fileAccessFailed": "파일이 없거나 읽을 수 없습니다. 위치와 권한을 확인하세요", + "registerMediaFailed": "미디어를 등록할 수 없습니다. 다시 시도해 주세요", + "mediaNoLongerExists": "미디어가 더 이상 존재하지 않습니다.", + "mediaNoTracks": "미디어에 사용 가능한 비디오 또는 오디오 트랙이 없습니다.", + "invalidMediaDuration": "잘못된 미디어 기간", + "mediaInfoUnsupported": "이 플랫폼에서는 아직 미디어 정보 읽기가 지원되지 않습니다.", + "mediaInfoFailed": "미디어 정보를 읽을 수 없습니다. 파일 및 접근권한을 확인하세요", + "saveTimelineFailed": "타임라인을 저장할 수 없습니다. 다시 시도해 보세요. 저장되지 않은 수정사항은 이 세션에 남아 있습니다.", + "addKeyframeAction": "추가", + "backgroundTasks": "백그라운드 작업", + "noBackgroundTasks": "백그라운드 작업이 없습니다", + "retryTask": "다시 시도", + "applyOriginalCaptions": "원문 자막 적용", + "applyTranslatedCaptions": "번역 자막 적용", + "subtitleTaskStarted": "자막 작업을 시작했습니다", + "fitTimeline": "전체 타임라인 맞춤", + "modify": "Modify", + "projectSettings": "Project settings", + "projectSettingsDescription": "Change project output settings while keeping clip timing and speed.", + "projectColorSpace": "Color space", + "projectWidth": "Width (px)", + "projectHeight": "Height (px)", + "projectResolutionInvalid": "Enter a whole number from 1 to 16384", + "previewFullscreen": "전체 화면 미리보기", + "exitPreviewFullscreen": "전체 화면 종료", + "previewGoToStart": "처음으로 이동", + "previewPreviousFrame": "이전 프레임", + "previewNextFrame": "다음 프레임", + "softwareUpdates": "소프트웨어 업데이트", + "checkForUpdates": "업데이트 확인", + "automaticallyCheckUpdates": "자동으로 업데이트 확인", + "updatesUnavailable": "이 빌드에서는 업데이트를 사용할 수 없습니다.", + "updateCheckFailed": "업데이트를 확인할 수 없습니다. 다시 시도해 주세요.", + "agentSettings": "Agent", + "agentSaveSettingsFailed": "Agent 설정을 저장할 수 없습니다.", + "agentDeleteProviderTitle": "공급자를 삭제할까요?", + "agentDeleteProviderDescription": "‘{providerName}’ 및 저장된 API 키가 이 기기에서 삭제됩니다.", + "agentProviderRequired": "도우미를 활성화하기 전에 공급자를 추가하세요.", + "agentUseSelectedModel": "새 Agent 요청에는 선택한 모델이 사용됩니다.", + "agentEnable": "Agent 활성화", + "agentDefaultModel": "기본 모델", + "agentConfigureModel": "모델 설정", + "agentSelectModel": "모델 선택", + "agentModelUnavailable": "이 대화의 모델을 사용할 수 없습니다. 다른 모델을 선택하여 새 대화를 시작하세요.", + "agentModelChangeSession": "모델을 변경하면 새 Agent 세션이 시작됩니다.", + "agentCustomProviders": "사용자 지정 공급자", + "agentProviderStorageDescription": "공급자 메타데이터는 로컬에 저장됩니다. API 키는 시스템 자격 증명 저장소에 보관됩니다.", + "agentAddProvider": "공급자 추가", + "agentBackToProviders": "Provider 목록으로 돌아가기", + "agentLoadSettingsFailed": "Agent 설정을 불러올 수 없습니다. 다시 시도", + "agentEnableProvider": "Provider 활성화", + "agentEditProvider": "공급자 편집", + "agentDeleteProvider": "공급자 삭제", + "agentModelIdsUnique": "모델 ID는 고유해야 합니다.", + "agentEditProviderTitle": "공급자 편집", + "agentProviderEndpointDescription": "OpenAI 호환 Chat Completions 엔드포인트를 구성합니다.", + "agentSaveProvider": "공급자 저장", + "agentProviderConfiguration": "Provider 설정", + "agentAuthenticationAndModels": "인증 및 모델", + "agentApiType": "API 유형", + "agentOpenAiChatCompletions": "OpenAI Completions", + "agentBaseUrl": "기본 URL", + "agentApiKey": "API 키", + "agentProviderNameHint": "내 공급자", + "agentApiKeyOptional": "인증이 필요하지 않은 엔드포인트에서는 선택 사항입니다.", + "agentApiKeyKeep": "저장된 키를 유지하려면 비워 두세요.", + "agentOptional": "선택 사항", + "agentApiKeyOneLine": "API 키는 한 줄이어야 합니다.", + "agentRemoveSavedApiKey": "저장된 API 키 제거", + "agentModels": "모델", + "agentAddModel": "모델 추가", + "agentRequiredField": "필수 입력 항목입니다.", + "agentInvalidBaseUrl": "자격 증명, 쿼리 또는 프래그먼트가 없는 HTTP(S) 기본 URL을 입력하세요.", + "agentModelId": "모델 ID", + "agentContextWindow": "컨텍스트 창", + "agentMaxOutputTokens": "최대 출력", + "agentMaxOutputBelowContext": "컨텍스트 창보다 작아야 합니다.", + "agentDeleteModel": "모델 삭제", + "agentPositiveInteger": "양의 정수를 입력하세요.", + "agentConfigurationReadFailed": "Agent 구성을 읽을 수 없습니다. 설정을 확인하고 다시 시도하세요.", + "agentConfigurationRequired": "먼저 설정에서 Agent를 구성하고 활성화하세요.", + "agentSessionRestoreFailed": "Agent 세션을 복원할 수 없습니다. 나중에 다시 시도해 주세요.", + "select": "선택", + "projectLocation": "프로젝트 저장 위치", + "projectLocationNotSet": "설정되지 않음", + "resourceLocation": "리소스 저장 위치", + "resourceLocationNotSet": "설정되지 않음", + "loadProjectLocationFailed": "프로젝트 저장 위치를 불러올 수 없습니다.", + "saveProjectLocationFailed": "프로젝트 저장 위치를 저장할 수 없습니다.", + "loadResourceLocationFailed": "리소스 저장 위치를 불러올 수 없습니다.", + "saveResourceLocationFailed": "리소스 저장 위치를 저장할 수 없습니다.", + "downloadAndContinue": "다운로드 후 계속", + "downloadInBackground": "백그라운드에서 다운로드", + "downloadingResource": "다운로드 중…", + "processingResourceDownloadFailed": "음성 인식 리소스를 다운로드할 수 없습니다. 다시 시도해 주세요.", + "transcriptionResourceRequired": "자막을 생성하려면 먼저 음성 인식 모델을 다운로드해야 합니다.", + "removeBackground": "배경 제거", + "startBackgroundRemoval": "배경 제거", + "backgroundRemovalResourceRequired": "배경 제거에는 로컬 모델이 필요합니다. 다운로드가 완료되면 자동으로 시작됩니다.", + "backgroundRemovalDownloadTask": "배경 제거 리소스 다운로드", + "backgroundRemovalResourceName": "배경 제거 모델", + "backgroundRemovalTaskStarted": "배경 제거를 시작했습니다", + "backgroundRemovalApplying": "클립 미디어 교체 중", + "backgroundRemovalComplete": "배경 제거 완료", + "backgroundRemovalFailed": "배경 제거 실패", + "backgroundRemovalDestructiveHint": "생성된 투명 미디어가 이 클립을 대체합니다. 실행 취소로 원본 클립을 복원할 수 있습니다.", + "startBackgroundRemovalFailed": "배경 제거를 시작할 수 없습니다. 미디어를 확인하거나 현재 처리 작업이 끝날 때까지 기다려 주세요.", + "agentContextBudgetExceeded": "시스템 지침, 도구 및 메시지를 위한 입력 공간이 부족합니다. 컨텍스트를 늘리거나 최대 출력을 줄이세요.", + "agentAuthenticationFailed": "인증에 실패했습니다. API Key와 권한을 확인하세요.", + "agentConnectionFailed": "연결에 실패했거나 시간이 초과되었습니다. Base URL과 네트워크를 확인하세요.", + "agentProtocolFailed": "응답이 선택한 API 유형과 다르거나 스트림이 불완전합니다.", + "agentContextBudgetTooSmall": "시스템 지침용 입력 공간을 확보하세요. 컨텍스트를 늘리거나 최대 출력을 줄이세요.", + "agentCompacting": "컨텍스트 정리 중…", + "agentEditing": "편집 중…", + "agentVerifying": "결과 확인 중…", + "agentTurnLimitReached": "작업 실행 한도에 도달했습니다. 편집 내용은 저장되었습니다. “계속”을 보내면 이어서 진행합니다.", + "agentRecoveryRequired": "이전 작업 결과가 확인되지 않았습니다. 계속하여 저장된 기록을 확인하세요. 확인되지 않은 편집은 반복하지 않습니다.", + "agentExportReplyFailed": "동영상 내보내기는 완료되었지만 요약 응답에 실패했습니다. 편집이나 내보내기를 반복하지 않고 요약을 다시 시도할 수 있습니다.", + "agentRetrySummary": "요약 재시도", + "agentResumeTask": "작업 계속", + "agentTaskInterrupted": "작업이 중단되었습니다. 저장된 진행 상태에서 계속할 수 있습니다.", + "downloadSubtitleModel": "자막 모델 다운로드", + "downloadModelAction": "다운로드", + "subtitleEngineUnavailable": "모델은 설치되었지만 자막 처리 엔진을 시작하지 못했습니다. 엔진을 복구하세요. 모델을 다시 다운로드할 필요는 없습니다.", + "backgroundTaskDetails": "작업 상세", + "backgroundTaskFailed": "실패", + "backgroundTaskCompleted": "완료", + "captionWrapLines": "자막 줄바꿈", + "captionSingleLine": "자막을 한 줄로 표시", + "noMatchingCaptions": "일치하는 자막 없음", + "subtitleResourcesRequired": "자막 생성에 필요한 리소스입니다. 다운로드가 끝나면 자동으로 생성이 시작됩니다.", + "subtitleResourcesDownloadSize": "다운로드할 용량: {size}", + "pauseDownload": "일시 중지", + "resumeDownload": "계속", + "downloadPaused": "일시 중지됨", + "cancelResourceDownloadTitle": "다운로드를 취소할까요?", + "cancelResourceDownloadMessage": "다운로드가 중지됩니다. 현재 리소스의 다운로드 진행 내용이 손실될 수 있습니다.", + "continueDownload": "다운로드 계속", + "cancelDownload": "다운로드 취소", + "speechResourceStage": "음성 인식 리소스", + "translationResourceStage": "번역 리소스", + "subtitleResourceDownloadTask": "음성 및 번역 리소스 다운로드", + "downloadingSpeechModel": "음성 모델 다운로드 중", + "downloadingTranslationModel": "번역 모델 다운로드 중", + "selectProject": "프로젝트 선택", + "searchProjects": "프로젝트 검색", + "noMatchingProjects": "일치하는 프로젝트가 없습니다", + "projectLocationMissing": "폴더가 없습니다. 프로젝트를 만들 때 생성됩니다.", + "projectLocationUnavailable": "프로젝트 저장 위치를 사용할 수 없습니다. 디스크나 네트워크를 확인하고 다시 시도하거나 위치를 변경하세요.", + "projectLocationNotWritable": "프로젝트 저장 위치에 쓸 수 없습니다. 권한을 확인하거나 위치를 변경하세요.", + "projectLocationCreateFailed": "프로젝트 저장 폴더를 만들거나 쓸 수 없습니다. 권한을 확인하거나 위치를 변경하세요.", + "removeProjectFromSidebar": "사이드바에서 제거", + "projectRemoved": "프로젝트를 목록에서 제거했습니다. 로컬 파일과 대화는 유지됩니다.", + "agentNoConversations": "아직 대화가 없습니다", + "collapseProject": "프로젝트 접기", + "expandProject": "프로젝트 펼치기", + "agentDeleteConfirmation": "“{title}” 및 모든 메시지를 영구적으로 삭제할까요? 이 작업은 취소할 수 없습니다. 로컬 프로젝트 파일에는 영향을 주지 않습니다.", + "agentEmptyTrashConfirmation": "휴지통의 모든 대화를 영구적으로 삭제할까요? 이 작업은 취소할 수 없습니다. 로컬 프로젝트 파일에는 영향을 주지 않습니다.", + "checkingForUpdates": "업데이트 확인 중…", + "appIsUpToDate": "최신 버전입니다.", + "downloadingUpdate": "업데이트 다운로드 중: {progress}%", + "updateAvailable": "버전 {version}을 사용할 수 있습니다.", + "downloadUpdate": "업데이트 다운로드", + "restartToUpdate": "다시 시작하여 업데이트", + "updateOperationFailed": "업데이트하지 못했습니다. 실행 중인 작업을 완료한 후 다시 시도하세요.", + "windowMinimize": "최소화", + "windowMaximize": "최대화", + "windowRestore": "복원", + "workspaceAgent": "도우미", + "workspaceCut": "편집", + "noAvailableOptions": "사용 가능한 옵션이 없습니다", + "composerReferenceInvalid": "참조가 만료되었습니다. 원래 프로젝트로 돌아가거나 참조를 제거하세요.", + "durationSeconds": "{seconds}초", + "durationMinutesSeconds": "{minutes}분 {seconds}초", + "projectNameInvalid": "잘못된 프로젝트 이름입니다", + "projectLocationDefaultUnavailable": "기본 프로젝트 위치에 접근할 수 없습니다. 설정에서 다시 선택하세요.", + "chooseProjectLocation": "먼저 설정에서 프로젝트 저장 위치를 선택하세요.", + "untitledTimeline": "제목 없는 타임라인", + "primarySequence": "주 시퀀스", + "primaryStoryline": "주 스토리라인", + "projectSessionClosed": "프로젝트 세션이 닫혔습니다. 프로젝트를 다시 여세요.", + "timelineSessionClosed": "타임라인 세션이 닫혔습니다. 타임라인을 다시 여세요.", + "timelineMissing": "타임라인이 없거나 삭제되었습니다.", + "timelineInUse": "사용 중인 타임라인은 삭제할 수 없습니다.", + "timelineHasBackgroundTasks": "타임라인의 백그라운드 작업을 완료한 후 삭제하세요.", + "timelineRequired": "프로젝트에 타임라인이 하나 이상 있어야 합니다.", + "mediaReadFailed": "미디어를 읽을 수 없습니다", + "mediaImportFailed": "미디어를 가져올 수 없습니다", + "unsupportedMediaType": "동영상, 오디오 및 이미지 파일만 가져올 수 있습니다.", + "mediaNoVideoTracks": "미디어에 사용 가능한 동영상 트랙이 없습니다", + "mediaDurationOutOfRange": "미디어 길이가 타임라인 범위를 초과합니다", + "resourceDownloadHttpFailed": "다운로드 실패 (HTTP {statusCode})", + "resourceChecksumFailed": "모델 파일 검증에 실패했습니다. 리소스를 다시 다운로드하세요.", + "subtitleLanguageAf": "아프리칸스어", + "subtitleLanguageAm": "암하라어", + "subtitleLanguageAr": "아랍어", + "subtitleLanguageAst": "아스투리아어", + "subtitleLanguageAz": "아제르바이잔어", + "subtitleLanguageBa": "바슈키르어", + "subtitleLanguageBe": "벨라루스어", + "subtitleLanguageBg": "불가리아어", + "subtitleLanguageBn": "벵골어", + "subtitleLanguageBr": "브르타뉴어", + "subtitleLanguageBs": "보스니아어", + "subtitleLanguageCa": "카탈로니아어", + "subtitleLanguageCeb": "세부아노어", + "subtitleLanguageCs": "체코어", + "subtitleLanguageCy": "웨일스어", + "subtitleLanguageDa": "덴마크어", + "subtitleLanguageDe": "독일어", + "subtitleLanguageEl": "그리스어", + "subtitleLanguageEn": "영어", + "subtitleLanguageEs": "스페인어", + "subtitleLanguageEt": "에스토니아어", + "subtitleLanguageFa": "페르시아어", + "subtitleLanguageFf": "풀라어", + "subtitleLanguageFi": "핀란드어", + "subtitleLanguageFr": "프랑스어", + "subtitleLanguageFy": "서부 프리지아어", + "subtitleLanguageGa": "아일랜드어", + "subtitleLanguageGd": "스코틀랜드 게일어", + "subtitleLanguageGl": "갈리시아어", + "subtitleLanguageGu": "구자라트어", + "subtitleLanguageHa": "하우사어", + "subtitleLanguageHe": "히브리어", + "subtitleLanguageHi": "힌디어", + "subtitleLanguageHr": "크로아티아어", + "subtitleLanguageHt": "아이티어", + "subtitleLanguageHu": "헝가리어", + "subtitleLanguageHy": "아르메니아어", + "subtitleLanguageId": "인도네시아어", + "subtitleLanguageIg": "이그보어", + "subtitleLanguageIlo": "이로코어", + "subtitleLanguageIs": "아이슬란드어", + "subtitleLanguageIt": "이탈리아어", + "subtitleLanguageJa": "일본어", + "subtitleLanguageJv": "자바어", + "subtitleLanguageKa": "조지아어", + "subtitleLanguageKk": "카자흐어", + "subtitleLanguageKm": "크메르어", + "subtitleLanguageKn": "칸나다어", + "subtitleLanguageKo": "한국어", + "subtitleLanguageLb": "룩셈부르크어", + "subtitleLanguageLg": "간다어", + "subtitleLanguageLn": "링갈라어", + "subtitleLanguageLo": "라오어", + "subtitleLanguageLt": "리투아니아어", + "subtitleLanguageLv": "라트비아어", + "subtitleLanguageMg": "말라가시어", + "subtitleLanguageMk": "마케도니아어", + "subtitleLanguageMl": "말라얄람어", + "subtitleLanguageMn": "몽골어", + "subtitleLanguageMr": "마라티어", + "subtitleLanguageMs": "말레이어", + "subtitleLanguageMy": "버마어", + "subtitleLanguageNe": "네팔어", + "subtitleLanguageNl": "네덜란드어", + "subtitleLanguageNo": "노르웨이어", + "subtitleLanguageNs": "북부 소토어", + "subtitleLanguageOc": "오크어", + "subtitleLanguageOr": "오리야어", + "subtitleLanguagePa": "펀자브어", + "subtitleLanguagePl": "폴란드어", + "subtitleLanguagePs": "파슈토어", + "subtitleLanguagePt": "포르투갈어", + "subtitleLanguageRo": "루마니아어", + "subtitleLanguageRu": "러시아어", + "subtitleLanguageSd": "신디어", + "subtitleLanguageSi": "싱할라어", + "subtitleLanguageSk": "슬로바키아어", + "subtitleLanguageSl": "슬로베니아어", + "subtitleLanguageSo": "소말리아어", + "subtitleLanguageSq": "알바니아어", + "subtitleLanguageSr": "세르비아어", + "subtitleLanguageSs": "시스와티어", + "subtitleLanguageSu": "순다어", + "subtitleLanguageSv": "스웨덴어", + "subtitleLanguageSw": "스와힐리어", + "subtitleLanguageTa": "타밀어", + "subtitleLanguageTh": "태국어", + "subtitleLanguageTl": "타갈로그어", + "subtitleLanguageTn": "츠와나어", + "subtitleLanguageTr": "튀르키예어", + "subtitleLanguageUk": "우크라이나어", + "subtitleLanguageUr": "우르두어", + "subtitleLanguageUz": "우즈베크어", + "subtitleLanguageVi": "베트남어", + "subtitleLanguageWo": "월로프어", + "subtitleLanguageXh": "코사어", + "subtitleLanguageYi": "이디시어", + "subtitleLanguageYo": "요루바어", + "subtitleLanguageYue": "광둥어", + "subtitleLanguageZh": "중국어", + "subtitleLanguageZu": "줄루어", + "linearRec2020": "선형 Rec.2020", + "diagnostics": "진단", + "exportDiagnostics": "진단 패키지 내보내기", + "exportDiagnosticsFailed": "진단을 내보낼 수 없습니다. 다시 시도해 주세요.", + "exportDiagnosticsSucceeded": "진단 패키지가 저장되었습니다." +} diff --git a/lib/l10n/app_localizations.dart b/lib/l10n/app_localizations.dart new file mode 100644 index 0000000..1076a2c --- /dev/null +++ b/lib/l10n/app_localizations.dart @@ -0,0 +1,4170 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_localizations/flutter_localizations.dart'; +import 'package:intl/intl.dart' as intl; + +import 'app_localizations_de.dart'; +import 'app_localizations_en.dart'; +import 'app_localizations_es.dart'; +import 'app_localizations_fr.dart'; +import 'app_localizations_it.dart'; +import 'app_localizations_ja.dart'; +import 'app_localizations_ko.dart'; +import 'app_localizations_pt.dart'; +import 'app_localizations_ru.dart'; +import 'app_localizations_zh.dart'; + +// ignore_for_file: type=lint + +/// Callers can lookup localized strings with an instance of AppLocalizations +/// returned by `AppLocalizations.of(context)`. +/// +/// Applications need to include `AppLocalizations.delegate()` in their app's +/// `localizationDelegates` list, and the locales they support in the app's +/// `supportedLocales` list. For example: +/// +/// ```dart +/// import 'l10n/app_localizations.dart'; +/// +/// return MaterialApp( +/// localizationsDelegates: AppLocalizations.localizationsDelegates, +/// supportedLocales: AppLocalizations.supportedLocales, +/// home: MyApplicationHome(), +/// ); +/// ``` +/// +/// ## Update pubspec.yaml +/// +/// Please make sure to update your pubspec.yaml to include the following +/// packages: +/// +/// ```yaml +/// dependencies: +/// # Internationalization support. +/// flutter_localizations: +/// sdk: flutter +/// intl: any # Use the pinned version from flutter_localizations +/// +/// # Rest of dependencies +/// ``` +/// +/// ## iOS Applications +/// +/// iOS applications define key application metadata, including supported +/// locales, in an Info.plist file that is built into the application bundle. +/// To configure the locales supported by your app, you’ll need to edit this +/// file. +/// +/// First, open your project’s ios/Runner.xcworkspace Xcode workspace file. +/// Then, in the Project Navigator, open the Info.plist file under the Runner +/// project’s Runner folder. +/// +/// Next, select the Information Property List item, select Add Item from the +/// Editor menu, then select Localizations from the pop-up menu. +/// +/// Select and expand the newly-created Localizations item then, for each +/// locale your application supports, add a new item and select the locale +/// you wish to add from the pop-up menu in the Value field. This list should +/// be consistent with the languages listed in the AppLocalizations.supportedLocales +/// property. +abstract class AppLocalizations { + AppLocalizations(String locale) + : localeName = intl.Intl.canonicalizedLocale(locale.toString()); + + final String localeName; + + static AppLocalizations? of(BuildContext context) { + return Localizations.of(context, AppLocalizations); + } + + static const LocalizationsDelegate delegate = + _AppLocalizationsDelegate(); + + /// A list of this localizations delegate along with the default localizations + /// delegates. + /// + /// Returns a list of localizations delegates containing this delegate along with + /// GlobalMaterialLocalizations.delegate, GlobalCupertinoLocalizations.delegate, + /// and GlobalWidgetsLocalizations.delegate. + /// + /// Additional delegates can be added by appending to this list in + /// MaterialApp. This list does not have to be used at all if a custom list + /// of delegates is preferred or required. + static const List> localizationsDelegates = + >[ + delegate, + GlobalMaterialLocalizations.delegate, + GlobalCupertinoLocalizations.delegate, + GlobalWidgetsLocalizations.delegate, + ]; + + /// A list of this localizations delegate's supported locales. + static const List supportedLocales = [ + Locale('en'), + Locale('de'), + Locale('es'), + Locale('fr'), + Locale('it'), + Locale('ja'), + Locale('ko'), + Locale('pt'), + Locale('ru'), + Locale('zh'), + Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hans'), + Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hant'), + ]; + + /// No description provided for @selectProject. + /// + /// In en, this message translates to: + /// **'Select project'** + String get selectProject; + + /// No description provided for @searchProjects. + /// + /// In en, this message translates to: + /// **'Search projects'** + String get searchProjects; + + /// No description provided for @noMatchingProjects. + /// + /// In en, this message translates to: + /// **'No matching projects'** + String get noMatchingProjects; + + /// No description provided for @projectsNone. + /// + /// In en, this message translates to: + /// **'No projects yet'** + String get projectsNone; + + /// No description provided for @projectLocationMissing. + /// + /// In en, this message translates to: + /// **'The folder does not exist. It will be created when you create a project.'** + String get projectLocationMissing; + + /// No description provided for @projectLocationUnavailable. + /// + /// In en, this message translates to: + /// **'The project save location is unavailable. Connect the disk or check the network and retry, or change the location.'** + String get projectLocationUnavailable; + + /// No description provided for @projectLocationNotWritable. + /// + /// In en, this message translates to: + /// **'The project save location is not writable. Check permissions or change the location.'** + String get projectLocationNotWritable; + + /// No description provided for @projectLocationCreateFailed. + /// + /// In en, this message translates to: + /// **'Could not create or write to the project save folder. Check permissions or change the location.'** + String get projectLocationCreateFailed; + + /// No description provided for @removeProjectFromSidebar. + /// + /// In en, this message translates to: + /// **'Remove from sidebar'** + String get removeProjectFromSidebar; + + /// No description provided for @projectRemoved. + /// + /// In en, this message translates to: + /// **'Project removed. Local files and conversations are preserved.'** + String get projectRemoved; + + /// No description provided for @agentNoConversations. + /// + /// In en, this message translates to: + /// **'No conversations yet'** + String get agentNoConversations; + + /// No description provided for @renameConversationTitle. + /// + /// In en, this message translates to: + /// **'Rename chat'** + String get renameConversationTitle; + + /// No description provided for @renameConversationDescription. + /// + /// In en, this message translates to: + /// **'Keep it short and easy to recognize.'** + String get renameConversationDescription; + + /// No description provided for @collapseProject. + /// + /// In en, this message translates to: + /// **'Collapse project'** + String get collapseProject; + + /// No description provided for @expandProject. + /// + /// In en, this message translates to: + /// **'Expand project'** + String get expandProject; + + /// No description provided for @agentDeleteConfirmation. + /// + /// In en, this message translates to: + /// **'Permanently delete “{title}” and all its messages? This cannot be undone. Local project files will not be affected.'** + String agentDeleteConfirmation(String title); + + /// No description provided for @agentEmptyTrashConfirmation. + /// + /// In en, this message translates to: + /// **'Permanently delete all conversations in Trash? This cannot be undone. Local project files will not be affected.'** + String get agentEmptyTrashConfirmation; + + /// No description provided for @agentConversations. + /// + /// In en, this message translates to: + /// **'Conversations'** + String get agentConversations; + + /// No description provided for @showMoreConversations. + /// + /// In en, this message translates to: + /// **'Show more'** + String get showMoreConversations; + + /// No description provided for @showFewerConversations. + /// + /// In en, this message translates to: + /// **'Show fewer'** + String get showFewerConversations; + + /// No description provided for @agentNewConversation. + /// + /// In en, this message translates to: + /// **'New conversation'** + String get agentNewConversation; + + /// No description provided for @agentElapsedTime. + /// + /// In en, this message translates to: + /// **'Took {duration}'** + String agentElapsedTime(String duration); + + /// No description provided for @agentConversationActions. + /// + /// In en, this message translates to: + /// **'Conversation actions'** + String get agentConversationActions; + + /// No description provided for @agentMoveToTrash. + /// + /// In en, this message translates to: + /// **'Move to Trash'** + String get agentMoveToTrash; + + /// No description provided for @agentTrash. + /// + /// In en, this message translates to: + /// **'Trash'** + String get agentTrash; + + /// No description provided for @agentRestore. + /// + /// In en, this message translates to: + /// **'Restore'** + String get agentRestore; + + /// No description provided for @agentEmptyTrash. + /// + /// In en, this message translates to: + /// **'Empty Trash'** + String get agentEmptyTrash; + + /// No description provided for @agentDeleteForever. + /// + /// In en, this message translates to: + /// **'Delete permanently'** + String get agentDeleteForever; + + /// No description provided for @agentConversationLocation. + /// + /// In en, this message translates to: + /// **'Conversation location'** + String get agentConversationLocation; + + /// No description provided for @agentChooseExistingConversations. + /// + /// In en, this message translates to: + /// **'Choose existing conversations'** + String get agentChooseExistingConversations; + + /// No description provided for @agentMoveConversations. + /// + /// In en, this message translates to: + /// **'Move conversations'** + String get agentMoveConversations; + + /// No description provided for @agentLocationUnavailable. + /// + /// In en, this message translates to: + /// **'Conversation location is unavailable'** + String get agentLocationUnavailable; + + /// No description provided for @agentLocationBusy. + /// + /// In en, this message translates to: + /// **'Finish current conversations before moving files'** + String get agentLocationBusy; + + /// No description provided for @agentRelinkProvider. + /// + /// In en, this message translates to: + /// **'Relink provider'** + String get agentRelinkProvider; + + /// No description provided for @settings. + /// + /// In en, this message translates to: + /// **'Settings'** + String get settings; + + /// No description provided for @closeSettings. + /// + /// In en, this message translates to: + /// **'Close settings'** + String get closeSettings; + + /// No description provided for @general. + /// + /// In en, this message translates to: + /// **'General'** + String get general; + + /// No description provided for @appearance. + /// + /// In en, this message translates to: + /// **'Appearance'** + String get appearance; + + /// No description provided for @theme. + /// + /// In en, this message translates to: + /// **'Theme'** + String get theme; + + /// No description provided for @system. + /// + /// In en, this message translates to: + /// **'System default'** + String get system; + + /// No description provided for @light. + /// + /// In en, this message translates to: + /// **'Light'** + String get light; + + /// No description provided for @dark. + /// + /// In en, this message translates to: + /// **'Dark'** + String get dark; + + /// No description provided for @saveAppearanceFailed. + /// + /// In en, this message translates to: + /// **'Could not save appearance. Please try again.'** + String get saveAppearanceFailed; + + /// No description provided for @loadAppearanceFailed. + /// + /// In en, this message translates to: + /// **'Could not load appearance. Please select a theme again.'** + String get loadAppearanceFailed; + + /// No description provided for @cancel. + /// + /// In en, this message translates to: + /// **'Cancel'** + String get cancel; + + /// No description provided for @save. + /// + /// In en, this message translates to: + /// **'Save'** + String get save; + + /// No description provided for @create. + /// + /// In en, this message translates to: + /// **'Create'** + String get create; + + /// No description provided for @close. + /// + /// In en, this message translates to: + /// **'Close'** + String get close; + + /// No description provided for @retry. + /// + /// In en, this message translates to: + /// **'Retry'** + String get retry; + + /// No description provided for @select. + /// + /// In en, this message translates to: + /// **'Select'** + String get select; + + /// No description provided for @name. + /// + /// In en, this message translates to: + /// **'Name'** + String get name; + + /// No description provided for @enterName. + /// + /// In en, this message translates to: + /// **'Enter a name'** + String get enterName; + + /// No description provided for @invalidName. + /// + /// In en, this message translates to: + /// **'Names cannot contain path separators or control characters'** + String get invalidName; + + /// No description provided for @projects. + /// + /// In en, this message translates to: + /// **'Projects'** + String get projects; + + /// No description provided for @projectName. + /// + /// In en, this message translates to: + /// **'Project name'** + String get projectName; + + /// No description provided for @projectLocation. + /// + /// In en, this message translates to: + /// **'Project save location'** + String get projectLocation; + + /// No description provided for @projectLocationNotSet. + /// + /// In en, this message translates to: + /// **'Not set'** + String get projectLocationNotSet; + + /// No description provided for @loadProjectLocationFailed. + /// + /// In en, this message translates to: + /// **'Could not load the project save location.'** + String get loadProjectLocationFailed; + + /// No description provided for @saveProjectLocationFailed. + /// + /// In en, this message translates to: + /// **'Could not save the project save location.'** + String get saveProjectLocationFailed; + + /// No description provided for @resourceLocation. + /// + /// In en, this message translates to: + /// **'Resource storage location'** + String get resourceLocation; + + /// No description provided for @resourceLocationNotSet. + /// + /// In en, this message translates to: + /// **'Not set'** + String get resourceLocationNotSet; + + /// No description provided for @loadResourceLocationFailed. + /// + /// In en, this message translates to: + /// **'Could not load the resource storage location.'** + String get loadResourceLocationFailed; + + /// No description provided for @saveResourceLocationFailed. + /// + /// In en, this message translates to: + /// **'Could not save the resource storage location.'** + String get saveResourceLocationFailed; + + /// No description provided for @transcriptionResourceRequired. + /// + /// In en, this message translates to: + /// **'Generating subtitles requires downloading a speech recognition model first.'** + String get transcriptionResourceRequired; + + /// No description provided for @downloadAndContinue. + /// + /// In en, this message translates to: + /// **'Download and continue'** + String get downloadAndContinue; + + /// No description provided for @downloadingResource. + /// + /// In en, this message translates to: + /// **'Downloading…'** + String get downloadingResource; + + /// No description provided for @downloadInBackground. + /// + /// In en, this message translates to: + /// **'Download in background'** + String get downloadInBackground; + + /// No description provided for @processingResourceDownloadFailed. + /// + /// In en, this message translates to: + /// **'Could not download the speech recognition resource. Please try again.'** + String get processingResourceDownloadFailed; + + /// No description provided for @newProject. + /// + /// In en, this message translates to: + /// **'New project'** + String get newProject; + + /// No description provided for @openProject. + /// + /// In en, this message translates to: + /// **'Open project'** + String get openProject; + + /// No description provided for @openProjectMore. + /// + /// In en, this message translates to: + /// **'Open project…'** + String get openProjectMore; + + /// No description provided for @saveHere. + /// + /// In en, this message translates to: + /// **'Save here'** + String get saveHere; + + /// No description provided for @selectDirectoryFailed. + /// + /// In en, this message translates to: + /// **'Could not select a directory. Check system permissions.'** + String get selectDirectoryFailed; + + /// No description provided for @openingWorkspace. + /// + /// In en, this message translates to: + /// **'Opening workspace…'** + String get openingWorkspace; + + /// No description provided for @loadProjectsFailed. + /// + /// In en, this message translates to: + /// **'Could not load projects'** + String get loadProjectsFailed; + + /// No description provided for @projectsEmpty. + /// + /// In en, this message translates to: + /// **'Create or open a project to start editing.'** + String get projectsEmpty; + + /// No description provided for @backToProjects. + /// + /// In en, this message translates to: + /// **'Back to editing'** + String get backToProjects; + + /// No description provided for @timelines. + /// + /// In en, this message translates to: + /// **'Timelines'** + String get timelines; + + /// No description provided for @timelineLimitReached. + /// + /// In en, this message translates to: + /// **'Each project can contain up to {count} timelines.'** + String timelineLimitReached(int count); + + /// No description provided for @timelineName. + /// + /// In en, this message translates to: + /// **'Timeline name'** + String get timelineName; + + /// Default name assigned to a newly created timeline. + /// + /// In en, this message translates to: + /// **'Timeline {index}'** + String defaultTimelineName(int index); + + /// No description provided for @newTimeline. + /// + /// In en, this message translates to: + /// **'New timeline'** + String get newTimeline; + + /// No description provided for @noTimelines. + /// + /// In en, this message translates to: + /// **'No timelines'** + String get noTimelines; + + /// No description provided for @activeTimeline. + /// + /// In en, this message translates to: + /// **'Current timeline'** + String get activeTimeline; + + /// No description provided for @timelineUnavailable. + /// + /// In en, this message translates to: + /// **'Timeline unavailable'** + String get timelineUnavailable; + + /// No description provided for @projectNoTimelines. + /// + /// In en, this message translates to: + /// **'This project has no timelines yet'** + String get projectNoTimelines; + + /// No description provided for @createTimelineHint. + /// + /// In en, this message translates to: + /// **'Create a timeline in the Timelines section on the left to start editing.'** + String get createTimelineHint; + + /// No description provided for @createTimelineChat. + /// + /// In en, this message translates to: + /// **'Create a timeline to start chatting'** + String get createTimelineChat; + + /// No description provided for @operationFailed. + /// + /// In en, this message translates to: + /// **'Operation failed. Please try again.'** + String get operationFailed; + + /// No description provided for @collapseSidebar. + /// + /// In en, this message translates to: + /// **'Collapse sidebar'** + String get collapseSidebar; + + /// No description provided for @expandSidebar. + /// + /// In en, this message translates to: + /// **'Expand sidebar'** + String get expandSidebar; + + /// No description provided for @expandEditor. + /// + /// In en, this message translates to: + /// **'Expand editing area'** + String get expandEditor; + + /// No description provided for @collapseProperties. + /// + /// In en, this message translates to: + /// **'Collapse properties'** + String get collapseProperties; + + /// No description provided for @expandProperties. + /// + /// In en, this message translates to: + /// **'Expand properties'** + String get expandProperties; + + /// No description provided for @layout. + /// + /// In en, this message translates to: + /// **'Layout'** + String get layout; + + /// No description provided for @editingFirstLayout. + /// + /// In en, this message translates to: + /// **'Editing first'** + String get editingFirstLayout; + + /// No description provided for @agentEditingLayout. + /// + /// In en, this message translates to: + /// **'Agent + editing'** + String get agentEditingLayout; + + /// No description provided for @agentLayoutDescription. + /// + /// In en, this message translates to: + /// **'Plan, collaborate, and execute'** + String get agentLayoutDescription; + + /// No description provided for @editingLayoutDescription. + /// + /// In en, this message translates to: + /// **'Preview, edit, and refine'** + String get editingLayoutDescription; + + /// No description provided for @materials. + /// + /// In en, this message translates to: + /// **'Media'** + String get materials; + + /// No description provided for @all. + /// + /// In en, this message translates to: + /// **'All'** + String get all; + + /// No description provided for @video. + /// + /// In en, this message translates to: + /// **'Video'** + String get video; + + /// No description provided for @audio. + /// + /// In en, this message translates to: + /// **'Audio'** + String get audio; + + /// No description provided for @image. + /// + /// In en, this message translates to: + /// **'Image'** + String get image; + + /// No description provided for @picture. + /// + /// In en, this message translates to: + /// **'Image'** + String get picture; + + /// No description provided for @captions. + /// + /// In en, this message translates to: + /// **'Captions'** + String get captions; + + /// No description provided for @text. + /// + /// In en, this message translates to: + /// **'Text'** + String get text; + + /// No description provided for @noMedia. + /// + /// In en, this message translates to: + /// **'No media'** + String get noMedia; + + /// No description provided for @mediaCategory. + /// + /// In en, this message translates to: + /// **'Media category'** + String get mediaCategory; + + /// No description provided for @captionTasks. + /// + /// In en, this message translates to: + /// **'Caption tasks'** + String get captionTasks; + + /// No description provided for @listLayout. + /// + /// In en, this message translates to: + /// **'List view'** + String get listLayout; + + /// No description provided for @gridLayout. + /// + /// In en, this message translates to: + /// **'Grid view'** + String get gridLayout; + + /// No description provided for @addToTimeline. + /// + /// In en, this message translates to: + /// **'Add to timeline'** + String get addToTimeline; + + /// No description provided for @rename. + /// + /// In en, this message translates to: + /// **'Rename'** + String get rename; + + /// No description provided for @renameMedia. + /// + /// In en, this message translates to: + /// **'Rename media'** + String get renameMedia; + + /// No description provided for @removeMedia. + /// + /// In en, this message translates to: + /// **'Remove media'** + String get removeMedia; + + /// No description provided for @remove. + /// + /// In en, this message translates to: + /// **'Remove'** + String get remove; + + /// No description provided for @revealFinder. + /// + /// In en, this message translates to: + /// **'Show in Finder'** + String get revealFinder; + + /// No description provided for @revealFileManager. + /// + /// In en, this message translates to: + /// **'Show in file manager'** + String get revealFileManager; + + /// No description provided for @dropToAdd. + /// + /// In en, this message translates to: + /// **'Release to add'** + String get dropToAdd; + + /// No description provided for @timelineDropToStart. + /// + /// In en, this message translates to: + /// **'Drag media here to get started.'** + String get timelineDropToStart; + + /// No description provided for @dragMediaHint. + /// + /// In en, this message translates to: + /// **'Drag video, audio, or images here\nOriginal files stay in their current location'** + String get dragMediaHint; + + /// No description provided for @transcribe. + /// + /// In en, this message translates to: + /// **'Transcribe'** + String get transcribe; + + /// No description provided for @generateCaptions. + /// + /// In en, this message translates to: + /// **'Generate captions'** + String get generateCaptions; + + /// No description provided for @play. + /// + /// In en, this message translates to: + /// **'Play'** + String get play; + + /// No description provided for @pause. + /// + /// In en, this message translates to: + /// **'Pause'** + String get pause; + + /// No description provided for @retryPreview. + /// + /// In en, this message translates to: + /// **'Retry preview'** + String get retryPreview; + + /// No description provided for @canvasRatio. + /// + /// In en, this message translates to: + /// **'Canvas aspect ratio'** + String get canvasRatio; + + /// No description provided for @noPreviewContent. + /// + /// In en, this message translates to: + /// **'No content to preview on the timeline'** + String get noPreviewContent; + + /// No description provided for @nativePreviewUnsupported. + /// + /// In en, this message translates to: + /// **'Native preview is unavailable on this platform'** + String get nativePreviewUnsupported; + + /// No description provided for @canvasTransformFailed. + /// + /// In en, this message translates to: + /// **'Could not transform the canvas. Please try again.'** + String get canvasTransformFailed; + + /// No description provided for @undo. + /// + /// In en, this message translates to: + /// **'Undo'** + String get undo; + + /// No description provided for @redo. + /// + /// In en, this message translates to: + /// **'Redo'** + String get redo; + + /// No description provided for @deleteSelectedClips. + /// + /// In en, this message translates to: + /// **'Delete selected clips'** + String get deleteSelectedClips; + + /// No description provided for @splitAtPlayhead. + /// + /// In en, this message translates to: + /// **'Split at playhead'** + String get splitAtPlayhead; + + /// No description provided for @trimLeft. + /// + /// In en, this message translates to: + /// **'Trim left'** + String get trimLeft; + + /// No description provided for @trimRight. + /// + /// In en, this message translates to: + /// **'Trim right'** + String get trimRight; + + /// No description provided for @trimLeftTooltip. + /// + /// In en, this message translates to: + /// **'Trim away the left of the playhead, keeping the right'** + String get trimLeftTooltip; + + /// No description provided for @trimRightTooltip. + /// + /// In en, this message translates to: + /// **'Trim away the right of the playhead, keeping the left'** + String get trimRightTooltip; + + /// No description provided for @currentSequence. + /// + /// In en, this message translates to: + /// **'Current sequence'** + String get currentSequence; + + /// No description provided for @projectProperties. + /// + /// In en, this message translates to: + /// **'Project properties'** + String get projectProperties; + + /// No description provided for @canvasSize. + /// + /// In en, this message translates to: + /// **'Canvas size'** + String get canvasSize; + + /// No description provided for @frameRate. + /// + /// In en, this message translates to: + /// **'Frame rate'** + String get frameRate; + + /// No description provided for @duration. + /// + /// In en, this message translates to: + /// **'Duration'** + String get duration; + + /// No description provided for @totalDuration. + /// + /// In en, this message translates to: + /// **'Total duration'** + String get totalDuration; + + /// No description provided for @clipDuration. + /// + /// In en, this message translates to: + /// **'Clip duration'** + String get clipDuration; + + /// No description provided for @seconds. + /// + /// In en, this message translates to: + /// **'seconds'** + String get seconds; + + /// No description provided for @clip. + /// + /// In en, this message translates to: + /// **'Clip'** + String get clip; + + /// No description provided for @unnamedClip. + /// + /// In en, this message translates to: + /// **'Unnamed clip'** + String get unnamedClip; + + /// No description provided for @gap. + /// + /// In en, this message translates to: + /// **'Gap'** + String get gap; + + /// No description provided for @compoundClip. + /// + /// In en, this message translates to: + /// **'Compound clip'** + String get compoundClip; + + /// No description provided for @textClip. + /// + /// In en, this message translates to: + /// **'Text clip'** + String get textClip; + + /// No description provided for @pictureProperties. + /// + /// In en, this message translates to: + /// **'Picture'** + String get pictureProperties; + + /// No description provided for @position. + /// + /// In en, this message translates to: + /// **'Position'** + String get position; + + /// No description provided for @rotation. + /// + /// In en, this message translates to: + /// **'Rotation'** + String get rotation; + + /// No description provided for @scale. + /// + /// In en, this message translates to: + /// **'Scale'** + String get scale; + + /// No description provided for @size. + /// + /// In en, this message translates to: + /// **'Size'** + String get size; + + /// No description provided for @transform. + /// + /// In en, this message translates to: + /// **'Transform'** + String get transform; + + /// No description provided for @resetPosition. + /// + /// In en, this message translates to: + /// **'Reset position'** + String get resetPosition; + + /// No description provided for @keepAspectRatio. + /// + /// In en, this message translates to: + /// **'Lock aspect ratio'** + String get keepAspectRatio; + + /// No description provided for @alignment. + /// + /// In en, this message translates to: + /// **'Alignment'** + String get alignment; + + /// No description provided for @alignLeft. + /// + /// In en, this message translates to: + /// **'Align left'** + String get alignLeft; + + /// No description provided for @alignRight. + /// + /// In en, this message translates to: + /// **'Align right'** + String get alignRight; + + /// No description provided for @alignTop. + /// + /// In en, this message translates to: + /// **'Align top'** + String get alignTop; + + /// No description provided for @alignBottom. + /// + /// In en, this message translates to: + /// **'Align bottom'** + String get alignBottom; + + /// No description provided for @alignHorizontalCenter. + /// + /// In en, this message translates to: + /// **'Center horizontally'** + String get alignHorizontalCenter; + + /// No description provided for @alignVerticalCenter. + /// + /// In en, this message translates to: + /// **'Center vertically'** + String get alignVerticalCenter; + + /// No description provided for @volume. + /// + /// In en, this message translates to: + /// **'Volume'** + String get volume; + + /// No description provided for @gain. + /// + /// In en, this message translates to: + /// **'Gain'** + String get gain; + + /// No description provided for @mute. + /// + /// In en, this message translates to: + /// **'Mute'** + String get mute; + + /// No description provided for @unmute. + /// + /// In en, this message translates to: + /// **'Unmute'** + String get unmute; + + /// No description provided for @resetVolume. + /// + /// In en, this message translates to: + /// **'Reset volume'** + String get resetVolume; + + /// No description provided for @invalidGain. + /// + /// In en, this message translates to: + /// **'Enter a value between -90 and +12'** + String get invalidGain; + + /// No description provided for @animation. + /// + /// In en, this message translates to: + /// **'Animation'** + String get animation; + + /// No description provided for @keyframes. + /// + /// In en, this message translates to: + /// **'Keyframes'** + String get keyframes; + + /// No description provided for @removeAllKeyframes. + /// + /// In en, this message translates to: + /// **'Remove all keyframes'** + String get removeAllKeyframes; + + /// No description provided for @linear. + /// + /// In en, this message translates to: + /// **'Linear'** + String get linear; + + /// No description provided for @easeIn. + /// + /// In en, this message translates to: + /// **'Ease in'** + String get easeIn; + + /// No description provided for @easeOut. + /// + /// In en, this message translates to: + /// **'Ease out'** + String get easeOut; + + /// No description provided for @easeInOut. + /// + /// In en, this message translates to: + /// **'Ease in and out'** + String get easeInOut; + + /// No description provided for @basic. + /// + /// In en, this message translates to: + /// **'Basic'** + String get basic; + + /// No description provided for @mask. + /// + /// In en, this message translates to: + /// **'Mask'** + String get mask; + + /// No description provided for @addMask. + /// + /// In en, this message translates to: + /// **'Add mask'** + String get addMask; + + /// No description provided for @deleteMask. + /// + /// In en, this message translates to: + /// **'Delete mask'** + String get deleteMask; + + /// No description provided for @resetMask. + /// + /// In en, this message translates to: + /// **'Reset mask'** + String get resetMask; + + /// No description provided for @enableMask. + /// + /// In en, this message translates to: + /// **'Enable mask'** + String get enableMask; + + /// No description provided for @disableMask. + /// + /// In en, this message translates to: + /// **'Disable mask'** + String get disableMask; + + /// No description provided for @moveMaskUp. + /// + /// In en, this message translates to: + /// **'Move mask up'** + String get moveMaskUp; + + /// No description provided for @moveMaskDown. + /// + /// In en, this message translates to: + /// **'Move mask down'** + String get moveMaskDown; + + /// No description provided for @rectangle. + /// + /// In en, this message translates to: + /// **'Rectangle'** + String get rectangle; + + /// No description provided for @ellipse. + /// + /// In en, this message translates to: + /// **'Ellipse'** + String get ellipse; + + /// No description provided for @invert. + /// + /// In en, this message translates to: + /// **'Invert'** + String get invert; + + /// No description provided for @feather. + /// + /// In en, this message translates to: + /// **'Feather'** + String get feather; + + /// No description provided for @add. + /// + /// In en, this message translates to: + /// **'Add'** + String get add; + + /// No description provided for @subtract. + /// + /// In en, this message translates to: + /// **'Subtract'** + String get subtract; + + /// No description provided for @intersect. + /// + /// In en, this message translates to: + /// **'Intersect'** + String get intersect; + + /// No description provided for @initialRegion. + /// + /// In en, this message translates to: + /// **'Initial region'** + String get initialRegion; + + /// No description provided for @none. + /// + /// In en, this message translates to: + /// **'None'** + String get none; + + /// No description provided for @color. + /// + /// In en, this message translates to: + /// **'Color'** + String get color; + + /// No description provided for @fontSize. + /// + /// In en, this message translates to: + /// **'Font size'** + String get fontSize; + + /// No description provided for @outlineWidth. + /// + /// In en, this message translates to: + /// **'Outline width'** + String get outlineWidth; + + /// No description provided for @outlineColor. + /// + /// In en, this message translates to: + /// **'Outline color'** + String get outlineColor; + + /// No description provided for @captionBaseline. + /// + /// In en, this message translates to: + /// **'Caption baseline'** + String get captionBaseline; + + /// No description provided for @content. + /// + /// In en, this message translates to: + /// **'Text'** + String get content; + + /// No description provided for @start. + /// + /// In en, this message translates to: + /// **'Start'** + String get start; + + /// No description provided for @time. + /// + /// In en, this message translates to: + /// **'Time'** + String get time; + + /// No description provided for @speed. + /// + /// In en, this message translates to: + /// **'Speed'** + String get speed; + + /// No description provided for @speedSegmentCount. + /// + /// In en, this message translates to: + /// **'{count} speed segments'** + String speedSegmentCount(int count); + + /// No description provided for @splitSpeedAtPlayhead. + /// + /// In en, this message translates to: + /// **'Split speed at playhead'** + String get splitSpeedAtPlayhead; + + /// No description provided for @speedChange. + /// + /// In en, this message translates to: + /// **'Speed'** + String get speedChange; + + /// No description provided for @speedMode. + /// + /// In en, this message translates to: + /// **'Speed mode'** + String get speedMode; + + /// No description provided for @constantSpeed. + /// + /// In en, this message translates to: + /// **'Constant speed'** + String get constantSpeed; + + /// No description provided for @segmentedSpeed. + /// + /// In en, this message translates to: + /// **'Segmented speed'** + String get segmentedSpeed; + + /// No description provided for @speedNotAvailable. + /// + /// In en, this message translates to: + /// **'Speed controls are not available yet'** + String get speedNotAvailable; + + /// No description provided for @custom. + /// + /// In en, this message translates to: + /// **'Custom'** + String get custom; + + /// No description provided for @invalidNumber. + /// + /// In en, this message translates to: + /// **'Invalid value'** + String get invalidNumber; + + /// No description provided for @mediaUnavailable. + /// + /// In en, this message translates to: + /// **'Media unavailable'** + String get mediaUnavailable; + + /// No description provided for @mediaMissing. + /// + /// In en, this message translates to: + /// **'Missing media'** + String get mediaMissing; + + /// No description provided for @mediaColorSpace. + /// + /// In en, this message translates to: + /// **'Media color space'** + String get mediaColorSpace; + + /// No description provided for @mediaColorInterpretation. + /// + /// In en, this message translates to: + /// **'Media color interpretation'** + String get mediaColorInterpretation; + + /// No description provided for @colorInfoNotLoaded. + /// + /// In en, this message translates to: + /// **'Color information not loaded'** + String get colorInfoNotLoaded; + + /// No description provided for @unknownColorSpace. + /// + /// In en, this message translates to: + /// **'Unknown color space. Displaying as Rec.709.'** + String get unknownColorSpace; + + /// No description provided for @colorBackendUnsupported. + /// + /// In en, this message translates to: + /// **'The current backend does not support media color interpretation.'** + String get colorBackendUnsupported; + + /// No description provided for @loadClipPropertiesFailed. + /// + /// In en, this message translates to: + /// **'Could not read clip properties'** + String get loadClipPropertiesFailed; + + /// No description provided for @updatePictureFailed. + /// + /// In en, this message translates to: + /// **'Could not update picture properties'** + String get updatePictureFailed; + + /// No description provided for @updateVolumeFailed. + /// + /// In en, this message translates to: + /// **'Could not update volume'** + String get updateVolumeFailed; + + /// No description provided for @updateMaskFailed. + /// + /// In en, this message translates to: + /// **'Could not update mask'** + String get updateMaskFailed; + + /// No description provided for @updateKeyframesFailed. + /// + /// In en, this message translates to: + /// **'Could not update keyframes'** + String get updateKeyframesFailed; + + /// No description provided for @maskPreviewFailed. + /// + /// In en, this message translates to: + /// **'Could not prepare mask preview'** + String get maskPreviewFailed; + + /// No description provided for @alignClipFailed. + /// + /// In en, this message translates to: + /// **'Could not align the clip. Wait for the preview, then try again.'** + String get alignClipFailed; + + /// No description provided for @invalidTransform. + /// + /// In en, this message translates to: + /// **'Scale must be 1%–10000%. Position and angle must be valid numbers.'** + String get invalidTransform; + + /// No description provided for @editFailed. + /// + /// In en, this message translates to: + /// **'Could not edit. Check the input and time range.'** + String get editFailed; + + /// No description provided for @addMediaFailed. + /// + /// In en, this message translates to: + /// **'Could not add media. Please try again.'** + String get addMediaFailed; + + /// No description provided for @deleteCaption. + /// + /// In en, this message translates to: + /// **'Delete caption'** + String get deleteCaption; + + /// No description provided for @mergeCaptions. + /// + /// In en, this message translates to: + /// **'Merge captions'** + String get mergeCaptions; + + /// No description provided for @captionDeleted. + /// + /// In en, this message translates to: + /// **'Caption deleted'** + String get captionDeleted; + + /// No description provided for @captionChanged. + /// + /// In en, this message translates to: + /// **'Captions have changed. Please try again.'** + String get captionChanged; + + /// No description provided for @captionEditChanged. + /// + /// In en, this message translates to: + /// **'Captions have changed. Please edit again.'** + String get captionEditChanged; + + /// No description provided for @assistantHint. + /// + /// In en, this message translates to: + /// **'Describe your editing idea'** + String get assistantHint; + + /// No description provided for @configureAgentHint. + /// + /// In en, this message translates to: + /// **'Configure the agent service to start chatting'** + String get configureAgentHint; + + /// No description provided for @agentRestartHint. + /// + /// In en, this message translates to: + /// **'Configure the agent service, then restart the app.'** + String get agentRestartHint; + + /// No description provided for @replyInterrupted. + /// + /// In en, this message translates to: + /// **'Response interrupted'** + String get replyInterrupted; + + /// No description provided for @replying. + /// + /// In en, this message translates to: + /// **'Responding…'** + String get replying; + + /// No description provided for @stopReply. + /// + /// In en, this message translates to: + /// **'Stop response'** + String get stopReply; + + /// No description provided for @sendMessage. + /// + /// In en, this message translates to: + /// **'Send message'** + String get sendMessage; + + /// No description provided for @addAttachment. + /// + /// In en, this message translates to: + /// **'Add attachment (not available yet)'** + String get addAttachment; + + /// No description provided for @replyFailed. + /// + /// In en, this message translates to: + /// **'Response failed. Check the connection or try again later.'** + String get replyFailed; + + /// No description provided for @mcpService. + /// + /// In en, this message translates to: + /// **'MCP service'** + String get mcpService; + + /// No description provided for @listenPort. + /// + /// In en, this message translates to: + /// **'Port'** + String get listenPort; + + /// No description provided for @accessToken. + /// + /// In en, this message translates to: + /// **'Access token'** + String get accessToken; + + /// No description provided for @copyAccessToken. + /// + /// In en, this message translates to: + /// **'Copy access token'** + String get copyAccessToken; + + /// No description provided for @accessTokenCopied. + /// + /// In en, this message translates to: + /// **'Access token copied'** + String get accessTokenCopied; + + /// No description provided for @loadMcpFailed. + /// + /// In en, this message translates to: + /// **'Could not load MCP settings. Retry'** + String get loadMcpFailed; + + /// No description provided for @saveMcpFailed. + /// + /// In en, this message translates to: + /// **'Could not save MCP settings. Please try again.'** + String get saveMcpFailed; + + /// No description provided for @retryStart. + /// + /// In en, this message translates to: + /// **'Retry starting'** + String get retryStart; + + /// No description provided for @invalidPort. + /// + /// In en, this message translates to: + /// **'Port must be between 1 and 65535'** + String get invalidPort; + + /// No description provided for @loadingSettings. + /// + /// In en, this message translates to: + /// **'Loading settings…'** + String get loadingSettings; + + /// No description provided for @starting. + /// + /// In en, this message translates to: + /// **'Starting…'** + String get starting; + + /// No description provided for @stopping. + /// + /// In en, this message translates to: + /// **'Stopping…'** + String get stopping; + + /// No description provided for @disabled. + /// + /// In en, this message translates to: + /// **'Disabled'** + String get disabled; + + /// No description provided for @running. + /// + /// In en, this message translates to: + /// **'Running'** + String get running; + + /// No description provided for @startFailed. + /// + /// In en, this message translates to: + /// **'Failed to start'** + String get startFailed; + + /// No description provided for @saved. + /// + /// In en, this message translates to: + /// **'Saved'** + String get saved; + + /// No description provided for @unsaved. + /// + /// In en, this message translates to: + /// **'Unsaved'** + String get unsaved; + + /// No description provided for @saving. + /// + /// In en, this message translates to: + /// **'Saving…'** + String get saving; + + /// No description provided for @pendingSave. + /// + /// In en, this message translates to: + /// **'Pending save'** + String get pendingSave; + + /// No description provided for @notApplied. + /// + /// In en, this message translates to: + /// **'Not applied'** + String get notApplied; + + /// No description provided for @enable. + /// + /// In en, this message translates to: + /// **'Enable'** + String get enable; + + /// No description provided for @disable. + /// + /// In en, this message translates to: + /// **'Disable'** + String get disable; + + /// No description provided for @type. + /// + /// In en, this message translates to: + /// **'Type'** + String get type; + + /// No description provided for @status. + /// + /// In en, this message translates to: + /// **'Status'** + String get status; + + /// No description provided for @file. + /// + /// In en, this message translates to: + /// **'File'** + String get file; + + /// No description provided for @unboundMedia. + /// + /// In en, this message translates to: + /// **'No media bound'** + String get unboundMedia; + + /// No description provided for @unboundAudio. + /// + /// In en, this message translates to: + /// **'No audio track bound'** + String get unboundAudio; + + /// No description provided for @vertical. + /// + /// In en, this message translates to: + /// **'Vertical'** + String get vertical; + + /// No description provided for @language. + /// + /// In en, this message translates to: + /// **'Language'** + String get language; + + /// No description provided for @saveLanguageFailed. + /// + /// In en, this message translates to: + /// **'Could not save language. Please try again.'** + String get saveLanguageFailed; + + /// No description provided for @loadLanguageFailed. + /// + /// In en, this message translates to: + /// **'Could not load language. Please select again.'** + String get loadLanguageFailed; + + /// No description provided for @propertiesFirstLayout. + /// + /// In en, this message translates to: + /// **'Properties first'** + String get propertiesFirstLayout; + + /// No description provided for @defaultLayout. + /// + /// In en, this message translates to: + /// **'Default layout'** + String get defaultLayout; + + /// No description provided for @separateVocals. + /// + /// In en, this message translates to: + /// **'Separate vocals'** + String get separateVocals; + + /// No description provided for @detachAudio. + /// + /// In en, this message translates to: + /// **'Detach audio'** + String get detachAudio; + + /// No description provided for @restoreAudio. + /// + /// In en, this message translates to: + /// **'Restore audio'** + String get restoreAudio; + + /// No description provided for @audioDetached. + /// + /// In en, this message translates to: + /// **'Audio detached'** + String get audioDetached; + + /// No description provided for @addAll. + /// + /// In en, this message translates to: + /// **'Add all'** + String get addAll; + + /// No description provided for @preparingMedia. + /// + /// In en, this message translates to: + /// **'Preparing media…'** + String get preparingMedia; + + /// No description provided for @cancelling. + /// + /// In en, this message translates to: + /// **'Cancelling…'** + String get cancelling; + + /// No description provided for @cancelled. + /// + /// In en, this message translates to: + /// **'Cancelled'** + String get cancelled; + + /// No description provided for @interruptedTask. + /// + /// In en, this message translates to: + /// **'Task interrupted. Restart to continue'** + String get interruptedTask; + + /// No description provided for @auto. + /// + /// In en, this message translates to: + /// **'Automatic'** + String get auto; + + /// No description provided for @autoDetect. + /// + /// In en, this message translates to: + /// **'Auto detect'** + String get autoDetect; + + /// No description provided for @noTranslation. + /// + /// In en, this message translates to: + /// **'No translation'** + String get noTranslation; + + /// No description provided for @sourceLanguage. + /// + /// In en, this message translates to: + /// **'Source language'** + String get sourceLanguage; + + /// No description provided for @translationLanguage. + /// + /// In en, this message translates to: + /// **'Translation language'** + String get translationLanguage; + + /// No description provided for @transcriptionNotConfigured. + /// + /// In en, this message translates to: + /// **'Transcription is not configured. Install the recognition component and Whisper Turbo model.'** + String get transcriptionNotConfigured; + + /// No description provided for @translationNotConfigured. + /// + /// In en, this message translates to: + /// **'Caption translation is not configured. You can generate captions in the source language.'** + String get translationNotConfigured; + + /// No description provided for @sourceLanguageUnknown. + /// + /// In en, this message translates to: + /// **'Could not determine a source language for translation.'** + String get sourceLanguageUnknown; + + /// No description provided for @startTranscriptionFailed. + /// + /// In en, this message translates to: + /// **'Could not start transcription. Check media or wait for the current task to finish.'** + String get startTranscriptionFailed; + + /// No description provided for @placeMediaFirst. + /// + /// In en, this message translates to: + /// **'Place this media on the timeline before applying captions.'** + String get placeMediaFirst; + + /// No description provided for @placeTranslationMediaFirst. + /// + /// In en, this message translates to: + /// **'Place the corresponding media on the timeline before applying translated captions.'** + String get placeTranslationMediaFirst; + + /// No description provided for @selectTargetClip. + /// + /// In en, this message translates to: + /// **'Select target clip'** + String get selectTargetClip; + + /// No description provided for @timelineChanged. + /// + /// In en, this message translates to: + /// **'The timeline has changed. Select the target clip again.'** + String get timelineChanged; + + /// No description provided for @transcriptionAccessFailed. + /// + /// In en, this message translates to: + /// **'Transcription failed: component, model, or source media inaccessible (notConfigured)'** + String get transcriptionAccessFailed; + + /// No description provided for @transcriptionNoAudio. + /// + /// In en, this message translates to: + /// **'Transcription failed: no recognizable audio in the selected media or track (noAudio)'** + String get transcriptionNoAudio; + + /// No description provided for @transcriptionInvalidResult. + /// + /// In en, this message translates to: + /// **'Transcription failed: invalid caption file returned (invalidResult)'** + String get transcriptionInvalidResult; + + /// No description provided for @transcriptionWorkerExited. + /// + /// In en, this message translates to: + /// **'Transcription failed: recognition component exited unexpectedly (workerExited)'** + String get transcriptionWorkerExited; + + /// No description provided for @transcriptionProcessingFailed. + /// + /// In en, this message translates to: + /// **'Transcription failed: native processing failed (processingFailed)'** + String get transcriptionProcessingFailed; + + /// No description provided for @transcriptionFailed. + /// + /// In en, this message translates to: + /// **'Transcription failed. Check the component, model, audio track, and duration'** + String get transcriptionFailed; + + /// No description provided for @transcribing. + /// + /// In en, this message translates to: + /// **'Transcribing…'** + String get transcribing; + + /// No description provided for @captionsGenerated. + /// + /// In en, this message translates to: + /// **'Captions generated'** + String get captionsGenerated; + + /// No description provided for @cancelTranscription. + /// + /// In en, this message translates to: + /// **'Cancel transcription'** + String get cancelTranscription; + + /// No description provided for @applyCaptions. + /// + /// In en, this message translates to: + /// **'Apply captions'** + String get applyCaptions; + + /// No description provided for @preparingTranslation. + /// + /// In en, this message translates to: + /// **'Preparing translation…'** + String get preparingTranslation; + + /// No description provided for @translatingCaptions. + /// + /// In en, this message translates to: + /// **'Translating captions…'** + String get translatingCaptions; + + /// No description provided for @cancellingTranslation. + /// + /// In en, this message translates to: + /// **'Cancelling translation…'** + String get cancellingTranslation; + + /// No description provided for @translatedCaptionsGenerated. + /// + /// In en, this message translates to: + /// **'Translated captions generated'** + String get translatedCaptionsGenerated; + + /// No description provided for @translationCancelled. + /// + /// In en, this message translates to: + /// **'Translation cancelled'** + String get translationCancelled; + + /// No description provided for @translationInterrupted. + /// + /// In en, this message translates to: + /// **'Translation interrupted'** + String get translationInterrupted; + + /// No description provided for @cancelTranslation. + /// + /// In en, this message translates to: + /// **'Cancel translation'** + String get cancelTranslation; + + /// No description provided for @editorServiceUnavailable. + /// + /// In en, this message translates to: + /// **'Editing service unavailable. Reopen the project.'** + String get editorServiceUnavailable; + + /// No description provided for @mcpUnavailable. + /// + /// In en, this message translates to: + /// **'MCP connection unavailable. Check the local port and token.'** + String get mcpUnavailable; + + /// No description provided for @openTimelineFailed. + /// + /// In en, this message translates to: + /// **'Could not open the timeline'** + String get openTimelineFailed; + + /// No description provided for @noTimelineSequence. + /// + /// In en, this message translates to: + /// **'This timeline has no sequence'** + String get noTimelineSequence; + + /// No description provided for @waitingForProject. + /// + /// In en, this message translates to: + /// **'Waiting for a project to open'** + String get waitingForProject; + + /// No description provided for @hold. + /// + /// In en, this message translates to: + /// **'Hold'** + String get hold; + + /// No description provided for @noImportableFiles. + /// + /// In en, this message translates to: + /// **'No importable files received'** + String get noImportableFiles; + + /// No description provided for @virtualFilesUnsupported. + /// + /// In en, this message translates to: + /// **'Drag original files from the file manager. Virtual files are not supported yet.'** + String get virtualFilesUnsupported; + + /// No description provided for @editorSessionStartFailed. + /// + /// In en, this message translates to: + /// **'Could not open the timeline editor'** + String get editorSessionStartFailed; + + /// No description provided for @previewStartFailed. + /// + /// In en, this message translates to: + /// **'Could not start native preview'** + String get previewStartFailed; + + /// No description provided for @previewInvalidTrack. + /// + /// In en, this message translates to: + /// **'The selected audio or video track does not exist in the media.'** + String get previewInvalidTrack; + + /// No description provided for @previewMissingBinding. + /// + /// In en, this message translates to: + /// **'Media bindings are missing. Could not preview this timeline.'** + String get previewMissingBinding; + + /// No description provided for @previewUnsupportedEdits. + /// + /// In en, this message translates to: + /// **'This timeline contains edits that are not yet supported by preview.'** + String get previewUnsupportedEdits; + + /// No description provided for @previewUnsupportedConfiguration. + /// + /// In en, this message translates to: + /// **'This preview configuration is not supported on the current platform or system version.'** + String get previewUnsupportedConfiguration; + + /// No description provided for @previewHdrUnsupported. + /// + /// In en, this message translates to: + /// **'HDR media requires tone mapping for SDR preview. The current system or preview configuration does not support it.'** + String get previewHdrUnsupported; + + /// No description provided for @previewAudioOutOfRange. + /// + /// In en, this message translates to: + /// **'The audio clip exceeds the source track range and cannot be previewed.'** + String get previewAudioOutOfRange; + + /// No description provided for @previewResourceMissing. + /// + /// In en, this message translates to: + /// **'Preview media no longer exists. Locate the original file again.'** + String get previewResourceMissing; + + /// No description provided for @previewInvalidComposition. + /// + /// In en, this message translates to: + /// **'Invalid video composition configuration. Could not create preview.'** + String get previewInvalidComposition; + + /// No description provided for @previewInvalidData. + /// + /// In en, this message translates to: + /// **'Invalid preview data. Please try again.'** + String get previewInvalidData; + + /// No description provided for @previewFailed. + /// + /// In en, this message translates to: + /// **'Preview failed. Check media access and try again.'** + String get previewFailed; + + /// No description provided for @chatFailed. + /// + /// In en, this message translates to: + /// **'Could not complete the conversation. Check the service configuration or try again later.'** + String get chatFailed; + + /// No description provided for @delete. + /// + /// In en, this message translates to: + /// **'Delete'** + String get delete; + + /// No description provided for @pinTimeline. + /// + /// In en, this message translates to: + /// **'Pin timeline'** + String get pinTimeline; + + /// No description provided for @unpinTimeline. + /// + /// In en, this message translates to: + /// **'Unpin timeline'** + String get unpinTimeline; + + /// No description provided for @deleteTimelineConfirmation. + /// + /// In en, this message translates to: + /// **'Delete “{name}” and its edit history? This cannot be undone.'** + String deleteTimelineConfirmation(String name); + + /// No description provided for @processingFailed. + /// + /// In en, this message translates to: + /// **'Processing failed'** + String get processingFailed; + + /// No description provided for @noMatchingOptions. + /// + /// In en, this message translates to: + /// **'No matching options'** + String get noMatchingOptions; + + /// No description provided for @removeMediaConfirmation. + /// + /// In en, this message translates to: + /// **'Remove “{name}” from the project? Existing clips, history, and the original file will be kept.'** + String removeMediaConfirmation(String name); + + /// No description provided for @mediaAdded. + /// + /// In en, this message translates to: + /// **'Added {count} media references'** + String mediaAdded(int count); + + /// No description provided for @duplicatesSkipped. + /// + /// In en, this message translates to: + /// **'Skipped {count} duplicate files'** + String duplicatesSkipped(int count); + + /// No description provided for @mediaCount. + /// + /// In en, this message translates to: + /// **'{count} media items'** + String mediaCount(int count); + + /// No description provided for @importMedia. + /// + /// In en, this message translates to: + /// **'Import'** + String get importMedia; + + /// No description provided for @noMediaOfType. + /// + /// In en, this message translates to: + /// **'No {type} media'** + String noMediaOfType(String type); + + /// No description provided for @captionsImported. + /// + /// In en, this message translates to: + /// **'Imported {count} captions'** + String captionsImported(String count); + + /// No description provided for @editCaptionError. + /// + /// In en, this message translates to: + /// **'Could not edit captions: {message}'** + String editCaptionError(String message); + + /// No description provided for @mcpStartError. + /// + /// In en, this message translates to: + /// **'Could not start MCP: {message}'** + String mcpStartError(String message); + + /// No description provided for @manualColorSpace. + /// + /// In en, this message translates to: + /// **'Manually selected: {name}'** + String manualColorSpace(String name); + + /// No description provided for @detectedColorSpace. + /// + /// In en, this message translates to: + /// **'Detected: {name}'** + String detectedColorSpace(String name); + + /// No description provided for @keyframeLabel. + /// + /// In en, this message translates to: + /// **'{channel} keyframe'** + String keyframeLabel(String channel); + + /// No description provided for @maskMode. + /// + /// In en, this message translates to: + /// **'Combination mode: {mode}'** + String maskMode(String mode); + + /// No description provided for @keyframeCount. + /// + /// In en, this message translates to: + /// **'{count} keyframes'** + String keyframeCount(int count); + + /// No description provided for @toggleKeyframe. + /// + /// In en, this message translates to: + /// **'{action} {channel} keyframe'** + String toggleKeyframe(String action, String channel); + + /// No description provided for @previousKeyframe. + /// + /// In en, this message translates to: + /// **'Previous {channel} keyframe'** + String previousKeyframe(String channel); + + /// No description provided for @nextKeyframe. + /// + /// In en, this message translates to: + /// **'Next {channel} keyframe'** + String nextKeyframe(String channel); + + /// No description provided for @keyframeSettings. + /// + /// In en, this message translates to: + /// **'{channel} keyframe settings'** + String keyframeSettings(String channel); + + /// No description provided for @selectedClipsHint. + /// + /// In en, this message translates to: + /// **'{count} clips selected\nSelect one clip to view its properties'** + String selectedClipsHint(int count); + + /// No description provided for @transcriptionError. + /// + /// In en, this message translates to: + /// **'Transcription failed. Check the component, model, audio track, and duration ({code})'** + String transcriptionError(String code); + + /// No description provided for @captionsAdded. + /// + /// In en, this message translates to: + /// **'Added {count} captions. Edit them in the properties panel.'** + String captionsAdded(String count); + + /// No description provided for @translatedCaptionsAdded. + /// + /// In en, this message translates to: + /// **'Added {count} translated captions. Edit them in the properties panel.'** + String translatedCaptionsAdded(String count); + + /// No description provided for @applyCaptionsError. + /// + /// In en, this message translates to: + /// **'Could not apply captions: {message}'** + String applyCaptionsError(String message); + + /// No description provided for @applyTranslatedCaptionsError. + /// + /// In en, this message translates to: + /// **'Could not apply translated captions: {message}'** + String applyTranslatedCaptionsError(String message); + + /// No description provided for @recognizedCaptions. + /// + /// In en, this message translates to: + /// **'Recognized {count} captions'** + String recognizedCaptions(int count); + + /// No description provided for @captionCount. + /// + /// In en, this message translates to: + /// **'{count} captions'** + String captionCount(int count); + + /// No description provided for @translationFailed. + /// + /// In en, this message translates to: + /// **'Translation failed: {message}'** + String translationFailed(String message); + + /// No description provided for @translatedCaptionCount. + /// + /// In en, this message translates to: + /// **'{count} {language} captions'** + String translatedCaptionCount(int count, String language); + + /// No description provided for @previewParameterError. + /// + /// In en, this message translates to: + /// **'Invalid preview parameters: {message}'** + String previewParameterError(String message); + + /// No description provided for @mediaOffline. + /// + /// In en, this message translates to: + /// **'Media offline or unavailable: {names}'** + String mediaOffline(String names); + + /// No description provided for @searchOptions. + /// + /// In en, this message translates to: + /// **'Search {label}…'** + String searchOptions(String label); + + /// No description provided for @loadRecentProjectsFailed. + /// + /// In en, this message translates to: + /// **'Could not load recent projects. You can still open a project manually.'** + String get loadRecentProjectsFailed; + + /// No description provided for @projectAccessFailed. + /// + /// In en, this message translates to: + /// **'Project unavailable'** + String get projectAccessFailed; + + /// No description provided for @projectMissingDirectory. + /// + /// In en, this message translates to: + /// **'Project not found'** + String get projectMissingDirectory; + + /// No description provided for @recentProjectSaveFailed. + /// + /// In en, this message translates to: + /// **'Project opened, but the recent project record could not be saved.'** + String get recentProjectSaveFailed; + + /// No description provided for @lastProjectSaveFailed. + /// + /// In en, this message translates to: + /// **'Project opened, but the last project record could not be saved.'** + String get lastProjectSaveFailed; + + /// No description provided for @enterProjectName. + /// + /// In en, this message translates to: + /// **'Enter a project name'** + String get enterProjectName; + + /// No description provided for @projectSwitched. + /// + /// In en, this message translates to: + /// **'The project has changed. Drag the media in again.'** + String get projectSwitched; + + /// No description provided for @notLocalMedia. + /// + /// In en, this message translates to: + /// **'This media is not a local file'** + String get notLocalMedia; + + /// No description provided for @revealMediaFailed. + /// + /// In en, this message translates to: + /// **'Could not show media in the file manager'** + String get revealMediaFailed; + + /// No description provided for @openMatchingProject. + /// + /// In en, this message translates to: + /// **'Open the corresponding project first'** + String get openMatchingProject; + + /// No description provided for @projectMismatch. + /// + /// In en, this message translates to: + /// **'The project at this location does not match the record. Select it again with Open project.'** + String get projectMismatch; + + /// No description provided for @openProjectFirst. + /// + /// In en, this message translates to: + /// **'Open a project first'** + String get openProjectFirst; + + /// No description provided for @localFilesOnly. + /// + /// In en, this message translates to: + /// **'Drag local files from the file manager'** + String get localFilesOnly; + + /// No description provided for @foldersUnsupported. + /// + /// In en, this message translates to: + /// **'Select files. Dragging folders is not supported yet.'** + String get foldersUnsupported; + + /// No description provided for @mediaImportCancelled. + /// + /// In en, this message translates to: + /// **'Media import cancelled'** + String get mediaImportCancelled; + + /// No description provided for @fileAccessFailed. + /// + /// In en, this message translates to: + /// **'The file is missing or unreadable. Check its location and permissions'** + String get fileAccessFailed; + + /// No description provided for @registerMediaFailed. + /// + /// In en, this message translates to: + /// **'Could not register media. Please try again'** + String get registerMediaFailed; + + /// No description provided for @mediaNoLongerExists. + /// + /// In en, this message translates to: + /// **'Media no longer exists'** + String get mediaNoLongerExists; + + /// No description provided for @mediaNoTracks. + /// + /// In en, this message translates to: + /// **'Media has no usable video or audio tracks'** + String get mediaNoTracks; + + /// No description provided for @invalidMediaDuration. + /// + /// In en, this message translates to: + /// **'Invalid media duration'** + String get invalidMediaDuration; + + /// No description provided for @mediaInfoUnsupported. + /// + /// In en, this message translates to: + /// **'Reading media information is not supported on this platform yet'** + String get mediaInfoUnsupported; + + /// No description provided for @mediaInfoFailed. + /// + /// In en, this message translates to: + /// **'Could not read media information. Check the file and access permissions'** + String get mediaInfoFailed; + + /// No description provided for @saveTimelineFailed. + /// + /// In en, this message translates to: + /// **'Could not save the timeline. Try again. Unsaved edits remain in this session.'** + String get saveTimelineFailed; + + /// No description provided for @addKeyframeAction. + /// + /// In en, this message translates to: + /// **'Add'** + String get addKeyframeAction; + + /// No description provided for @backgroundTasks. + /// + /// In en, this message translates to: + /// **'Background tasks'** + String get backgroundTasks; + + /// No description provided for @noBackgroundTasks. + /// + /// In en, this message translates to: + /// **'No background tasks'** + String get noBackgroundTasks; + + /// No description provided for @retryTask. + /// + /// In en, this message translates to: + /// **'Retry'** + String get retryTask; + + /// No description provided for @applyOriginalCaptions. + /// + /// In en, this message translates to: + /// **'Apply original captions'** + String get applyOriginalCaptions; + + /// No description provided for @applyTranslatedCaptions. + /// + /// In en, this message translates to: + /// **'Apply translated captions'** + String get applyTranslatedCaptions; + + /// No description provided for @subtitleTaskStarted. + /// + /// In en, this message translates to: + /// **'Subtitle task started'** + String get subtitleTaskStarted; + + /// No description provided for @fitTimeline. + /// + /// In en, this message translates to: + /// **'Fit entire timeline'** + String get fitTimeline; + + /// No description provided for @modify. + /// + /// In en, this message translates to: + /// **'Modify'** + String get modify; + + /// No description provided for @projectSettings. + /// + /// In en, this message translates to: + /// **'Project settings'** + String get projectSettings; + + /// No description provided for @projectSettingsDescription. + /// + /// In en, this message translates to: + /// **'Change project output settings while keeping clip timing and speed.'** + String get projectSettingsDescription; + + /// No description provided for @projectColorSpace. + /// + /// In en, this message translates to: + /// **'Color space'** + String get projectColorSpace; + + /// No description provided for @projectWidth. + /// + /// In en, this message translates to: + /// **'Width (px)'** + String get projectWidth; + + /// No description provided for @projectHeight. + /// + /// In en, this message translates to: + /// **'Height (px)'** + String get projectHeight; + + /// No description provided for @projectResolutionInvalid. + /// + /// In en, this message translates to: + /// **'Enter a whole number from 1 to 16384'** + String get projectResolutionInvalid; + + /// No description provided for @previewFullscreen. + /// + /// In en, this message translates to: + /// **'Fullscreen preview'** + String get previewFullscreen; + + /// No description provided for @exitPreviewFullscreen. + /// + /// In en, this message translates to: + /// **'Exit fullscreen'** + String get exitPreviewFullscreen; + + /// No description provided for @previewGoToStart. + /// + /// In en, this message translates to: + /// **'Go to start'** + String get previewGoToStart; + + /// No description provided for @previewPreviousFrame. + /// + /// In en, this message translates to: + /// **'Previous frame'** + String get previewPreviousFrame; + + /// No description provided for @previewNextFrame. + /// + /// In en, this message translates to: + /// **'Next frame'** + String get previewNextFrame; + + /// No description provided for @softwareUpdates. + /// + /// In en, this message translates to: + /// **'Software updates'** + String get softwareUpdates; + + /// No description provided for @checkForUpdates. + /// + /// In en, this message translates to: + /// **'Check for updates'** + String get checkForUpdates; + + /// No description provided for @automaticallyCheckUpdates. + /// + /// In en, this message translates to: + /// **'Automatically check for updates'** + String get automaticallyCheckUpdates; + + /// No description provided for @updatesUnavailable. + /// + /// In en, this message translates to: + /// **'Updates are unavailable in this build.'** + String get updatesUnavailable; + + /// No description provided for @updateCheckFailed. + /// + /// In en, this message translates to: + /// **'Could not check for updates. Please try again.'** + String get updateCheckFailed; + + /// No description provided for @removeBackground. + /// + /// In en, this message translates to: + /// **'Remove background'** + String get removeBackground; + + /// No description provided for @startBackgroundRemoval. + /// + /// In en, this message translates to: + /// **'Remove background'** + String get startBackgroundRemoval; + + /// No description provided for @backgroundRemovalResourceRequired. + /// + /// In en, this message translates to: + /// **'Background removal needs a local model. It starts automatically after download.'** + String get backgroundRemovalResourceRequired; + + /// No description provided for @backgroundRemovalDownloadTask. + /// + /// In en, this message translates to: + /// **'Download background removal resource'** + String get backgroundRemovalDownloadTask; + + /// No description provided for @backgroundRemovalResourceName. + /// + /// In en, this message translates to: + /// **'Background removal model'** + String get backgroundRemovalResourceName; + + /// No description provided for @backgroundRemovalDestructiveHint. + /// + /// In en, this message translates to: + /// **'The generated transparent media will replace this clip. You can still use Undo to restore the original clip.'** + String get backgroundRemovalDestructiveHint; + + /// No description provided for @backgroundRemovalTaskStarted. + /// + /// In en, this message translates to: + /// **'Background removal started'** + String get backgroundRemovalTaskStarted; + + /// No description provided for @startBackgroundRemovalFailed. + /// + /// In en, this message translates to: + /// **'Could not start background removal. Check the media or wait for the current processing task.'** + String get startBackgroundRemovalFailed; + + /// No description provided for @backgroundRemovalComplete. + /// + /// In en, this message translates to: + /// **'Background removal complete'** + String get backgroundRemovalComplete; + + /// No description provided for @backgroundRemovalApplying. + /// + /// In en, this message translates to: + /// **'Replacing clip media'** + String get backgroundRemovalApplying; + + /// No description provided for @backgroundRemovalFailed. + /// + /// In en, this message translates to: + /// **'Background removal failed'** + String get backgroundRemovalFailed; + + /// No description provided for @agentSettings. + /// + /// In en, this message translates to: + /// **'Agent'** + String get agentSettings; + + /// No description provided for @agentSaveSettingsFailed. + /// + /// In en, this message translates to: + /// **'Could not save Agent settings.'** + String get agentSaveSettingsFailed; + + /// No description provided for @agentDeleteProviderTitle. + /// + /// In en, this message translates to: + /// **'Delete provider?'** + String get agentDeleteProviderTitle; + + /// No description provided for @agentDeleteProviderDescription. + /// + /// In en, this message translates to: + /// **'“{providerName}” and its saved API key will be removed from this device.'** + String agentDeleteProviderDescription(String providerName); + + /// No description provided for @agentProviderRequired. + /// + /// In en, this message translates to: + /// **'Add a provider before enabling the assistant.'** + String get agentProviderRequired; + + /// No description provided for @agentUseSelectedModel. + /// + /// In en, this message translates to: + /// **'Use the selected model for new Agent requests.'** + String get agentUseSelectedModel; + + /// No description provided for @agentEnable. + /// + /// In en, this message translates to: + /// **'Enable Agent'** + String get agentEnable; + + /// No description provided for @agentDefaultModel. + /// + /// In en, this message translates to: + /// **'Default model'** + String get agentDefaultModel; + + /// No description provided for @agentConfigureModel. + /// + /// In en, this message translates to: + /// **'Configure models'** + String get agentConfigureModel; + + /// No description provided for @agentSelectModel. + /// + /// In en, this message translates to: + /// **'Select model'** + String get agentSelectModel; + + /// No description provided for @agentModelUnavailable. + /// + /// In en, this message translates to: + /// **'The model for this conversation is unavailable. Select another model to start a new conversation.'** + String get agentModelUnavailable; + + /// No description provided for @agentModelChangeSession. + /// + /// In en, this message translates to: + /// **'Changing the model starts a new Agent session.'** + String get agentModelChangeSession; + + /// No description provided for @agentCustomProviders. + /// + /// In en, this message translates to: + /// **'Custom providers'** + String get agentCustomProviders; + + /// No description provided for @agentProviderStorageDescription. + /// + /// In en, this message translates to: + /// **'Provider metadata is stored locally. API keys are kept in the system credential store.'** + String get agentProviderStorageDescription; + + /// No description provided for @agentAddProvider. + /// + /// In en, this message translates to: + /// **'Add provider'** + String get agentAddProvider; + + /// No description provided for @agentBackToProviders. + /// + /// In en, this message translates to: + /// **'Back to providers'** + String get agentBackToProviders; + + /// No description provided for @agentLoadSettingsFailed. + /// + /// In en, this message translates to: + /// **'Could not load Agent settings. Retry'** + String get agentLoadSettingsFailed; + + /// No description provided for @agentEnableProvider. + /// + /// In en, this message translates to: + /// **'Enable provider'** + String get agentEnableProvider; + + /// No description provided for @agentEditProvider. + /// + /// In en, this message translates to: + /// **'Edit provider'** + String get agentEditProvider; + + /// No description provided for @agentDeleteProvider. + /// + /// In en, this message translates to: + /// **'Delete provider'** + String get agentDeleteProvider; + + /// No description provided for @agentModelIdsUnique. + /// + /// In en, this message translates to: + /// **'Model IDs must be unique.'** + String get agentModelIdsUnique; + + /// No description provided for @agentEditProviderTitle. + /// + /// In en, this message translates to: + /// **'Edit provider'** + String get agentEditProviderTitle; + + /// No description provided for @agentProviderEndpointDescription. + /// + /// In en, this message translates to: + /// **'Configure an OpenAI-compatible Chat Completions endpoint.'** + String get agentProviderEndpointDescription; + + /// No description provided for @agentSaveProvider. + /// + /// In en, this message translates to: + /// **'Save provider'** + String get agentSaveProvider; + + /// No description provided for @agentProviderConfiguration. + /// + /// In en, this message translates to: + /// **'Provider configuration'** + String get agentProviderConfiguration; + + /// No description provided for @agentAuthenticationAndModels. + /// + /// In en, this message translates to: + /// **'Authentication & models'** + String get agentAuthenticationAndModels; + + /// No description provided for @agentApiType. + /// + /// In en, this message translates to: + /// **'API type'** + String get agentApiType; + + /// No description provided for @agentOpenAiChatCompletions. + /// + /// In en, this message translates to: + /// **'OpenAI Completions'** + String get agentOpenAiChatCompletions; + + /// No description provided for @agentBaseUrl. + /// + /// In en, this message translates to: + /// **'Base URL'** + String get agentBaseUrl; + + /// No description provided for @agentApiKey. + /// + /// In en, this message translates to: + /// **'API key'** + String get agentApiKey; + + /// No description provided for @agentProviderNameHint. + /// + /// In en, this message translates to: + /// **'My provider'** + String get agentProviderNameHint; + + /// No description provided for @agentApiKeyOptional. + /// + /// In en, this message translates to: + /// **'Optional for endpoints that do not require authentication.'** + String get agentApiKeyOptional; + + /// No description provided for @agentApiKeyKeep. + /// + /// In en, this message translates to: + /// **'Leave blank to keep the saved key.'** + String get agentApiKeyKeep; + + /// No description provided for @agentOptional. + /// + /// In en, this message translates to: + /// **'Optional'** + String get agentOptional; + + /// No description provided for @agentApiKeyOneLine. + /// + /// In en, this message translates to: + /// **'The API key must be one line.'** + String get agentApiKeyOneLine; + + /// No description provided for @agentRemoveSavedApiKey. + /// + /// In en, this message translates to: + /// **'Remove saved API key'** + String get agentRemoveSavedApiKey; + + /// No description provided for @agentModels. + /// + /// In en, this message translates to: + /// **'Models'** + String get agentModels; + + /// No description provided for @agentAddModel. + /// + /// In en, this message translates to: + /// **'Add model'** + String get agentAddModel; + + /// No description provided for @agentRequiredField. + /// + /// In en, this message translates to: + /// **'This field is required.'** + String get agentRequiredField; + + /// No description provided for @agentInvalidBaseUrl. + /// + /// In en, this message translates to: + /// **'Enter an HTTP(S) base URL without credentials, query, or fragment.'** + String get agentInvalidBaseUrl; + + /// No description provided for @agentModelId. + /// + /// In en, this message translates to: + /// **'Model ID'** + String get agentModelId; + + /// No description provided for @agentContextWindow. + /// + /// In en, this message translates to: + /// **'Context window'** + String get agentContextWindow; + + /// No description provided for @agentMaxOutputTokens. + /// + /// In en, this message translates to: + /// **'Max output'** + String get agentMaxOutputTokens; + + /// No description provided for @agentMaxOutputBelowContext. + /// + /// In en, this message translates to: + /// **'Must be below context.'** + String get agentMaxOutputBelowContext; + + /// No description provided for @agentDeleteModel. + /// + /// In en, this message translates to: + /// **'Delete model'** + String get agentDeleteModel; + + /// No description provided for @agentPositiveInteger. + /// + /// In en, this message translates to: + /// **'Use a positive integer.'** + String get agentPositiveInteger; + + /// No description provided for @agentConfigurationReadFailed. + /// + /// In en, this message translates to: + /// **'Could not read the Agent configuration. Check settings and try again.'** + String get agentConfigurationReadFailed; + + /// No description provided for @agentConfigurationRequired. + /// + /// In en, this message translates to: + /// **'Configure and enable Agent in Settings first.'** + String get agentConfigurationRequired; + + /// No description provided for @agentSessionRestoreFailed. + /// + /// In en, this message translates to: + /// **'Could not restore the Agent session. Try again later.'** + String get agentSessionRestoreFailed; + + /// No description provided for @agentContextBudgetExceeded. + /// + /// In en, this message translates to: + /// **'Input budget is too small for the system instructions, tools and message. Increase the context window or reduce maximum output tokens.'** + String get agentContextBudgetExceeded; + + /// No description provided for @agentAuthenticationFailed. + /// + /// In en, this message translates to: + /// **'Authentication failed. Check the Provider API key and permissions.'** + String get agentAuthenticationFailed; + + /// No description provided for @agentConnectionFailed. + /// + /// In en, this message translates to: + /// **'Could not connect to the model service, or the request timed out. Check the Base URL and network.'** + String get agentConnectionFailed; + + /// No description provided for @agentProtocolFailed. + /// + /// In en, this message translates to: + /// **'The service response does not match the selected API type, or the response stream is incomplete.'** + String get agentProtocolFailed; + + /// No description provided for @agentContextBudgetTooSmall. + /// + /// In en, this message translates to: + /// **'Reserve more input space for system instructions. Increase the context window or reduce maximum output tokens.'** + String get agentContextBudgetTooSmall; + + /// No description provided for @agentCompacting. + /// + /// In en, this message translates to: + /// **'Organizing context…'** + String get agentCompacting; + + /// No description provided for @agentEditing. + /// + /// In en, this message translates to: + /// **'Editing…'** + String get agentEditing; + + /// No description provided for @agentVerifying. + /// + /// In en, this message translates to: + /// **'Checking results…'** + String get agentVerifying; + + /// No description provided for @agentTurnLimitReached. + /// + /// In en, this message translates to: + /// **'This task reached its execution limit. Edits have been saved. Send “Continue” to resume.'** + String get agentTurnLimitReached; + + /// No description provided for @agentRecoveryRequired. + /// + /// In en, this message translates to: + /// **'The previous operation is unconfirmed. Continue to check saved receipts; unconfirmed edits will not be repeated.'** + String get agentRecoveryRequired; + + /// No description provided for @agentExportReplyFailed. + /// + /// In en, this message translates to: + /// **'Video exported successfully. The summary reply failed. Retry the summary without repeating edits or export.'** + String get agentExportReplyFailed; + + /// No description provided for @agentRetrySummary. + /// + /// In en, this message translates to: + /// **'Retry summary'** + String get agentRetrySummary; + + /// No description provided for @agentResumeTask. + /// + /// In en, this message translates to: + /// **'Continue task'** + String get agentResumeTask; + + /// No description provided for @agentTaskInterrupted. + /// + /// In en, this message translates to: + /// **'This task was interrupted. Continue from its saved progress.'** + String get agentTaskInterrupted; + + /// No description provided for @downloadSubtitleModel. + /// + /// In en, this message translates to: + /// **'Download subtitle model'** + String get downloadSubtitleModel; + + /// No description provided for @downloadModelAction. + /// + /// In en, this message translates to: + /// **'Download'** + String get downloadModelAction; + + /// No description provided for @subtitleEngineUnavailable. + /// + /// In en, this message translates to: + /// **'The model is installed, but the subtitle engine could not start. Repair the processing engine; the model does not need to be downloaded again.'** + String get subtitleEngineUnavailable; + + /// No description provided for @backgroundTaskDetails. + /// + /// In en, this message translates to: + /// **'Task details'** + String get backgroundTaskDetails; + + /// No description provided for @backgroundTaskFailed. + /// + /// In en, this message translates to: + /// **'Failed'** + String get backgroundTaskFailed; + + /// No description provided for @backgroundTaskCompleted. + /// + /// In en, this message translates to: + /// **'Completed'** + String get backgroundTaskCompleted; + + /// No description provided for @captionWrapLines. + /// + /// In en, this message translates to: + /// **'Wrap subtitle text'** + String get captionWrapLines; + + /// No description provided for @captionSingleLine. + /// + /// In en, this message translates to: + /// **'Show subtitles on one line'** + String get captionSingleLine; + + /// No description provided for @noMatchingCaptions. + /// + /// In en, this message translates to: + /// **'No matching subtitles'** + String get noMatchingCaptions; + + /// No description provided for @subtitleResourcesRequired. + /// + /// In en, this message translates to: + /// **'These resources are needed for subtitles. Generation starts automatically after download.'** + String get subtitleResourcesRequired; + + /// No description provided for @subtitleResourcesDownloadSize. + /// + /// In en, this message translates to: + /// **'To download: {size}'** + String subtitleResourcesDownloadSize(String size); + + /// No description provided for @pauseDownload. + /// + /// In en, this message translates to: + /// **'Pause'** + String get pauseDownload; + + /// No description provided for @resumeDownload. + /// + /// In en, this message translates to: + /// **'Resume'** + String get resumeDownload; + + /// No description provided for @downloadPaused. + /// + /// In en, this message translates to: + /// **'Paused'** + String get downloadPaused; + + /// No description provided for @cancelResourceDownloadTitle. + /// + /// In en, this message translates to: + /// **'Cancel download?'** + String get cancelResourceDownloadTitle; + + /// No description provided for @cancelResourceDownloadMessage. + /// + /// In en, this message translates to: + /// **'The download will stop. Progress on the current resource may be lost.'** + String get cancelResourceDownloadMessage; + + /// No description provided for @continueDownload. + /// + /// In en, this message translates to: + /// **'Continue downloading'** + String get continueDownload; + + /// No description provided for @cancelDownload. + /// + /// In en, this message translates to: + /// **'Cancel download'** + String get cancelDownload; + + /// No description provided for @speechResourceStage. + /// + /// In en, this message translates to: + /// **'Speech recognition resource'** + String get speechResourceStage; + + /// No description provided for @translationResourceStage. + /// + /// In en, this message translates to: + /// **'Translation resource'** + String get translationResourceStage; + + /// No description provided for @subtitleResourceDownloadTask. + /// + /// In en, this message translates to: + /// **'Download speech and translation resources'** + String get subtitleResourceDownloadTask; + + /// No description provided for @downloadingSpeechModel. + /// + /// In en, this message translates to: + /// **'Downloading speech model'** + String get downloadingSpeechModel; + + /// No description provided for @downloadingTranslationModel. + /// + /// In en, this message translates to: + /// **'Downloading translation model'** + String get downloadingTranslationModel; + + /// No description provided for @checkingForUpdates. + /// + /// In en, this message translates to: + /// **'Checking for updates…'** + String get checkingForUpdates; + + /// No description provided for @appIsUpToDate. + /// + /// In en, this message translates to: + /// **'You are up to date.'** + String get appIsUpToDate; + + /// No description provided for @downloadingUpdate. + /// + /// In en, this message translates to: + /// **'Downloading update: {progress}%'** + String downloadingUpdate(int progress); + + /// No description provided for @updateAvailable. + /// + /// In en, this message translates to: + /// **'Version {version} is available.'** + String updateAvailable(String version); + + /// No description provided for @downloadUpdate. + /// + /// In en, this message translates to: + /// **'Download update'** + String get downloadUpdate; + + /// No description provided for @restartToUpdate. + /// + /// In en, this message translates to: + /// **'Restart to update'** + String get restartToUpdate; + + /// No description provided for @updateOperationFailed. + /// + /// In en, this message translates to: + /// **'Could not update. Finish active tasks and try again.'** + String get updateOperationFailed; + + /// No description provided for @windowMinimize. + /// + /// In en, this message translates to: + /// **'Minimize'** + String get windowMinimize; + + /// No description provided for @windowMaximize. + /// + /// In en, this message translates to: + /// **'Maximize'** + String get windowMaximize; + + /// No description provided for @windowRestore. + /// + /// In en, this message translates to: + /// **'Restore'** + String get windowRestore; + + /// Localized workspaceAgent shown in the Cutdex interface. + /// + /// In en, this message translates to: + /// **'Agent'** + String get workspaceAgent; + + /// Localized workspaceCut shown in the Cutdex interface. + /// + /// In en, this message translates to: + /// **'Cut'** + String get workspaceCut; + + /// Localized noAvailableOptions shown in the Cutdex interface. + /// + /// In en, this message translates to: + /// **'No options available'** + String get noAvailableOptions; + + /// Localized composerReferenceInvalid shown in the Cutdex interface. + /// + /// In en, this message translates to: + /// **'A reference is no longer valid. Return to its project or remove it.'** + String get composerReferenceInvalid; + + /// Localized durationSeconds shown in the Cutdex interface. + /// + /// In en, this message translates to: + /// **'{seconds}s'** + String durationSeconds(int seconds); + + /// Localized durationMinutesSeconds shown in the Cutdex interface. + /// + /// In en, this message translates to: + /// **'{minutes}m {seconds}s'** + String durationMinutesSeconds(int minutes, int seconds); + + /// Localized projectNameInvalid shown in the Cutdex interface. + /// + /// In en, this message translates to: + /// **'Invalid project name'** + String get projectNameInvalid; + + /// Localized projectLocationDefaultUnavailable shown in the Cutdex interface. + /// + /// In en, this message translates to: + /// **'Could not access the default project location. Select it again in Settings.'** + String get projectLocationDefaultUnavailable; + + /// Localized chooseProjectLocation shown in the Cutdex interface. + /// + /// In en, this message translates to: + /// **'Select a project save location in Settings first.'** + String get chooseProjectLocation; + + /// Localized untitledTimeline shown in the Cutdex interface. + /// + /// In en, this message translates to: + /// **'Untitled timeline'** + String get untitledTimeline; + + /// Localized primarySequence shown in the Cutdex interface. + /// + /// In en, this message translates to: + /// **'Main sequence'** + String get primarySequence; + + /// Localized primaryStoryline shown in the Cutdex interface. + /// + /// In en, this message translates to: + /// **'Main storyline'** + String get primaryStoryline; + + /// Localized projectSessionClosed shown in the Cutdex interface. + /// + /// In en, this message translates to: + /// **'The project session has closed. Reopen the project.'** + String get projectSessionClosed; + + /// Localized timelineSessionClosed shown in the Cutdex interface. + /// + /// In en, this message translates to: + /// **'The timeline session has closed. Reopen the timeline.'** + String get timelineSessionClosed; + + /// Localized timelineMissing shown in the Cutdex interface. + /// + /// In en, this message translates to: + /// **'The timeline does not exist or has been deleted.'** + String get timelineMissing; + + /// Localized timelineInUse shown in the Cutdex interface. + /// + /// In en, this message translates to: + /// **'The timeline is in use and cannot be deleted yet.'** + String get timelineInUse; + + /// Localized timelineHasBackgroundTasks shown in the Cutdex interface. + /// + /// In en, this message translates to: + /// **'Finish the timeline’s background tasks before deleting it.'** + String get timelineHasBackgroundTasks; + + /// Localized timelineRequired shown in the Cutdex interface. + /// + /// In en, this message translates to: + /// **'A project must keep at least one timeline.'** + String get timelineRequired; + + /// Localized mediaReadFailed shown in the Cutdex interface. + /// + /// In en, this message translates to: + /// **'Could not read media'** + String get mediaReadFailed; + + /// Localized mediaImportFailed shown in the Cutdex interface. + /// + /// In en, this message translates to: + /// **'Could not import media'** + String get mediaImportFailed; + + /// Localized unsupportedMediaType shown in the Cutdex interface. + /// + /// In en, this message translates to: + /// **'Only video, audio, and image files can be imported.'** + String get unsupportedMediaType; + + /// Localized mediaNoVideoTracks shown in the Cutdex interface. + /// + /// In en, this message translates to: + /// **'Media has no usable video track'** + String get mediaNoVideoTracks; + + /// Localized mediaDurationOutOfRange shown in the Cutdex interface. + /// + /// In en, this message translates to: + /// **'Media duration exceeds the timeline range'** + String get mediaDurationOutOfRange; + + /// Localized resourceDownloadHttpFailed shown in the Cutdex interface. + /// + /// In en, this message translates to: + /// **'Download failed (HTTP {statusCode})'** + String resourceDownloadHttpFailed(String statusCode); + + /// Localized resourceChecksumFailed shown in the Cutdex interface. + /// + /// In en, this message translates to: + /// **'Model file verification failed. Download the resource again.'** + String get resourceChecksumFailed; + + /// Display name of subtitle language af (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Afrikaans'** + String get subtitleLanguageAf; + + /// Display name of subtitle language am (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Amharic'** + String get subtitleLanguageAm; + + /// Display name of subtitle language ar (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Arabic'** + String get subtitleLanguageAr; + + /// Display name of subtitle language ast (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Asturian'** + String get subtitleLanguageAst; + + /// Display name of subtitle language az (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Azerbaijani'** + String get subtitleLanguageAz; + + /// Display name of subtitle language ba (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Bashkir'** + String get subtitleLanguageBa; + + /// Display name of subtitle language be (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Belarusian'** + String get subtitleLanguageBe; + + /// Display name of subtitle language bg (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Bulgarian'** + String get subtitleLanguageBg; + + /// Display name of subtitle language bn (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Bangla'** + String get subtitleLanguageBn; + + /// Display name of subtitle language br (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Breton'** + String get subtitleLanguageBr; + + /// Display name of subtitle language bs (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Bosnian'** + String get subtitleLanguageBs; + + /// Display name of subtitle language ca (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Catalan'** + String get subtitleLanguageCa; + + /// Display name of subtitle language ceb (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Cebuano'** + String get subtitleLanguageCeb; + + /// Display name of subtitle language cs (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Czech'** + String get subtitleLanguageCs; + + /// Display name of subtitle language cy (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Welsh'** + String get subtitleLanguageCy; + + /// Display name of subtitle language da (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Danish'** + String get subtitleLanguageDa; + + /// Display name of subtitle language de (Unicode locale data). + /// + /// In en, this message translates to: + /// **'German'** + String get subtitleLanguageDe; + + /// Display name of subtitle language el (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Greek'** + String get subtitleLanguageEl; + + /// Display name of subtitle language en (Unicode locale data). + /// + /// In en, this message translates to: + /// **'English'** + String get subtitleLanguageEn; + + /// Display name of subtitle language es (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Spanish'** + String get subtitleLanguageEs; + + /// Display name of subtitle language et (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Estonian'** + String get subtitleLanguageEt; + + /// Display name of subtitle language fa (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Persian'** + String get subtitleLanguageFa; + + /// Display name of subtitle language ff (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Fula'** + String get subtitleLanguageFf; + + /// Display name of subtitle language fi (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Finnish'** + String get subtitleLanguageFi; + + /// Display name of subtitle language fr (Unicode locale data). + /// + /// In en, this message translates to: + /// **'French'** + String get subtitleLanguageFr; + + /// Display name of subtitle language fy (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Western Frisian'** + String get subtitleLanguageFy; + + /// Display name of subtitle language ga (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Irish'** + String get subtitleLanguageGa; + + /// Display name of subtitle language gd (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Scottish Gaelic'** + String get subtitleLanguageGd; + + /// Display name of subtitle language gl (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Galician'** + String get subtitleLanguageGl; + + /// Display name of subtitle language gu (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Gujarati'** + String get subtitleLanguageGu; + + /// Display name of subtitle language ha (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Hausa'** + String get subtitleLanguageHa; + + /// Display name of subtitle language he (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Hebrew'** + String get subtitleLanguageHe; + + /// Display name of subtitle language hi (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Hindi'** + String get subtitleLanguageHi; + + /// Display name of subtitle language hr (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Croatian'** + String get subtitleLanguageHr; + + /// Display name of subtitle language ht (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Haitian Creole'** + String get subtitleLanguageHt; + + /// Display name of subtitle language hu (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Hungarian'** + String get subtitleLanguageHu; + + /// Display name of subtitle language hy (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Armenian'** + String get subtitleLanguageHy; + + /// Display name of subtitle language id (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Indonesian'** + String get subtitleLanguageId; + + /// Display name of subtitle language ig (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Igbo'** + String get subtitleLanguageIg; + + /// Display name of subtitle language ilo (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Iloko'** + String get subtitleLanguageIlo; + + /// Display name of subtitle language is (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Icelandic'** + String get subtitleLanguageIs; + + /// Display name of subtitle language it (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Italian'** + String get subtitleLanguageIt; + + /// Display name of subtitle language ja (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Japanese'** + String get subtitleLanguageJa; + + /// Display name of subtitle language jv (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Javanese'** + String get subtitleLanguageJv; + + /// Display name of subtitle language ka (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Georgian'** + String get subtitleLanguageKa; + + /// Display name of subtitle language kk (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Kazakh'** + String get subtitleLanguageKk; + + /// Display name of subtitle language km (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Khmer'** + String get subtitleLanguageKm; + + /// Display name of subtitle language kn (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Kannada'** + String get subtitleLanguageKn; + + /// Display name of subtitle language ko (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Korean'** + String get subtitleLanguageKo; + + /// Display name of subtitle language lb (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Luxembourgish'** + String get subtitleLanguageLb; + + /// Display name of subtitle language lg (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Ganda'** + String get subtitleLanguageLg; + + /// Display name of subtitle language ln (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Lingala'** + String get subtitleLanguageLn; + + /// Display name of subtitle language lo (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Lao'** + String get subtitleLanguageLo; + + /// Display name of subtitle language lt (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Lithuanian'** + String get subtitleLanguageLt; + + /// Display name of subtitle language lv (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Latvian'** + String get subtitleLanguageLv; + + /// Display name of subtitle language mg (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Malagasy'** + String get subtitleLanguageMg; + + /// Display name of subtitle language mk (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Macedonian'** + String get subtitleLanguageMk; + + /// Display name of subtitle language ml (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Malayalam'** + String get subtitleLanguageMl; + + /// Display name of subtitle language mn (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Mongolian'** + String get subtitleLanguageMn; + + /// Display name of subtitle language mr (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Marathi'** + String get subtitleLanguageMr; + + /// Display name of subtitle language ms (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Malay'** + String get subtitleLanguageMs; + + /// Display name of subtitle language my (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Burmese'** + String get subtitleLanguageMy; + + /// Display name of subtitle language ne (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Nepali'** + String get subtitleLanguageNe; + + /// Display name of subtitle language nl (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Dutch'** + String get subtitleLanguageNl; + + /// Display name of subtitle language no (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Norwegian'** + String get subtitleLanguageNo; + + /// Display name of subtitle language ns (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Northern Sotho'** + String get subtitleLanguageNs; + + /// Display name of subtitle language oc (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Occitan'** + String get subtitleLanguageOc; + + /// Display name of subtitle language or (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Odia'** + String get subtitleLanguageOr; + + /// Display name of subtitle language pa (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Punjabi'** + String get subtitleLanguagePa; + + /// Display name of subtitle language pl (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Polish'** + String get subtitleLanguagePl; + + /// Display name of subtitle language ps (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Pashto'** + String get subtitleLanguagePs; + + /// Display name of subtitle language pt (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Portuguese'** + String get subtitleLanguagePt; + + /// Display name of subtitle language ro (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Romanian'** + String get subtitleLanguageRo; + + /// Display name of subtitle language ru (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Russian'** + String get subtitleLanguageRu; + + /// Display name of subtitle language sd (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Sindhi'** + String get subtitleLanguageSd; + + /// Display name of subtitle language si (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Sinhala'** + String get subtitleLanguageSi; + + /// Display name of subtitle language sk (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Slovak'** + String get subtitleLanguageSk; + + /// Display name of subtitle language sl (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Slovenian'** + String get subtitleLanguageSl; + + /// Display name of subtitle language so (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Somali'** + String get subtitleLanguageSo; + + /// Display name of subtitle language sq (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Albanian'** + String get subtitleLanguageSq; + + /// Display name of subtitle language sr (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Serbian'** + String get subtitleLanguageSr; + + /// Display name of subtitle language ss (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Swati'** + String get subtitleLanguageSs; + + /// Display name of subtitle language su (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Sundanese'** + String get subtitleLanguageSu; + + /// Display name of subtitle language sv (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Swedish'** + String get subtitleLanguageSv; + + /// Display name of subtitle language sw (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Swahili'** + String get subtitleLanguageSw; + + /// Display name of subtitle language ta (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Tamil'** + String get subtitleLanguageTa; + + /// Display name of subtitle language th (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Thai'** + String get subtitleLanguageTh; + + /// Display name of subtitle language tl (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Tagalog'** + String get subtitleLanguageTl; + + /// Display name of subtitle language tn (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Tswana'** + String get subtitleLanguageTn; + + /// Display name of subtitle language tr (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Turkish'** + String get subtitleLanguageTr; + + /// Display name of subtitle language uk (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Ukrainian'** + String get subtitleLanguageUk; + + /// Display name of subtitle language ur (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Urdu'** + String get subtitleLanguageUr; + + /// Display name of subtitle language uz (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Uzbek'** + String get subtitleLanguageUz; + + /// Display name of subtitle language vi (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Vietnamese'** + String get subtitleLanguageVi; + + /// Display name of subtitle language wo (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Wolof'** + String get subtitleLanguageWo; + + /// Display name of subtitle language xh (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Xhosa'** + String get subtitleLanguageXh; + + /// Display name of subtitle language yi (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Yiddish'** + String get subtitleLanguageYi; + + /// Display name of subtitle language yo (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Yoruba'** + String get subtitleLanguageYo; + + /// Display name of subtitle language yue (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Cantonese'** + String get subtitleLanguageYue; + + /// Display name of subtitle language zh (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Chinese'** + String get subtitleLanguageZh; + + /// Display name of subtitle language zu (Unicode locale data). + /// + /// In en, this message translates to: + /// **'Zulu'** + String get subtitleLanguageZu; + + /// Linear-light Rec.2020 color interpretation. Keep Rec.2020 unchanged. + /// + /// In en, this message translates to: + /// **'Linear Rec.2020'** + String get linearRec2020; + + /// No description provided for @diagnostics. + /// + /// In en, this message translates to: + /// **'Diagnostics'** + String get diagnostics; + + /// No description provided for @exportDiagnostics. + /// + /// In en, this message translates to: + /// **'Export diagnostic package'** + String get exportDiagnostics; + + /// No description provided for @exportDiagnosticsFailed. + /// + /// In en, this message translates to: + /// **'Could not export diagnostics. Please try again.'** + String get exportDiagnosticsFailed; + + /// No description provided for @exportDiagnosticsSucceeded. + /// + /// In en, this message translates to: + /// **'Diagnostic package saved.'** + String get exportDiagnosticsSucceeded; +} + +class _AppLocalizationsDelegate + extends LocalizationsDelegate { + const _AppLocalizationsDelegate(); + + @override + Future load(Locale locale) { + return SynchronousFuture(lookupAppLocalizations(locale)); + } + + @override + bool isSupported(Locale locale) => [ + 'de', + 'en', + 'es', + 'fr', + 'it', + 'ja', + 'ko', + 'pt', + 'ru', + 'zh', + ].contains(locale.languageCode); + + @override + bool shouldReload(_AppLocalizationsDelegate old) => false; +} + +AppLocalizations lookupAppLocalizations(Locale locale) { + // Lookup logic when language+script codes are specified. + switch (locale.languageCode) { + case 'zh': + { + switch (locale.scriptCode) { + case 'Hans': + return AppLocalizationsZhHans(); + case 'Hant': + return AppLocalizationsZhHant(); + } + break; + } + } + + // Lookup logic when only language code is specified. + switch (locale.languageCode) { + case 'de': + return AppLocalizationsDe(); + case 'en': + return AppLocalizationsEn(); + case 'es': + return AppLocalizationsEs(); + case 'fr': + return AppLocalizationsFr(); + case 'it': + return AppLocalizationsIt(); + case 'ja': + return AppLocalizationsJa(); + case 'ko': + return AppLocalizationsKo(); + case 'pt': + return AppLocalizationsPt(); + case 'ru': + return AppLocalizationsRu(); + case 'zh': + return AppLocalizationsZh(); + } + + throw FlutterError( + 'AppLocalizations.delegate failed to load unsupported locale "$locale". This is likely ' + 'an issue with the localizations generation tool. Please file an issue ' + 'on GitHub with a reproducible sample app and the gen-l10n configuration ' + 'that was used.', + ); +} diff --git a/lib/l10n/app_localizations_de.dart b/lib/l10n/app_localizations_de.dart new file mode 100644 index 0000000..2a41893 --- /dev/null +++ b/lib/l10n/app_localizations_de.dart @@ -0,0 +1,2232 @@ +// ignore: unused_import +import 'package:intl/intl.dart' as intl; + +import 'app_localizations.dart'; + +// ignore_for_file: type=lint + +/// The translations for German (`de`). +class AppLocalizationsDe extends AppLocalizations { + AppLocalizationsDe([String locale = 'de']) : super(locale); + + @override + String get selectProject => 'Projekt auswählen'; + + @override + String get searchProjects => 'Projekte suchen'; + + @override + String get noMatchingProjects => 'Keine passenden Projekte'; + + @override + String get projectsNone => 'Keine Projekte'; + + @override + String get projectLocationMissing => + 'Der Ordner ist nicht vorhanden. Er wird beim Erstellen eines Projekts angelegt.'; + + @override + String get projectLocationUnavailable => + 'Der Projektspeicherort ist nicht verfügbar. Verbinden Sie das Laufwerk oder prüfen Sie das Netzwerk und versuchen Sie es erneut, oder ändern Sie den Speicherort.'; + + @override + String get projectLocationNotWritable => + 'Der Projektspeicherort ist nicht beschreibbar. Prüfen Sie die Berechtigungen oder ändern Sie den Speicherort.'; + + @override + String get projectLocationCreateFailed => + 'Der Projektordner konnte nicht erstellt oder beschrieben werden. Prüfen Sie die Berechtigungen oder ändern Sie den Speicherort.'; + + @override + String get removeProjectFromSidebar => 'Aus der Seitenleiste entfernen'; + + @override + String get projectRemoved => + 'Projekt entfernt. Lokale Dateien und Unterhaltungen bleiben erhalten.'; + + @override + String get agentNoConversations => 'Noch keine Unterhaltungen'; + + @override + String get renameConversationTitle => 'Chat umbenennen'; + + @override + String get renameConversationDescription => + 'Wähle einen kurzen, leicht erkennbaren Namen.'; + + @override + String get collapseProject => 'Projekt einklappen'; + + @override + String get expandProject => 'Projekt ausklappen'; + + @override + String agentDeleteConfirmation(String title) { + return '„$title“ und alle Nachrichten endgültig löschen? Dies kann nicht rückgängig gemacht werden. Lokale Projektdateien sind nicht betroffen.'; + } + + @override + String get agentEmptyTrashConfirmation => + 'Alle Unterhaltungen im Papierkorb endgültig löschen? Dies kann nicht rückgängig gemacht werden. Lokale Projektdateien sind nicht betroffen.'; + + @override + String get agentConversations => 'Unterhaltungen'; + + @override + String get showMoreConversations => 'Mehr anzeigen'; + + @override + String get showFewerConversations => 'Weniger anzeigen'; + + @override + String get agentNewConversation => 'Neue Unterhaltung'; + + @override + String agentElapsedTime(String duration) { + return 'Dauer $duration'; + } + + @override + String get agentConversationActions => 'Unterhaltungsaktionen'; + + @override + String get agentMoveToTrash => 'In den Papierkorb verschieben'; + + @override + String get agentTrash => 'Papierkorb'; + + @override + String get agentRestore => 'Wiederherstellen'; + + @override + String get agentEmptyTrash => 'Papierkorb leeren'; + + @override + String get agentDeleteForever => 'Dauerhaft löschen'; + + @override + String get agentConversationLocation => 'Speicherort für Unterhaltungen'; + + @override + String get agentChooseExistingConversations => + 'Vorhandene Unterhaltungen auswählen'; + + @override + String get agentMoveConversations => 'Unterhaltungen verschieben'; + + @override + String get agentLocationUnavailable => + 'Speicherort für Unterhaltungen nicht verfügbar'; + + @override + String get agentLocationBusy => + 'Warten Sie, bis laufende Unterhaltungen beendet sind'; + + @override + String get agentRelinkProvider => 'Anbieter neu verknüpfen'; + + @override + String get settings => 'Einstellungen'; + + @override + String get closeSettings => 'Einstellungen schließen'; + + @override + String get general => 'Allgemein'; + + @override + String get appearance => 'Darstellung'; + + @override + String get theme => 'Design'; + + @override + String get system => 'Systemeinstellung'; + + @override + String get light => 'Hell'; + + @override + String get dark => 'Dunkel'; + + @override + String get saveAppearanceFailed => + 'Das Erscheinungsbild konnte nicht gespeichert werden. Bitte versuchen Sie es erneut.'; + + @override + String get loadAppearanceFailed => + 'Die Darstellungseinstellungen konnten nicht geladen werden. Bitte wählen Sie erneut ein Design aus.'; + + @override + String get cancel => 'Abbrechen'; + + @override + String get save => 'Speichern'; + + @override + String get create => 'Erstellen'; + + @override + String get close => 'Schließen'; + + @override + String get retry => 'Erneut versuchen'; + + @override + String get select => 'Auswählen'; + + @override + String get name => 'Name'; + + @override + String get enterName => 'Geben Sie einen Namen ein'; + + @override + String get invalidName => + 'Namen dürfen keine Pfadtrennzeichen oder Steuerzeichen enthalten'; + + @override + String get projects => 'Projekte'; + + @override + String get projectName => 'Projektname'; + + @override + String get projectLocation => 'Projektspeicherort'; + + @override + String get projectLocationNotSet => 'Nicht festgelegt'; + + @override + String get loadProjectLocationFailed => + 'Der Projektspeicherort konnte nicht geladen werden.'; + + @override + String get saveProjectLocationFailed => + 'Der Projektspeicherort konnte nicht gespeichert werden.'; + + @override + String get resourceLocation => 'Ressourcenspeicherort'; + + @override + String get resourceLocationNotSet => 'Nicht festgelegt'; + + @override + String get loadResourceLocationFailed => + 'Der Ressourcenspeicherort konnte nicht geladen werden.'; + + @override + String get saveResourceLocationFailed => + 'Der Ressourcenspeicherort konnte nicht gespeichert werden.'; + + @override + String get transcriptionResourceRequired => + 'Zum Erstellen von Untertiteln muss zuerst ein Spracherkennungsmodell heruntergeladen werden.'; + + @override + String get downloadAndContinue => 'Herunterladen und fortfahren'; + + @override + String get downloadingResource => 'Wird heruntergeladen…'; + + @override + String get downloadInBackground => 'Im Hintergrund herunterladen'; + + @override + String get processingResourceDownloadFailed => + 'Die Ressource für die Spracherkennung konnte nicht heruntergeladen werden. Versuchen Sie es erneut.'; + + @override + String get newProject => 'Neues Projekt'; + + @override + String get openProject => 'Projekt öffnen'; + + @override + String get openProjectMore => 'Weiteres Projekt öffnen'; + + @override + String get saveHere => 'Hier speichern'; + + @override + String get selectDirectoryFailed => + 'Es konnte kein Verzeichnis ausgewählt werden. Überprüfen Sie die Systemberechtigungen.'; + + @override + String get openingWorkspace => 'Arbeitsbereich wird geöffnet…'; + + @override + String get loadProjectsFailed => 'Projekte konnten nicht geladen werden'; + + @override + String get projectsEmpty => 'Keine Projekte'; + + @override + String get backToProjects => 'Zurück zum Schnitt'; + + @override + String get timelines => 'Timelines'; + + @override + String timelineLimitReached(int count) { + return 'Jedes Projekt kann maximal $count Timelines enthalten.'; + } + + @override + String get timelineName => 'Name der Timeline'; + + @override + String defaultTimelineName(int index) { + return 'Timeline $index'; + } + + @override + String get newTimeline => 'Neue Timeline'; + + @override + String get noTimelines => 'Keine Timelines'; + + @override + String get activeTimeline => 'Aktuelle Timeline'; + + @override + String get timelineUnavailable => 'Timeline nicht verfügbar'; + + @override + String get projectNoTimelines => + 'Dieses Projekt enthält noch keine Timelines'; + + @override + String get createTimelineHint => + 'Erstellen Sie links unter „Timelines“ eine Timeline, um mit dem Schnitt zu beginnen.'; + + @override + String get createTimelineChat => + 'Erstellen Sie eine Timeline, um den Chat zu starten'; + + @override + String get operationFailed => + 'Der Vorgang ist fehlgeschlagen. Bitte versuchen Sie es erneut.'; + + @override + String get collapseSidebar => 'Seitenleiste einklappen'; + + @override + String get expandSidebar => 'Seitenleiste erweitern'; + + @override + String get expandEditor => 'Schnittbereich öffnen'; + + @override + String get collapseProperties => 'Eigenschaften reduzieren'; + + @override + String get expandProperties => 'Eigenschaften erweitern'; + + @override + String get layout => 'Layout'; + + @override + String get editingFirstLayout => 'Schnitt im Vordergrund'; + + @override + String get agentEditingLayout => 'Agent und Schnitt'; + + @override + String get agentLayoutDescription => 'Planen, zusammenarbeiten und ausführen'; + + @override + String get editingLayoutDescription => 'Vorschau, schneiden und verfeinern'; + + @override + String get materials => 'Medien'; + + @override + String get all => 'Alle'; + + @override + String get video => 'Video'; + + @override + String get audio => 'Audio'; + + @override + String get image => 'Bild'; + + @override + String get picture => 'Bild'; + + @override + String get captions => 'Untertitel'; + + @override + String get text => 'Text'; + + @override + String get noMedia => 'Keine Medien'; + + @override + String get mediaCategory => 'Medienkategorie'; + + @override + String get captionTasks => 'Untertitelaufgaben'; + + @override + String get listLayout => 'Listenansicht'; + + @override + String get gridLayout => 'Rasteransicht'; + + @override + String get addToTimeline => 'Zur Timeline hinzufügen'; + + @override + String get rename => 'Umbenennen'; + + @override + String get renameMedia => 'Medien umbenennen'; + + @override + String get removeMedia => 'Medien entfernen'; + + @override + String get remove => 'Entfernen'; + + @override + String get revealFinder => 'Im Finder anzeigen'; + + @override + String get revealFileManager => 'Im Dateimanager anzeigen'; + + @override + String get dropToAdd => 'Loslassen zum Hinzufügen'; + + @override + String get timelineDropToStart => 'Medien hierher ziehen, um zu beginnen.'; + + @override + String get dragMediaHint => + 'Ziehen Sie Video, Audio oder Bilder hierher\nOriginaldateien bleiben an ihrem aktuellen Speicherort'; + + @override + String get transcribe => 'Transkribieren'; + + @override + String get generateCaptions => 'Untertitel erstellen'; + + @override + String get play => 'Wiedergeben'; + + @override + String get pause => 'Pause'; + + @override + String get retryPreview => 'Vorschau erneut versuchen'; + + @override + String get canvasRatio => 'Bildseitenverhältnis'; + + @override + String get noPreviewContent => + 'Kein Inhalt zur Vorschau auf der Timeline vorhanden'; + + @override + String get nativePreviewUnsupported => + 'Die native Vorschau ist auf dieser Plattform nicht verfügbar'; + + @override + String get canvasTransformFailed => + 'Die Leinwand konnte nicht transformiert werden. Bitte versuchen Sie es erneut.'; + + @override + String get undo => 'Rückgängig'; + + @override + String get redo => 'Wiederholen'; + + @override + String get deleteSelectedClips => 'Ausgewählte Clips löschen'; + + @override + String get splitAtPlayhead => 'Am Abspielkopf teilen'; + + @override + String get trimLeft => 'Links kürzen'; + + @override + String get trimRight => 'Rechts kürzen'; + + @override + String get trimLeftTooltip => + 'Links vom Abspielkopf entfernen, rechts behalten'; + + @override + String get trimRightTooltip => + 'Rechts vom Abspielkopf entfernen, links behalten'; + + @override + String get currentSequence => 'Aktuelle Sequenz'; + + @override + String get projectProperties => 'Projekteigenschaften'; + + @override + String get canvasSize => 'Leinwandgröße'; + + @override + String get frameRate => 'Bildrate'; + + @override + String get duration => 'Dauer'; + + @override + String get totalDuration => 'Gesamtdauer'; + + @override + String get clipDuration => 'Clipdauer'; + + @override + String get seconds => 'Sekunden'; + + @override + String get clip => 'Clip'; + + @override + String get unnamedClip => 'Unbenannter Clip'; + + @override + String get gap => 'Lücke'; + + @override + String get compoundClip => 'Zusammengesetzter Clip'; + + @override + String get textClip => 'Textclip'; + + @override + String get pictureProperties => 'Bild'; + + @override + String get position => 'Position'; + + @override + String get rotation => 'Drehung'; + + @override + String get scale => 'Skalierung'; + + @override + String get size => 'Größe'; + + @override + String get transform => 'Transformation'; + + @override + String get resetPosition => 'Position zurücksetzen'; + + @override + String get keepAspectRatio => 'Seitenverhältnis sperren'; + + @override + String get alignment => 'Ausrichtung'; + + @override + String get alignLeft => 'Links ausrichten'; + + @override + String get alignRight => 'Rechts ausrichten'; + + @override + String get alignTop => 'Oben ausrichten'; + + @override + String get alignBottom => 'Unten ausrichten'; + + @override + String get alignHorizontalCenter => 'Horizontal zentrieren'; + + @override + String get alignVerticalCenter => 'Vertikal zentrieren'; + + @override + String get volume => 'Lautstärke'; + + @override + String get gain => 'Verstärkung'; + + @override + String get mute => 'Stummschalten'; + + @override + String get unmute => 'Stummschaltung aufheben'; + + @override + String get resetVolume => 'Lautstärke zurücksetzen'; + + @override + String get invalidGain => 'Geben Sie einen Wert zwischen -90 und +12 ein'; + + @override + String get animation => 'Animation'; + + @override + String get keyframes => 'Keyframes'; + + @override + String get removeAllKeyframes => 'Entfernen Sie alle Keyframes'; + + @override + String get linear => 'Linear'; + + @override + String get easeIn => 'Langsam beschleunigen'; + + @override + String get easeOut => 'Langsam abbremsen'; + + @override + String get easeInOut => 'Sanft beschleunigen und abbremsen'; + + @override + String get basic => 'Grundlagen'; + + @override + String get mask => 'Maske'; + + @override + String get addMask => 'Maske hinzufügen'; + + @override + String get deleteMask => 'Maske löschen'; + + @override + String get resetMask => 'Maske zurücksetzen'; + + @override + String get enableMask => 'Maske aktivieren'; + + @override + String get disableMask => 'Maske deaktivieren'; + + @override + String get moveMaskUp => 'Maske nach oben verschieben'; + + @override + String get moveMaskDown => 'Maske nach unten verschieben'; + + @override + String get rectangle => 'Rechteck'; + + @override + String get ellipse => 'Ellipse'; + + @override + String get invert => 'Invertieren'; + + @override + String get feather => 'Weiche Kante'; + + @override + String get add => 'Addieren'; + + @override + String get subtract => 'Subtrahieren'; + + @override + String get intersect => 'Schnittmenge'; + + @override + String get initialRegion => 'Ausgangsbereich'; + + @override + String get none => 'Keine'; + + @override + String get color => 'Farbe'; + + @override + String get fontSize => 'Schriftgröße'; + + @override + String get outlineWidth => 'Konturstärke'; + + @override + String get outlineColor => 'Konturfarbe'; + + @override + String get captionBaseline => 'Untertitel-Grundlinie'; + + @override + String get content => 'Text'; + + @override + String get start => 'Start'; + + @override + String get time => 'Zeit'; + + @override + String get speed => 'Geschwindigkeit'; + + @override + String speedSegmentCount(int count) { + return '$count Geschwindigkeitssegmente'; + } + + @override + String get splitSpeedAtPlayhead => 'Geschwindigkeit am Abspielkopf teilen'; + + @override + String get speedChange => 'Geschwindigkeit'; + + @override + String get speedMode => 'Geschwindigkeitsmodus'; + + @override + String get constantSpeed => 'Konstante Geschwindigkeit'; + + @override + String get segmentedSpeed => 'Segmentierte Geschwindigkeit'; + + @override + String get speedNotAvailable => + 'Geschwindigkeitskontrollen sind noch nicht verfügbar'; + + @override + String get custom => 'Benutzerdefiniert'; + + @override + String get invalidNumber => 'Ungültiger Wert'; + + @override + String get mediaUnavailable => 'Medien nicht verfügbar'; + + @override + String get mediaMissing => 'Fehlende Medien'; + + @override + String get mediaColorSpace => 'Medienfarbraum'; + + @override + String get mediaColorInterpretation => 'Interpretation der Medienfarbe'; + + @override + String get colorInfoNotLoaded => 'Farbinformationen nicht geladen'; + + @override + String get unknownColorSpace => 'Unbekannter Farbraum. Anzeige als Rec.709.'; + + @override + String get colorBackendUnsupported => + 'Das aktuelle Backend unterstützt keine Medienfarbinterpretation.'; + + @override + String get loadClipPropertiesFailed => + 'Clip-Eigenschaften konnten nicht gelesen werden'; + + @override + String get updatePictureFailed => + 'Bildeigenschaften konnten nicht aktualisiert werden'; + + @override + String get updateVolumeFailed => + 'Die Lautstärke konnte nicht aktualisiert werden'; + + @override + String get updateMaskFailed => 'Maske konnte nicht aktualisiert werden'; + + @override + String get updateKeyframesFailed => + 'Keyframes konnten nicht aktualisiert werden'; + + @override + String get maskPreviewFailed => + 'Die Maskenvorschau konnte nicht vorbereitet werden'; + + @override + String get alignClipFailed => + 'Der Clip konnte nicht ausgerichtet werden. Warten Sie auf die Vorschau und versuchen Sie es dann erneut.'; + + @override + String get invalidTransform => + 'Die Skalierung muss 1 % bis 10.000 % betragen. Position und Winkel müssen gültige Zahlen sein.'; + + @override + String get editFailed => + 'Konnte nicht bearbeitet werden. Überprüfen Sie die Eingabe und den Zeitbereich.'; + + @override + String get addMediaFailed => + 'Medien konnten nicht hinzugefügt werden. Bitte versuchen Sie es erneut.'; + + @override + String get deleteCaption => 'Untertitel löschen'; + + @override + String get mergeCaptions => 'Untertitel zusammenführen'; + + @override + String get captionDeleted => 'Untertitel gelöscht'; + + @override + String get captionChanged => + 'Die Untertitel haben sich geändert. Bitte versuchen Sie es erneut.'; + + @override + String get captionEditChanged => + 'Die Untertitel haben sich geändert. Bitte erneut bearbeiten.'; + + @override + String get assistantHint => 'Beschreiben Sie Ihre Bearbeitungsidee'; + + @override + String get configureAgentHint => + 'Konfigurieren Sie den Agentendienst, um mit dem Chatten zu beginnen'; + + @override + String get agentRestartHint => + 'Konfigurieren Sie den Agentendienst und starten Sie dann die App neu.'; + + @override + String get replyInterrupted => 'Antwort unterbrochen'; + + @override + String get replying => 'Antwort wird erstellt…'; + + @override + String get stopReply => 'Antwort stoppen'; + + @override + String get sendMessage => 'Nachricht senden'; + + @override + String get addAttachment => 'Anhang hinzufügen (noch nicht verfügbar)'; + + @override + String get replyFailed => + 'Antwort fehlgeschlagen. Überprüfen Sie die Verbindung oder versuchen Sie es später noch einmal.'; + + @override + String get mcpService => 'MCP-Dienst'; + + @override + String get listenPort => 'Port'; + + @override + String get accessToken => 'Zugriffstoken'; + + @override + String get copyAccessToken => 'Zugriffstoken kopieren'; + + @override + String get accessTokenCopied => 'Zugriffstoken kopiert'; + + @override + String get loadMcpFailed => + 'Die MCP-Einstellungen konnten nicht geladen werden. Wiederholen'; + + @override + String get saveMcpFailed => + 'MCP-Einstellungen konnten nicht gespeichert werden. Bitte versuchen Sie es erneut.'; + + @override + String get retryStart => 'Versuchen Sie es erneut'; + + @override + String get invalidPort => 'Der Port muss zwischen 1 und 65535 liegen'; + + @override + String get loadingSettings => 'Einstellungen werden geladen…'; + + @override + String get starting => 'Wird gestartet…'; + + @override + String get stopping => 'Wird gestoppt…'; + + @override + String get disabled => 'Deaktiviert'; + + @override + String get running => 'Aktiv'; + + @override + String get startFailed => 'Start fehlgeschlagen'; + + @override + String get saved => 'Gespeichert'; + + @override + String get unsaved => 'Nicht gespeichert'; + + @override + String get saving => 'Wird gespeichert…'; + + @override + String get pendingSave => 'Speichern steht aus'; + + @override + String get notApplied => 'Nicht angewendet'; + + @override + String get enable => 'Aktivieren'; + + @override + String get disable => 'Deaktivieren'; + + @override + String get type => 'Typ'; + + @override + String get status => 'Status'; + + @override + String get file => 'Datei'; + + @override + String get unboundMedia => 'Keine Medien zugeordnet'; + + @override + String get unboundAudio => 'Keine Audiospur zugeordnet'; + + @override + String get vertical => 'Vertikal'; + + @override + String get language => 'Sprache'; + + @override + String get saveLanguageFailed => + 'Die Sprache konnte nicht gespeichert werden. Bitte versuchen Sie es erneut.'; + + @override + String get loadLanguageFailed => + 'Die Sprache konnte nicht geladen werden. Bitte wählen Sie erneut aus.'; + + @override + String get propertiesFirstLayout => 'Eigenschaften zuerst'; + + @override + String get defaultLayout => 'Standardlayout'; + + @override + String get separateVocals => 'Gesang trennen'; + + @override + String get detachAudio => 'Audio abtrennen'; + + @override + String get restoreAudio => 'Audio wiederherstellen'; + + @override + String get audioDetached => 'Audio abgetrennt'; + + @override + String get addAll => 'Alle hinzufügen'; + + @override + String get preparingMedia => 'Medien werden vorbereitet…'; + + @override + String get cancelling => 'Wird abgebrochen…'; + + @override + String get cancelled => 'Abgebrochen'; + + @override + String get interruptedTask => + 'Aufgabe unterbrochen. Starten Sie neu, um fortzufahren'; + + @override + String get auto => 'Automatisch'; + + @override + String get autoDetect => 'Automatisch erkennen'; + + @override + String get noTranslation => 'Nicht übersetzen'; + + @override + String get sourceLanguage => 'Ausgangssprache'; + + @override + String get translationLanguage => 'Zielsprache'; + + @override + String get transcriptionNotConfigured => + 'Die Transkription ist nicht konfiguriert. Installieren Sie die Erkennungskomponente und das Whisper Turbo-Modell.'; + + @override + String get translationNotConfigured => + 'Die Untertitelübersetzung ist nicht konfiguriert. Sie können Untertitel in der Ausgangssprache generieren.'; + + @override + String get sourceLanguageUnknown => + 'Es konnte keine Ausgangssprache für die Übersetzung ermittelt werden.'; + + @override + String get startTranscriptionFailed => + 'Die Transkription konnte nicht gestartet werden. Überprüfen Sie die Medien oder warten Sie, bis die aktuelle Aufgabe abgeschlossen ist.'; + + @override + String get placeMediaFirst => + 'Platzieren Sie dieses Medium auf der Timeline, bevor Sie Untertitel anwenden.'; + + @override + String get placeTranslationMediaFirst => + 'Platzieren Sie die entsprechenden Medien auf der Timeline, bevor Sie übersetzte Untertitel anwenden.'; + + @override + String get selectTargetClip => 'Wählen Sie den Zielclip aus'; + + @override + String get timelineChanged => + 'Die Zeitleiste hat sich geändert. Wählen Sie den Zielclip erneut aus.'; + + @override + String get transcriptionAccessFailed => + 'Transkription fehlgeschlagen: Auf Komponente, Modell oder Quellmedium kann nicht zugegriffen werden (notConfigured)'; + + @override + String get transcriptionNoAudio => + 'Transkription fehlgeschlagen: Kein erkennbares Audio im ausgewählten Medium oder Track (noAudio)'; + + @override + String get transcriptionInvalidResult => + 'Transkription fehlgeschlagen: Ungültige Untertiteldatei zurückgegeben (invalidResult)'; + + @override + String get transcriptionWorkerExited => + 'Transkription fehlgeschlagen: Erkennungskomponente wurde unerwartet beendet (workerExited)'; + + @override + String get transcriptionProcessingFailed => + 'Transkription fehlgeschlagen: native Verarbeitung fehlgeschlagen (processingFailed)'; + + @override + String get transcriptionFailed => + 'Die Transkription ist fehlgeschlagen. Überprüfen Sie Komponente, Modell, Audiospur und Dauer'; + + @override + String get transcribing => 'Wird transkribiert…'; + + @override + String get captionsGenerated => 'Untertitel erstellt'; + + @override + String get cancelTranscription => 'Transkription abbrechen'; + + @override + String get applyCaptions => 'Untertitel anwenden'; + + @override + String get preparingTranslation => 'Übersetzung wird vorbereitet…'; + + @override + String get translatingCaptions => 'Untertitel werden übersetzt…'; + + @override + String get cancellingTranslation => 'Übersetzung wird abgebrochen…'; + + @override + String get translatedCaptionsGenerated => 'Übersetzte Untertitel erstellt'; + + @override + String get translationCancelled => 'Übersetzung abgebrochen'; + + @override + String get translationInterrupted => 'Übersetzung unterbrochen'; + + @override + String get cancelTranslation => 'Übersetzung abbrechen'; + + @override + String get editorServiceUnavailable => + 'Bearbeitungsdienst nicht verfügbar. Öffnen Sie das Projekt erneut.'; + + @override + String get mcpUnavailable => + 'MCP-Verbindung nicht verfügbar. Überprüfen Sie den lokalen Port und das Token.'; + + @override + String get openTimelineFailed => + 'Die Zeitleiste konnte nicht geöffnet werden'; + + @override + String get noTimelineSequence => 'Diese Timeline enthält keine Sequenz.'; + + @override + String get waitingForProject => 'Warten auf das Öffnen eines Projekts'; + + @override + String get hold => 'Halten'; + + @override + String get noImportableFiles => 'Keine importierbaren Dateien erhalten'; + + @override + String get virtualFilesUnsupported => + 'Ziehen Sie Originaldateien aus dem Dateimanager. Virtuelle Dateien werden noch nicht unterstützt.'; + + @override + String get editorSessionStartFailed => + 'Der Timeline-Editor konnte nicht geöffnet werden'; + + @override + String get previewStartFailed => + 'Die native Vorschau konnte nicht gestartet werden'; + + @override + String get previewInvalidTrack => + 'Die ausgewählte Audio- oder Videospur ist im Medium nicht vorhanden.'; + + @override + String get previewMissingBinding => + 'Medienbindungen fehlen. Diese Zeitleiste konnte nicht in der Vorschau angezeigt werden.'; + + @override + String get previewUnsupportedEdits => + 'Diese Zeitleiste enthält Bearbeitungen, die noch nicht von der Vorschau unterstützt werden.'; + + @override + String get previewUnsupportedConfiguration => + 'Diese Vorschaukonfiguration wird auf der aktuellen Plattform oder Systemversion nicht unterstützt.'; + + @override + String get previewHdrUnsupported => + 'HDR-Medien erfordern Tone Mapping für die SDR-Vorschau. Das aktuelle System oder die Vorschaukonfiguration unterstützt dies nicht.'; + + @override + String get previewAudioOutOfRange => + 'Der Audioclip überschreitet den Quellspurbereich und kann nicht in der Vorschau angezeigt werden.'; + + @override + String get previewResourceMissing => + 'Vorschaumedien sind nicht mehr vorhanden. Suchen Sie die Originaldatei erneut.'; + + @override + String get previewInvalidComposition => + 'Ungültige Videokompositionskonfiguration. Vorschau konnte nicht erstellt werden.'; + + @override + String get previewInvalidData => + 'Invalid preview data. Bitte versuchen Sie es erneut.'; + + @override + String get previewFailed => + 'Preview failed. Überprüfen Sie den Medienzugriff und versuchen Sie es erneut.'; + + @override + String get chatFailed => + 'Das Gespräch konnte nicht abgeschlossen werden. Überprüfen Sie die Dienstkonfiguration oder versuchen Sie es später erneut.'; + + @override + String get delete => 'Löschen'; + + @override + String get pinTimeline => 'Zeitleiste anheften'; + + @override + String get unpinTimeline => 'Zeitleiste lösen'; + + @override + String deleteTimelineConfirmation(String name) { + return '„$name“ und den Bearbeitungsverlauf löschen? Dies kann nicht rückgängig gemacht werden.'; + } + + @override + String get processingFailed => 'Verarbeitung fehlgeschlagen'; + + @override + String get noMatchingOptions => 'Keine passenden Optionen'; + + @override + String removeMediaConfirmation(String name) { + return '„$name“ aus der Bibliothek entfernen? Vorhandene Clips, Verlauf und die Originaldatei bleiben erhalten.'; + } + + @override + String mediaAdded(int count) { + return '$count Medienreferenzen hinzugefügt'; + } + + @override + String duplicatesSkipped(int count) { + return 'Doppelte $count-Dateien wurden übersprungen'; + } + + @override + String mediaCount(int count) { + return '$count Medienelemente'; + } + + @override + String get importMedia => 'Importieren'; + + @override + String noMediaOfType(String type) { + return 'Kein $type-Medium'; + } + + @override + String captionsImported(String count) { + return 'Importierte $count-Untertitel'; + } + + @override + String editCaptionError(String message) { + return 'Untertitel konnten nicht bearbeitet werden: $message'; + } + + @override + String mcpStartError(String message) { + return 'MCP konnte nicht gestartet werden: $message'; + } + + @override + String manualColorSpace(String name) { + return 'Manuell ausgewählt: $name'; + } + + @override + String detectedColorSpace(String name) { + return 'Erkannt: $name'; + } + + @override + String keyframeLabel(String channel) { + return '$channel-Keyframe'; + } + + @override + String maskMode(String mode) { + return 'Kombinationsmodus: $mode'; + } + + @override + String keyframeCount(int count) { + return '$count Keyframes'; + } + + @override + String toggleKeyframe(String action, String channel) { + return '$channel-Keyframe: $action'; + } + + @override + String previousKeyframe(String channel) { + return 'Vorheriger $channel-Keyframe'; + } + + @override + String nextKeyframe(String channel) { + return 'Nächster $channel-Keyframe'; + } + + @override + String keyframeSettings(String channel) { + return '$channel-Keyframe-Einstellungen'; + } + + @override + String selectedClipsHint(int count) { + return '$count Clips ausgewählt\nWählen Sie einen Clip aus, um seine Eigenschaften anzuzeigen'; + } + + @override + String transcriptionError(String code) { + return 'Die Transkription ist fehlgeschlagen. Überprüfen Sie die Komponente, das Modell, die Audiospur und die Dauer ($code).'; + } + + @override + String captionsAdded(String count) { + return '$count-Untertitel hinzugefügt. Bearbeiten Sie sie im Eigenschaftenfenster.'; + } + + @override + String translatedCaptionsAdded(String count) { + return '$count übersetzte Untertitel hinzugefügt. Bearbeiten Sie sie im Eigenschaftenfenster.'; + } + + @override + String applyCaptionsError(String message) { + return 'Untertitel konnten nicht angewendet werden: $message'; + } + + @override + String applyTranslatedCaptionsError(String message) { + return 'Übersetzte Untertitel konnten nicht angewendet werden: $message'; + } + + @override + String recognizedCaptions(int count) { + return '$count Untertitel erkannt'; + } + + @override + String captionCount(int count) { + return '$count Untertitel'; + } + + @override + String translationFailed(String message) { + return 'Übersetzung fehlgeschlagen: $message'; + } + + @override + String translatedCaptionCount(int count, String language) { + return '$count Untertitel ($language)'; + } + + @override + String previewParameterError(String message) { + return 'Ungültige Vorschauparameter: $message'; + } + + @override + String mediaOffline(String names) { + return 'Medien offline oder nicht verfügbar: $names'; + } + + @override + String searchOptions(String label) { + return 'Suche $label…'; + } + + @override + String get loadRecentProjectsFailed => + 'Aktuelle Bibliotheken konnten nicht geladen werden. Sie können eine Bibliothek weiterhin manuell öffnen.'; + + @override + String get projectAccessFailed => 'Projekt nicht verfügbar'; + + @override + String get projectMissingDirectory => 'Projekt nicht gefunden'; + + @override + String get recentProjectSaveFailed => + 'Die Bibliothek wurde geöffnet, aber der aktuelle Bibliothekseintrag konnte nicht gespeichert werden.'; + + @override + String get lastProjectSaveFailed => + 'Projekt geöffnet, aber der letzte Projektdatensatz konnte nicht gespeichert werden.'; + + @override + String get enterProjectName => 'Geben Sie einen Projektnamen ein'; + + @override + String get projectSwitched => + 'Das Projekt hat sich geändert. Ziehen Sie das Medium erneut hinein.'; + + @override + String get notLocalMedia => 'Dieses Medium ist keine lokale Datei'; + + @override + String get revealMediaFailed => + 'Medien konnten im Dateimanager nicht angezeigt werden'; + + @override + String get openMatchingProject => + 'Öffnen Sie zunächst das entsprechende Projekt'; + + @override + String get projectMismatch => + 'Die Bibliothek an diesem Standort stimmt nicht mit dem Datensatz überein. Wählen Sie es erneut mit Bibliothek öffnen aus.'; + + @override + String get openProjectFirst => 'Öffnen Sie zunächst eine Bibliothek'; + + @override + String get localFilesOnly => 'Ziehen Sie lokale Dateien aus dem Dateimanager'; + + @override + String get foldersUnsupported => + 'Wählen Sie Dateien aus. Das Ziehen von Ordnern wird noch nicht unterstützt.'; + + @override + String get mediaImportCancelled => 'Medienimport abgebrochen'; + + @override + String get fileAccessFailed => + 'Die Datei fehlt oder ist nicht lesbar. Überprüfen Sie den Standort und die Berechtigungen'; + + @override + String get registerMediaFailed => + 'Medien konnten nicht registriert werden. Bitte versuchen Sie es erneut'; + + @override + String get mediaNoLongerExists => 'Medien gibt es nicht mehr'; + + @override + String get mediaNoTracks => + 'Das Medium verfügt über keine verwendbaren Video- oder Audiospuren'; + + @override + String get invalidMediaDuration => 'Ungültige Mediendauer'; + + @override + String get mediaInfoUnsupported => + 'Das Lesen von Medieninformationen wird auf dieser Plattform noch nicht unterstützt'; + + @override + String get mediaInfoFailed => + 'Medieninformationen konnten nicht gelesen werden. Überprüfen Sie die Datei- und Zugriffsberechtigungen'; + + @override + String get saveTimelineFailed => + 'Die Zeitleiste konnte nicht gespeichert werden. Versuchen Sie es erneut. Nicht gespeicherte Änderungen bleiben in dieser Sitzung bestehen.'; + + @override + String get addKeyframeAction => 'Hinzufügen'; + + @override + String get backgroundTasks => 'Hintergrundaufgaben'; + + @override + String get noBackgroundTasks => 'Keine Hintergrundaufgaben'; + + @override + String get retryTask => 'Erneut versuchen'; + + @override + String get applyOriginalCaptions => 'Originaluntertitel anwenden'; + + @override + String get applyTranslatedCaptions => 'Übersetzte Untertitel anwenden'; + + @override + String get subtitleTaskStarted => 'Untertitelaufgabe gestartet'; + + @override + String get fitTimeline => 'Gesamte Zeitleiste einpassen'; + + @override + String get modify => 'Modify'; + + @override + String get projectSettings => 'Project settings'; + + @override + String get projectSettingsDescription => + 'Change project output settings while keeping clip timing and speed.'; + + @override + String get projectColorSpace => 'Color space'; + + @override + String get projectWidth => 'Width (px)'; + + @override + String get projectHeight => 'Height (px)'; + + @override + String get projectResolutionInvalid => 'Enter a whole number from 1 to 16384'; + + @override + String get previewFullscreen => 'Vollbildvorschau'; + + @override + String get exitPreviewFullscreen => 'Vollbild verlassen'; + + @override + String get previewGoToStart => 'Zum Anfang'; + + @override + String get previewPreviousFrame => 'Vorheriges Bild'; + + @override + String get previewNextFrame => 'Nächstes Bild'; + + @override + String get softwareUpdates => 'Softwareupdates'; + + @override + String get checkForUpdates => 'Nach Updates suchen'; + + @override + String get automaticallyCheckUpdates => 'Automatisch nach Updates suchen'; + + @override + String get updatesUnavailable => + 'Updates sind in diesem Build nicht verfügbar.'; + + @override + String get updateCheckFailed => + 'Updates konnten nicht geprüft werden. Bitte erneut versuchen.'; + + @override + String get removeBackground => 'Hintergrund entfernen'; + + @override + String get startBackgroundRemoval => 'Hintergrund entfernen'; + + @override + String get backgroundRemovalResourceRequired => + 'Für die Hintergrundentfernung ist ein lokales Modell erforderlich. Nach dem Download startet sie automatisch.'; + + @override + String get backgroundRemovalDownloadTask => + 'Ressource zur Hintergrundentfernung herunterladen'; + + @override + String get backgroundRemovalResourceName => + 'Modell zur Hintergrundentfernung'; + + @override + String get backgroundRemovalDestructiveHint => + 'Das erzeugte transparente Medium ersetzt diesen Clip. Mit Rückgängig können Sie den ursprünglichen Clip wiederherstellen.'; + + @override + String get backgroundRemovalTaskStarted => 'Hintergrundentfernung gestartet'; + + @override + String get startBackgroundRemovalFailed => + 'Die Hintergrundentfernung konnte nicht gestartet werden. Prüfen Sie das Medium oder warten Sie, bis die aktuelle Verarbeitung abgeschlossen ist.'; + + @override + String get backgroundRemovalComplete => 'Hintergrundentfernung abgeschlossen'; + + @override + String get backgroundRemovalApplying => 'Clip-Medium wird ersetzt'; + + @override + String get backgroundRemovalFailed => 'Hintergrundentfernung fehlgeschlagen'; + + @override + String get agentSettings => 'Agent'; + + @override + String get agentSaveSettingsFailed => + 'Die Agent-Einstellungen konnten nicht gespeichert werden.'; + + @override + String get agentDeleteProviderTitle => 'Anbieter löschen?'; + + @override + String agentDeleteProviderDescription(String providerName) { + return '„$providerName“ und der gespeicherte API-Schlüssel werden von diesem Gerät entfernt.'; + } + + @override + String get agentProviderRequired => + 'Fügen Sie einen Anbieter hinzu, bevor Sie den Assistenten aktivieren.'; + + @override + String get agentUseSelectedModel => + 'Neue Agent-Anfragen verwenden das ausgewählte Modell.'; + + @override + String get agentEnable => 'Agent aktivieren'; + + @override + String get agentDefaultModel => 'Standardmodell'; + + @override + String get agentConfigureModel => 'Modelle konfigurieren'; + + @override + String get agentSelectModel => 'Modell auswählen'; + + @override + String get agentModelUnavailable => + 'Das Modell dieser Unterhaltung ist nicht verfügbar. Wählen Sie ein anderes Modell für eine neue Unterhaltung.'; + + @override + String get agentModelChangeSession => + 'Beim Wechseln des Modells wird eine neue Agent-Sitzung gestartet.'; + + @override + String get agentCustomProviders => 'Benutzerdefinierte Anbieter'; + + @override + String get agentProviderStorageDescription => + 'Anbietermetadaten werden lokal gespeichert. API-Schlüssel werden im Anmeldedatenspeicher des Systems aufbewahrt.'; + + @override + String get agentAddProvider => 'Anbieter hinzufügen'; + + @override + String get agentBackToProviders => 'Zurück zu den Anbietern'; + + @override + String get agentLoadSettingsFailed => + 'Agent-Einstellungen konnten nicht geladen werden. Erneut versuchen'; + + @override + String get agentEnableProvider => 'Provider aktivieren'; + + @override + String get agentEditProvider => 'Anbieter bearbeiten'; + + @override + String get agentDeleteProvider => 'Anbieter löschen'; + + @override + String get agentModelIdsUnique => 'Modell-IDs müssen eindeutig sein.'; + + @override + String get agentEditProviderTitle => 'Anbieter bearbeiten'; + + @override + String get agentProviderEndpointDescription => + 'Konfigurieren Sie einen OpenAI-kompatiblen Chat-Completions-Endpunkt.'; + + @override + String get agentSaveProvider => 'Anbieter speichern'; + + @override + String get agentProviderConfiguration => 'Provider-Konfiguration'; + + @override + String get agentAuthenticationAndModels => 'Authentifizierung und Modelle'; + + @override + String get agentApiType => 'API-Typ'; + + @override + String get agentOpenAiChatCompletions => 'OpenAI Completions'; + + @override + String get agentBaseUrl => 'Basis-URL'; + + @override + String get agentApiKey => 'API-Schlüssel'; + + @override + String get agentProviderNameHint => 'Mein Anbieter'; + + @override + String get agentApiKeyOptional => + 'Optional für Endpunkte, die keine Authentifizierung erfordern.'; + + @override + String get agentApiKeyKeep => + 'Leer lassen, um den gespeicherten Schlüssel beizubehalten.'; + + @override + String get agentOptional => 'Optional'; + + @override + String get agentApiKeyOneLine => 'Der API-Schlüssel muss einzeilig sein.'; + + @override + String get agentRemoveSavedApiKey => 'Gespeicherten API-Schlüssel entfernen'; + + @override + String get agentModels => 'Modelle'; + + @override + String get agentAddModel => 'Modell hinzufügen'; + + @override + String get agentRequiredField => 'Dieses Feld ist erforderlich.'; + + @override + String get agentInvalidBaseUrl => + 'Geben Sie eine HTTP(S)-Basis-URL ohne Anmeldedaten, Abfrage oder Fragment ein.'; + + @override + String get agentModelId => 'Modell-ID'; + + @override + String get agentContextWindow => 'Kontextfenster'; + + @override + String get agentMaxOutputTokens => 'Maximale Ausgabe'; + + @override + String get agentMaxOutputBelowContext => + 'Muss kleiner als das Kontextfenster sein.'; + + @override + String get agentDeleteModel => 'Modell löschen'; + + @override + String get agentPositiveInteger => 'Geben Sie eine positive Ganzzahl ein.'; + + @override + String get agentConfigurationReadFailed => + 'Die Agent-Konfiguration konnte nicht gelesen werden. Prüfen Sie die Einstellungen und versuchen Sie es erneut.'; + + @override + String get agentConfigurationRequired => + 'Konfigurieren und aktivieren Sie zuerst den Agent in den Einstellungen.'; + + @override + String get agentSessionRestoreFailed => + 'Die Agent-Sitzung konnte nicht wiederhergestellt werden. Versuchen Sie es später erneut.'; + + @override + String get agentContextBudgetExceeded => + 'Das Eingabebudget reicht für Systemanweisungen, Werkzeuge und Nachricht nicht aus. Kontextfenster vergrößern oder maximale Ausgabe reduzieren.'; + + @override + String get agentAuthenticationFailed => + 'Authentifizierung fehlgeschlagen. API Key und Berechtigungen prüfen.'; + + @override + String get agentConnectionFailed => + 'Verbindung fehlgeschlagen oder Zeitlimit überschritten. Base URL und Netzwerk prüfen.'; + + @override + String get agentProtocolFailed => + 'Die Antwort passt nicht zum gewählten API-Typ oder der Stream ist unvollständig.'; + + @override + String get agentContextBudgetTooSmall => + 'Mehr Eingaberaum für Systemanweisungen reservieren. Kontextfenster vergrößern oder maximale Ausgabe reduzieren.'; + + @override + String get agentCompacting => 'Kontext aufbereiten…'; + + @override + String get agentEditing => 'Bearbeiten…'; + + @override + String get agentVerifying => 'Ergebnisse prüfen…'; + + @override + String get agentTurnLimitReached => + 'Diese Aufgabe hat das Ausführungslimit erreicht. Änderungen wurden gespeichert. Sende „Weiter“, um fortzufahren.'; + + @override + String get agentRecoveryRequired => + 'Das vorherige Ergebnis ist unbestätigt. Fortsetzen prüft gespeicherte Belege; unbestätigte Änderungen werden nicht wiederholt.'; + + @override + String get agentExportReplyFailed => + 'Video erfolgreich exportiert. Die Zusammenfassung ist fehlgeschlagen. Erneut versuchen, ohne Bearbeitung oder Export zu wiederholen.'; + + @override + String get agentRetrySummary => 'Zusammenfassung wiederholen'; + + @override + String get agentResumeTask => 'Aufgabe fortsetzen'; + + @override + String get agentTaskInterrupted => + 'Die Aufgabe wurde unterbrochen. Vom gespeicherten Stand fortsetzen.'; + + @override + String get downloadSubtitleModel => 'Untertitelmodell herunterladen'; + + @override + String get downloadModelAction => 'Herunterladen'; + + @override + String get subtitleEngineUnavailable => + 'Das Modell ist installiert, aber die Untertitel-Engine konnte nicht starten. Reparieren Sie die Engine; das Modell muss nicht erneut heruntergeladen werden.'; + + @override + String get backgroundTaskDetails => 'Aufgabendetails'; + + @override + String get backgroundTaskFailed => 'Fehlgeschlagen'; + + @override + String get backgroundTaskCompleted => 'Abgeschlossen'; + + @override + String get captionWrapLines => 'Untertitel umbrechen'; + + @override + String get captionSingleLine => 'Untertitel einzeilig anzeigen'; + + @override + String get noMatchingCaptions => 'Keine passenden Untertitel'; + + @override + String get subtitleResourcesRequired => + 'Diese Ressourcen werden für Untertitel benötigt. Nach dem Download beginnt die Erstellung automatisch.'; + + @override + String subtitleResourcesDownloadSize(String size) { + return 'Herunterzuladen: $size'; + } + + @override + String get pauseDownload => 'Pausieren'; + + @override + String get resumeDownload => 'Fortsetzen'; + + @override + String get downloadPaused => 'Pausiert'; + + @override + String get cancelResourceDownloadTitle => 'Download abbrechen?'; + + @override + String get cancelResourceDownloadMessage => + 'Der Download wird beendet. Der Fortschritt der aktuellen Ressource kann verloren gehen.'; + + @override + String get continueDownload => 'Download fortsetzen'; + + @override + String get cancelDownload => 'Download abbrechen'; + + @override + String get speechResourceStage => 'Spracherkennungsressource'; + + @override + String get translationResourceStage => 'Übersetzungsressource'; + + @override + String get subtitleResourceDownloadTask => + 'Sprach- und Übersetzungsressourcen herunterladen'; + + @override + String get downloadingSpeechModel => 'Sprachmodell wird heruntergeladen'; + + @override + String get downloadingTranslationModel => + 'Übersetzungsmodell wird heruntergeladen'; + + @override + String get checkingForUpdates => 'Suche nach Updates…'; + + @override + String get appIsUpToDate => 'Die App ist aktuell.'; + + @override + String downloadingUpdate(int progress) { + return 'Update wird heruntergeladen: $progress%'; + } + + @override + String updateAvailable(String version) { + return 'Version $version ist verfügbar.'; + } + + @override + String get downloadUpdate => 'Update herunterladen'; + + @override + String get restartToUpdate => 'Für Update neu starten'; + + @override + String get updateOperationFailed => + 'Update fehlgeschlagen. Aktive Aufgaben abschließen und erneut versuchen.'; + + @override + String get windowMinimize => 'Minimieren'; + + @override + String get windowMaximize => 'Maximieren'; + + @override + String get windowRestore => 'Wiederherstellen'; + + @override + String get workspaceAgent => 'Assistent'; + + @override + String get workspaceCut => 'Schnitt'; + + @override + String get noAvailableOptions => 'Keine Optionen verfügbar'; + + @override + String get composerReferenceInvalid => + 'Ein Verweis ist nicht mehr gültig. Öffnen Sie sein Projekt oder entfernen Sie ihn.'; + + @override + String durationSeconds(int seconds) { + return '$seconds s'; + } + + @override + String durationMinutesSeconds(int minutes, int seconds) { + return '$minutes min $seconds s'; + } + + @override + String get projectNameInvalid => 'Ungültiger Projektname'; + + @override + String get projectLocationDefaultUnavailable => + 'Der Standard-Projektordner ist nicht zugänglich. Wählen Sie ihn in den Einstellungen erneut aus.'; + + @override + String get chooseProjectLocation => + 'Wählen Sie zuerst einen Projektordner in den Einstellungen.'; + + @override + String get untitledTimeline => 'Unbenannte Timeline'; + + @override + String get primarySequence => 'Hauptsequenz'; + + @override + String get primaryStoryline => 'Haupthandlung'; + + @override + String get projectSessionClosed => + 'Die Projektsitzung wurde geschlossen. Öffnen Sie das Projekt erneut.'; + + @override + String get timelineSessionClosed => + 'Die Timeline-Sitzung wurde geschlossen. Öffnen Sie die Timeline erneut.'; + + @override + String get timelineMissing => + 'Die Timeline existiert nicht oder wurde gelöscht.'; + + @override + String get timelineInUse => + 'Die Timeline wird verwendet und kann noch nicht gelöscht werden.'; + + @override + String get timelineHasBackgroundTasks => + 'Beenden Sie die Hintergrundaufgaben der Timeline, bevor Sie sie löschen.'; + + @override + String get timelineRequired => + 'Ein Projekt muss mindestens eine Timeline behalten.'; + + @override + String get mediaReadFailed => 'Medium konnte nicht gelesen werden'; + + @override + String get mediaImportFailed => 'Medium konnte nicht importiert werden'; + + @override + String get unsupportedMediaType => + 'Es können nur Video-, Audio- und Bilddateien importiert werden.'; + + @override + String get mediaNoVideoTracks => 'Das Medium hat keine verwendbare Videospur'; + + @override + String get mediaDurationOutOfRange => + 'Die Mediendauer überschreitet den Timeline-Bereich'; + + @override + String resourceDownloadHttpFailed(String statusCode) { + return 'Download fehlgeschlagen (HTTP $statusCode)'; + } + + @override + String get resourceChecksumFailed => + 'Die Modelldatei konnte nicht überprüft werden. Laden Sie die Ressource erneut herunter.'; + + @override + String get subtitleLanguageAf => 'Afrikaans'; + + @override + String get subtitleLanguageAm => 'Amharisch'; + + @override + String get subtitleLanguageAr => 'Arabisch'; + + @override + String get subtitleLanguageAst => 'Asturisch'; + + @override + String get subtitleLanguageAz => 'Aserbaidschanisch'; + + @override + String get subtitleLanguageBa => 'Baschkirisch'; + + @override + String get subtitleLanguageBe => 'Belarussisch'; + + @override + String get subtitleLanguageBg => 'Bulgarisch'; + + @override + String get subtitleLanguageBn => 'Bengalisch'; + + @override + String get subtitleLanguageBr => 'Bretonisch'; + + @override + String get subtitleLanguageBs => 'Bosnisch'; + + @override + String get subtitleLanguageCa => 'Katalanisch'; + + @override + String get subtitleLanguageCeb => 'Cebuano'; + + @override + String get subtitleLanguageCs => 'Tschechisch'; + + @override + String get subtitleLanguageCy => 'Walisisch'; + + @override + String get subtitleLanguageDa => 'Dänisch'; + + @override + String get subtitleLanguageDe => 'Deutsch'; + + @override + String get subtitleLanguageEl => 'Griechisch'; + + @override + String get subtitleLanguageEn => 'Englisch'; + + @override + String get subtitleLanguageEs => 'Spanisch'; + + @override + String get subtitleLanguageEt => 'Estnisch'; + + @override + String get subtitleLanguageFa => 'Persisch'; + + @override + String get subtitleLanguageFf => 'Ful'; + + @override + String get subtitleLanguageFi => 'Finnisch'; + + @override + String get subtitleLanguageFr => 'Französisch'; + + @override + String get subtitleLanguageFy => 'Westfriesisch'; + + @override + String get subtitleLanguageGa => 'Irisch'; + + @override + String get subtitleLanguageGd => 'Gälisch (Schottland)'; + + @override + String get subtitleLanguageGl => 'Galicisch'; + + @override + String get subtitleLanguageGu => 'Gujarati'; + + @override + String get subtitleLanguageHa => 'Haussa'; + + @override + String get subtitleLanguageHe => 'Hebräisch'; + + @override + String get subtitleLanguageHi => 'Hindi'; + + @override + String get subtitleLanguageHr => 'Kroatisch'; + + @override + String get subtitleLanguageHt => 'Haiti-Kreolisch'; + + @override + String get subtitleLanguageHu => 'Ungarisch'; + + @override + String get subtitleLanguageHy => 'Armenisch'; + + @override + String get subtitleLanguageId => 'Indonesisch'; + + @override + String get subtitleLanguageIg => 'Igbo'; + + @override + String get subtitleLanguageIlo => 'Ilokano'; + + @override + String get subtitleLanguageIs => 'Isländisch'; + + @override + String get subtitleLanguageIt => 'Italienisch'; + + @override + String get subtitleLanguageJa => 'Japanisch'; + + @override + String get subtitleLanguageJv => 'Javanisch'; + + @override + String get subtitleLanguageKa => 'Georgisch'; + + @override + String get subtitleLanguageKk => 'Kasachisch'; + + @override + String get subtitleLanguageKm => 'Khmer'; + + @override + String get subtitleLanguageKn => 'Kannada'; + + @override + String get subtitleLanguageKo => 'Koreanisch'; + + @override + String get subtitleLanguageLb => 'Luxemburgisch'; + + @override + String get subtitleLanguageLg => 'Ganda'; + + @override + String get subtitleLanguageLn => 'Lingala'; + + @override + String get subtitleLanguageLo => 'Laotisch'; + + @override + String get subtitleLanguageLt => 'Litauisch'; + + @override + String get subtitleLanguageLv => 'Lettisch'; + + @override + String get subtitleLanguageMg => 'Malagasy'; + + @override + String get subtitleLanguageMk => 'Mazedonisch'; + + @override + String get subtitleLanguageMl => 'Malayalam'; + + @override + String get subtitleLanguageMn => 'Mongolisch'; + + @override + String get subtitleLanguageMr => 'Marathi'; + + @override + String get subtitleLanguageMs => 'Malaiisch'; + + @override + String get subtitleLanguageMy => 'Birmanisch'; + + @override + String get subtitleLanguageNe => 'Nepalesisch'; + + @override + String get subtitleLanguageNl => 'Niederländisch'; + + @override + String get subtitleLanguageNo => 'Norwegisch'; + + @override + String get subtitleLanguageNs => 'Nord-Sotho'; + + @override + String get subtitleLanguageOc => 'Okzitanisch'; + + @override + String get subtitleLanguageOr => 'Oriya'; + + @override + String get subtitleLanguagePa => 'Punjabi'; + + @override + String get subtitleLanguagePl => 'Polnisch'; + + @override + String get subtitleLanguagePs => 'Paschtu'; + + @override + String get subtitleLanguagePt => 'Portugiesisch'; + + @override + String get subtitleLanguageRo => 'Rumänisch'; + + @override + String get subtitleLanguageRu => 'Russisch'; + + @override + String get subtitleLanguageSd => 'Sindhi'; + + @override + String get subtitleLanguageSi => 'Singhalesisch'; + + @override + String get subtitleLanguageSk => 'Slowakisch'; + + @override + String get subtitleLanguageSl => 'Slowenisch'; + + @override + String get subtitleLanguageSo => 'Somali'; + + @override + String get subtitleLanguageSq => 'Albanisch'; + + @override + String get subtitleLanguageSr => 'Serbisch'; + + @override + String get subtitleLanguageSs => 'Swazi'; + + @override + String get subtitleLanguageSu => 'Sundanesisch'; + + @override + String get subtitleLanguageSv => 'Schwedisch'; + + @override + String get subtitleLanguageSw => 'Suaheli'; + + @override + String get subtitleLanguageTa => 'Tamil'; + + @override + String get subtitleLanguageTh => 'Thailändisch'; + + @override + String get subtitleLanguageTl => 'Tagalog'; + + @override + String get subtitleLanguageTn => 'Tswana'; + + @override + String get subtitleLanguageTr => 'Türkisch'; + + @override + String get subtitleLanguageUk => 'Ukrainisch'; + + @override + String get subtitleLanguageUr => 'Urdu'; + + @override + String get subtitleLanguageUz => 'Usbekisch'; + + @override + String get subtitleLanguageVi => 'Vietnamesisch'; + + @override + String get subtitleLanguageWo => 'Wolof'; + + @override + String get subtitleLanguageXh => 'Xhosa'; + + @override + String get subtitleLanguageYi => 'Jiddisch'; + + @override + String get subtitleLanguageYo => 'Yoruba'; + + @override + String get subtitleLanguageYue => 'Kantonesisch'; + + @override + String get subtitleLanguageZh => 'Chinesisch'; + + @override + String get subtitleLanguageZu => 'Zulu'; + + @override + String get linearRec2020 => 'Lineares Rec.2020'; + + @override + String get diagnostics => 'Diagnose'; + + @override + String get exportDiagnostics => 'Diagnosepaket exportieren'; + + @override + String get exportDiagnosticsFailed => + 'Die Diagnose konnte nicht exportiert werden. Bitte erneut versuchen.'; + + @override + String get exportDiagnosticsSucceeded => 'Diagnosepaket gespeichert.'; +} diff --git a/lib/l10n/app_localizations_en.dart b/lib/l10n/app_localizations_en.dart new file mode 100644 index 0000000..0582ea7 --- /dev/null +++ b/lib/l10n/app_localizations_en.dart @@ -0,0 +1,2198 @@ +// ignore: unused_import +import 'package:intl/intl.dart' as intl; + +import 'app_localizations.dart'; + +// ignore_for_file: type=lint + +/// The translations for English (`en`). +class AppLocalizationsEn extends AppLocalizations { + AppLocalizationsEn([String locale = 'en']) : super(locale); + + @override + String get selectProject => 'Select project'; + + @override + String get searchProjects => 'Search projects'; + + @override + String get noMatchingProjects => 'No matching projects'; + + @override + String get projectsNone => 'No projects yet'; + + @override + String get projectLocationMissing => + 'The folder does not exist. It will be created when you create a project.'; + + @override + String get projectLocationUnavailable => + 'The project save location is unavailable. Connect the disk or check the network and retry, or change the location.'; + + @override + String get projectLocationNotWritable => + 'The project save location is not writable. Check permissions or change the location.'; + + @override + String get projectLocationCreateFailed => + 'Could not create or write to the project save folder. Check permissions or change the location.'; + + @override + String get removeProjectFromSidebar => 'Remove from sidebar'; + + @override + String get projectRemoved => + 'Project removed. Local files and conversations are preserved.'; + + @override + String get agentNoConversations => 'No conversations yet'; + + @override + String get renameConversationTitle => 'Rename chat'; + + @override + String get renameConversationDescription => + 'Keep it short and easy to recognize.'; + + @override + String get collapseProject => 'Collapse project'; + + @override + String get expandProject => 'Expand project'; + + @override + String agentDeleteConfirmation(String title) { + return 'Permanently delete “$title” and all its messages? This cannot be undone. Local project files will not be affected.'; + } + + @override + String get agentEmptyTrashConfirmation => + 'Permanently delete all conversations in Trash? This cannot be undone. Local project files will not be affected.'; + + @override + String get agentConversations => 'Conversations'; + + @override + String get showMoreConversations => 'Show more'; + + @override + String get showFewerConversations => 'Show fewer'; + + @override + String get agentNewConversation => 'New conversation'; + + @override + String agentElapsedTime(String duration) { + return 'Took $duration'; + } + + @override + String get agentConversationActions => 'Conversation actions'; + + @override + String get agentMoveToTrash => 'Move to Trash'; + + @override + String get agentTrash => 'Trash'; + + @override + String get agentRestore => 'Restore'; + + @override + String get agentEmptyTrash => 'Empty Trash'; + + @override + String get agentDeleteForever => 'Delete permanently'; + + @override + String get agentConversationLocation => 'Conversation location'; + + @override + String get agentChooseExistingConversations => + 'Choose existing conversations'; + + @override + String get agentMoveConversations => 'Move conversations'; + + @override + String get agentLocationUnavailable => 'Conversation location is unavailable'; + + @override + String get agentLocationBusy => + 'Finish current conversations before moving files'; + + @override + String get agentRelinkProvider => 'Relink provider'; + + @override + String get settings => 'Settings'; + + @override + String get closeSettings => 'Close settings'; + + @override + String get general => 'General'; + + @override + String get appearance => 'Appearance'; + + @override + String get theme => 'Theme'; + + @override + String get system => 'System default'; + + @override + String get light => 'Light'; + + @override + String get dark => 'Dark'; + + @override + String get saveAppearanceFailed => + 'Could not save appearance. Please try again.'; + + @override + String get loadAppearanceFailed => + 'Could not load appearance. Please select a theme again.'; + + @override + String get cancel => 'Cancel'; + + @override + String get save => 'Save'; + + @override + String get create => 'Create'; + + @override + String get close => 'Close'; + + @override + String get retry => 'Retry'; + + @override + String get select => 'Select'; + + @override + String get name => 'Name'; + + @override + String get enterName => 'Enter a name'; + + @override + String get invalidName => + 'Names cannot contain path separators or control characters'; + + @override + String get projects => 'Projects'; + + @override + String get projectName => 'Project name'; + + @override + String get projectLocation => 'Project save location'; + + @override + String get projectLocationNotSet => 'Not set'; + + @override + String get loadProjectLocationFailed => + 'Could not load the project save location.'; + + @override + String get saveProjectLocationFailed => + 'Could not save the project save location.'; + + @override + String get resourceLocation => 'Resource storage location'; + + @override + String get resourceLocationNotSet => 'Not set'; + + @override + String get loadResourceLocationFailed => + 'Could not load the resource storage location.'; + + @override + String get saveResourceLocationFailed => + 'Could not save the resource storage location.'; + + @override + String get transcriptionResourceRequired => + 'Generating subtitles requires downloading a speech recognition model first.'; + + @override + String get downloadAndContinue => 'Download and continue'; + + @override + String get downloadingResource => 'Downloading…'; + + @override + String get downloadInBackground => 'Download in background'; + + @override + String get processingResourceDownloadFailed => + 'Could not download the speech recognition resource. Please try again.'; + + @override + String get newProject => 'New project'; + + @override + String get openProject => 'Open project'; + + @override + String get openProjectMore => 'Open project…'; + + @override + String get saveHere => 'Save here'; + + @override + String get selectDirectoryFailed => + 'Could not select a directory. Check system permissions.'; + + @override + String get openingWorkspace => 'Opening workspace…'; + + @override + String get loadProjectsFailed => 'Could not load projects'; + + @override + String get projectsEmpty => 'Create or open a project to start editing.'; + + @override + String get backToProjects => 'Back to editing'; + + @override + String get timelines => 'Timelines'; + + @override + String timelineLimitReached(int count) { + return 'Each project can contain up to $count timelines.'; + } + + @override + String get timelineName => 'Timeline name'; + + @override + String defaultTimelineName(int index) { + return 'Timeline $index'; + } + + @override + String get newTimeline => 'New timeline'; + + @override + String get noTimelines => 'No timelines'; + + @override + String get activeTimeline => 'Current timeline'; + + @override + String get timelineUnavailable => 'Timeline unavailable'; + + @override + String get projectNoTimelines => 'This project has no timelines yet'; + + @override + String get createTimelineHint => + 'Create a timeline in the Timelines section on the left to start editing.'; + + @override + String get createTimelineChat => 'Create a timeline to start chatting'; + + @override + String get operationFailed => 'Operation failed. Please try again.'; + + @override + String get collapseSidebar => 'Collapse sidebar'; + + @override + String get expandSidebar => 'Expand sidebar'; + + @override + String get expandEditor => 'Expand editing area'; + + @override + String get collapseProperties => 'Collapse properties'; + + @override + String get expandProperties => 'Expand properties'; + + @override + String get layout => 'Layout'; + + @override + String get editingFirstLayout => 'Editing first'; + + @override + String get agentEditingLayout => 'Agent + editing'; + + @override + String get agentLayoutDescription => 'Plan, collaborate, and execute'; + + @override + String get editingLayoutDescription => 'Preview, edit, and refine'; + + @override + String get materials => 'Media'; + + @override + String get all => 'All'; + + @override + String get video => 'Video'; + + @override + String get audio => 'Audio'; + + @override + String get image => 'Image'; + + @override + String get picture => 'Image'; + + @override + String get captions => 'Captions'; + + @override + String get text => 'Text'; + + @override + String get noMedia => 'No media'; + + @override + String get mediaCategory => 'Media category'; + + @override + String get captionTasks => 'Caption tasks'; + + @override + String get listLayout => 'List view'; + + @override + String get gridLayout => 'Grid view'; + + @override + String get addToTimeline => 'Add to timeline'; + + @override + String get rename => 'Rename'; + + @override + String get renameMedia => 'Rename media'; + + @override + String get removeMedia => 'Remove media'; + + @override + String get remove => 'Remove'; + + @override + String get revealFinder => 'Show in Finder'; + + @override + String get revealFileManager => 'Show in file manager'; + + @override + String get dropToAdd => 'Release to add'; + + @override + String get timelineDropToStart => 'Drag media here to get started.'; + + @override + String get dragMediaHint => + 'Drag video, audio, or images here\nOriginal files stay in their current location'; + + @override + String get transcribe => 'Transcribe'; + + @override + String get generateCaptions => 'Generate captions'; + + @override + String get play => 'Play'; + + @override + String get pause => 'Pause'; + + @override + String get retryPreview => 'Retry preview'; + + @override + String get canvasRatio => 'Canvas aspect ratio'; + + @override + String get noPreviewContent => 'No content to preview on the timeline'; + + @override + String get nativePreviewUnsupported => + 'Native preview is unavailable on this platform'; + + @override + String get canvasTransformFailed => + 'Could not transform the canvas. Please try again.'; + + @override + String get undo => 'Undo'; + + @override + String get redo => 'Redo'; + + @override + String get deleteSelectedClips => 'Delete selected clips'; + + @override + String get splitAtPlayhead => 'Split at playhead'; + + @override + String get trimLeft => 'Trim left'; + + @override + String get trimRight => 'Trim right'; + + @override + String get trimLeftTooltip => + 'Trim away the left of the playhead, keeping the right'; + + @override + String get trimRightTooltip => + 'Trim away the right of the playhead, keeping the left'; + + @override + String get currentSequence => 'Current sequence'; + + @override + String get projectProperties => 'Project properties'; + + @override + String get canvasSize => 'Canvas size'; + + @override + String get frameRate => 'Frame rate'; + + @override + String get duration => 'Duration'; + + @override + String get totalDuration => 'Total duration'; + + @override + String get clipDuration => 'Clip duration'; + + @override + String get seconds => 'seconds'; + + @override + String get clip => 'Clip'; + + @override + String get unnamedClip => 'Unnamed clip'; + + @override + String get gap => 'Gap'; + + @override + String get compoundClip => 'Compound clip'; + + @override + String get textClip => 'Text clip'; + + @override + String get pictureProperties => 'Picture'; + + @override + String get position => 'Position'; + + @override + String get rotation => 'Rotation'; + + @override + String get scale => 'Scale'; + + @override + String get size => 'Size'; + + @override + String get transform => 'Transform'; + + @override + String get resetPosition => 'Reset position'; + + @override + String get keepAspectRatio => 'Lock aspect ratio'; + + @override + String get alignment => 'Alignment'; + + @override + String get alignLeft => 'Align left'; + + @override + String get alignRight => 'Align right'; + + @override + String get alignTop => 'Align top'; + + @override + String get alignBottom => 'Align bottom'; + + @override + String get alignHorizontalCenter => 'Center horizontally'; + + @override + String get alignVerticalCenter => 'Center vertically'; + + @override + String get volume => 'Volume'; + + @override + String get gain => 'Gain'; + + @override + String get mute => 'Mute'; + + @override + String get unmute => 'Unmute'; + + @override + String get resetVolume => 'Reset volume'; + + @override + String get invalidGain => 'Enter a value between -90 and +12'; + + @override + String get animation => 'Animation'; + + @override + String get keyframes => 'Keyframes'; + + @override + String get removeAllKeyframes => 'Remove all keyframes'; + + @override + String get linear => 'Linear'; + + @override + String get easeIn => 'Ease in'; + + @override + String get easeOut => 'Ease out'; + + @override + String get easeInOut => 'Ease in and out'; + + @override + String get basic => 'Basic'; + + @override + String get mask => 'Mask'; + + @override + String get addMask => 'Add mask'; + + @override + String get deleteMask => 'Delete mask'; + + @override + String get resetMask => 'Reset mask'; + + @override + String get enableMask => 'Enable mask'; + + @override + String get disableMask => 'Disable mask'; + + @override + String get moveMaskUp => 'Move mask up'; + + @override + String get moveMaskDown => 'Move mask down'; + + @override + String get rectangle => 'Rectangle'; + + @override + String get ellipse => 'Ellipse'; + + @override + String get invert => 'Invert'; + + @override + String get feather => 'Feather'; + + @override + String get add => 'Add'; + + @override + String get subtract => 'Subtract'; + + @override + String get intersect => 'Intersect'; + + @override + String get initialRegion => 'Initial region'; + + @override + String get none => 'None'; + + @override + String get color => 'Color'; + + @override + String get fontSize => 'Font size'; + + @override + String get outlineWidth => 'Outline width'; + + @override + String get outlineColor => 'Outline color'; + + @override + String get captionBaseline => 'Caption baseline'; + + @override + String get content => 'Text'; + + @override + String get start => 'Start'; + + @override + String get time => 'Time'; + + @override + String get speed => 'Speed'; + + @override + String speedSegmentCount(int count) { + return '$count speed segments'; + } + + @override + String get splitSpeedAtPlayhead => 'Split speed at playhead'; + + @override + String get speedChange => 'Speed'; + + @override + String get speedMode => 'Speed mode'; + + @override + String get constantSpeed => 'Constant speed'; + + @override + String get segmentedSpeed => 'Segmented speed'; + + @override + String get speedNotAvailable => 'Speed controls are not available yet'; + + @override + String get custom => 'Custom'; + + @override + String get invalidNumber => 'Invalid value'; + + @override + String get mediaUnavailable => 'Media unavailable'; + + @override + String get mediaMissing => 'Missing media'; + + @override + String get mediaColorSpace => 'Media color space'; + + @override + String get mediaColorInterpretation => 'Media color interpretation'; + + @override + String get colorInfoNotLoaded => 'Color information not loaded'; + + @override + String get unknownColorSpace => 'Unknown color space. Displaying as Rec.709.'; + + @override + String get colorBackendUnsupported => + 'The current backend does not support media color interpretation.'; + + @override + String get loadClipPropertiesFailed => 'Could not read clip properties'; + + @override + String get updatePictureFailed => 'Could not update picture properties'; + + @override + String get updateVolumeFailed => 'Could not update volume'; + + @override + String get updateMaskFailed => 'Could not update mask'; + + @override + String get updateKeyframesFailed => 'Could not update keyframes'; + + @override + String get maskPreviewFailed => 'Could not prepare mask preview'; + + @override + String get alignClipFailed => + 'Could not align the clip. Wait for the preview, then try again.'; + + @override + String get invalidTransform => + 'Scale must be 1%–10000%. Position and angle must be valid numbers.'; + + @override + String get editFailed => 'Could not edit. Check the input and time range.'; + + @override + String get addMediaFailed => 'Could not add media. Please try again.'; + + @override + String get deleteCaption => 'Delete caption'; + + @override + String get mergeCaptions => 'Merge captions'; + + @override + String get captionDeleted => 'Caption deleted'; + + @override + String get captionChanged => 'Captions have changed. Please try again.'; + + @override + String get captionEditChanged => 'Captions have changed. Please edit again.'; + + @override + String get assistantHint => 'Describe your editing idea'; + + @override + String get configureAgentHint => + 'Configure the agent service to start chatting'; + + @override + String get agentRestartHint => + 'Configure the agent service, then restart the app.'; + + @override + String get replyInterrupted => 'Response interrupted'; + + @override + String get replying => 'Responding…'; + + @override + String get stopReply => 'Stop response'; + + @override + String get sendMessage => 'Send message'; + + @override + String get addAttachment => 'Add attachment (not available yet)'; + + @override + String get replyFailed => + 'Response failed. Check the connection or try again later.'; + + @override + String get mcpService => 'MCP service'; + + @override + String get listenPort => 'Port'; + + @override + String get accessToken => 'Access token'; + + @override + String get copyAccessToken => 'Copy access token'; + + @override + String get accessTokenCopied => 'Access token copied'; + + @override + String get loadMcpFailed => 'Could not load MCP settings. Retry'; + + @override + String get saveMcpFailed => 'Could not save MCP settings. Please try again.'; + + @override + String get retryStart => 'Retry starting'; + + @override + String get invalidPort => 'Port must be between 1 and 65535'; + + @override + String get loadingSettings => 'Loading settings…'; + + @override + String get starting => 'Starting…'; + + @override + String get stopping => 'Stopping…'; + + @override + String get disabled => 'Disabled'; + + @override + String get running => 'Running'; + + @override + String get startFailed => 'Failed to start'; + + @override + String get saved => 'Saved'; + + @override + String get unsaved => 'Unsaved'; + + @override + String get saving => 'Saving…'; + + @override + String get pendingSave => 'Pending save'; + + @override + String get notApplied => 'Not applied'; + + @override + String get enable => 'Enable'; + + @override + String get disable => 'Disable'; + + @override + String get type => 'Type'; + + @override + String get status => 'Status'; + + @override + String get file => 'File'; + + @override + String get unboundMedia => 'No media bound'; + + @override + String get unboundAudio => 'No audio track bound'; + + @override + String get vertical => 'Vertical'; + + @override + String get language => 'Language'; + + @override + String get saveLanguageFailed => 'Could not save language. Please try again.'; + + @override + String get loadLanguageFailed => + 'Could not load language. Please select again.'; + + @override + String get propertiesFirstLayout => 'Properties first'; + + @override + String get defaultLayout => 'Default layout'; + + @override + String get separateVocals => 'Separate vocals'; + + @override + String get detachAudio => 'Detach audio'; + + @override + String get restoreAudio => 'Restore audio'; + + @override + String get audioDetached => 'Audio detached'; + + @override + String get addAll => 'Add all'; + + @override + String get preparingMedia => 'Preparing media…'; + + @override + String get cancelling => 'Cancelling…'; + + @override + String get cancelled => 'Cancelled'; + + @override + String get interruptedTask => 'Task interrupted. Restart to continue'; + + @override + String get auto => 'Automatic'; + + @override + String get autoDetect => 'Auto detect'; + + @override + String get noTranslation => 'No translation'; + + @override + String get sourceLanguage => 'Source language'; + + @override + String get translationLanguage => 'Translation language'; + + @override + String get transcriptionNotConfigured => + 'Transcription is not configured. Install the recognition component and Whisper Turbo model.'; + + @override + String get translationNotConfigured => + 'Caption translation is not configured. You can generate captions in the source language.'; + + @override + String get sourceLanguageUnknown => + 'Could not determine a source language for translation.'; + + @override + String get startTranscriptionFailed => + 'Could not start transcription. Check media or wait for the current task to finish.'; + + @override + String get placeMediaFirst => + 'Place this media on the timeline before applying captions.'; + + @override + String get placeTranslationMediaFirst => + 'Place the corresponding media on the timeline before applying translated captions.'; + + @override + String get selectTargetClip => 'Select target clip'; + + @override + String get timelineChanged => + 'The timeline has changed. Select the target clip again.'; + + @override + String get transcriptionAccessFailed => + 'Transcription failed: component, model, or source media inaccessible (notConfigured)'; + + @override + String get transcriptionNoAudio => + 'Transcription failed: no recognizable audio in the selected media or track (noAudio)'; + + @override + String get transcriptionInvalidResult => + 'Transcription failed: invalid caption file returned (invalidResult)'; + + @override + String get transcriptionWorkerExited => + 'Transcription failed: recognition component exited unexpectedly (workerExited)'; + + @override + String get transcriptionProcessingFailed => + 'Transcription failed: native processing failed (processingFailed)'; + + @override + String get transcriptionFailed => + 'Transcription failed. Check the component, model, audio track, and duration'; + + @override + String get transcribing => 'Transcribing…'; + + @override + String get captionsGenerated => 'Captions generated'; + + @override + String get cancelTranscription => 'Cancel transcription'; + + @override + String get applyCaptions => 'Apply captions'; + + @override + String get preparingTranslation => 'Preparing translation…'; + + @override + String get translatingCaptions => 'Translating captions…'; + + @override + String get cancellingTranslation => 'Cancelling translation…'; + + @override + String get translatedCaptionsGenerated => 'Translated captions generated'; + + @override + String get translationCancelled => 'Translation cancelled'; + + @override + String get translationInterrupted => 'Translation interrupted'; + + @override + String get cancelTranslation => 'Cancel translation'; + + @override + String get editorServiceUnavailable => + 'Editing service unavailable. Reopen the project.'; + + @override + String get mcpUnavailable => + 'MCP connection unavailable. Check the local port and token.'; + + @override + String get openTimelineFailed => 'Could not open the timeline'; + + @override + String get noTimelineSequence => 'This timeline has no sequence'; + + @override + String get waitingForProject => 'Waiting for a project to open'; + + @override + String get hold => 'Hold'; + + @override + String get noImportableFiles => 'No importable files received'; + + @override + String get virtualFilesUnsupported => + 'Drag original files from the file manager. Virtual files are not supported yet.'; + + @override + String get editorSessionStartFailed => 'Could not open the timeline editor'; + + @override + String get previewStartFailed => 'Could not start native preview'; + + @override + String get previewInvalidTrack => + 'The selected audio or video track does not exist in the media.'; + + @override + String get previewMissingBinding => + 'Media bindings are missing. Could not preview this timeline.'; + + @override + String get previewUnsupportedEdits => + 'This timeline contains edits that are not yet supported by preview.'; + + @override + String get previewUnsupportedConfiguration => + 'This preview configuration is not supported on the current platform or system version.'; + + @override + String get previewHdrUnsupported => + 'HDR media requires tone mapping for SDR preview. The current system or preview configuration does not support it.'; + + @override + String get previewAudioOutOfRange => + 'The audio clip exceeds the source track range and cannot be previewed.'; + + @override + String get previewResourceMissing => + 'Preview media no longer exists. Locate the original file again.'; + + @override + String get previewInvalidComposition => + 'Invalid video composition configuration. Could not create preview.'; + + @override + String get previewInvalidData => 'Invalid preview data. Please try again.'; + + @override + String get previewFailed => + 'Preview failed. Check media access and try again.'; + + @override + String get chatFailed => + 'Could not complete the conversation. Check the service configuration or try again later.'; + + @override + String get delete => 'Delete'; + + @override + String get pinTimeline => 'Pin timeline'; + + @override + String get unpinTimeline => 'Unpin timeline'; + + @override + String deleteTimelineConfirmation(String name) { + return 'Delete “$name” and its edit history? This cannot be undone.'; + } + + @override + String get processingFailed => 'Processing failed'; + + @override + String get noMatchingOptions => 'No matching options'; + + @override + String removeMediaConfirmation(String name) { + return 'Remove “$name” from the project? Existing clips, history, and the original file will be kept.'; + } + + @override + String mediaAdded(int count) { + return 'Added $count media references'; + } + + @override + String duplicatesSkipped(int count) { + return 'Skipped $count duplicate files'; + } + + @override + String mediaCount(int count) { + return '$count media items'; + } + + @override + String get importMedia => 'Import'; + + @override + String noMediaOfType(String type) { + return 'No $type media'; + } + + @override + String captionsImported(String count) { + return 'Imported $count captions'; + } + + @override + String editCaptionError(String message) { + return 'Could not edit captions: $message'; + } + + @override + String mcpStartError(String message) { + return 'Could not start MCP: $message'; + } + + @override + String manualColorSpace(String name) { + return 'Manually selected: $name'; + } + + @override + String detectedColorSpace(String name) { + return 'Detected: $name'; + } + + @override + String keyframeLabel(String channel) { + return '$channel keyframe'; + } + + @override + String maskMode(String mode) { + return 'Combination mode: $mode'; + } + + @override + String keyframeCount(int count) { + return '$count keyframes'; + } + + @override + String toggleKeyframe(String action, String channel) { + return '$action $channel keyframe'; + } + + @override + String previousKeyframe(String channel) { + return 'Previous $channel keyframe'; + } + + @override + String nextKeyframe(String channel) { + return 'Next $channel keyframe'; + } + + @override + String keyframeSettings(String channel) { + return '$channel keyframe settings'; + } + + @override + String selectedClipsHint(int count) { + return '$count clips selected\nSelect one clip to view its properties'; + } + + @override + String transcriptionError(String code) { + return 'Transcription failed. Check the component, model, audio track, and duration ($code)'; + } + + @override + String captionsAdded(String count) { + return 'Added $count captions. Edit them in the properties panel.'; + } + + @override + String translatedCaptionsAdded(String count) { + return 'Added $count translated captions. Edit them in the properties panel.'; + } + + @override + String applyCaptionsError(String message) { + return 'Could not apply captions: $message'; + } + + @override + String applyTranslatedCaptionsError(String message) { + return 'Could not apply translated captions: $message'; + } + + @override + String recognizedCaptions(int count) { + return 'Recognized $count captions'; + } + + @override + String captionCount(int count) { + return '$count captions'; + } + + @override + String translationFailed(String message) { + return 'Translation failed: $message'; + } + + @override + String translatedCaptionCount(int count, String language) { + return '$count $language captions'; + } + + @override + String previewParameterError(String message) { + return 'Invalid preview parameters: $message'; + } + + @override + String mediaOffline(String names) { + return 'Media offline or unavailable: $names'; + } + + @override + String searchOptions(String label) { + return 'Search $label…'; + } + + @override + String get loadRecentProjectsFailed => + 'Could not load recent projects. You can still open a project manually.'; + + @override + String get projectAccessFailed => 'Project unavailable'; + + @override + String get projectMissingDirectory => 'Project not found'; + + @override + String get recentProjectSaveFailed => + 'Project opened, but the recent project record could not be saved.'; + + @override + String get lastProjectSaveFailed => + 'Project opened, but the last project record could not be saved.'; + + @override + String get enterProjectName => 'Enter a project name'; + + @override + String get projectSwitched => + 'The project has changed. Drag the media in again.'; + + @override + String get notLocalMedia => 'This media is not a local file'; + + @override + String get revealMediaFailed => 'Could not show media in the file manager'; + + @override + String get openMatchingProject => 'Open the corresponding project first'; + + @override + String get projectMismatch => + 'The project at this location does not match the record. Select it again with Open project.'; + + @override + String get openProjectFirst => 'Open a project first'; + + @override + String get localFilesOnly => 'Drag local files from the file manager'; + + @override + String get foldersUnsupported => + 'Select files. Dragging folders is not supported yet.'; + + @override + String get mediaImportCancelled => 'Media import cancelled'; + + @override + String get fileAccessFailed => + 'The file is missing or unreadable. Check its location and permissions'; + + @override + String get registerMediaFailed => + 'Could not register media. Please try again'; + + @override + String get mediaNoLongerExists => 'Media no longer exists'; + + @override + String get mediaNoTracks => 'Media has no usable video or audio tracks'; + + @override + String get invalidMediaDuration => 'Invalid media duration'; + + @override + String get mediaInfoUnsupported => + 'Reading media information is not supported on this platform yet'; + + @override + String get mediaInfoFailed => + 'Could not read media information. Check the file and access permissions'; + + @override + String get saveTimelineFailed => + 'Could not save the timeline. Try again. Unsaved edits remain in this session.'; + + @override + String get addKeyframeAction => 'Add'; + + @override + String get backgroundTasks => 'Background tasks'; + + @override + String get noBackgroundTasks => 'No background tasks'; + + @override + String get retryTask => 'Retry'; + + @override + String get applyOriginalCaptions => 'Apply original captions'; + + @override + String get applyTranslatedCaptions => 'Apply translated captions'; + + @override + String get subtitleTaskStarted => 'Subtitle task started'; + + @override + String get fitTimeline => 'Fit entire timeline'; + + @override + String get modify => 'Modify'; + + @override + String get projectSettings => 'Project settings'; + + @override + String get projectSettingsDescription => + 'Change project output settings while keeping clip timing and speed.'; + + @override + String get projectColorSpace => 'Color space'; + + @override + String get projectWidth => 'Width (px)'; + + @override + String get projectHeight => 'Height (px)'; + + @override + String get projectResolutionInvalid => 'Enter a whole number from 1 to 16384'; + + @override + String get previewFullscreen => 'Fullscreen preview'; + + @override + String get exitPreviewFullscreen => 'Exit fullscreen'; + + @override + String get previewGoToStart => 'Go to start'; + + @override + String get previewPreviousFrame => 'Previous frame'; + + @override + String get previewNextFrame => 'Next frame'; + + @override + String get softwareUpdates => 'Software updates'; + + @override + String get checkForUpdates => 'Check for updates'; + + @override + String get automaticallyCheckUpdates => 'Automatically check for updates'; + + @override + String get updatesUnavailable => 'Updates are unavailable in this build.'; + + @override + String get updateCheckFailed => + 'Could not check for updates. Please try again.'; + + @override + String get removeBackground => 'Remove background'; + + @override + String get startBackgroundRemoval => 'Remove background'; + + @override + String get backgroundRemovalResourceRequired => + 'Background removal needs a local model. It starts automatically after download.'; + + @override + String get backgroundRemovalDownloadTask => + 'Download background removal resource'; + + @override + String get backgroundRemovalResourceName => 'Background removal model'; + + @override + String get backgroundRemovalDestructiveHint => + 'The generated transparent media will replace this clip. You can still use Undo to restore the original clip.'; + + @override + String get backgroundRemovalTaskStarted => 'Background removal started'; + + @override + String get startBackgroundRemovalFailed => + 'Could not start background removal. Check the media or wait for the current processing task.'; + + @override + String get backgroundRemovalComplete => 'Background removal complete'; + + @override + String get backgroundRemovalApplying => 'Replacing clip media'; + + @override + String get backgroundRemovalFailed => 'Background removal failed'; + + @override + String get agentSettings => 'Agent'; + + @override + String get agentSaveSettingsFailed => 'Could not save Agent settings.'; + + @override + String get agentDeleteProviderTitle => 'Delete provider?'; + + @override + String agentDeleteProviderDescription(String providerName) { + return '“$providerName” and its saved API key will be removed from this device.'; + } + + @override + String get agentProviderRequired => + 'Add a provider before enabling the assistant.'; + + @override + String get agentUseSelectedModel => + 'Use the selected model for new Agent requests.'; + + @override + String get agentEnable => 'Enable Agent'; + + @override + String get agentDefaultModel => 'Default model'; + + @override + String get agentConfigureModel => 'Configure models'; + + @override + String get agentSelectModel => 'Select model'; + + @override + String get agentModelUnavailable => + 'The model for this conversation is unavailable. Select another model to start a new conversation.'; + + @override + String get agentModelChangeSession => + 'Changing the model starts a new Agent session.'; + + @override + String get agentCustomProviders => 'Custom providers'; + + @override + String get agentProviderStorageDescription => + 'Provider metadata is stored locally. API keys are kept in the system credential store.'; + + @override + String get agentAddProvider => 'Add provider'; + + @override + String get agentBackToProviders => 'Back to providers'; + + @override + String get agentLoadSettingsFailed => 'Could not load Agent settings. Retry'; + + @override + String get agentEnableProvider => 'Enable provider'; + + @override + String get agentEditProvider => 'Edit provider'; + + @override + String get agentDeleteProvider => 'Delete provider'; + + @override + String get agentModelIdsUnique => 'Model IDs must be unique.'; + + @override + String get agentEditProviderTitle => 'Edit provider'; + + @override + String get agentProviderEndpointDescription => + 'Configure an OpenAI-compatible Chat Completions endpoint.'; + + @override + String get agentSaveProvider => 'Save provider'; + + @override + String get agentProviderConfiguration => 'Provider configuration'; + + @override + String get agentAuthenticationAndModels => 'Authentication & models'; + + @override + String get agentApiType => 'API type'; + + @override + String get agentOpenAiChatCompletions => 'OpenAI Completions'; + + @override + String get agentBaseUrl => 'Base URL'; + + @override + String get agentApiKey => 'API key'; + + @override + String get agentProviderNameHint => 'My provider'; + + @override + String get agentApiKeyOptional => + 'Optional for endpoints that do not require authentication.'; + + @override + String get agentApiKeyKeep => 'Leave blank to keep the saved key.'; + + @override + String get agentOptional => 'Optional'; + + @override + String get agentApiKeyOneLine => 'The API key must be one line.'; + + @override + String get agentRemoveSavedApiKey => 'Remove saved API key'; + + @override + String get agentModels => 'Models'; + + @override + String get agentAddModel => 'Add model'; + + @override + String get agentRequiredField => 'This field is required.'; + + @override + String get agentInvalidBaseUrl => + 'Enter an HTTP(S) base URL without credentials, query, or fragment.'; + + @override + String get agentModelId => 'Model ID'; + + @override + String get agentContextWindow => 'Context window'; + + @override + String get agentMaxOutputTokens => 'Max output'; + + @override + String get agentMaxOutputBelowContext => 'Must be below context.'; + + @override + String get agentDeleteModel => 'Delete model'; + + @override + String get agentPositiveInteger => 'Use a positive integer.'; + + @override + String get agentConfigurationReadFailed => + 'Could not read the Agent configuration. Check settings and try again.'; + + @override + String get agentConfigurationRequired => + 'Configure and enable Agent in Settings first.'; + + @override + String get agentSessionRestoreFailed => + 'Could not restore the Agent session. Try again later.'; + + @override + String get agentContextBudgetExceeded => + 'Input budget is too small for the system instructions, tools and message. Increase the context window or reduce maximum output tokens.'; + + @override + String get agentAuthenticationFailed => + 'Authentication failed. Check the Provider API key and permissions.'; + + @override + String get agentConnectionFailed => + 'Could not connect to the model service, or the request timed out. Check the Base URL and network.'; + + @override + String get agentProtocolFailed => + 'The service response does not match the selected API type, or the response stream is incomplete.'; + + @override + String get agentContextBudgetTooSmall => + 'Reserve more input space for system instructions. Increase the context window or reduce maximum output tokens.'; + + @override + String get agentCompacting => 'Organizing context…'; + + @override + String get agentEditing => 'Editing…'; + + @override + String get agentVerifying => 'Checking results…'; + + @override + String get agentTurnLimitReached => + 'This task reached its execution limit. Edits have been saved. Send “Continue” to resume.'; + + @override + String get agentRecoveryRequired => + 'The previous operation is unconfirmed. Continue to check saved receipts; unconfirmed edits will not be repeated.'; + + @override + String get agentExportReplyFailed => + 'Video exported successfully. The summary reply failed. Retry the summary without repeating edits or export.'; + + @override + String get agentRetrySummary => 'Retry summary'; + + @override + String get agentResumeTask => 'Continue task'; + + @override + String get agentTaskInterrupted => + 'This task was interrupted. Continue from its saved progress.'; + + @override + String get downloadSubtitleModel => 'Download subtitle model'; + + @override + String get downloadModelAction => 'Download'; + + @override + String get subtitleEngineUnavailable => + 'The model is installed, but the subtitle engine could not start. Repair the processing engine; the model does not need to be downloaded again.'; + + @override + String get backgroundTaskDetails => 'Task details'; + + @override + String get backgroundTaskFailed => 'Failed'; + + @override + String get backgroundTaskCompleted => 'Completed'; + + @override + String get captionWrapLines => 'Wrap subtitle text'; + + @override + String get captionSingleLine => 'Show subtitles on one line'; + + @override + String get noMatchingCaptions => 'No matching subtitles'; + + @override + String get subtitleResourcesRequired => + 'These resources are needed for subtitles. Generation starts automatically after download.'; + + @override + String subtitleResourcesDownloadSize(String size) { + return 'To download: $size'; + } + + @override + String get pauseDownload => 'Pause'; + + @override + String get resumeDownload => 'Resume'; + + @override + String get downloadPaused => 'Paused'; + + @override + String get cancelResourceDownloadTitle => 'Cancel download?'; + + @override + String get cancelResourceDownloadMessage => + 'The download will stop. Progress on the current resource may be lost.'; + + @override + String get continueDownload => 'Continue downloading'; + + @override + String get cancelDownload => 'Cancel download'; + + @override + String get speechResourceStage => 'Speech recognition resource'; + + @override + String get translationResourceStage => 'Translation resource'; + + @override + String get subtitleResourceDownloadTask => + 'Download speech and translation resources'; + + @override + String get downloadingSpeechModel => 'Downloading speech model'; + + @override + String get downloadingTranslationModel => 'Downloading translation model'; + + @override + String get checkingForUpdates => 'Checking for updates…'; + + @override + String get appIsUpToDate => 'You are up to date.'; + + @override + String downloadingUpdate(int progress) { + return 'Downloading update: $progress%'; + } + + @override + String updateAvailable(String version) { + return 'Version $version is available.'; + } + + @override + String get downloadUpdate => 'Download update'; + + @override + String get restartToUpdate => 'Restart to update'; + + @override + String get updateOperationFailed => + 'Could not update. Finish active tasks and try again.'; + + @override + String get windowMinimize => 'Minimize'; + + @override + String get windowMaximize => 'Maximize'; + + @override + String get windowRestore => 'Restore'; + + @override + String get workspaceAgent => 'Agent'; + + @override + String get workspaceCut => 'Cut'; + + @override + String get noAvailableOptions => 'No options available'; + + @override + String get composerReferenceInvalid => + 'A reference is no longer valid. Return to its project or remove it.'; + + @override + String durationSeconds(int seconds) { + return '${seconds}s'; + } + + @override + String durationMinutesSeconds(int minutes, int seconds) { + return '${minutes}m ${seconds}s'; + } + + @override + String get projectNameInvalid => 'Invalid project name'; + + @override + String get projectLocationDefaultUnavailable => + 'Could not access the default project location. Select it again in Settings.'; + + @override + String get chooseProjectLocation => + 'Select a project save location in Settings first.'; + + @override + String get untitledTimeline => 'Untitled timeline'; + + @override + String get primarySequence => 'Main sequence'; + + @override + String get primaryStoryline => 'Main storyline'; + + @override + String get projectSessionClosed => + 'The project session has closed. Reopen the project.'; + + @override + String get timelineSessionClosed => + 'The timeline session has closed. Reopen the timeline.'; + + @override + String get timelineMissing => + 'The timeline does not exist or has been deleted.'; + + @override + String get timelineInUse => + 'The timeline is in use and cannot be deleted yet.'; + + @override + String get timelineHasBackgroundTasks => + 'Finish the timeline’s background tasks before deleting it.'; + + @override + String get timelineRequired => 'A project must keep at least one timeline.'; + + @override + String get mediaReadFailed => 'Could not read media'; + + @override + String get mediaImportFailed => 'Could not import media'; + + @override + String get unsupportedMediaType => + 'Only video, audio, and image files can be imported.'; + + @override + String get mediaNoVideoTracks => 'Media has no usable video track'; + + @override + String get mediaDurationOutOfRange => + 'Media duration exceeds the timeline range'; + + @override + String resourceDownloadHttpFailed(String statusCode) { + return 'Download failed (HTTP $statusCode)'; + } + + @override + String get resourceChecksumFailed => + 'Model file verification failed. Download the resource again.'; + + @override + String get subtitleLanguageAf => 'Afrikaans'; + + @override + String get subtitleLanguageAm => 'Amharic'; + + @override + String get subtitleLanguageAr => 'Arabic'; + + @override + String get subtitleLanguageAst => 'Asturian'; + + @override + String get subtitleLanguageAz => 'Azerbaijani'; + + @override + String get subtitleLanguageBa => 'Bashkir'; + + @override + String get subtitleLanguageBe => 'Belarusian'; + + @override + String get subtitleLanguageBg => 'Bulgarian'; + + @override + String get subtitleLanguageBn => 'Bangla'; + + @override + String get subtitleLanguageBr => 'Breton'; + + @override + String get subtitleLanguageBs => 'Bosnian'; + + @override + String get subtitleLanguageCa => 'Catalan'; + + @override + String get subtitleLanguageCeb => 'Cebuano'; + + @override + String get subtitleLanguageCs => 'Czech'; + + @override + String get subtitleLanguageCy => 'Welsh'; + + @override + String get subtitleLanguageDa => 'Danish'; + + @override + String get subtitleLanguageDe => 'German'; + + @override + String get subtitleLanguageEl => 'Greek'; + + @override + String get subtitleLanguageEn => 'English'; + + @override + String get subtitleLanguageEs => 'Spanish'; + + @override + String get subtitleLanguageEt => 'Estonian'; + + @override + String get subtitleLanguageFa => 'Persian'; + + @override + String get subtitleLanguageFf => 'Fula'; + + @override + String get subtitleLanguageFi => 'Finnish'; + + @override + String get subtitleLanguageFr => 'French'; + + @override + String get subtitleLanguageFy => 'Western Frisian'; + + @override + String get subtitleLanguageGa => 'Irish'; + + @override + String get subtitleLanguageGd => 'Scottish Gaelic'; + + @override + String get subtitleLanguageGl => 'Galician'; + + @override + String get subtitleLanguageGu => 'Gujarati'; + + @override + String get subtitleLanguageHa => 'Hausa'; + + @override + String get subtitleLanguageHe => 'Hebrew'; + + @override + String get subtitleLanguageHi => 'Hindi'; + + @override + String get subtitleLanguageHr => 'Croatian'; + + @override + String get subtitleLanguageHt => 'Haitian Creole'; + + @override + String get subtitleLanguageHu => 'Hungarian'; + + @override + String get subtitleLanguageHy => 'Armenian'; + + @override + String get subtitleLanguageId => 'Indonesian'; + + @override + String get subtitleLanguageIg => 'Igbo'; + + @override + String get subtitleLanguageIlo => 'Iloko'; + + @override + String get subtitleLanguageIs => 'Icelandic'; + + @override + String get subtitleLanguageIt => 'Italian'; + + @override + String get subtitleLanguageJa => 'Japanese'; + + @override + String get subtitleLanguageJv => 'Javanese'; + + @override + String get subtitleLanguageKa => 'Georgian'; + + @override + String get subtitleLanguageKk => 'Kazakh'; + + @override + String get subtitleLanguageKm => 'Khmer'; + + @override + String get subtitleLanguageKn => 'Kannada'; + + @override + String get subtitleLanguageKo => 'Korean'; + + @override + String get subtitleLanguageLb => 'Luxembourgish'; + + @override + String get subtitleLanguageLg => 'Ganda'; + + @override + String get subtitleLanguageLn => 'Lingala'; + + @override + String get subtitleLanguageLo => 'Lao'; + + @override + String get subtitleLanguageLt => 'Lithuanian'; + + @override + String get subtitleLanguageLv => 'Latvian'; + + @override + String get subtitleLanguageMg => 'Malagasy'; + + @override + String get subtitleLanguageMk => 'Macedonian'; + + @override + String get subtitleLanguageMl => 'Malayalam'; + + @override + String get subtitleLanguageMn => 'Mongolian'; + + @override + String get subtitleLanguageMr => 'Marathi'; + + @override + String get subtitleLanguageMs => 'Malay'; + + @override + String get subtitleLanguageMy => 'Burmese'; + + @override + String get subtitleLanguageNe => 'Nepali'; + + @override + String get subtitleLanguageNl => 'Dutch'; + + @override + String get subtitleLanguageNo => 'Norwegian'; + + @override + String get subtitleLanguageNs => 'Northern Sotho'; + + @override + String get subtitleLanguageOc => 'Occitan'; + + @override + String get subtitleLanguageOr => 'Odia'; + + @override + String get subtitleLanguagePa => 'Punjabi'; + + @override + String get subtitleLanguagePl => 'Polish'; + + @override + String get subtitleLanguagePs => 'Pashto'; + + @override + String get subtitleLanguagePt => 'Portuguese'; + + @override + String get subtitleLanguageRo => 'Romanian'; + + @override + String get subtitleLanguageRu => 'Russian'; + + @override + String get subtitleLanguageSd => 'Sindhi'; + + @override + String get subtitleLanguageSi => 'Sinhala'; + + @override + String get subtitleLanguageSk => 'Slovak'; + + @override + String get subtitleLanguageSl => 'Slovenian'; + + @override + String get subtitleLanguageSo => 'Somali'; + + @override + String get subtitleLanguageSq => 'Albanian'; + + @override + String get subtitleLanguageSr => 'Serbian'; + + @override + String get subtitleLanguageSs => 'Swati'; + + @override + String get subtitleLanguageSu => 'Sundanese'; + + @override + String get subtitleLanguageSv => 'Swedish'; + + @override + String get subtitleLanguageSw => 'Swahili'; + + @override + String get subtitleLanguageTa => 'Tamil'; + + @override + String get subtitleLanguageTh => 'Thai'; + + @override + String get subtitleLanguageTl => 'Tagalog'; + + @override + String get subtitleLanguageTn => 'Tswana'; + + @override + String get subtitleLanguageTr => 'Turkish'; + + @override + String get subtitleLanguageUk => 'Ukrainian'; + + @override + String get subtitleLanguageUr => 'Urdu'; + + @override + String get subtitleLanguageUz => 'Uzbek'; + + @override + String get subtitleLanguageVi => 'Vietnamese'; + + @override + String get subtitleLanguageWo => 'Wolof'; + + @override + String get subtitleLanguageXh => 'Xhosa'; + + @override + String get subtitleLanguageYi => 'Yiddish'; + + @override + String get subtitleLanguageYo => 'Yoruba'; + + @override + String get subtitleLanguageYue => 'Cantonese'; + + @override + String get subtitleLanguageZh => 'Chinese'; + + @override + String get subtitleLanguageZu => 'Zulu'; + + @override + String get linearRec2020 => 'Linear Rec.2020'; + + @override + String get diagnostics => 'Diagnostics'; + + @override + String get exportDiagnostics => 'Export diagnostic package'; + + @override + String get exportDiagnosticsFailed => + 'Could not export diagnostics. Please try again.'; + + @override + String get exportDiagnosticsSucceeded => 'Diagnostic package saved.'; +} diff --git a/lib/l10n/app_localizations_es.dart b/lib/l10n/app_localizations_es.dart new file mode 100644 index 0000000..869d8b1 --- /dev/null +++ b/lib/l10n/app_localizations_es.dart @@ -0,0 +1,2232 @@ +// ignore: unused_import +import 'package:intl/intl.dart' as intl; + +import 'app_localizations.dart'; + +// ignore_for_file: type=lint + +/// The translations for Spanish Castilian (`es`). +class AppLocalizationsEs extends AppLocalizations { + AppLocalizationsEs([String locale = 'es']) : super(locale); + + @override + String get selectProject => 'Seleccionar proyecto'; + + @override + String get searchProjects => 'Buscar proyectos'; + + @override + String get noMatchingProjects => 'No hay proyectos coincidentes'; + + @override + String get projectsNone => 'No hay proyectos'; + + @override + String get projectLocationMissing => + 'La carpeta no existe. Se creará al crear un proyecto.'; + + @override + String get projectLocationUnavailable => + 'La ubicación de guardado no está disponible. Conecta el disco o comprueba la red y vuelve a intentarlo, o cambia la ubicación.'; + + @override + String get projectLocationNotWritable => + 'No se puede escribir en la ubicación de guardado. Comprueba los permisos o cambia la ubicación.'; + + @override + String get projectLocationCreateFailed => + 'No se pudo crear la carpeta del proyecto o escribir en ella. Comprueba los permisos o cambia la ubicación.'; + + @override + String get removeProjectFromSidebar => 'Quitar de la barra lateral'; + + @override + String get projectRemoved => + 'Proyecto eliminado de la lista. Se conservan los archivos locales y las conversaciones.'; + + @override + String get agentNoConversations => 'Aún no hay conversaciones'; + + @override + String get renameConversationTitle => 'Renombrar chat'; + + @override + String get renameConversationDescription => + 'Usa un nombre breve y fácil de reconocer.'; + + @override + String get collapseProject => 'Contraer proyecto'; + + @override + String get expandProject => 'Expandir proyecto'; + + @override + String agentDeleteConfirmation(String title) { + return '¿Eliminar permanentemente «$title» y todos sus mensajes? Esta acción no se puede deshacer. Los archivos locales del proyecto no se verán afectados.'; + } + + @override + String get agentEmptyTrashConfirmation => + '¿Eliminar permanentemente todas las conversaciones de la papelera? Esta acción no se puede deshacer. Los archivos locales del proyecto no se verán afectados.'; + + @override + String get agentConversations => 'Conversaciones'; + + @override + String get showMoreConversations => 'Mostrar más'; + + @override + String get showFewerConversations => 'Mostrar menos'; + + @override + String get agentNewConversation => 'Nueva conversación'; + + @override + String agentElapsedTime(String duration) { + return 'Duración $duration'; + } + + @override + String get agentConversationActions => 'Acciones de conversación'; + + @override + String get agentMoveToTrash => 'Mover a la papelera'; + + @override + String get agentTrash => 'Papelera'; + + @override + String get agentRestore => 'Restaurar'; + + @override + String get agentEmptyTrash => 'Vaciar papelera'; + + @override + String get agentDeleteForever => 'Eliminar permanentemente'; + + @override + String get agentConversationLocation => 'Ubicación de conversaciones'; + + @override + String get agentChooseExistingConversations => + 'Elegir conversaciones existentes'; + + @override + String get agentMoveConversations => 'Mover conversaciones'; + + @override + String get agentLocationUnavailable => + 'La ubicación de conversaciones no está disponible'; + + @override + String get agentLocationBusy => + 'Espera a que terminen las conversaciones activas'; + + @override + String get agentRelinkProvider => 'Volver a vincular proveedor'; + + @override + String get settings => 'Ajustes'; + + @override + String get closeSettings => 'Cerrar configuración'; + + @override + String get general => 'General'; + + @override + String get appearance => 'Apariencia'; + + @override + String get theme => 'Tema'; + + @override + String get system => 'Seguir el sistema'; + + @override + String get light => 'Claro'; + + @override + String get dark => 'Oscuro'; + + @override + String get saveAppearanceFailed => + 'No se pudo salvar la apariencia. Por favor inténtalo de nuevo.'; + + @override + String get loadAppearanceFailed => + 'No se pudo cargar la apariencia. Por favor seleccione un tema nuevamente.'; + + @override + String get cancel => 'Cancelar'; + + @override + String get save => 'Guardar'; + + @override + String get create => 'Crear'; + + @override + String get close => 'Cerrar'; + + @override + String get retry => 'Reintentar'; + + @override + String get select => 'Seleccionar'; + + @override + String get name => 'Nombre'; + + @override + String get enterName => 'Introduce un nombre'; + + @override + String get invalidName => + 'Los nombres no pueden contener separadores de ruta ni caracteres de control.'; + + @override + String get projects => 'Proyectos'; + + @override + String get projectName => 'Nombre del proyecto'; + + @override + String get projectLocation => 'Ubicación de guardado de proyectos'; + + @override + String get projectLocationNotSet => 'Sin configurar'; + + @override + String get loadProjectLocationFailed => + 'No se pudo cargar la ubicación de guardado de proyectos.'; + + @override + String get saveProjectLocationFailed => + 'No se pudo guardar la ubicación de proyectos.'; + + @override + String get resourceLocation => 'Ubicación de almacenamiento de recursos'; + + @override + String get resourceLocationNotSet => 'Sin configurar'; + + @override + String get loadResourceLocationFailed => + 'No se pudo cargar la ubicación de almacenamiento de recursos.'; + + @override + String get saveResourceLocationFailed => + 'No se pudo guardar la ubicación de recursos.'; + + @override + String get transcriptionResourceRequired => + 'Para generar subtítulos, primero debes descargar un modelo de reconocimiento de voz.'; + + @override + String get downloadAndContinue => 'Descargar y continuar'; + + @override + String get downloadingResource => 'Descargando…'; + + @override + String get downloadInBackground => 'Descargar en segundo plano'; + + @override + String get processingResourceDownloadFailed => + 'No se pudo descargar el recurso de reconocimiento de voz. Inténtalo de nuevo.'; + + @override + String get newProject => 'Nuevo proyecto'; + + @override + String get openProject => 'Abrir proyecto'; + + @override + String get openProjectMore => 'Abrir otro proyecto'; + + @override + String get saveHere => 'Guardar aquí'; + + @override + String get selectDirectoryFailed => + 'No se pudo seleccionar un directorio. Verifique los permisos del sistema.'; + + @override + String get openingWorkspace => 'Abriendo el espacio de trabajo…'; + + @override + String get loadProjectsFailed => 'No se pudieron cargar los proyectos'; + + @override + String get projectsEmpty => 'No hay proyectos'; + + @override + String get backToProjects => 'Volver a la edición'; + + @override + String get timelines => 'Líneas de tiempo'; + + @override + String timelineLimitReached(int count) { + return 'Cada proyecto puede contener hasta $count líneas de tiempo.'; + } + + @override + String get timelineName => 'Nombre de la línea de tiempo'; + + @override + String defaultTimelineName(int index) { + return 'Línea de tiempo $index'; + } + + @override + String get newTimeline => 'Nueva línea de tiempo'; + + @override + String get noTimelines => 'No hay líneas de tiempo'; + + @override + String get activeTimeline => 'Línea de tiempo actual'; + + @override + String get timelineUnavailable => 'Línea de tiempo no disponible'; + + @override + String get projectNoTimelines => + 'Este proyecto aún no tiene líneas de tiempo'; + + @override + String get createTimelineHint => + 'Crea una línea de tiempo en la sección «Líneas de tiempo» de la izquierda para empezar a editar.'; + + @override + String get createTimelineChat => + 'Crea una línea de tiempo para iniciar el chat'; + + @override + String get operationFailed => + 'La operación falló. Por favor inténtalo de nuevo.'; + + @override + String get collapseSidebar => 'Contraer barra lateral'; + + @override + String get expandSidebar => 'Expandir barra lateral'; + + @override + String get expandEditor => 'Expandir área de edición'; + + @override + String get collapseProperties => 'Contraer propiedades'; + + @override + String get expandProperties => 'Expandir propiedades'; + + @override + String get layout => 'Diseño'; + + @override + String get editingFirstLayout => 'Edición prioritaria'; + + @override + String get agentEditingLayout => 'Agente y edición'; + + @override + String get agentLayoutDescription => 'Planificar, colaborar y ejecutar'; + + @override + String get editingLayoutDescription => 'Previsualizar, editar y ajustar'; + + @override + String get materials => 'Medios'; + + @override + String get all => 'Todos'; + + @override + String get video => 'Video'; + + @override + String get audio => 'Audio'; + + @override + String get image => 'Imagen'; + + @override + String get picture => 'Imagen'; + + @override + String get captions => 'Subtítulos'; + + @override + String get text => 'Texto'; + + @override + String get noMedia => 'Sin medios'; + + @override + String get mediaCategory => 'Categoría de medios'; + + @override + String get captionTasks => 'Tareas de subtítulos'; + + @override + String get listLayout => 'Vista de lista'; + + @override + String get gridLayout => 'Vista de cuadrícula'; + + @override + String get addToTimeline => 'Añadir a la línea de tiempo'; + + @override + String get rename => 'Cambiar nombre'; + + @override + String get renameMedia => 'Cambiar nombre del medio'; + + @override + String get removeMedia => 'Quitar medio'; + + @override + String get remove => 'Quitar'; + + @override + String get revealFinder => 'Mostrar en Finder'; + + @override + String get revealFileManager => 'Mostrar en el gestor de archivos'; + + @override + String get dropToAdd => 'Suelta para añadir'; + + @override + String get timelineDropToStart => + 'Arrastra contenido multimedia aquí para empezar.'; + + @override + String get dragMediaHint => + 'Arrastra vídeo, audio o imágenes aquí\nLos archivos originales permanecen en su ubicación actual'; + + @override + String get transcribe => 'Transcribir'; + + @override + String get generateCaptions => 'Generar subtítulos'; + + @override + String get play => 'Reproducir'; + + @override + String get pause => 'Pausar'; + + @override + String get retryPreview => 'Reintentar vista previa'; + + @override + String get canvasRatio => 'Relación de aspecto'; + + @override + String get noPreviewContent => + 'No hay contenido para obtener una vista previa en la línea de tiempo.'; + + @override + String get nativePreviewUnsupported => + 'La vista previa nativa no está disponible en esta plataforma'; + + @override + String get canvasTransformFailed => + 'No se pudo transformar el lienzo. Por favor inténtalo de nuevo.'; + + @override + String get undo => 'Deshacer'; + + @override + String get redo => 'Rehacer'; + + @override + String get deleteSelectedClips => 'Eliminar clips seleccionados'; + + @override + String get splitAtPlayhead => 'Dividir en el cabezal de reproducción'; + + @override + String get trimLeft => 'Recortar izquierda'; + + @override + String get trimRight => 'Recortar derecha'; + + @override + String get trimLeftTooltip => + 'Eliminar a la izquierda del cabezal y conservar la derecha'; + + @override + String get trimRightTooltip => + 'Eliminar a la derecha del cabezal y conservar la izquierda'; + + @override + String get currentSequence => 'Secuencia actual'; + + @override + String get projectProperties => 'Propiedades del proyecto'; + + @override + String get canvasSize => 'Tamaño del lienzo'; + + @override + String get frameRate => 'Tasa de fotogramas'; + + @override + String get duration => 'Duración'; + + @override + String get totalDuration => 'Duración total'; + + @override + String get clipDuration => 'Duración del clip'; + + @override + String get seconds => 'segundos'; + + @override + String get clip => 'Clip'; + + @override + String get unnamedClip => 'Clip sin nombre'; + + @override + String get gap => 'Espacio vacío'; + + @override + String get compoundClip => 'Clip compuesto'; + + @override + String get textClip => 'Clip de texto'; + + @override + String get pictureProperties => 'Imagen'; + + @override + String get position => 'Posición'; + + @override + String get rotation => 'Rotación'; + + @override + String get scale => 'Escala'; + + @override + String get size => 'Tamaño'; + + @override + String get transform => 'Transformación'; + + @override + String get resetPosition => 'Restablecer posición'; + + @override + String get keepAspectRatio => 'Bloquear relación de aspecto'; + + @override + String get alignment => 'Alineación'; + + @override + String get alignLeft => 'Alinear a la izquierda'; + + @override + String get alignRight => 'Alinear a la derecha'; + + @override + String get alignTop => 'Alinear arriba'; + + @override + String get alignBottom => 'Alinear abajo'; + + @override + String get alignHorizontalCenter => 'Centrar horizontalmente'; + + @override + String get alignVerticalCenter => 'Centrar verticalmente'; + + @override + String get volume => 'Volumen'; + + @override + String get gain => 'Ganancia'; + + @override + String get mute => 'Silenciar'; + + @override + String get unmute => 'Activar sonido'; + + @override + String get resetVolume => 'Restablecer volumen'; + + @override + String get invalidGain => 'Introduzca un valor entre -90 y +12'; + + @override + String get animation => 'Animación'; + + @override + String get keyframes => 'Fotogramas clave'; + + @override + String get removeAllKeyframes => 'Eliminar todos los fotogramas clave'; + + @override + String get linear => 'Lineal'; + + @override + String get easeIn => 'Entrada suave'; + + @override + String get easeOut => 'Salida suave'; + + @override + String get easeInOut => 'Entrada y salida suaves'; + + @override + String get basic => 'Básico'; + + @override + String get mask => 'Máscara'; + + @override + String get addMask => 'Agregar máscara'; + + @override + String get deleteMask => 'Eliminar máscara'; + + @override + String get resetMask => 'Restablecer máscara'; + + @override + String get enableMask => 'Habilitar máscara'; + + @override + String get disableMask => 'Desactivar máscara'; + + @override + String get moveMaskUp => 'Mover máscara hacia arriba'; + + @override + String get moveMaskDown => 'Mover máscara hacia abajo'; + + @override + String get rectangle => 'Rectángulo'; + + @override + String get ellipse => 'Elipse'; + + @override + String get invert => 'Invertir'; + + @override + String get feather => 'Desvanecimiento'; + + @override + String get add => 'Sumar'; + + @override + String get subtract => 'Restar'; + + @override + String get intersect => 'Intersección'; + + @override + String get initialRegion => 'Región inicial'; + + @override + String get none => 'Ninguno'; + + @override + String get color => 'Color'; + + @override + String get fontSize => 'Tamaño de fuente'; + + @override + String get outlineWidth => 'Grosor del contorno'; + + @override + String get outlineColor => 'Color del contorno'; + + @override + String get captionBaseline => 'Línea base de subtítulos'; + + @override + String get content => 'Texto'; + + @override + String get start => 'Inicio'; + + @override + String get time => 'Tiempo'; + + @override + String get speed => 'Velocidad'; + + @override + String speedSegmentCount(int count) { + return '$count segmentos de velocidad'; + } + + @override + String get splitSpeedAtPlayhead => 'Dividir velocidad en el cabezal'; + + @override + String get speedChange => 'Velocidad'; + + @override + String get speedMode => 'Modo de velocidad'; + + @override + String get constantSpeed => 'Velocidad constante'; + + @override + String get segmentedSpeed => 'Velocidad segmentada'; + + @override + String get speedNotAvailable => + 'Los controles de velocidad aún no están disponibles'; + + @override + String get custom => 'Personalizado'; + + @override + String get invalidNumber => 'Valor no válido'; + + @override + String get mediaUnavailable => 'Medios no disponibles'; + + @override + String get mediaMissing => 'Medios faltantes'; + + @override + String get mediaColorSpace => 'Espacio de color de medios'; + + @override + String get mediaColorInterpretation => + 'Interpretación del color de los medios.'; + + @override + String get colorInfoNotLoaded => 'Información de color no cargada'; + + @override + String get unknownColorSpace => + 'Espacio de color desconocido. Mostrando como Rec.709.'; + + @override + String get colorBackendUnsupported => + 'El backend actual no admite la interpretación del color de los medios.'; + + @override + String get loadClipPropertiesFailed => + 'No se pudieron leer las propiedades del clip'; + + @override + String get updatePictureFailed => + 'No se pudieron actualizar las propiedades de la imagen'; + + @override + String get updateVolumeFailed => 'No se pudo actualizar el volumen'; + + @override + String get updateMaskFailed => 'No se pudo actualizar la máscara'; + + @override + String get updateKeyframesFailed => + 'No se pudieron actualizar los fotogramas clave'; + + @override + String get maskPreviewFailed => + 'No se pudo preparar la vista previa de la máscara'; + + @override + String get alignClipFailed => + 'No se pudo alinear el clip. Espere la vista previa y vuelva a intentarlo.'; + + @override + String get invalidTransform => + 'La escala debe ser del 1% al 10000%. La posición y el ángulo deben ser números válidos.'; + + @override + String get editFailed => + 'No se pudo editar. Verifique la entrada y el rango de tiempo.'; + + @override + String get addMediaFailed => + 'No se pudieron agregar medios. Por favor inténtalo de nuevo.'; + + @override + String get deleteCaption => 'Eliminar subtítulo'; + + @override + String get mergeCaptions => 'Combinar subtítulos'; + + @override + String get captionDeleted => 'Subtítulo eliminado'; + + @override + String get captionChanged => + 'Los subtítulos han cambiado. Por favor inténtalo de nuevo.'; + + @override + String get captionEditChanged => + 'Los subtítulos han cambiado. Por favor edite nuevamente.'; + + @override + String get assistantHint => 'Describe tu idea de edición'; + + @override + String get configureAgentHint => + 'Configurar el servicio de agente para comenzar a chatear'; + + @override + String get agentRestartHint => + 'Configure el servicio del agente y luego reinicie la aplicación.'; + + @override + String get replyInterrupted => 'Respuesta interrumpida'; + + @override + String get replying => 'Respondiendo…'; + + @override + String get stopReply => 'Detener respuesta'; + + @override + String get sendMessage => 'Enviar mensaje'; + + @override + String get addAttachment => 'Agregar archivo adjunto (aún no disponible)'; + + @override + String get replyFailed => + 'La respuesta falló. Verifique la conexión o vuelva a intentarlo más tarde.'; + + @override + String get mcpService => 'servicio MCP'; + + @override + String get listenPort => 'Puerto'; + + @override + String get accessToken => 'token de acceso'; + + @override + String get copyAccessToken => 'Copiar token de acceso'; + + @override + String get accessTokenCopied => 'Token de acceso copiado'; + + @override + String get loadMcpFailed => + 'No se pudo cargar la configuración de MCP. Rever'; + + @override + String get saveMcpFailed => + 'No se pudo guardar la configuración de MCP. Por favor inténtalo de nuevo.'; + + @override + String get retryStart => 'Reintentar inicio'; + + @override + String get invalidPort => 'El puerto debe estar entre 1 y 65535'; + + @override + String get loadingSettings => 'Cargando ajustes…'; + + @override + String get starting => 'Iniciando…'; + + @override + String get stopping => 'Deteniendo…'; + + @override + String get disabled => 'Desactivado'; + + @override + String get running => 'En ejecución'; + + @override + String get startFailed => 'No se pudo iniciar'; + + @override + String get saved => 'Guardado'; + + @override + String get unsaved => 'No guardado'; + + @override + String get saving => 'Guardando…'; + + @override + String get pendingSave => 'Pendiente de guardar'; + + @override + String get notApplied => 'No aplicado'; + + @override + String get enable => 'Activar'; + + @override + String get disable => 'Desactivar'; + + @override + String get type => 'Tipo'; + + @override + String get status => 'Estado'; + + @override + String get file => 'Archivo'; + + @override + String get unboundMedia => 'Sin medio asociado'; + + @override + String get unboundAudio => 'Sin pista de audio asociada'; + + @override + String get vertical => 'Vertical'; + + @override + String get language => 'Idioma'; + + @override + String get saveLanguageFailed => + 'No se pudo guardar el idioma. Por favor inténtalo de nuevo.'; + + @override + String get loadLanguageFailed => + 'No se pudo cargar el idioma. Por favor seleccione nuevamente.'; + + @override + String get propertiesFirstLayout => 'Propiedades primero'; + + @override + String get defaultLayout => 'Diseño predeterminado'; + + @override + String get separateVocals => 'Separar voces'; + + @override + String get detachAudio => 'Separar audio'; + + @override + String get restoreAudio => 'Restaurar audio'; + + @override + String get audioDetached => 'Audio separado'; + + @override + String get addAll => 'Añadir todo'; + + @override + String get preparingMedia => 'Preparando medios…'; + + @override + String get cancelling => 'Cancelando…'; + + @override + String get cancelled => 'Cancelado'; + + @override + String get interruptedTask => 'Tarea interrumpida. Reiniciar para continuar'; + + @override + String get auto => 'Automático'; + + @override + String get autoDetect => 'Detección automática'; + + @override + String get noTranslation => 'No traducir'; + + @override + String get sourceLanguage => 'Idioma de origen'; + + @override + String get translationLanguage => 'Idioma de destino'; + + @override + String get transcriptionNotConfigured => + 'La transcripción no está configurada. Instale el componente de reconocimiento y el modelo Whisper Turbo.'; + + @override + String get translationNotConfigured => + 'La traducción de subtítulos no está configurada. Puede generar subtítulos en el idioma de origen.'; + + @override + String get sourceLanguageUnknown => + 'No se pudo determinar un idioma de origen para la traducción.'; + + @override + String get startTranscriptionFailed => + 'No se pudo iniciar la transcripción. Verifique los medios o espere a que finalice la tarea actual.'; + + @override + String get placeMediaFirst => + 'Coloque este medio en la línea de tiempo antes de aplicar subtítulos.'; + + @override + String get placeTranslationMediaFirst => + 'Coloque los medios correspondientes en la línea de tiempo antes de aplicar subtítulos traducidos.'; + + @override + String get selectTargetClip => 'Seleccionar clip de destino'; + + @override + String get timelineChanged => + 'La línea de tiempo ha cambiado. Seleccione el clip de destino nuevamente.'; + + @override + String get transcriptionAccessFailed => + 'Error de transcripción: componente, modelo o medio de origen inaccesible (notConfigured)'; + + @override + String get transcriptionNoAudio => + 'Error de transcripción: no hay audio reconocible en el medio o pista seleccionada (noAudio)'; + + @override + String get transcriptionInvalidResult => + 'Error de transcripción: se devolvió un archivo de subtítulos no válido (invalidResult)'; + + @override + String get transcriptionWorkerExited => + 'Error de transcripción: el componente de reconocimiento salió inesperadamente (workerExited)'; + + @override + String get transcriptionProcessingFailed => + 'Error de transcripción: error en el procesamiento nativo (processingFailed)'; + + @override + String get transcriptionFailed => + 'La transcripción falló. Verifique el componente, modelo, pista de audio y duración.'; + + @override + String get transcribing => 'Transcribiendo…'; + + @override + String get captionsGenerated => 'Subtítulos generados'; + + @override + String get cancelTranscription => 'Cancelar transcripción'; + + @override + String get applyCaptions => 'Aplicar subtítulos'; + + @override + String get preparingTranslation => 'Preparando traducción…'; + + @override + String get translatingCaptions => 'Traduciendo subtítulos…'; + + @override + String get cancellingTranslation => 'Cancelando traducción…'; + + @override + String get translatedCaptionsGenerated => 'Subtítulos traducidos generados'; + + @override + String get translationCancelled => 'Traducción cancelada'; + + @override + String get translationInterrupted => 'Traducción interrumpida'; + + @override + String get cancelTranslation => 'Cancelar traducción'; + + @override + String get editorServiceUnavailable => + 'Servicio de edición no disponible. Vuelva a abrir el proyecto.'; + + @override + String get mcpUnavailable => + 'Conexión MCP no disponible. Verifique el puerto local y el token.'; + + @override + String get openTimelineFailed => 'No se pudo abrir la línea de tiempo'; + + @override + String get noTimelineSequence => + 'Esta línea de tiempo no tiene ninguna secuencia.'; + + @override + String get waitingForProject => 'Esperando a que se abra un proyecto'; + + @override + String get hold => 'Mantener'; + + @override + String get noImportableFiles => 'No se han recibido archivos importables'; + + @override + String get virtualFilesUnsupported => + 'Arrastre los archivos originales desde el administrador de archivos. Los archivos virtuales aún no son compatibles.'; + + @override + String get editorSessionStartFailed => + 'No se pudo abrir el editor de la línea de tiempo'; + + @override + String get previewStartFailed => 'No se pudo iniciar la vista previa nativa'; + + @override + String get previewInvalidTrack => + 'La pista de audio o vídeo seleccionada no existe en el medio.'; + + @override + String get previewMissingBinding => + 'Faltan enlaces de medios. No se pudo obtener una vista previa de esta línea de tiempo.'; + + @override + String get previewUnsupportedEdits => + 'Esta línea de tiempo contiene ediciones que aún no son compatibles con la vista previa.'; + + @override + String get previewUnsupportedConfiguration => + 'Esta configuración de vista previa no es compatible con la plataforma o versión actual del sistema.'; + + @override + String get previewHdrUnsupported => + 'Los medios HDR requieren mapeo de tonos para la vista previa SDR. El sistema actual o la configuración de vista previa no lo admiten.'; + + @override + String get previewAudioOutOfRange => + 'El clip de audio excede el rango de pistas de origen y no se puede obtener una vista previa.'; + + @override + String get previewResourceMissing => + 'Los medios de vista previa ya no existen. Localice el archivo original nuevamente.'; + + @override + String get previewInvalidComposition => + 'Configuración de composición de vídeo no válida. No se pudo crear una vista previa.'; + + @override + String get previewInvalidData => + 'Datos de vista previa no válidos. Por favor inténtalo de nuevo.'; + + @override + String get previewFailed => + 'La vista previa falló. Verifique el acceso a los medios e inténtelo nuevamente.'; + + @override + String get chatFailed => + 'No se pudo completar la conversación. Verifique la configuración del servicio o vuelva a intentarlo más tarde.'; + + @override + String get delete => 'Eliminar'; + + @override + String get pinTimeline => 'Fijar línea de tiempo'; + + @override + String get unpinTimeline => 'Desfijar línea de tiempo'; + + @override + String deleteTimelineConfirmation(String name) { + return '¿Eliminar «$name» y su historial de edición? Esta acción no se puede deshacer.'; + } + + @override + String get processingFailed => 'Error de procesamiento'; + + @override + String get noMatchingOptions => 'No hay opciones coincidentes'; + + @override + String removeMediaConfirmation(String name) { + return '¿Eliminar “$name” de la biblioteca? Se conservarán los clips existentes, el historial y el archivo original.'; + } + + @override + String mediaAdded(int count) { + return 'Se añadieron $count referencias de medios'; + } + + @override + String duplicatesSkipped(int count) { + return 'Archivos duplicados $count omitidos'; + } + + @override + String mediaCount(int count) { + return '$count medios'; + } + + @override + String get importMedia => 'Importar'; + + @override + String noMediaOfType(String type) { + return 'Sin medios $type'; + } + + @override + String captionsImported(String count) { + return 'Subtítulos $count importados'; + } + + @override + String editCaptionError(String message) { + return 'No se pudieron editar los subtítulos: $message'; + } + + @override + String mcpStartError(String message) { + return 'No se pudo iniciar MCP: $message'; + } + + @override + String manualColorSpace(String name) { + return 'Seleccionado manualmente: $name'; + } + + @override + String detectedColorSpace(String name) { + return 'Detectado: $name'; + } + + @override + String keyframeLabel(String channel) { + return 'Fotograma clave de $channel'; + } + + @override + String maskMode(String mode) { + return 'Modo de combinación: $mode'; + } + + @override + String keyframeCount(int count) { + return '$count fotogramas clave'; + } + + @override + String toggleKeyframe(String action, String channel) { + return '$action fotograma clave de $channel'; + } + + @override + String previousKeyframe(String channel) { + return 'Fotograma clave anterior de $channel'; + } + + @override + String nextKeyframe(String channel) { + return 'Siguiente fotograma clave de $channel'; + } + + @override + String keyframeSettings(String channel) { + return 'Ajustes de fotogramas clave de $channel'; + } + + @override + String selectedClipsHint(int count) { + return 'Clips $count seleccionados\nSeleccione un clip para ver sus propiedades'; + } + + @override + String transcriptionError(String code) { + return 'La transcripción falló. Verifique el componente, modelo, pista de audio y duración ($code)'; + } + + @override + String captionsAdded(String count) { + return 'Se agregaron subtítulos $count. Edítalos en el panel de propiedades.'; + } + + @override + String translatedCaptionsAdded(String count) { + return 'Se agregaron subtítulos traducidos $count. Edítalos en el panel de propiedades.'; + } + + @override + String applyCaptionsError(String message) { + return 'No se pudieron aplicar subtítulos: $message'; + } + + @override + String applyTranslatedCaptionsError(String message) { + return 'No se pudieron aplicar subtítulos traducidos: $message'; + } + + @override + String recognizedCaptions(int count) { + return '$count subtítulos reconocidos'; + } + + @override + String captionCount(int count) { + return '$count subtítulos'; + } + + @override + String translationFailed(String message) { + return 'Error de traducción: $message'; + } + + @override + String translatedCaptionCount(int count, String language) { + return '$count subtítulos en $language'; + } + + @override + String previewParameterError(String message) { + return 'Parámetros de vista previa no válidos: $message'; + } + + @override + String mediaOffline(String names) { + return 'Medios sin conexión o no disponibles: $names'; + } + + @override + String searchOptions(String label) { + return 'Buscar $label…'; + } + + @override + String get loadRecentProjectsFailed => + 'No se pudieron cargar bibliotecas recientes. Aún puedes abrir una biblioteca manualmente.'; + + @override + String get projectAccessFailed => 'Proyecto no disponible'; + + @override + String get projectMissingDirectory => 'Proyecto no encontrado'; + + @override + String get recentProjectSaveFailed => + 'La biblioteca se abrió, pero no se pudo guardar el registro reciente de la biblioteca.'; + + @override + String get lastProjectSaveFailed => + 'El proyecto se abrió, pero no se pudo guardar el último registro del proyecto.'; + + @override + String get enterProjectName => 'Introduzca un nombre de proyecto'; + + @override + String get projectSwitched => + 'El proyecto ha cambiado. Arrastre los medios nuevamente.'; + + @override + String get notLocalMedia => 'Este medio no es un archivo local.'; + + @override + String get revealMediaFailed => + 'No se pudieron mostrar los medios en el administrador de archivos'; + + @override + String get openMatchingProject => 'Abra primero el proyecto correspondiente'; + + @override + String get projectMismatch => + 'La biblioteca en esta ubicación no coincide con el registro. Selecciónelo nuevamente con Abrir biblioteca.'; + + @override + String get openProjectFirst => 'Abra una biblioteca primero'; + + @override + String get localFilesOnly => + 'Arrastre archivos locales desde el administrador de archivos'; + + @override + String get foldersUnsupported => + 'Seleccionar archivos. Aún no se admite arrastrar carpetas.'; + + @override + String get mediaImportCancelled => 'Importación de medios cancelada'; + + @override + String get fileAccessFailed => + 'El archivo falta o es ilegible. Comprueba su ubicación y permisos.'; + + @override + String get registerMediaFailed => + 'No se pudieron registrar los medios. Por favor inténtalo de nuevo'; + + @override + String get mediaNoLongerExists => 'Los medios ya no existen.'; + + @override + String get mediaNoTracks => + 'Los medios no tienen pistas de audio o video utilizables.'; + + @override + String get invalidMediaDuration => 'Duración de medios no válida'; + + @override + String get mediaInfoUnsupported => + 'La lectura de información multimedia aún no es compatible con esta plataforma'; + + @override + String get mediaInfoFailed => + 'No se pudo leer la información de los medios. Comprueba el archivo y los permisos de acceso.'; + + @override + String get saveTimelineFailed => + 'No se pudo guardar la línea de tiempo. Intentar otra vez. Las ediciones no guardadas permanecen en esta sesión.'; + + @override + String get addKeyframeAction => 'Añadir'; + + @override + String get backgroundTasks => 'Tareas en segundo plano'; + + @override + String get noBackgroundTasks => 'No hay tareas en segundo plano'; + + @override + String get retryTask => 'Reintentar'; + + @override + String get applyOriginalCaptions => 'Aplicar subtítulos originales'; + + @override + String get applyTranslatedCaptions => 'Aplicar subtítulos traducidos'; + + @override + String get subtitleTaskStarted => 'Tarea de subtítulos iniciada'; + + @override + String get fitTimeline => 'Ajustar toda la línea de tiempo'; + + @override + String get modify => 'Modify'; + + @override + String get projectSettings => 'Project settings'; + + @override + String get projectSettingsDescription => + 'Change project output settings while keeping clip timing and speed.'; + + @override + String get projectColorSpace => 'Color space'; + + @override + String get projectWidth => 'Width (px)'; + + @override + String get projectHeight => 'Height (px)'; + + @override + String get projectResolutionInvalid => 'Enter a whole number from 1 to 16384'; + + @override + String get previewFullscreen => 'Vista previa a pantalla completa'; + + @override + String get exitPreviewFullscreen => 'Salir de pantalla completa'; + + @override + String get previewGoToStart => 'Ir al inicio'; + + @override + String get previewPreviousFrame => 'Fotograma anterior'; + + @override + String get previewNextFrame => 'Fotograma siguiente'; + + @override + String get softwareUpdates => 'Actualizaciones'; + + @override + String get checkForUpdates => 'Buscar actualizaciones'; + + @override + String get automaticallyCheckUpdates => + 'Buscar actualizaciones automáticamente'; + + @override + String get updatesUnavailable => 'Este paquete no ofrece actualizaciones.'; + + @override + String get updateCheckFailed => + 'No se pudieron buscar actualizaciones. Inténtalo de nuevo.'; + + @override + String get removeBackground => 'Eliminar fondo'; + + @override + String get startBackgroundRemoval => 'Eliminar fondo'; + + @override + String get backgroundRemovalResourceRequired => + 'La eliminación de fondo necesita un modelo local. Comenzará automáticamente después de la descarga.'; + + @override + String get backgroundRemovalDownloadTask => + 'Descargar recurso de eliminación de fondo'; + + @override + String get backgroundRemovalResourceName => 'Modelo de eliminación de fondo'; + + @override + String get backgroundRemovalDestructiveHint => + 'El contenido transparente generado reemplazará este clip. Puedes usar Deshacer para restaurar el clip original.'; + + @override + String get backgroundRemovalTaskStarted => 'Eliminación de fondo iniciada'; + + @override + String get startBackgroundRemovalFailed => + 'No se pudo iniciar la eliminación de fondo. Comprueba el contenido o espera a que termine la tarea de procesamiento actual.'; + + @override + String get backgroundRemovalComplete => 'Eliminación de fondo completada'; + + @override + String get backgroundRemovalApplying => 'Reemplazando el contenido del clip'; + + @override + String get backgroundRemovalFailed => 'Error al eliminar el fondo'; + + @override + String get agentSettings => 'Agente'; + + @override + String get agentSaveSettingsFailed => + 'No se pudo guardar la configuración del agente.'; + + @override + String get agentDeleteProviderTitle => '¿Eliminar proveedor?'; + + @override + String agentDeleteProviderDescription(String providerName) { + return '“$providerName” y su clave de API guardada se eliminarán de este dispositivo.'; + } + + @override + String get agentProviderRequired => + 'Añade un proveedor antes de activar el asistente.'; + + @override + String get agentUseSelectedModel => + 'Las nuevas solicitudes del agente usarán el modelo seleccionado.'; + + @override + String get agentEnable => 'Activar agente'; + + @override + String get agentDefaultModel => 'Modelo predeterminado'; + + @override + String get agentConfigureModel => 'Configurar modelos'; + + @override + String get agentSelectModel => 'Seleccionar modelo'; + + @override + String get agentModelUnavailable => + 'El modelo de esta conversación no está disponible. Selecciona otro modelo para iniciar una nueva conversación.'; + + @override + String get agentModelChangeSession => + 'Al cambiar el modelo se inicia una nueva sesión del agente.'; + + @override + String get agentCustomProviders => 'Proveedores personalizados'; + + @override + String get agentProviderStorageDescription => + 'Los metadatos del proveedor se guardan localmente. Las claves de API se conservan en el almacén de credenciales del sistema.'; + + @override + String get agentAddProvider => 'Añadir proveedor'; + + @override + String get agentBackToProviders => 'Volver a proveedores'; + + @override + String get agentLoadSettingsFailed => + 'No se pudo cargar la configuración del agente. Reintentar'; + + @override + String get agentEnableProvider => 'Activar proveedor'; + + @override + String get agentEditProvider => 'Editar proveedor'; + + @override + String get agentDeleteProvider => 'Eliminar proveedor'; + + @override + String get agentModelIdsUnique => 'Los ID de modelo deben ser únicos.'; + + @override + String get agentEditProviderTitle => 'Editar proveedor'; + + @override + String get agentProviderEndpointDescription => + 'Configura un endpoint de Chat Completions compatible con OpenAI.'; + + @override + String get agentSaveProvider => 'Guardar proveedor'; + + @override + String get agentProviderConfiguration => 'Configuración del proveedor'; + + @override + String get agentAuthenticationAndModels => 'Autenticación y modelos'; + + @override + String get agentApiType => 'Tipo de API'; + + @override + String get agentOpenAiChatCompletions => 'OpenAI Completions'; + + @override + String get agentBaseUrl => 'URL base'; + + @override + String get agentApiKey => 'Clave de API'; + + @override + String get agentProviderNameHint => 'Mi proveedor'; + + @override + String get agentApiKeyOptional => + 'Opcional para endpoints que no requieren autenticación.'; + + @override + String get agentApiKeyKeep => + 'Déjalo en blanco para conservar la clave guardada.'; + + @override + String get agentOptional => 'Opcional'; + + @override + String get agentApiKeyOneLine => + 'La clave de API debe ocupar una sola línea.'; + + @override + String get agentRemoveSavedApiKey => 'Eliminar clave de API guardada'; + + @override + String get agentModels => 'Modelos'; + + @override + String get agentAddModel => 'Añadir modelo'; + + @override + String get agentRequiredField => 'Este campo es obligatorio.'; + + @override + String get agentInvalidBaseUrl => + 'Introduce una URL base HTTP(S) sin credenciales, consulta ni fragmento.'; + + @override + String get agentModelId => 'ID de modelo'; + + @override + String get agentContextWindow => 'Ventana de contexto'; + + @override + String get agentMaxOutputTokens => 'Salida máxima'; + + @override + String get agentMaxOutputBelowContext => + 'Debe ser menor que la ventana de contexto.'; + + @override + String get agentDeleteModel => 'Eliminar modelo'; + + @override + String get agentPositiveInteger => 'Introduce un número entero positivo.'; + + @override + String get agentConfigurationReadFailed => + 'No se pudo leer la configuración del agente. Revisa los ajustes e inténtalo de nuevo.'; + + @override + String get agentConfigurationRequired => + 'Primero configura y activa el agente en Ajustes.'; + + @override + String get agentSessionRestoreFailed => + 'No se pudo restaurar la sesión del agente. Inténtalo de nuevo más tarde.'; + + @override + String get agentContextBudgetExceeded => + 'El presupuesto de entrada no alcanza para las instrucciones, herramientas y mensaje. Amplía el contexto o reduce la salida máxima.'; + + @override + String get agentAuthenticationFailed => + 'Error de autenticación. Comprueba la API Key y los permisos.'; + + @override + String get agentConnectionFailed => + 'Error de conexión o tiempo de espera agotado. Comprueba la Base URL y la red.'; + + @override + String get agentProtocolFailed => + 'La respuesta no coincide con el tipo de API elegido o el flujo está incompleto.'; + + @override + String get agentContextBudgetTooSmall => + 'Reserva más espacio para las instrucciones. Amplía el contexto o reduce la salida máxima.'; + + @override + String get agentCompacting => 'Organizando el contexto…'; + + @override + String get agentEditing => 'Editando…'; + + @override + String get agentVerifying => 'Comprobando resultados…'; + + @override + String get agentTurnLimitReached => + 'La tarea alcanzó su límite de ejecución. Los cambios se han guardado. Envía «Continuar» para reanudar.'; + + @override + String get agentRecoveryRequired => + 'El resultado anterior no está confirmado. Continúa para verificar los registros guardados; no se repetirán cambios no confirmados.'; + + @override + String get agentExportReplyFailed => + 'Vídeo exportado. Falló la respuesta de resumen. Puedes reintentar el resumen sin repetir la edición ni la exportación.'; + + @override + String get agentRetrySummary => 'Reintentar resumen'; + + @override + String get agentResumeTask => 'Continuar tarea'; + + @override + String get agentTaskInterrupted => + 'La tarea se interrumpió. Continúa desde el progreso guardado.'; + + @override + String get downloadSubtitleModel => 'Descargar modelo de subtítulos'; + + @override + String get downloadModelAction => 'Descargar'; + + @override + String get subtitleEngineUnavailable => + 'El modelo está instalado, pero el motor de subtítulos no pudo iniciarse. Repara el motor; no es necesario volver a descargar el modelo.'; + + @override + String get backgroundTaskDetails => 'Detalles de la tarea'; + + @override + String get backgroundTaskFailed => 'Error'; + + @override + String get backgroundTaskCompleted => 'Completado'; + + @override + String get captionWrapLines => 'Ajustar texto de subtítulos'; + + @override + String get captionSingleLine => 'Mostrar subtítulos en una línea'; + + @override + String get noMatchingCaptions => 'No hay subtítulos coincidentes'; + + @override + String get subtitleResourcesRequired => + 'Estos recursos son necesarios para los subtítulos. La generación comenzará automáticamente al terminar la descarga.'; + + @override + String subtitleResourcesDownloadSize(String size) { + return 'Por descargar: $size'; + } + + @override + String get pauseDownload => 'Pausar'; + + @override + String get resumeDownload => 'Reanudar'; + + @override + String get downloadPaused => 'En pausa'; + + @override + String get cancelResourceDownloadTitle => '¿Cancelar la descarga?'; + + @override + String get cancelResourceDownloadMessage => + 'La descarga se detendrá. Es posible que se pierda el progreso del recurso actual.'; + + @override + String get continueDownload => 'Continuar descarga'; + + @override + String get cancelDownload => 'Cancelar descarga'; + + @override + String get speechResourceStage => 'Recurso de reconocimiento de voz'; + + @override + String get translationResourceStage => 'Recurso de traducción'; + + @override + String get subtitleResourceDownloadTask => + 'Descargar recursos de voz y traducción'; + + @override + String get downloadingSpeechModel => 'Descargando modelo de voz'; + + @override + String get downloadingTranslationModel => 'Descargando modelo de traducción'; + + @override + String get checkingForUpdates => 'Buscando actualizaciones…'; + + @override + String get appIsUpToDate => 'La aplicación está actualizada.'; + + @override + String downloadingUpdate(int progress) { + return 'Descargando actualización: $progress%'; + } + + @override + String updateAvailable(String version) { + return 'La versión $version está disponible.'; + } + + @override + String get downloadUpdate => 'Descargar actualización'; + + @override + String get restartToUpdate => 'Reiniciar y actualizar'; + + @override + String get updateOperationFailed => + 'No se pudo actualizar. Termina las tareas activas e inténtalo de nuevo.'; + + @override + String get windowMinimize => 'Minimizar'; + + @override + String get windowMaximize => 'Maximizar'; + + @override + String get windowRestore => 'Restaurar'; + + @override + String get workspaceAgent => 'Asistente'; + + @override + String get workspaceCut => 'Edición'; + + @override + String get noAvailableOptions => 'No hay opciones disponibles'; + + @override + String get composerReferenceInvalid => + 'Una referencia ya no es válida. Vuelve a su proyecto o elimínala.'; + + @override + String durationSeconds(int seconds) { + return '$seconds s'; + } + + @override + String durationMinutesSeconds(int minutes, int seconds) { + return '$minutes min $seconds s'; + } + + @override + String get projectNameInvalid => 'Nombre de proyecto no válido'; + + @override + String get projectLocationDefaultUnavailable => + 'No se puede acceder a la ubicación predeterminada de los proyectos. Vuelve a seleccionarla en Ajustes.'; + + @override + String get chooseProjectLocation => + 'Selecciona primero una ubicación para guardar proyectos en Ajustes.'; + + @override + String get untitledTimeline => 'Línea de tiempo sin título'; + + @override + String get primarySequence => 'Secuencia principal'; + + @override + String get primaryStoryline => 'Línea principal'; + + @override + String get projectSessionClosed => + 'La sesión del proyecto se ha cerrado. Abre el proyecto de nuevo.'; + + @override + String get timelineSessionClosed => + 'La sesión de la línea de tiempo se ha cerrado. Ábrela de nuevo.'; + + @override + String get timelineMissing => + 'La línea de tiempo no existe o se ha eliminado.'; + + @override + String get timelineInUse => + 'La línea de tiempo está en uso y aún no se puede eliminar.'; + + @override + String get timelineHasBackgroundTasks => + 'Finaliza las tareas en segundo plano de la línea de tiempo antes de eliminarla.'; + + @override + String get timelineRequired => + 'Un proyecto debe conservar al menos una línea de tiempo.'; + + @override + String get mediaReadFailed => 'No se pudo leer el medio'; + + @override + String get mediaImportFailed => 'No se pudo importar el medio'; + + @override + String get unsupportedMediaType => + 'Solo se pueden importar archivos de vídeo, audio e imagen.'; + + @override + String get mediaNoVideoTracks => + 'El medio no tiene ninguna pista de vídeo utilizable'; + + @override + String get mediaDurationOutOfRange => + 'La duración del medio supera el rango de la línea de tiempo'; + + @override + String resourceDownloadHttpFailed(String statusCode) { + return 'Error de descarga (HTTP $statusCode)'; + } + + @override + String get resourceChecksumFailed => + 'Error al verificar el archivo del modelo. Descarga el recurso de nuevo.'; + + @override + String get subtitleLanguageAf => 'afrikáans'; + + @override + String get subtitleLanguageAm => 'amárico'; + + @override + String get subtitleLanguageAr => 'árabe'; + + @override + String get subtitleLanguageAst => 'asturiano'; + + @override + String get subtitleLanguageAz => 'azerbaiyano'; + + @override + String get subtitleLanguageBa => 'baskir'; + + @override + String get subtitleLanguageBe => 'bielorruso'; + + @override + String get subtitleLanguageBg => 'búlgaro'; + + @override + String get subtitleLanguageBn => 'bengalí'; + + @override + String get subtitleLanguageBr => 'bretón'; + + @override + String get subtitleLanguageBs => 'bosnio'; + + @override + String get subtitleLanguageCa => 'catalán'; + + @override + String get subtitleLanguageCeb => 'cebuano'; + + @override + String get subtitleLanguageCs => 'checo'; + + @override + String get subtitleLanguageCy => 'galés'; + + @override + String get subtitleLanguageDa => 'danés'; + + @override + String get subtitleLanguageDe => 'alemán'; + + @override + String get subtitleLanguageEl => 'griego'; + + @override + String get subtitleLanguageEn => 'inglés'; + + @override + String get subtitleLanguageEs => 'español'; + + @override + String get subtitleLanguageEt => 'estonio'; + + @override + String get subtitleLanguageFa => 'persa'; + + @override + String get subtitleLanguageFf => 'fula'; + + @override + String get subtitleLanguageFi => 'finés'; + + @override + String get subtitleLanguageFr => 'francés'; + + @override + String get subtitleLanguageFy => 'frisón occidental'; + + @override + String get subtitleLanguageGa => 'irlandés'; + + @override + String get subtitleLanguageGd => 'gaélico escocés'; + + @override + String get subtitleLanguageGl => 'gallego'; + + @override + String get subtitleLanguageGu => 'guyaratí'; + + @override + String get subtitleLanguageHa => 'hausa'; + + @override + String get subtitleLanguageHe => 'hebreo'; + + @override + String get subtitleLanguageHi => 'hindi'; + + @override + String get subtitleLanguageHr => 'croata'; + + @override + String get subtitleLanguageHt => 'criollo haitiano'; + + @override + String get subtitleLanguageHu => 'húngaro'; + + @override + String get subtitleLanguageHy => 'armenio'; + + @override + String get subtitleLanguageId => 'indonesio'; + + @override + String get subtitleLanguageIg => 'igbo'; + + @override + String get subtitleLanguageIlo => 'ilocano'; + + @override + String get subtitleLanguageIs => 'islandés'; + + @override + String get subtitleLanguageIt => 'italiano'; + + @override + String get subtitleLanguageJa => 'japonés'; + + @override + String get subtitleLanguageJv => 'javanés'; + + @override + String get subtitleLanguageKa => 'georgiano'; + + @override + String get subtitleLanguageKk => 'kazajo'; + + @override + String get subtitleLanguageKm => 'jemer'; + + @override + String get subtitleLanguageKn => 'canarés'; + + @override + String get subtitleLanguageKo => 'coreano'; + + @override + String get subtitleLanguageLb => 'luxemburgués'; + + @override + String get subtitleLanguageLg => 'ganda'; + + @override + String get subtitleLanguageLn => 'lingala'; + + @override + String get subtitleLanguageLo => 'lao'; + + @override + String get subtitleLanguageLt => 'lituano'; + + @override + String get subtitleLanguageLv => 'letón'; + + @override + String get subtitleLanguageMg => 'malgache'; + + @override + String get subtitleLanguageMk => 'macedonio'; + + @override + String get subtitleLanguageMl => 'malayálam'; + + @override + String get subtitleLanguageMn => 'mongol'; + + @override + String get subtitleLanguageMr => 'maratí'; + + @override + String get subtitleLanguageMs => 'malayo'; + + @override + String get subtitleLanguageMy => 'birmano'; + + @override + String get subtitleLanguageNe => 'nepalí'; + + @override + String get subtitleLanguageNl => 'neerlandés'; + + @override + String get subtitleLanguageNo => 'noruego'; + + @override + String get subtitleLanguageNs => 'sotho septentrional'; + + @override + String get subtitleLanguageOc => 'occitano'; + + @override + String get subtitleLanguageOr => 'oriya'; + + @override + String get subtitleLanguagePa => 'panyabí'; + + @override + String get subtitleLanguagePl => 'polaco'; + + @override + String get subtitleLanguagePs => 'pastún'; + + @override + String get subtitleLanguagePt => 'portugués'; + + @override + String get subtitleLanguageRo => 'rumano'; + + @override + String get subtitleLanguageRu => 'ruso'; + + @override + String get subtitleLanguageSd => 'sindi'; + + @override + String get subtitleLanguageSi => 'cingalés'; + + @override + String get subtitleLanguageSk => 'eslovaco'; + + @override + String get subtitleLanguageSl => 'esloveno'; + + @override + String get subtitleLanguageSo => 'somalí'; + + @override + String get subtitleLanguageSq => 'albanés'; + + @override + String get subtitleLanguageSr => 'serbio'; + + @override + String get subtitleLanguageSs => 'suazi'; + + @override + String get subtitleLanguageSu => 'sundanés'; + + @override + String get subtitleLanguageSv => 'sueco'; + + @override + String get subtitleLanguageSw => 'suajili'; + + @override + String get subtitleLanguageTa => 'tamil'; + + @override + String get subtitleLanguageTh => 'tailandés'; + + @override + String get subtitleLanguageTl => 'tagalo'; + + @override + String get subtitleLanguageTn => 'setsuana'; + + @override + String get subtitleLanguageTr => 'turco'; + + @override + String get subtitleLanguageUk => 'ucraniano'; + + @override + String get subtitleLanguageUr => 'urdu'; + + @override + String get subtitleLanguageUz => 'uzbeko'; + + @override + String get subtitleLanguageVi => 'vietnamita'; + + @override + String get subtitleLanguageWo => 'wólof'; + + @override + String get subtitleLanguageXh => 'xhosa'; + + @override + String get subtitleLanguageYi => 'yidis'; + + @override + String get subtitleLanguageYo => 'yoruba'; + + @override + String get subtitleLanguageYue => 'cantonés'; + + @override + String get subtitleLanguageZh => 'chino'; + + @override + String get subtitleLanguageZu => 'zulú'; + + @override + String get linearRec2020 => 'Rec.2020 lineal'; + + @override + String get diagnostics => 'Diagnóstico'; + + @override + String get exportDiagnostics => 'Exportar paquete de diagnóstico'; + + @override + String get exportDiagnosticsFailed => + 'No se pudo exportar el diagnóstico. Inténtalo de nuevo.'; + + @override + String get exportDiagnosticsSucceeded => 'Paquete de diagnóstico guardado.'; +} diff --git a/lib/l10n/app_localizations_fr.dart b/lib/l10n/app_localizations_fr.dart new file mode 100644 index 0000000..fea434f --- /dev/null +++ b/lib/l10n/app_localizations_fr.dart @@ -0,0 +1,2235 @@ +// ignore: unused_import +import 'package:intl/intl.dart' as intl; + +import 'app_localizations.dart'; + +// ignore_for_file: type=lint + +/// The translations for French (`fr`). +class AppLocalizationsFr extends AppLocalizations { + AppLocalizationsFr([String locale = 'fr']) : super(locale); + + @override + String get selectProject => 'Sélectionner un projet'; + + @override + String get searchProjects => 'Rechercher des projets'; + + @override + String get noMatchingProjects => 'Aucun projet correspondant'; + + @override + String get projectsNone => 'Aucun projet'; + + @override + String get projectLocationMissing => + 'Le dossier n’existe pas. Il sera créé lors de la création d’un projet.'; + + @override + String get projectLocationUnavailable => + 'L’emplacement de sauvegarde est indisponible. Connectez le disque ou vérifiez le réseau et réessayez, ou changez d’emplacement.'; + + @override + String get projectLocationNotWritable => + 'L’emplacement de sauvegarde n’est pas accessible en écriture. Vérifiez les autorisations ou changez d’emplacement.'; + + @override + String get projectLocationCreateFailed => + 'Impossible de créer le dossier de sauvegarde ou d’y écrire. Vérifiez les autorisations ou changez d’emplacement.'; + + @override + String get removeProjectFromSidebar => 'Retirer de la barre latérale'; + + @override + String get projectRemoved => + 'Projet retiré. Les fichiers locaux et les conversations sont conservés.'; + + @override + String get agentNoConversations => 'Aucune conversation pour le moment'; + + @override + String get renameConversationTitle => 'Renommer la discussion'; + + @override + String get renameConversationDescription => + 'Choisissez un nom court et facile à reconnaître.'; + + @override + String get collapseProject => 'Réduire le projet'; + + @override + String get expandProject => 'Développer le projet'; + + @override + String agentDeleteConfirmation(String title) { + return 'Supprimer définitivement « $title » et tous ses messages ? Cette action est irréversible. Les fichiers locaux du projet ne seront pas affectés.'; + } + + @override + String get agentEmptyTrashConfirmation => + 'Supprimer définitivement toutes les conversations de la corbeille ? Cette action est irréversible. Les fichiers locaux du projet ne seront pas affectés.'; + + @override + String get agentConversations => 'Conversations'; + + @override + String get showMoreConversations => 'Afficher plus'; + + @override + String get showFewerConversations => 'Afficher moins'; + + @override + String get agentNewConversation => 'Nouvelle conversation'; + + @override + String agentElapsedTime(String duration) { + return 'Durée $duration'; + } + + @override + String get agentConversationActions => 'Actions de la conversation'; + + @override + String get agentMoveToTrash => 'Déplacer vers la corbeille'; + + @override + String get agentTrash => 'Corbeille'; + + @override + String get agentRestore => 'Restaurer'; + + @override + String get agentEmptyTrash => 'Vider la corbeille'; + + @override + String get agentDeleteForever => 'Supprimer définitivement'; + + @override + String get agentConversationLocation => 'Emplacement des conversations'; + + @override + String get agentChooseExistingConversations => + 'Choisir des conversations existantes'; + + @override + String get agentMoveConversations => 'Déplacer les conversations'; + + @override + String get agentLocationUnavailable => + 'Emplacement des conversations indisponible'; + + @override + String get agentLocationBusy => 'Attendez la fin des conversations en cours'; + + @override + String get agentRelinkProvider => 'Réassocier le fournisseur'; + + @override + String get settings => 'Paramètres'; + + @override + String get closeSettings => 'Fermer les paramètres'; + + @override + String get general => 'Général'; + + @override + String get appearance => 'Apparence'; + + @override + String get theme => 'Thème'; + + @override + String get system => 'Suivre le système'; + + @override + String get light => 'Clair'; + + @override + String get dark => 'Sombre'; + + @override + String get saveAppearanceFailed => + 'Impossible de sauvegarder l\'apparence. Veuillez réessayer.'; + + @override + String get loadAppearanceFailed => + 'Impossible de charger l\'apparence. Veuillez sélectionner à nouveau un thème.'; + + @override + String get cancel => 'Annuler'; + + @override + String get save => 'Enregistrer'; + + @override + String get create => 'Créer'; + + @override + String get close => 'Fermer'; + + @override + String get retry => 'Réessayer'; + + @override + String get select => 'Sélectionner'; + + @override + String get name => 'Nom'; + + @override + String get enterName => 'Entrez un nom'; + + @override + String get invalidName => + 'Les noms ne peuvent pas contenir de séparateurs de chemin ni de caractères de contrôle'; + + @override + String get projects => 'Projets'; + + @override + String get projectName => 'Nom du projet'; + + @override + String get projectLocation => 'Emplacement d’enregistrement des projets'; + + @override + String get projectLocationNotSet => 'Non défini'; + + @override + String get loadProjectLocationFailed => + 'Impossible de charger l’emplacement d’enregistrement des projets.'; + + @override + String get saveProjectLocationFailed => + 'Impossible d’enregistrer l’emplacement des projets.'; + + @override + String get resourceLocation => 'Emplacement de stockage des ressources'; + + @override + String get resourceLocationNotSet => 'Non défini'; + + @override + String get loadResourceLocationFailed => + 'Impossible de charger l’emplacement de stockage des ressources.'; + + @override + String get saveResourceLocationFailed => + 'Impossible d’enregistrer l’emplacement des ressources.'; + + @override + String get transcriptionResourceRequired => + 'Pour générer des sous-titres, vous devez d’abord télécharger un modèle de reconnaissance vocale.'; + + @override + String get downloadAndContinue => 'Télécharger et continuer'; + + @override + String get downloadingResource => 'Téléchargement…'; + + @override + String get downloadInBackground => 'Télécharger en arrière-plan'; + + @override + String get processingResourceDownloadFailed => + 'Impossible de télécharger la ressource de reconnaissance vocale. Réessayez.'; + + @override + String get newProject => 'Nouveau projet'; + + @override + String get openProject => 'Ouvrir un projet'; + + @override + String get openProjectMore => 'Ouvrir un autre projet'; + + @override + String get saveHere => 'Enregistrer ici'; + + @override + String get selectDirectoryFailed => + 'Impossible de sélectionner un répertoire. Vérifiez les autorisations du système.'; + + @override + String get openingWorkspace => 'Ouverture de l’espace de travail…'; + + @override + String get loadProjectsFailed => 'Impossible de charger les projets'; + + @override + String get projectsEmpty => 'Aucun projet'; + + @override + String get backToProjects => 'Retour au montage'; + + @override + String get timelines => 'Timelines'; + + @override + String timelineLimitReached(int count) { + return 'Chaque projet peut contenir jusqu’à $count timelines.'; + } + + @override + String get timelineName => 'Nom de la timeline'; + + @override + String defaultTimelineName(int index) { + return 'Timeline $index'; + } + + @override + String get newTimeline => 'Nouvelle timeline'; + + @override + String get noTimelines => 'Aucune timeline'; + + @override + String get activeTimeline => 'Timeline actuelle'; + + @override + String get timelineUnavailable => 'Timeline indisponible'; + + @override + String get projectNoTimelines => 'Ce projet ne contient aucune timeline'; + + @override + String get createTimelineHint => + 'Créez une timeline dans la section « Timelines » à gauche pour commencer le montage.'; + + @override + String get createTimelineChat => + 'Créez une timeline pour commencer à discuter'; + + @override + String get operationFailed => 'L\'opération a échoué. Veuillez réessayer.'; + + @override + String get collapseSidebar => 'Réduire la barre latérale'; + + @override + String get expandSidebar => 'Développer la barre latérale'; + + @override + String get expandEditor => 'Développer la zone de montage'; + + @override + String get collapseProperties => 'Réduire les propriétés'; + + @override + String get expandProperties => 'Développer les propriétés'; + + @override + String get layout => 'Disposition'; + + @override + String get editingFirstLayout => 'Montage prioritaire'; + + @override + String get agentEditingLayout => 'Agent et montage'; + + @override + String get agentLayoutDescription => 'Planifier, collaborer et exécuter'; + + @override + String get editingLayoutDescription => 'Prévisualiser, monter et affiner'; + + @override + String get materials => 'Médias'; + + @override + String get all => 'Tous'; + + @override + String get video => 'Vidéo'; + + @override + String get audio => 'Audio'; + + @override + String get image => 'Image'; + + @override + String get picture => 'Image'; + + @override + String get captions => 'Sous-titres'; + + @override + String get text => 'Texte'; + + @override + String get noMedia => 'Aucun média'; + + @override + String get mediaCategory => 'Catégorie de médias'; + + @override + String get captionTasks => 'Tâches de sous-titrage'; + + @override + String get listLayout => 'Vue en liste'; + + @override + String get gridLayout => 'Vue grille'; + + @override + String get addToTimeline => 'Ajouter à la timeline'; + + @override + String get rename => 'Renommer'; + + @override + String get renameMedia => 'Renommer le média'; + + @override + String get removeMedia => 'Retirer le média'; + + @override + String get remove => 'Retirer'; + + @override + String get revealFinder => 'Afficher dans le Finder'; + + @override + String get revealFileManager => 'Afficher dans le gestionnaire de fichiers'; + + @override + String get dropToAdd => 'Relâcher pour ajouter'; + + @override + String get timelineDropToStart => + 'Faites glisser des médias ici pour commencer.'; + + @override + String get dragMediaHint => + 'Faites glisser la vidéo, l\'audio ou les images ici\nLes fichiers originaux restent à leur emplacement actuel'; + + @override + String get transcribe => 'Transcrire'; + + @override + String get generateCaptions => 'Générer des sous-titres'; + + @override + String get play => 'Lire'; + + @override + String get pause => 'Pause'; + + @override + String get retryPreview => 'Réessayer l\'aperçu'; + + @override + String get canvasRatio => 'Rapport d’image'; + + @override + String get noPreviewContent => + 'Aucun contenu à prévisualiser sur la timeline'; + + @override + String get nativePreviewUnsupported => + 'L\'aperçu natif n\'est pas disponible sur cette plateforme'; + + @override + String get canvasTransformFailed => + 'Impossible de transformer la toile. Veuillez réessayer.'; + + @override + String get undo => 'Annuler'; + + @override + String get redo => 'Rétablir'; + + @override + String get deleteSelectedClips => 'Supprimer les clips sélectionnés'; + + @override + String get splitAtPlayhead => 'Diviser au niveau de la tête de lecture'; + + @override + String get trimLeft => 'Rogner à gauche'; + + @override + String get trimRight => 'Rogner à droite'; + + @override + String get trimLeftTooltip => + 'Supprimer à gauche de la tête de lecture et conserver la droite'; + + @override + String get trimRightTooltip => + 'Supprimer à droite de la tête de lecture et conserver la gauche'; + + @override + String get currentSequence => 'Séquence actuelle'; + + @override + String get projectProperties => 'Propriétés du projet'; + + @override + String get canvasSize => 'Taille du canevas'; + + @override + String get frameRate => 'Fréquence d’images'; + + @override + String get duration => 'Durée'; + + @override + String get totalDuration => 'Durée totale'; + + @override + String get clipDuration => 'Durée du clip'; + + @override + String get seconds => 'secondes'; + + @override + String get clip => 'Clip'; + + @override + String get unnamedClip => 'Clip sans nom'; + + @override + String get gap => 'Intervalle'; + + @override + String get compoundClip => 'Clip composé'; + + @override + String get textClip => 'Clip de texte'; + + @override + String get pictureProperties => 'Image'; + + @override + String get position => 'Position'; + + @override + String get rotation => 'Rotation'; + + @override + String get scale => 'Échelle'; + + @override + String get size => 'Taille'; + + @override + String get transform => 'Transformation'; + + @override + String get resetPosition => 'Réinitialiser la position'; + + @override + String get keepAspectRatio => 'Verrouiller le rapport hauteur/largeur'; + + @override + String get alignment => 'Alignement'; + + @override + String get alignLeft => 'Aligner à gauche'; + + @override + String get alignRight => 'Aligner à droite'; + + @override + String get alignTop => 'Aligner en haut'; + + @override + String get alignBottom => 'Aligner en bas'; + + @override + String get alignHorizontalCenter => 'Centrer horizontalement'; + + @override + String get alignVerticalCenter => 'Centrer verticalement'; + + @override + String get volume => 'Volume'; + + @override + String get gain => 'Gain'; + + @override + String get mute => 'Couper le son'; + + @override + String get unmute => 'Activer le son'; + + @override + String get resetVolume => 'Réinitialiser le volume'; + + @override + String get invalidGain => 'Saisissez une valeur comprise entre -90 et +12'; + + @override + String get animation => 'Animation'; + + @override + String get keyframes => 'Images clés'; + + @override + String get removeAllKeyframes => 'Supprimer toutes les images clés'; + + @override + String get linear => 'Linéaire'; + + @override + String get easeIn => 'Accélération progressive'; + + @override + String get easeOut => 'Décélération progressive'; + + @override + String get easeInOut => 'Accélération et décélération'; + + @override + String get basic => 'Général'; + + @override + String get mask => 'Masque'; + + @override + String get addMask => 'Ajouter un masque'; + + @override + String get deleteMask => 'Supprimer le masque'; + + @override + String get resetMask => 'Réinitialiser le masque'; + + @override + String get enableMask => 'Activer le masque'; + + @override + String get disableMask => 'Désactiver le masque'; + + @override + String get moveMaskUp => 'Déplacer le masque vers le haut'; + + @override + String get moveMaskDown => 'Descendre le masque'; + + @override + String get rectangle => 'Rectangle'; + + @override + String get ellipse => 'Ellipse'; + + @override + String get invert => 'Inverser'; + + @override + String get feather => 'Contour progressif'; + + @override + String get add => 'Addition'; + + @override + String get subtract => 'Soustraction'; + + @override + String get intersect => 'Intersection'; + + @override + String get initialRegion => 'Région initiale'; + + @override + String get none => 'Aucun'; + + @override + String get color => 'Couleur'; + + @override + String get fontSize => 'Taille de la police'; + + @override + String get outlineWidth => 'Épaisseur du contour'; + + @override + String get outlineColor => 'Couleur du contour'; + + @override + String get captionBaseline => 'Ligne de base des sous-titres'; + + @override + String get content => 'Texte'; + + @override + String get start => 'Début'; + + @override + String get time => 'Temps'; + + @override + String get speed => 'Vitesse'; + + @override + String speedSegmentCount(int count) { + return '$count segments de vitesse'; + } + + @override + String get splitSpeedAtPlayhead => 'Scinder la vitesse à la tête de lecture'; + + @override + String get speedChange => 'Vitesse'; + + @override + String get speedMode => 'Mode de vitesse'; + + @override + String get constantSpeed => 'Vitesse constante'; + + @override + String get segmentedSpeed => 'Vitesse segmentée'; + + @override + String get speedNotAvailable => + 'Les contrôles de vitesse ne sont pas encore disponibles'; + + @override + String get custom => 'Personnalisé'; + + @override + String get invalidNumber => 'Valeur invalide'; + + @override + String get mediaUnavailable => 'Médias indisponibles'; + + @override + String get mediaMissing => 'Média manquant'; + + @override + String get mediaColorSpace => 'Espace colorimétrique des médias'; + + @override + String get mediaColorInterpretation => + 'Interprétation des couleurs des médias'; + + @override + String get colorInfoNotLoaded => + 'Les informations de couleur ne sont pas chargées'; + + @override + String get unknownColorSpace => + 'Espace colorimétrique inconnu. Affichage sous forme de Rec.709.'; + + @override + String get colorBackendUnsupported => + 'Le backend actuel ne prend pas en charge l’interprétation des couleurs du support.'; + + @override + String get loadClipPropertiesFailed => + 'Impossible de lire les propriétés du clip'; + + @override + String get updatePictureFailed => + 'Impossible de mettre à jour les propriétés de l\'image'; + + @override + String get updateVolumeFailed => 'Impossible de mettre à jour le volume'; + + @override + String get updateMaskFailed => 'Impossible de mettre à jour le masque'; + + @override + String get updateKeyframesFailed => + 'Impossible de mettre à jour les images clés'; + + @override + String get maskPreviewFailed => 'Impossible de préparer l\'aperçu du masque'; + + @override + String get alignClipFailed => + 'Impossible d\'aligner le clip. Attendez l\'aperçu, puis réessayez.'; + + @override + String get invalidTransform => + 'L\'échelle doit être comprise entre 1 % et 10 000 %. La position et l\'angle doivent être des nombres valides.'; + + @override + String get editFailed => + 'Impossible de modifier. Vérifiez l\'entrée et la plage horaire.'; + + @override + String get addMediaFailed => + 'Impossible d\'ajouter des médias. Veuillez réessayer.'; + + @override + String get deleteCaption => 'Supprimer le sous-titre'; + + @override + String get mergeCaptions => 'Fusionner les sous-titres'; + + @override + String get captionDeleted => 'Sous-titre supprimé'; + + @override + String get captionChanged => + 'Les sous-titres ont changé. Veuillez réessayer.'; + + @override + String get captionEditChanged => + 'Les sous-titres ont changé. Veuillez modifier à nouveau.'; + + @override + String get assistantHint => 'Décrivez votre idée d\'édition'; + + @override + String get configureAgentHint => + 'Configurer le service d\'agent pour commencer à discuter'; + + @override + String get agentRestartHint => + 'Configurez le service d\'agent, puis redémarrez l\'application.'; + + @override + String get replyInterrupted => 'Réponse interrompue'; + + @override + String get replying => 'Réponse en cours…'; + + @override + String get stopReply => 'Arrêter la réponse'; + + @override + String get sendMessage => 'Envoyer un message'; + + @override + String get addAttachment => + 'Ajouter une pièce jointe (pas encore disponible)'; + + @override + String get replyFailed => + 'La réponse a échoué. Vérifiez la connexion ou réessayez plus tard.'; + + @override + String get mcpService => 'Service MCP'; + + @override + String get listenPort => 'Port'; + + @override + String get accessToken => 'Jeton d\'accès'; + + @override + String get copyAccessToken => 'Copier le jeton d\'accès'; + + @override + String get accessTokenCopied => 'Jeton d\'accès copié'; + + @override + String get loadMcpFailed => + 'Impossible de charger les paramètres MCP. Réessayer'; + + @override + String get saveMcpFailed => + 'Impossible d\'enregistrer les paramètres MCP. Veuillez réessayer.'; + + @override + String get retryStart => 'Réessayez de démarrer'; + + @override + String get invalidPort => 'Le port doit être compris entre 1 et 65535'; + + @override + String get loadingSettings => 'Chargement des paramètres…'; + + @override + String get starting => 'Démarrage…'; + + @override + String get stopping => 'Arrêt…'; + + @override + String get disabled => 'Désactivé'; + + @override + String get running => 'En cours d’exécution'; + + @override + String get startFailed => 'Échec du démarrage'; + + @override + String get saved => 'Enregistré'; + + @override + String get unsaved => 'Non enregistré'; + + @override + String get saving => 'Enregistrement…'; + + @override + String get pendingSave => 'En attente de sauvegarde'; + + @override + String get notApplied => 'Non appliqué'; + + @override + String get enable => 'Activer'; + + @override + String get disable => 'Désactiver'; + + @override + String get type => 'Type'; + + @override + String get status => 'Statut'; + + @override + String get file => 'Fichier'; + + @override + String get unboundMedia => 'Aucun média associé'; + + @override + String get unboundAudio => 'Aucune piste audio associée'; + + @override + String get vertical => 'Vertical'; + + @override + String get language => 'Langue'; + + @override + String get saveLanguageFailed => + 'Impossible d\'enregistrer la langue. Veuillez réessayer.'; + + @override + String get loadLanguageFailed => + 'Impossible de charger la langue. Veuillez sélectionner à nouveau.'; + + @override + String get propertiesFirstLayout => 'Les propriétés d\'abord'; + + @override + String get defaultLayout => 'Disposition par défaut'; + + @override + String get separateVocals => 'Séparer la voix'; + + @override + String get detachAudio => 'Détacher l’audio'; + + @override + String get restoreAudio => 'Restaurer l’audio'; + + @override + String get audioDetached => 'Audio détaché'; + + @override + String get addAll => 'Tout ajouter'; + + @override + String get preparingMedia => 'Préparation des médias…'; + + @override + String get cancelling => 'Annulation…'; + + @override + String get cancelled => 'Annulé'; + + @override + String get interruptedTask => 'Tâche interrompue. Redémarrez pour continuer'; + + @override + String get auto => 'Automatique'; + + @override + String get autoDetect => 'Détection automatique'; + + @override + String get noTranslation => 'Ne pas traduire'; + + @override + String get sourceLanguage => 'Langue source'; + + @override + String get translationLanguage => 'Langue cible'; + + @override + String get transcriptionNotConfigured => + 'La transcription n\'est pas configurée. Installez le composant de reconnaissance et le modèle Whisper Turbo.'; + + @override + String get translationNotConfigured => + 'La traduction des sous-titres n\'est pas configurée. Vous pouvez générer des sous-titres dans la langue source.'; + + @override + String get sourceLanguageUnknown => + 'Impossible de déterminer une langue source pour la traduction.'; + + @override + String get startTranscriptionFailed => + 'Impossible de démarrer la transcription. Vérifiez les médias ou attendez la fin de la tâche en cours.'; + + @override + String get placeMediaFirst => + 'Placez ce média sur la timeline avant d\'appliquer des sous-titres.'; + + @override + String get placeTranslationMediaFirst => + 'Placez le média correspondant sur la timeline avant d\'appliquer les sous-titres traduits.'; + + @override + String get selectTargetClip => 'Sélectionner le clip cible'; + + @override + String get timelineChanged => + 'La chronologie a changé. Sélectionnez à nouveau le clip cible.'; + + @override + String get transcriptionAccessFailed => + 'Échec de la transcription : composant, modèle ou média source inaccessible (notConfigured)'; + + @override + String get transcriptionNoAudio => + 'Échec de la transcription : aucun son reconnaissable dans le média ou la piste sélectionné (noAudio)'; + + @override + String get transcriptionInvalidResult => + 'Échec de la transcription : fichier de sous-titre non valide renvoyé (invalidResult)'; + + @override + String get transcriptionWorkerExited => + 'Échec de la transcription : le composant de reconnaissance s\'est arrêté de manière inattendue (workerExited)'; + + @override + String get transcriptionProcessingFailed => + 'Échec de la transcription : échec du traitement natif (processingFailed)'; + + @override + String get transcriptionFailed => + 'La transcription a échoué. Vérifiez le composant, le modèle, la piste audio et la durée'; + + @override + String get transcribing => 'Transcription…'; + + @override + String get captionsGenerated => 'Sous-titres générés'; + + @override + String get cancelTranscription => 'Annuler la transcription'; + + @override + String get applyCaptions => 'Appliquer les sous-titres'; + + @override + String get preparingTranslation => 'Préparation de la traduction…'; + + @override + String get translatingCaptions => 'Traduction des sous-titres…'; + + @override + String get cancellingTranslation => 'Annulation de la traduction…'; + + @override + String get translatedCaptionsGenerated => 'Sous-titres traduits générés'; + + @override + String get translationCancelled => 'Traduction annulée'; + + @override + String get translationInterrupted => 'Traduction interrompue'; + + @override + String get cancelTranslation => 'Annuler la traduction'; + + @override + String get editorServiceUnavailable => + 'Service d\'édition indisponible. Rouvrez le projet.'; + + @override + String get mcpUnavailable => + 'Connexion MCP indisponible. Vérifiez le port local et le jeton.'; + + @override + String get openTimelineFailed => 'Impossible d\'ouvrir la chronologie'; + + @override + String get noTimelineSequence => + 'Cette timeline ne contient aucune séquence.'; + + @override + String get waitingForProject => 'En attente d\'ouverture d\'un projet'; + + @override + String get hold => 'Maintien'; + + @override + String get noImportableFiles => 'Aucun fichier importable reçu'; + + @override + String get virtualFilesUnsupported => + 'Faites glisser les fichiers originaux depuis le gestionnaire de fichiers. Les fichiers virtuels ne sont pas encore pris en charge.'; + + @override + String get editorSessionStartFailed => + 'Impossible d’ouvrir l’éditeur de timeline'; + + @override + String get previewStartFailed => 'Impossible de démarrer l\'aperçu natif'; + + @override + String get previewInvalidTrack => + 'La piste audio ou vidéo sélectionnée n\'existe pas dans le média.'; + + @override + String get previewMissingBinding => + 'Les liaisons multimédias sont manquantes. Impossible de prévisualiser cette chronologie.'; + + @override + String get previewUnsupportedEdits => + 'Cette chronologie contient des modifications qui ne sont pas encore prises en charge par l\'aperçu.'; + + @override + String get previewUnsupportedConfiguration => + 'Cette configuration d\'aperçu n\'est pas prise en charge sur la plateforme ou la version actuelle du système.'; + + @override + String get previewHdrUnsupported => + 'Les médias HDR nécessitent un mappage de tons pour l\'aperçu SDR. Le système actuel ou la configuration d\'aperçu ne le prend pas en charge.'; + + @override + String get previewAudioOutOfRange => + 'Le clip audio dépasse la plage de la piste source et ne peut pas être prévisualisé.'; + + @override + String get previewResourceMissing => + 'Le média de prévisualisation n\'existe plus. Localisez à nouveau le fichier d\'origine.'; + + @override + String get previewInvalidComposition => + 'Configuration de composition vidéo non valide. Impossible de créer un aperçu.'; + + @override + String get previewInvalidData => + 'Données d\'aperçu non valides. Veuillez réessayer.'; + + @override + String get previewFailed => + 'L\'aperçu a échoué. Vérifiez l\'accès aux médias et réessayez.'; + + @override + String get chatFailed => + 'Impossible de terminer la conversation. Vérifiez la configuration du service ou réessayez plus tard.'; + + @override + String get delete => 'Supprimer'; + + @override + String get pinTimeline => 'Épingler la timeline'; + + @override + String get unpinTimeline => 'Désépingler la timeline'; + + @override + String deleteTimelineConfirmation(String name) { + return 'Supprimer « $name » et son historique de modification ? Cette action est irréversible.'; + } + + @override + String get processingFailed => 'Échec du traitement'; + + @override + String get noMatchingOptions => 'Aucune option correspondante'; + + @override + String removeMediaConfirmation(String name) { + return 'Supprimer « $name » de la bibliothèque ? Les clips existants, l\'historique et le fichier original seront conservés.'; + } + + @override + String mediaAdded(int count) { + return '$count références de médias ajoutées'; + } + + @override + String duplicatesSkipped(int count) { + return 'Fichiers en double $count ignorés'; + } + + @override + String mediaCount(int count) { + return '$count médias'; + } + + @override + String get importMedia => 'Importer'; + + @override + String noMediaOfType(String type) { + return 'Aucun support $type'; + } + + @override + String captionsImported(String count) { + return 'Sous-titres $count importées'; + } + + @override + String editCaptionError(String message) { + return 'Impossible de modifier les sous-titres : $message'; + } + + @override + String mcpStartError(String message) { + return 'Impossible de démarrer MCP : $message'; + } + + @override + String manualColorSpace(String name) { + return 'Sélectionné manuellement : $name'; + } + + @override + String detectedColorSpace(String name) { + return 'Détecté : $name'; + } + + @override + String keyframeLabel(String channel) { + return 'Image clé de $channel'; + } + + @override + String maskMode(String mode) { + return 'Mode combiné : $mode'; + } + + @override + String keyframeCount(int count) { + return '$count images clés'; + } + + @override + String toggleKeyframe(String action, String channel) { + return '$action une image clé de $channel'; + } + + @override + String previousKeyframe(String channel) { + return 'Image clé précédente de $channel'; + } + + @override + String nextKeyframe(String channel) { + return 'Image clé suivante de $channel'; + } + + @override + String keyframeSettings(String channel) { + return 'Réglages des images clés de $channel'; + } + + @override + String selectedClipsHint(int count) { + return 'Clips $count sélectionnés\nSélectionnez un clip pour afficher ses propriétés'; + } + + @override + String transcriptionError(String code) { + return 'La transcription a échoué. Vérifiez le composant, le modèle, la piste audio et la durée ($code)'; + } + + @override + String captionsAdded(String count) { + return 'Ajout des sous-titres $count. Modifiez-les dans le panneau des propriétés.'; + } + + @override + String translatedCaptionsAdded(String count) { + return 'Ajout des sous-titres traduits $count. Modifiez-les dans le panneau des propriétés.'; + } + + @override + String applyCaptionsError(String message) { + return 'Impossible d\'appliquer les sous-titres : $message'; + } + + @override + String applyTranslatedCaptionsError(String message) { + return 'Impossible d\'appliquer les sous-titres traduits : $message'; + } + + @override + String recognizedCaptions(int count) { + return '$count sous-titres reconnus'; + } + + @override + String captionCount(int count) { + return '$count sous-titres'; + } + + @override + String translationFailed(String message) { + return 'Échec de la traduction : $message'; + } + + @override + String translatedCaptionCount(int count, String language) { + return '$count sous-titres en $language'; + } + + @override + String previewParameterError(String message) { + return 'Paramètres d\'aperçu non valides : $message'; + } + + @override + String mediaOffline(String names) { + return 'Média hors ligne ou indisponible : $names'; + } + + @override + String searchOptions(String label) { + return 'Rechercher $label…'; + } + + @override + String get loadRecentProjectsFailed => + 'Impossible de charger les bibliothèques récentes. Vous pouvez toujours ouvrir une bibliothèque manuellement.'; + + @override + String get projectAccessFailed => 'Projet indisponible'; + + @override + String get projectMissingDirectory => 'Projet introuvable'; + + @override + String get recentProjectSaveFailed => + 'Bibliothèque ouverte, mais l\'enregistrement récent de la bibliothèque n\'a pas pu être enregistré.'; + + @override + String get lastProjectSaveFailed => + 'Projet ouvert, mais le dernier enregistrement du projet n\'a pas pu être enregistré.'; + + @override + String get enterProjectName => 'Entrez un nom de projet'; + + @override + String get projectSwitched => + 'Le projet a changé. Faites glisser à nouveau le média.'; + + @override + String get notLocalMedia => 'Ce média n\'est pas un fichier local'; + + @override + String get revealMediaFailed => + 'Impossible d\'afficher les médias dans le gestionnaire de fichiers'; + + @override + String get openMatchingProject => 'Ouvrez d\'abord le projet correspondant'; + + @override + String get projectMismatch => + 'La bibliothèque à cet emplacement ne correspond pas à la notice. Sélectionnez-le à nouveau avec Ouvrir la bibliothèque.'; + + @override + String get openProjectFirst => 'Ouvrez d\'abord une bibliothèque'; + + @override + String get localFilesOnly => + 'Faites glisser les fichiers locaux depuis le gestionnaire de fichiers'; + + @override + String get foldersUnsupported => + 'Sélectionnez les fichiers. Le déplacement de dossiers n\'est pas encore pris en charge.'; + + @override + String get mediaImportCancelled => 'Importation multimédia annulée'; + + @override + String get fileAccessFailed => + 'Le fichier est manquant ou illisible. Vérifiez son emplacement et ses autorisations'; + + @override + String get registerMediaFailed => + 'Impossible d\'enregistrer le média. Veuillez réessayer'; + + @override + String get mediaNoLongerExists => 'Les médias n\'existent plus'; + + @override + String get mediaNoTracks => + 'Le média n\'a aucune piste vidéo ou audio utilisable'; + + @override + String get invalidMediaDuration => 'Durée du média invalide'; + + @override + String get mediaInfoUnsupported => + 'La lecture des informations multimédias n\'est pas encore prise en charge sur cette plate-forme'; + + @override + String get mediaInfoFailed => + 'Impossible de lire les informations multimédias. Vérifiez le fichier et les autorisations d\'accès'; + + @override + String get saveTimelineFailed => + 'Impossible d\'enregistrer la chronologie. Essayer à nouveau. Les modifications non enregistrées restent dans cette session.'; + + @override + String get addKeyframeAction => 'Ajouter'; + + @override + String get backgroundTasks => 'Tâches en arrière-plan'; + + @override + String get noBackgroundTasks => 'Aucune tâche en arrière-plan'; + + @override + String get retryTask => 'Réessayer'; + + @override + String get applyOriginalCaptions => 'Appliquer les sous-titres originaux'; + + @override + String get applyTranslatedCaptions => 'Appliquer les sous-titres traduits'; + + @override + String get subtitleTaskStarted => 'Tâche de sous-titres démarrée'; + + @override + String get fitTimeline => 'Afficher toute la chronologie'; + + @override + String get modify => 'Modify'; + + @override + String get projectSettings => 'Project settings'; + + @override + String get projectSettingsDescription => + 'Change project output settings while keeping clip timing and speed.'; + + @override + String get projectColorSpace => 'Color space'; + + @override + String get projectWidth => 'Width (px)'; + + @override + String get projectHeight => 'Height (px)'; + + @override + String get projectResolutionInvalid => 'Enter a whole number from 1 to 16384'; + + @override + String get previewFullscreen => 'Aperçu plein écran'; + + @override + String get exitPreviewFullscreen => 'Quitter le plein écran'; + + @override + String get previewGoToStart => 'Aller au début'; + + @override + String get previewPreviousFrame => 'Image précédente'; + + @override + String get previewNextFrame => 'Image suivante'; + + @override + String get softwareUpdates => 'Mises à jour'; + + @override + String get checkForUpdates => 'Rechercher des mises à jour'; + + @override + String get automaticallyCheckUpdates => + 'Rechercher automatiquement les mises à jour'; + + @override + String get updatesUnavailable => + 'Les mises à jour sont indisponibles pour cette version.'; + + @override + String get updateCheckFailed => + 'Impossible de rechercher les mises à jour. Réessayez.'; + + @override + String get removeBackground => 'Supprimer l’arrière-plan'; + + @override + String get startBackgroundRemoval => 'Supprimer l’arrière-plan'; + + @override + String get backgroundRemovalResourceRequired => + 'La suppression de l’arrière-plan nécessite un modèle local. Elle démarre automatiquement après le téléchargement.'; + + @override + String get backgroundRemovalDownloadTask => + 'Télécharger la ressource de suppression d’arrière-plan'; + + @override + String get backgroundRemovalResourceName => + 'Modèle de suppression d’arrière-plan'; + + @override + String get backgroundRemovalDestructiveHint => + 'Le média transparent généré remplacera ce clip. Vous pouvez utiliser Annuler pour restaurer le clip d’origine.'; + + @override + String get backgroundRemovalTaskStarted => + 'Suppression de l’arrière-plan démarrée'; + + @override + String get startBackgroundRemovalFailed => + 'Impossible de démarrer la suppression de l’arrière-plan. Vérifiez le média ou attendez la fin de la tâche de traitement en cours.'; + + @override + String get backgroundRemovalComplete => + 'Suppression de l’arrière-plan terminée'; + + @override + String get backgroundRemovalApplying => 'Remplacement du média du clip'; + + @override + String get backgroundRemovalFailed => + 'Échec de la suppression de l’arrière-plan'; + + @override + String get agentSettings => 'Agent'; + + @override + String get agentSaveSettingsFailed => + 'Impossible d’enregistrer les réglages de l’Agent.'; + + @override + String get agentDeleteProviderTitle => 'Supprimer le fournisseur ?'; + + @override + String agentDeleteProviderDescription(String providerName) { + return '« $providerName » et sa clé API enregistrée seront supprimés de cet appareil.'; + } + + @override + String get agentProviderRequired => + 'Ajoutez un fournisseur avant d’activer l’assistant.'; + + @override + String get agentUseSelectedModel => + 'Les nouvelles requêtes de l’Agent utiliseront le modèle sélectionné.'; + + @override + String get agentEnable => 'Activer l’Agent'; + + @override + String get agentDefaultModel => 'Modèle par défaut'; + + @override + String get agentConfigureModel => 'Configurer les modèles'; + + @override + String get agentSelectModel => 'Choisir un modèle'; + + @override + String get agentModelUnavailable => + 'Le modèle de cette conversation est indisponible. Choisissez un autre modèle pour démarrer une nouvelle conversation.'; + + @override + String get agentModelChangeSession => + 'Changer de modèle démarre une nouvelle session de l’Agent.'; + + @override + String get agentCustomProviders => 'Fournisseurs personnalisés'; + + @override + String get agentProviderStorageDescription => + 'Les métadonnées du fournisseur sont stockées localement. Les clés API sont conservées dans le gestionnaire d’identifiants du système.'; + + @override + String get agentAddProvider => 'Ajouter un fournisseur'; + + @override + String get agentBackToProviders => 'Retour aux fournisseurs'; + + @override + String get agentLoadSettingsFailed => + 'Impossible de charger les réglages de l’Agent. Réessayer'; + + @override + String get agentEnableProvider => 'Activer le fournisseur'; + + @override + String get agentEditProvider => 'Modifier le fournisseur'; + + @override + String get agentDeleteProvider => 'Supprimer le fournisseur'; + + @override + String get agentModelIdsUnique => + 'Les identifiants de modèle doivent être uniques.'; + + @override + String get agentEditProviderTitle => 'Modifier le fournisseur'; + + @override + String get agentProviderEndpointDescription => + 'Configurez un endpoint Chat Completions compatible avec OpenAI.'; + + @override + String get agentSaveProvider => 'Enregistrer le fournisseur'; + + @override + String get agentProviderConfiguration => 'Configuration du fournisseur'; + + @override + String get agentAuthenticationAndModels => 'Authentification et modèles'; + + @override + String get agentApiType => 'Type d’API'; + + @override + String get agentOpenAiChatCompletions => 'OpenAI Completions'; + + @override + String get agentBaseUrl => 'URL de base'; + + @override + String get agentApiKey => 'Clé API'; + + @override + String get agentProviderNameHint => 'Mon fournisseur'; + + @override + String get agentApiKeyOptional => + 'Facultatif pour les endpoints qui ne nécessitent pas d’authentification.'; + + @override + String get agentApiKeyKeep => + 'Laissez ce champ vide pour conserver la clé enregistrée.'; + + @override + String get agentOptional => 'Facultatif'; + + @override + String get agentApiKeyOneLine => 'La clé API doit tenir sur une seule ligne.'; + + @override + String get agentRemoveSavedApiKey => 'Supprimer la clé API enregistrée'; + + @override + String get agentModels => 'Modèles'; + + @override + String get agentAddModel => 'Ajouter un modèle'; + + @override + String get agentRequiredField => 'Ce champ est obligatoire.'; + + @override + String get agentInvalidBaseUrl => + 'Saisissez une URL de base HTTP(S) sans identifiants, requête ni fragment.'; + + @override + String get agentModelId => 'Identifiant du modèle'; + + @override + String get agentContextWindow => 'Fenêtre de contexte'; + + @override + String get agentMaxOutputTokens => 'Sortie maximale'; + + @override + String get agentMaxOutputBelowContext => + 'Doit être inférieur à la fenêtre de contexte.'; + + @override + String get agentDeleteModel => 'Supprimer le modèle'; + + @override + String get agentPositiveInteger => 'Saisissez un entier positif.'; + + @override + String get agentConfigurationReadFailed => + 'Impossible de lire la configuration de l’Agent. Vérifiez les réglages et réessayez.'; + + @override + String get agentConfigurationRequired => + 'Configurez et activez d’abord l’Agent dans les réglages.'; + + @override + String get agentSessionRestoreFailed => + 'Impossible de restaurer la session de l’Agent. Réessayez plus tard.'; + + @override + String get agentContextBudgetExceeded => + 'Le budget d’entrée ne suffit pas pour les instructions, outils et message. Augmentez le contexte ou réduisez la sortie maximale.'; + + @override + String get agentAuthenticationFailed => + 'Échec de l’authentification. Vérifiez la clé API et les autorisations.'; + + @override + String get agentConnectionFailed => + 'Connexion impossible ou délai dépassé. Vérifiez la Base URL et le réseau.'; + + @override + String get agentProtocolFailed => + 'La réponse ne correspond pas au type d’API choisi ou le flux est incomplet.'; + + @override + String get agentContextBudgetTooSmall => + 'Réservez plus d’espace pour les instructions système. Augmentez le contexte ou réduisez la sortie maximale.'; + + @override + String get agentCompacting => 'Organisation du contexte…'; + + @override + String get agentEditing => 'Modification en cours…'; + + @override + String get agentVerifying => 'Vérification des résultats…'; + + @override + String get agentTurnLimitReached => + 'La tâche a atteint sa limite d’exécution. Les modifications sont enregistrées. Envoyez « Continuer » pour reprendre.'; + + @override + String get agentRecoveryRequired => + 'Le résultat précédent est incertain. Reprenez pour vérifier les opérations enregistrées ; les modifications non confirmées ne seront pas répétées.'; + + @override + String get agentExportReplyFailed => + 'Vidéo exportée. La réponse récapitulative a échoué. Réessayez le résumé sans répéter le montage ni l’exportation.'; + + @override + String get agentRetrySummary => 'Réessayer le résumé'; + + @override + String get agentResumeTask => 'Reprendre la tâche'; + + @override + String get agentTaskInterrupted => + 'La tâche a été interrompue. Reprenez depuis la progression enregistrée.'; + + @override + String get downloadSubtitleModel => 'Télécharger le modèle de sous-titres'; + + @override + String get downloadModelAction => 'Télécharger'; + + @override + String get subtitleEngineUnavailable => + 'Le modèle est installé, mais le moteur de sous-titres n’a pas pu démarrer. Réparez le moteur ; il n’est pas nécessaire de télécharger à nouveau le modèle.'; + + @override + String get backgroundTaskDetails => 'Détails de la tâche'; + + @override + String get backgroundTaskFailed => 'Échec'; + + @override + String get backgroundTaskCompleted => 'Terminé'; + + @override + String get captionWrapLines => 'Renvoyer les sous-titres à la ligne'; + + @override + String get captionSingleLine => 'Afficher les sous-titres sur une ligne'; + + @override + String get noMatchingCaptions => 'Aucun sous-titre correspondant'; + + @override + String get subtitleResourcesRequired => + 'Ces ressources sont nécessaires aux sous-titres. La génération démarrera automatiquement après le téléchargement.'; + + @override + String subtitleResourcesDownloadSize(String size) { + return 'À télécharger : $size'; + } + + @override + String get pauseDownload => 'Suspendre'; + + @override + String get resumeDownload => 'Reprendre'; + + @override + String get downloadPaused => 'En pause'; + + @override + String get cancelResourceDownloadTitle => 'Annuler le téléchargement ?'; + + @override + String get cancelResourceDownloadMessage => + 'Le téléchargement s’arrêtera. La progression de la ressource en cours peut être perdue.'; + + @override + String get continueDownload => 'Continuer le téléchargement'; + + @override + String get cancelDownload => 'Annuler le téléchargement'; + + @override + String get speechResourceStage => 'Ressource de reconnaissance vocale'; + + @override + String get translationResourceStage => 'Ressource de traduction'; + + @override + String get subtitleResourceDownloadTask => + 'Télécharger les ressources vocales et de traduction'; + + @override + String get downloadingSpeechModel => 'Téléchargement du modèle vocal'; + + @override + String get downloadingTranslationModel => + 'Téléchargement du modèle de traduction'; + + @override + String get checkingForUpdates => 'Recherche de mises à jour…'; + + @override + String get appIsUpToDate => 'L’application est à jour.'; + + @override + String downloadingUpdate(int progress) { + return 'Téléchargement : $progress %'; + } + + @override + String updateAvailable(String version) { + return 'La version $version est disponible.'; + } + + @override + String get downloadUpdate => 'Télécharger la mise à jour'; + + @override + String get restartToUpdate => 'Redémarrer et mettre à jour'; + + @override + String get updateOperationFailed => + 'Mise à jour impossible. Terminez les tâches en cours et réessayez.'; + + @override + String get windowMinimize => 'Réduire'; + + @override + String get windowMaximize => 'Agrandir'; + + @override + String get windowRestore => 'Restaurer'; + + @override + String get workspaceAgent => 'Assistant'; + + @override + String get workspaceCut => 'Montage'; + + @override + String get noAvailableOptions => 'Aucune option disponible'; + + @override + String get composerReferenceInvalid => + 'Une référence est devenue invalide. Revenez à son projet ou supprimez-la.'; + + @override + String durationSeconds(int seconds) { + return '$seconds s'; + } + + @override + String durationMinutesSeconds(int minutes, int seconds) { + return '$minutes min $seconds s'; + } + + @override + String get projectNameInvalid => 'Nom de projet invalide'; + + @override + String get projectLocationDefaultUnavailable => + 'Impossible d’accéder à l’emplacement par défaut des projets. Sélectionnez-le à nouveau dans les paramètres.'; + + @override + String get chooseProjectLocation => + 'Sélectionnez d’abord un emplacement de sauvegarde des projets dans les paramètres.'; + + @override + String get untitledTimeline => 'Timeline sans titre'; + + @override + String get primarySequence => 'Séquence principale'; + + @override + String get primaryStoryline => 'Scénario principal'; + + @override + String get projectSessionClosed => + 'La session du projet est fermée. Rouvrez le projet.'; + + @override + String get timelineSessionClosed => + 'La session de la timeline est fermée. Rouvrez la timeline.'; + + @override + String get timelineMissing => 'La timeline n’existe pas ou a été supprimée.'; + + @override + String get timelineInUse => + 'La timeline est utilisée et ne peut pas encore être supprimée.'; + + @override + String get timelineHasBackgroundTasks => + 'Terminez les tâches en arrière-plan de la timeline avant de la supprimer.'; + + @override + String get timelineRequired => + 'Un projet doit conserver au moins une timeline.'; + + @override + String get mediaReadFailed => 'Impossible de lire le média'; + + @override + String get mediaImportFailed => 'Impossible d’importer le média'; + + @override + String get unsupportedMediaType => + 'Seuls les fichiers vidéo, audio et image peuvent être importés.'; + + @override + String get mediaNoVideoTracks => + 'Le média ne contient aucune piste vidéo utilisable'; + + @override + String get mediaDurationOutOfRange => + 'La durée du média dépasse la plage de la timeline'; + + @override + String resourceDownloadHttpFailed(String statusCode) { + return 'Échec du téléchargement (HTTP $statusCode)'; + } + + @override + String get resourceChecksumFailed => + 'La vérification du modèle a échoué. Téléchargez à nouveau la ressource.'; + + @override + String get subtitleLanguageAf => 'afrikaans'; + + @override + String get subtitleLanguageAm => 'amharique'; + + @override + String get subtitleLanguageAr => 'arabe'; + + @override + String get subtitleLanguageAst => 'asturien'; + + @override + String get subtitleLanguageAz => 'azerbaïdjanais'; + + @override + String get subtitleLanguageBa => 'bachkir'; + + @override + String get subtitleLanguageBe => 'biélorusse'; + + @override + String get subtitleLanguageBg => 'bulgare'; + + @override + String get subtitleLanguageBn => 'bengali'; + + @override + String get subtitleLanguageBr => 'breton'; + + @override + String get subtitleLanguageBs => 'bosniaque'; + + @override + String get subtitleLanguageCa => 'catalan'; + + @override + String get subtitleLanguageCeb => 'cebuano'; + + @override + String get subtitleLanguageCs => 'tchèque'; + + @override + String get subtitleLanguageCy => 'gallois'; + + @override + String get subtitleLanguageDa => 'danois'; + + @override + String get subtitleLanguageDe => 'allemand'; + + @override + String get subtitleLanguageEl => 'grec'; + + @override + String get subtitleLanguageEn => 'anglais'; + + @override + String get subtitleLanguageEs => 'espagnol'; + + @override + String get subtitleLanguageEt => 'estonien'; + + @override + String get subtitleLanguageFa => 'persan'; + + @override + String get subtitleLanguageFf => 'peul'; + + @override + String get subtitleLanguageFi => 'finnois'; + + @override + String get subtitleLanguageFr => 'français'; + + @override + String get subtitleLanguageFy => 'frison occidental'; + + @override + String get subtitleLanguageGa => 'irlandais'; + + @override + String get subtitleLanguageGd => 'gaélique écossais'; + + @override + String get subtitleLanguageGl => 'galicien'; + + @override + String get subtitleLanguageGu => 'goudjarati'; + + @override + String get subtitleLanguageHa => 'haoussa'; + + @override + String get subtitleLanguageHe => 'hébreu'; + + @override + String get subtitleLanguageHi => 'hindi'; + + @override + String get subtitleLanguageHr => 'croate'; + + @override + String get subtitleLanguageHt => 'créole haïtien'; + + @override + String get subtitleLanguageHu => 'hongrois'; + + @override + String get subtitleLanguageHy => 'arménien'; + + @override + String get subtitleLanguageId => 'indonésien'; + + @override + String get subtitleLanguageIg => 'igbo'; + + @override + String get subtitleLanguageIlo => 'ilocano'; + + @override + String get subtitleLanguageIs => 'islandais'; + + @override + String get subtitleLanguageIt => 'italien'; + + @override + String get subtitleLanguageJa => 'japonais'; + + @override + String get subtitleLanguageJv => 'javanais'; + + @override + String get subtitleLanguageKa => 'géorgien'; + + @override + String get subtitleLanguageKk => 'kazakh'; + + @override + String get subtitleLanguageKm => 'khmer'; + + @override + String get subtitleLanguageKn => 'kannada'; + + @override + String get subtitleLanguageKo => 'coréen'; + + @override + String get subtitleLanguageLb => 'luxembourgeois'; + + @override + String get subtitleLanguageLg => 'ganda'; + + @override + String get subtitleLanguageLn => 'lingala'; + + @override + String get subtitleLanguageLo => 'lao'; + + @override + String get subtitleLanguageLt => 'lituanien'; + + @override + String get subtitleLanguageLv => 'letton'; + + @override + String get subtitleLanguageMg => 'malgache'; + + @override + String get subtitleLanguageMk => 'macédonien'; + + @override + String get subtitleLanguageMl => 'malayalam'; + + @override + String get subtitleLanguageMn => 'mongol'; + + @override + String get subtitleLanguageMr => 'marathi'; + + @override + String get subtitleLanguageMs => 'malais'; + + @override + String get subtitleLanguageMy => 'birman'; + + @override + String get subtitleLanguageNe => 'népalais'; + + @override + String get subtitleLanguageNl => 'néerlandais'; + + @override + String get subtitleLanguageNo => 'norvégien'; + + @override + String get subtitleLanguageNs => 'sotho du Nord'; + + @override + String get subtitleLanguageOc => 'occitan'; + + @override + String get subtitleLanguageOr => 'odia'; + + @override + String get subtitleLanguagePa => 'pendjabi'; + + @override + String get subtitleLanguagePl => 'polonais'; + + @override + String get subtitleLanguagePs => 'pachto'; + + @override + String get subtitleLanguagePt => 'portugais'; + + @override + String get subtitleLanguageRo => 'roumain'; + + @override + String get subtitleLanguageRu => 'russe'; + + @override + String get subtitleLanguageSd => 'sindhi'; + + @override + String get subtitleLanguageSi => 'cingalais'; + + @override + String get subtitleLanguageSk => 'slovaque'; + + @override + String get subtitleLanguageSl => 'slovène'; + + @override + String get subtitleLanguageSo => 'somali'; + + @override + String get subtitleLanguageSq => 'albanais'; + + @override + String get subtitleLanguageSr => 'serbe'; + + @override + String get subtitleLanguageSs => 'swati'; + + @override + String get subtitleLanguageSu => 'soundanais'; + + @override + String get subtitleLanguageSv => 'suédois'; + + @override + String get subtitleLanguageSw => 'swahili'; + + @override + String get subtitleLanguageTa => 'tamoul'; + + @override + String get subtitleLanguageTh => 'thaï'; + + @override + String get subtitleLanguageTl => 'tagalog'; + + @override + String get subtitleLanguageTn => 'tswana'; + + @override + String get subtitleLanguageTr => 'turc'; + + @override + String get subtitleLanguageUk => 'ukrainien'; + + @override + String get subtitleLanguageUr => 'ourdou'; + + @override + String get subtitleLanguageUz => 'ouzbek'; + + @override + String get subtitleLanguageVi => 'vietnamien'; + + @override + String get subtitleLanguageWo => 'wolof'; + + @override + String get subtitleLanguageXh => 'xhosa'; + + @override + String get subtitleLanguageYi => 'yiddish'; + + @override + String get subtitleLanguageYo => 'yoruba'; + + @override + String get subtitleLanguageYue => 'cantonais'; + + @override + String get subtitleLanguageZh => 'chinois'; + + @override + String get subtitleLanguageZu => 'zoulou'; + + @override + String get linearRec2020 => 'Rec.2020 linéaire'; + + @override + String get diagnostics => 'Diagnostic'; + + @override + String get exportDiagnostics => 'Exporter le diagnostic'; + + @override + String get exportDiagnosticsFailed => + 'Impossible d’exporter le diagnostic. Réessayez.'; + + @override + String get exportDiagnosticsSucceeded => 'Diagnostic enregistré.'; +} diff --git a/lib/l10n/app_localizations_it.dart b/lib/l10n/app_localizations_it.dart new file mode 100644 index 0000000..879839d --- /dev/null +++ b/lib/l10n/app_localizations_it.dart @@ -0,0 +1,2225 @@ +// ignore: unused_import +import 'package:intl/intl.dart' as intl; + +import 'app_localizations.dart'; + +// ignore_for_file: type=lint + +/// The translations for Italian (`it`). +class AppLocalizationsIt extends AppLocalizations { + AppLocalizationsIt([String locale = 'it']) : super(locale); + + @override + String get selectProject => 'Seleziona progetto'; + + @override + String get searchProjects => 'Cerca progetti'; + + @override + String get noMatchingProjects => 'Nessun progetto corrispondente'; + + @override + String get projectsNone => 'Nessun progetto'; + + @override + String get projectLocationMissing => + 'La cartella non esiste. Verrà creata quando crei un progetto.'; + + @override + String get projectLocationUnavailable => + 'La posizione di salvataggio non è disponibile. Collega il disco o controlla la rete e riprova, oppure cambia posizione.'; + + @override + String get projectLocationNotWritable => + 'La posizione di salvataggio non è scrivibile. Controlla le autorizzazioni o cambia posizione.'; + + @override + String get projectLocationCreateFailed => + 'Impossibile creare la cartella del progetto o scrivervi. Controlla le autorizzazioni o cambia posizione.'; + + @override + String get removeProjectFromSidebar => 'Rimuovi dalla barra laterale'; + + @override + String get projectRemoved => + 'Progetto rimosso. I file locali e le conversazioni sono conservati.'; + + @override + String get agentNoConversations => 'Nessuna conversazione'; + + @override + String get renameConversationTitle => 'Rinomina chat'; + + @override + String get renameConversationDescription => + 'Usa un nome breve e facile da riconoscere.'; + + @override + String get collapseProject => 'Comprimi progetto'; + + @override + String get expandProject => 'Espandi progetto'; + + @override + String agentDeleteConfirmation(String title) { + return 'Eliminare definitivamente “$title” e tutti i suoi messaggi? Questa azione non può essere annullata. I file locali del progetto non saranno modificati.'; + } + + @override + String get agentEmptyTrashConfirmation => + 'Eliminare definitivamente tutte le conversazioni nel cestino? Questa azione non può essere annullata. I file locali del progetto non saranno modificati.'; + + @override + String get agentConversations => 'Conversazioni'; + + @override + String get showMoreConversations => 'Mostra altro'; + + @override + String get showFewerConversations => 'Mostra meno'; + + @override + String get agentNewConversation => 'Nuova conversazione'; + + @override + String agentElapsedTime(String duration) { + return 'Durata $duration'; + } + + @override + String get agentConversationActions => 'Azioni della conversazione'; + + @override + String get agentMoveToTrash => 'Sposta nel cestino'; + + @override + String get agentTrash => 'Cestino'; + + @override + String get agentRestore => 'Ripristina'; + + @override + String get agentEmptyTrash => 'Svuota cestino'; + + @override + String get agentDeleteForever => 'Elimina definitivamente'; + + @override + String get agentConversationLocation => 'Posizione delle conversazioni'; + + @override + String get agentChooseExistingConversations => + 'Scegli conversazioni esistenti'; + + @override + String get agentMoveConversations => 'Sposta conversazioni'; + + @override + String get agentLocationUnavailable => + 'Posizione delle conversazioni non disponibile'; + + @override + String get agentLocationBusy => 'Attendi la fine delle conversazioni attive'; + + @override + String get agentRelinkProvider => 'Ricollega provider'; + + @override + String get settings => 'Impostazioni'; + + @override + String get closeSettings => 'Chiudi le impostazioni'; + + @override + String get general => 'Generale'; + + @override + String get appearance => 'Aspetto'; + + @override + String get theme => 'Tema'; + + @override + String get system => 'Segui il sistema'; + + @override + String get light => 'Chiaro'; + + @override + String get dark => 'Scuro'; + + @override + String get saveAppearanceFailed => + 'Impossibile salvare l\'aspetto. Per favore riprova.'; + + @override + String get loadAppearanceFailed => + 'Impossibile caricare l\'aspetto. Seleziona di nuovo un tema.'; + + @override + String get cancel => 'Annulla'; + + @override + String get save => 'Salva'; + + @override + String get create => 'Crea'; + + @override + String get close => 'Chiudi'; + + @override + String get retry => 'Riprova'; + + @override + String get select => 'Seleziona'; + + @override + String get name => 'Nome'; + + @override + String get enterName => 'Inserisci un nome'; + + @override + String get invalidName => + 'I nomi non possono contenere separatori di percorso o caratteri di controllo'; + + @override + String get projects => 'Progetti'; + + @override + String get projectName => 'Nome del progetto'; + + @override + String get projectLocation => 'Posizione di salvataggio dei progetti'; + + @override + String get projectLocationNotSet => 'Non impostata'; + + @override + String get loadProjectLocationFailed => + 'Impossibile caricare la posizione di salvataggio dei progetti.'; + + @override + String get saveProjectLocationFailed => + 'Impossibile salvare la posizione dei progetti.'; + + @override + String get resourceLocation => 'Posizione di archiviazione delle risorse'; + + @override + String get resourceLocationNotSet => 'Non impostata'; + + @override + String get loadResourceLocationFailed => + 'Impossibile caricare la posizione di archiviazione delle risorse.'; + + @override + String get saveResourceLocationFailed => + 'Impossibile salvare la posizione delle risorse.'; + + @override + String get transcriptionResourceRequired => + 'Per generare i sottotitoli, devi prima scaricare un modello di riconoscimento vocale.'; + + @override + String get downloadAndContinue => 'Scarica e continua'; + + @override + String get downloadingResource => 'Download in corso…'; + + @override + String get downloadInBackground => 'Scarica in background'; + + @override + String get processingResourceDownloadFailed => + 'Impossibile scaricare la risorsa di riconoscimento vocale. Riprova.'; + + @override + String get newProject => 'Nuovo progetto'; + + @override + String get openProject => 'Apri progetto'; + + @override + String get openProjectMore => 'Apri un altro progetto'; + + @override + String get saveHere => 'Salva qui'; + + @override + String get selectDirectoryFailed => + 'Impossibile selezionare una directory. Controlla i permessi di sistema.'; + + @override + String get openingWorkspace => 'Apertura dell’area di lavoro…'; + + @override + String get loadProjectsFailed => 'Impossibile caricare i progetti'; + + @override + String get projectsEmpty => 'Nessun progetto'; + + @override + String get backToProjects => 'Torna al montaggio'; + + @override + String get timelines => 'Timeline'; + + @override + String timelineLimitReached(int count) { + return 'Ogni progetto può contenere fino a $count timeline.'; + } + + @override + String get timelineName => 'Nome della timeline'; + + @override + String defaultTimelineName(int index) { + return 'Timeline $index'; + } + + @override + String get newTimeline => 'Nuova timeline'; + + @override + String get noTimelines => 'Nessuna timeline'; + + @override + String get activeTimeline => 'Timeline corrente'; + + @override + String get timelineUnavailable => 'Timeline non disponibile'; + + @override + String get projectNoTimelines => + 'Questo progetto non contiene ancora timeline'; + + @override + String get createTimelineHint => + 'Crea una timeline nella sezione “Timeline” a sinistra per iniziare il montaggio.'; + + @override + String get createTimelineChat => 'Crea una timeline per iniziare la chat'; + + @override + String get operationFailed => 'Operazione fallita. Per favore riprova.'; + + @override + String get collapseSidebar => 'Comprimi la barra laterale'; + + @override + String get expandSidebar => 'Espandi la barra laterale'; + + @override + String get expandEditor => 'Espandi area di montaggio'; + + @override + String get collapseProperties => 'Comprimi proprietà'; + + @override + String get expandProperties => 'Espandi proprietà'; + + @override + String get layout => 'Layout'; + + @override + String get editingFirstLayout => 'Priorità al montaggio'; + + @override + String get agentEditingLayout => 'Agente e montaggio'; + + @override + String get agentLayoutDescription => 'Pianifica, collabora ed esegui'; + + @override + String get editingLayoutDescription => 'Anteprima, montaggio e rifinitura'; + + @override + String get materials => 'Media'; + + @override + String get all => 'Tutti'; + + @override + String get video => 'Video'; + + @override + String get audio => 'Audio'; + + @override + String get image => 'Immagine'; + + @override + String get picture => 'Immagine'; + + @override + String get captions => 'Sottotitoli'; + + @override + String get text => 'Testo'; + + @override + String get noMedia => 'Nessun media'; + + @override + String get mediaCategory => 'Categoria media'; + + @override + String get captionTasks => 'Attività sottotitoli'; + + @override + String get listLayout => 'Visualizzazione elenco'; + + @override + String get gridLayout => 'Visualizzazione griglia'; + + @override + String get addToTimeline => 'Aggiungi alla timeline'; + + @override + String get rename => 'Rinomina'; + + @override + String get renameMedia => 'Rinomina media'; + + @override + String get removeMedia => 'Rimuovi media'; + + @override + String get remove => 'Rimuovi'; + + @override + String get revealFinder => 'Mostra nel Finder'; + + @override + String get revealFileManager => 'Mostra nel gestore file'; + + @override + String get dropToAdd => 'Rilascia per aggiungere'; + + @override + String get timelineDropToStart => + 'Trascina qui i contenuti multimediali per iniziare.'; + + @override + String get dragMediaHint => + 'Trascina qui video, audio o immagini\nI file originali rimangono nella posizione corrente'; + + @override + String get transcribe => 'Trascrivi'; + + @override + String get generateCaptions => 'Genera sottotitoli'; + + @override + String get play => 'Riproduci'; + + @override + String get pause => 'Pausa'; + + @override + String get retryPreview => 'Riprova l\'anteprima'; + + @override + String get canvasRatio => 'Rapporto d\'aspetto'; + + @override + String get noPreviewContent => + 'Nessun contenuto da visualizzare in anteprima sulla timeline'; + + @override + String get nativePreviewUnsupported => + 'L\'anteprima nativa non è disponibile su questa piattaforma'; + + @override + String get canvasTransformFailed => + 'Impossibile trasformare la tela. Per favore riprova.'; + + @override + String get undo => 'Annulla'; + + @override + String get redo => 'Ripristina'; + + @override + String get deleteSelectedClips => 'Elimina i clip selezionati'; + + @override + String get splitAtPlayhead => 'Dividi in playhead'; + + @override + String get trimLeft => 'Taglia a sinistra'; + + @override + String get trimRight => 'Taglia a destra'; + + @override + String get trimLeftTooltip => + 'Rimuovi a sinistra della testina e conserva la destra'; + + @override + String get trimRightTooltip => + 'Rimuovi a destra della testina e conserva la sinistra'; + + @override + String get currentSequence => 'Sequenza corrente'; + + @override + String get projectProperties => 'Proprietà del progetto'; + + @override + String get canvasSize => 'Dimensioni del canvas'; + + @override + String get frameRate => 'Frequenza fotogrammi'; + + @override + String get duration => 'Durata'; + + @override + String get totalDuration => 'Durata totale'; + + @override + String get clipDuration => 'Durata della clip'; + + @override + String get seconds => 'secondi'; + + @override + String get clip => 'Clip'; + + @override + String get unnamedClip => 'Clip senza nome'; + + @override + String get gap => 'Spazio vuoto'; + + @override + String get compoundClip => 'Clip composta'; + + @override + String get textClip => 'Clip di testo'; + + @override + String get pictureProperties => 'Immagine'; + + @override + String get position => 'Posizione'; + + @override + String get rotation => 'Rotazione'; + + @override + String get scale => 'Scala'; + + @override + String get size => 'Dimensioni'; + + @override + String get transform => 'Trasformazione'; + + @override + String get resetPosition => 'Ripristina posizione'; + + @override + String get keepAspectRatio => 'Blocca le proporzioni'; + + @override + String get alignment => 'Allineamento'; + + @override + String get alignLeft => 'Allinea a sinistra'; + + @override + String get alignRight => 'Allinea a destra'; + + @override + String get alignTop => 'Allinea in alto'; + + @override + String get alignBottom => 'Allinea il fondo'; + + @override + String get alignHorizontalCenter => 'Centra orizzontalmente'; + + @override + String get alignVerticalCenter => 'Centra verticalmente'; + + @override + String get volume => 'Volume'; + + @override + String get gain => 'Guadagno'; + + @override + String get mute => 'Disattiva audio'; + + @override + String get unmute => 'Riattiva audio'; + + @override + String get resetVolume => 'Reimposta il volume'; + + @override + String get invalidGain => 'Immettere un valore compreso tra -90 e +12'; + + @override + String get animation => 'Animazione'; + + @override + String get keyframes => 'Fotogrammi chiave'; + + @override + String get removeAllKeyframes => 'Rimuovi tutti i fotogrammi chiave'; + + @override + String get linear => 'Lineare'; + + @override + String get easeIn => 'Accelerazione graduale'; + + @override + String get easeOut => 'Decelerazione graduale'; + + @override + String get easeInOut => 'Accelerazione e decelerazione graduali'; + + @override + String get basic => 'Base'; + + @override + String get mask => 'Maschera'; + + @override + String get addMask => 'Aggiungi maschera'; + + @override + String get deleteMask => 'Elimina maschera'; + + @override + String get resetMask => 'Reimposta la maschera'; + + @override + String get enableMask => 'Abilita maschera'; + + @override + String get disableMask => 'Disabilita maschera'; + + @override + String get moveMaskUp => 'Sposta la maschera verso l\'alto'; + + @override + String get moveMaskDown => 'Sposta la maschera verso il basso'; + + @override + String get rectangle => 'Rettangolo'; + + @override + String get ellipse => 'Ellisse'; + + @override + String get invert => 'Inverti'; + + @override + String get feather => 'Sfumatura'; + + @override + String get add => 'Somma'; + + @override + String get subtract => 'Sottrazione'; + + @override + String get intersect => 'Intersezione'; + + @override + String get initialRegion => 'Area iniziale'; + + @override + String get none => 'Nessuno'; + + @override + String get color => 'Colore'; + + @override + String get fontSize => 'Dimensione del carattere'; + + @override + String get outlineWidth => 'Spessore contorno'; + + @override + String get outlineColor => 'Colore contorno'; + + @override + String get captionBaseline => 'Linea di base sottotitoli'; + + @override + String get content => 'Testo'; + + @override + String get start => 'Inizio'; + + @override + String get time => 'Tempo'; + + @override + String get speed => 'Velocità'; + + @override + String speedSegmentCount(int count) { + return '$count segmenti di velocità'; + } + + @override + String get splitSpeedAtPlayhead => 'Dividi velocità sulla testina'; + + @override + String get speedChange => 'Velocità'; + + @override + String get speedMode => 'Modalità velocità'; + + @override + String get constantSpeed => 'Velocità costante'; + + @override + String get segmentedSpeed => 'Velocità segmentata'; + + @override + String get speedNotAvailable => + 'I controlli di velocità non sono ancora disponibili'; + + @override + String get custom => 'Personalizzato'; + + @override + String get invalidNumber => 'Valore non valido'; + + @override + String get mediaUnavailable => 'Supporto non disponibile'; + + @override + String get mediaMissing => 'Media mancanti'; + + @override + String get mediaColorSpace => 'Spazio colore multimediale'; + + @override + String get mediaColorInterpretation => 'Interpretazione del colore dei media'; + + @override + String get colorInfoNotLoaded => 'Informazioni sul colore non caricate'; + + @override + String get unknownColorSpace => + 'Spazio colore sconosciuto. Visualizzato come Rec.709.'; + + @override + String get colorBackendUnsupported => + 'Il backend attuale non supporta l\'interpretazione del colore dei media.'; + + @override + String get loadClipPropertiesFailed => + 'Impossibile leggere le proprietà della clip'; + + @override + String get updatePictureFailed => + 'Impossibile aggiornare le proprietà dell\'immagine'; + + @override + String get updateVolumeFailed => 'Impossibile aggiornare il volume'; + + @override + String get updateMaskFailed => 'Impossibile aggiornare la maschera'; + + @override + String get updateKeyframesFailed => + 'Impossibile aggiornare i fotogrammi chiave'; + + @override + String get maskPreviewFailed => + 'Impossibile preparare l\'anteprima della maschera'; + + @override + String get alignClipFailed => + 'Impossibile allineare la clip. Attendi l\'anteprima, quindi riprova.'; + + @override + String get invalidTransform => + 'La scala deve essere compresa tra 1% e 10.000%. La posizione e l\'angolo devono essere numeri validi.'; + + @override + String get editFailed => + 'Impossibile modificare. Controllare l\'input e l\'intervallo di tempo.'; + + @override + String get addMediaFailed => + 'Impossibile aggiungere contenuti multimediali. Per favore riprova.'; + + @override + String get deleteCaption => 'Elimina sottotitolo'; + + @override + String get mergeCaptions => 'Unisci sottotitoli'; + + @override + String get captionDeleted => 'Sottotitolo eliminato'; + + @override + String get captionChanged => + 'Le sottotitoli sono cambiate. Per favore riprova.'; + + @override + String get captionEditChanged => + 'Le sottotitoli sono cambiate. Per favore modifica di nuovo.'; + + @override + String get assistantHint => 'Descrivi la tua idea di editing'; + + @override + String get configureAgentHint => + 'Configura il servizio dell\'agente per iniziare a chattare'; + + @override + String get agentRestartHint => + 'Configura il servizio dell\'agente, quindi riavvia l\'app.'; + + @override + String get replyInterrupted => 'Risposta interrotta'; + + @override + String get replying => 'Risposta in corso…'; + + @override + String get stopReply => 'Interrompi risposta'; + + @override + String get sendMessage => 'Invia messaggio'; + + @override + String get addAttachment => 'Aggiungi allegato (non ancora disponibile)'; + + @override + String get replyFailed => + 'La risposta non è riuscita. Controlla la connessione o riprova più tardi.'; + + @override + String get mcpService => 'Servizio MCP'; + + @override + String get listenPort => 'Porta'; + + @override + String get accessToken => 'Token di accesso'; + + @override + String get copyAccessToken => 'Copia token di accesso'; + + @override + String get accessTokenCopied => 'Token di accesso copiato'; + + @override + String get loadMcpFailed => + 'Impossibile caricare le impostazioni MCP. Riprova'; + + @override + String get saveMcpFailed => + 'Impossibile salvare le impostazioni MCP. Per favore riprova.'; + + @override + String get retryStart => 'Riprovare ad avviare'; + + @override + String get invalidPort => 'La porta deve essere compresa tra 1 e 65535'; + + @override + String get loadingSettings => 'Caricamento impostazioni…'; + + @override + String get starting => 'Avvio…'; + + @override + String get stopping => 'Arresto…'; + + @override + String get disabled => 'Disattivato'; + + @override + String get running => 'In esecuzione'; + + @override + String get startFailed => 'Impossibile avviare'; + + @override + String get saved => 'Salvato'; + + @override + String get unsaved => 'Non salvato'; + + @override + String get saving => 'Salvataggio…'; + + @override + String get pendingSave => 'Salvataggio in sospeso'; + + @override + String get notApplied => 'Non applicato'; + + @override + String get enable => 'Attiva'; + + @override + String get disable => 'Disattiva'; + + @override + String get type => 'Tipo'; + + @override + String get status => 'Stato'; + + @override + String get file => 'File'; + + @override + String get unboundMedia => 'Nessun media associato'; + + @override + String get unboundAudio => 'Nessuna traccia audio associata'; + + @override + String get vertical => 'Verticale'; + + @override + String get language => 'Lingua'; + + @override + String get saveLanguageFailed => + 'Impossibile salvare la lingua. Per favore riprova.'; + + @override + String get loadLanguageFailed => + 'Impossibile caricare la lingua. Seleziona di nuovo.'; + + @override + String get propertiesFirstLayout => 'Prima le proprietà'; + + @override + String get defaultLayout => 'Disposizione predefinita'; + + @override + String get separateVocals => 'Separa voce'; + + @override + String get detachAudio => 'Separa audio'; + + @override + String get restoreAudio => 'Ripristina audio'; + + @override + String get audioDetached => 'Audio separato'; + + @override + String get addAll => 'Aggiungi tutto'; + + @override + String get preparingMedia => 'Preparazione media…'; + + @override + String get cancelling => 'Annullamento…'; + + @override + String get cancelled => 'Annullato'; + + @override + String get interruptedTask => 'Compito interrotto. Ricomincia per continuare'; + + @override + String get auto => 'Automatico'; + + @override + String get autoDetect => 'Rilevamento automatico'; + + @override + String get noTranslation => 'Non tradurre'; + + @override + String get sourceLanguage => 'Lingua di origine'; + + @override + String get translationLanguage => 'Lingua di destinazione'; + + @override + String get transcriptionNotConfigured => + 'La trascrizione non è configurata. Installa il componente di riconoscimento e il modello Whisper Turbo.'; + + @override + String get translationNotConfigured => + 'La traduzione dei sottotitoli non è configurata. Puoi generare sottotitoli nella lingua di origine.'; + + @override + String get sourceLanguageUnknown => + 'Impossibile determinare una lingua di origine per la traduzione.'; + + @override + String get startTranscriptionFailed => + 'Impossibile avviare la trascrizione. Controlla il supporto o attendi il completamento dell\'attività corrente.'; + + @override + String get placeMediaFirst => + 'Posiziona questo supporto sulla timeline prima di applicare i sottotitoli.'; + + @override + String get placeTranslationMediaFirst => + 'Posiziona i media corrispondenti sulla timeline prima di applicare i sottotitoli tradotti.'; + + @override + String get selectTargetClip => 'Seleziona la clip di destinazione'; + + @override + String get timelineChanged => + 'La sequenza temporale è cambiata. Seleziona nuovamente la clip di destinazione.'; + + @override + String get transcriptionAccessFailed => + 'Trascrizione non riuscita: componente, modello o supporto di origine inaccessibile (notConfigured)'; + + @override + String get transcriptionNoAudio => + 'Trascrizione non riuscita: nessun audio riconoscibile nel supporto o nella traccia selezionata (noAudio)'; + + @override + String get transcriptionInvalidResult => + 'Trascrizione non riuscita: restituito un file di sottotitoli non valido (invalidResult)'; + + @override + String get transcriptionWorkerExited => + 'Trascrizione non riuscita: il componente di riconoscimento è terminato in modo imprevisto (workerExited)'; + + @override + String get transcriptionProcessingFailed => + 'Trascrizione non riuscita: elaborazione nativa non riuscita (processingFailed)'; + + @override + String get transcriptionFailed => + 'La trascrizione non è riuscita. Controlla il componente, il modello, la traccia audio e la durata'; + + @override + String get transcribing => 'Trascrizione…'; + + @override + String get captionsGenerated => 'Sottotitoli generati'; + + @override + String get cancelTranscription => 'Annulla trascrizione'; + + @override + String get applyCaptions => 'Applica sottotitoli'; + + @override + String get preparingTranslation => 'Preparazione traduzione…'; + + @override + String get translatingCaptions => 'Traduzione sottotitoli…'; + + @override + String get cancellingTranslation => 'Annullamento traduzione…'; + + @override + String get translatedCaptionsGenerated => 'Sottotitoli tradotti generati'; + + @override + String get translationCancelled => 'Traduzione annullata'; + + @override + String get translationInterrupted => 'Traduzione interrotta'; + + @override + String get cancelTranslation => 'Annulla traduzione'; + + @override + String get editorServiceUnavailable => + 'Servizio di modifica non disponibile. Riaprire il progetto.'; + + @override + String get mcpUnavailable => + 'Connessione MCP non disponibile. Controlla la porta locale e il token.'; + + @override + String get openTimelineFailed => 'Impossibile aprire la sequenza temporale'; + + @override + String get noTimelineSequence => 'Questa timeline non contiene sequenze.'; + + @override + String get waitingForProject => 'In attesa dell\'apertura di un progetto'; + + @override + String get hold => 'Mantieni'; + + @override + String get noImportableFiles => 'Nessun file importabile ricevuto'; + + @override + String get virtualFilesUnsupported => + 'Trascina i file originali dal file manager. I file virtuali non sono ancora supportati.'; + + @override + String get editorSessionStartFailed => + 'Impossibile aprire l’editor della timeline'; + + @override + String get previewStartFailed => 'Impossibile avviare l\'anteprima nativa'; + + @override + String get previewInvalidTrack => + 'La traccia audio o video selezionata non esiste nel media.'; + + @override + String get previewMissingBinding => + 'Mancano i collegamenti multimediali. Impossibile visualizzare l\'anteprima di questa sequenza temporale.'; + + @override + String get previewUnsupportedEdits => + 'Questa sequenza temporale contiene modifiche che non sono ancora supportate dall\'anteprima.'; + + @override + String get previewUnsupportedConfiguration => + 'Questa configurazione di anteprima non è supportata sulla piattaforma o sulla versione del sistema corrente.'; + + @override + String get previewHdrUnsupported => + 'I contenuti multimediali HDR richiedono la mappatura dei toni per l\'anteprima SDR. Il sistema attuale o la configurazione di anteprima non lo supportano.'; + + @override + String get previewAudioOutOfRange => + 'La clip audio supera l\'intervallo della traccia sorgente e non è possibile visualizzarne l\'anteprima.'; + + @override + String get previewResourceMissing => + 'Il supporto di anteprima non esiste più. Individua nuovamente il file originale.'; + + @override + String get previewInvalidComposition => + 'Configurazione della composizione video non valida. Impossibile creare l\'anteprima.'; + + @override + String get previewInvalidData => + 'Dati di anteprima non validi. Per favore riprova.'; + + @override + String get previewFailed => + 'Anteprima non riuscita. Controlla l\'accesso ai contenuti multimediali e riprova.'; + + @override + String get chatFailed => + 'Impossibile completare la conversazione. Controlla la configurazione del servizio o riprova più tardi.'; + + @override + String get delete => 'Elimina'; + + @override + String get pinTimeline => 'Fissa timeline'; + + @override + String get unpinTimeline => 'Rimuovi timeline fissata'; + + @override + String deleteTimelineConfirmation(String name) { + return 'Eliminare «$name» e la cronologia delle modifiche? Questa azione non può essere annullata.'; + } + + @override + String get processingFailed => 'Elaborazione non riuscita'; + + @override + String get noMatchingOptions => 'Nessuna opzione corrispondente'; + + @override + String removeMediaConfirmation(String name) { + return 'Rimuovere \"$name\" dalla libreria? I clip esistenti, la cronologia e il file originale verranno conservati.'; + } + + @override + String mediaAdded(int count) { + return 'Aggiunti $count riferimenti ai media'; + } + + @override + String duplicatesSkipped(int count) { + return 'File duplicati $count saltati'; + } + + @override + String mediaCount(int count) { + return '$count elementi multimediali'; + } + + @override + String get importMedia => 'Importa'; + + @override + String noMediaOfType(String type) { + return 'Nessun supporto $type'; + } + + @override + String captionsImported(String count) { + return 'Sottotitoli $count importate'; + } + + @override + String editCaptionError(String message) { + return 'Impossibile modificare i sottotitoli: $message'; + } + + @override + String mcpStartError(String message) { + return 'Impossibile avviare MCP: $message'; + } + + @override + String manualColorSpace(String name) { + return 'Selezionato manualmente: $name'; + } + + @override + String detectedColorSpace(String name) { + return 'Rilevato: $name'; + } + + @override + String keyframeLabel(String channel) { + return 'Fotogramma chiave di $channel'; + } + + @override + String maskMode(String mode) { + return 'Modalità combinata: $mode'; + } + + @override + String keyframeCount(int count) { + return '$count fotogrammi chiave'; + } + + @override + String toggleKeyframe(String action, String channel) { + return '$action fotogramma chiave di $channel'; + } + + @override + String previousKeyframe(String channel) { + return 'Fotogramma chiave precedente di $channel'; + } + + @override + String nextKeyframe(String channel) { + return 'Fotogramma chiave successivo di $channel'; + } + + @override + String keyframeSettings(String channel) { + return 'Impostazioni fotogrammi chiave di $channel'; + } + + @override + String selectedClipsHint(int count) { + return 'Clip $count selezionate\nSeleziona una clip per visualizzarne le proprietà'; + } + + @override + String transcriptionError(String code) { + return 'La trascrizione non è riuscita. Controlla il componente, il modello, la traccia audio e la durata ($code)'; + } + + @override + String captionsAdded(String count) { + return 'Aggiunte sottotitoli $count. Modificali nel pannello delle proprietà.'; + } + + @override + String translatedCaptionsAdded(String count) { + return 'Aggiunti i sottotitoli tradotti $count. Modificali nel pannello delle proprietà.'; + } + + @override + String applyCaptionsError(String message) { + return 'Impossibile applicare i sottotitoli: $message'; + } + + @override + String applyTranslatedCaptionsError(String message) { + return 'Impossibile applicare i sottotitoli tradotti: $message'; + } + + @override + String recognizedCaptions(int count) { + return '$count sottotitoli riconosciuti'; + } + + @override + String captionCount(int count) { + return '$count sottotitoli'; + } + + @override + String translationFailed(String message) { + return 'Traduzione non riuscita: $message'; + } + + @override + String translatedCaptionCount(int count, String language) { + return '$count sottotitoli in $language'; + } + + @override + String previewParameterError(String message) { + return 'Parametri di anteprima non validi: $message'; + } + + @override + String mediaOffline(String names) { + return 'File multimediali offline o non disponibili: $names'; + } + + @override + String searchOptions(String label) { + return 'Cerca $label…'; + } + + @override + String get loadRecentProjectsFailed => + 'Impossibile caricare le librerie recenti. È comunque possibile aprire una libreria manualmente.'; + + @override + String get projectAccessFailed => 'Progetto non disponibile'; + + @override + String get projectMissingDirectory => 'Progetto non trovato'; + + @override + String get recentProjectSaveFailed => + 'Libreria aperta, ma non è stato possibile salvare il record recente della libreria.'; + + @override + String get lastProjectSaveFailed => + 'Progetto aperto, ma non è stato possibile salvare l\'ultimo record del progetto.'; + + @override + String get enterProjectName => 'Inserisci un nome per il progetto'; + + @override + String get projectSwitched => + 'Il progetto è cambiato. Trascina nuovamente il supporto.'; + + @override + String get notLocalMedia => 'Questo supporto non è un file locale'; + + @override + String get revealMediaFailed => + 'Impossibile mostrare i media nel file manager'; + + @override + String get openMatchingProject => 'Apri prima il progetto corrispondente'; + + @override + String get projectMismatch => + 'La libreria in questa posizione non corrisponde al record. Selezionalo di nuovo con Apri libreria.'; + + @override + String get openProjectFirst => 'Apri prima una libreria'; + + @override + String get localFilesOnly => 'Trascina i file locali dal file manager'; + + @override + String get foldersUnsupported => + 'Seleziona i file. Il trascinamento delle cartelle non è ancora supportato.'; + + @override + String get mediaImportCancelled => 'Importazione multimediale annullata'; + + @override + String get fileAccessFailed => + 'Il file è mancante o illeggibile. Controlla la sua posizione e le autorizzazioni'; + + @override + String get registerMediaFailed => + 'Impossibile registrare il supporto. Per favore riprova'; + + @override + String get mediaNoLongerExists => 'I media non esistono più'; + + @override + String get mediaNoTracks => + 'I contenuti multimediali non dispongono di tracce video o audio utilizzabili'; + + @override + String get invalidMediaDuration => 'Durata multimediale non valida'; + + @override + String get mediaInfoUnsupported => + 'La lettura delle informazioni multimediali non è ancora supportata su questa piattaforma'; + + @override + String get mediaInfoFailed => + 'Impossibile leggere le informazioni dei media. Controlla il file e i permessi di accesso'; + + @override + String get saveTimelineFailed => + 'Impossibile salvare la sequenza temporale. Riprova. Le modifiche non salvate rimangono in questa sessione.'; + + @override + String get addKeyframeAction => 'Aggiungi'; + + @override + String get backgroundTasks => 'Attività in background'; + + @override + String get noBackgroundTasks => 'Nessuna attività in background'; + + @override + String get retryTask => 'Riprova'; + + @override + String get applyOriginalCaptions => 'Applica sottotitoli originali'; + + @override + String get applyTranslatedCaptions => 'Applica sottotitoli tradotti'; + + @override + String get subtitleTaskStarted => 'Attività dei sottotitoli avviata'; + + @override + String get fitTimeline => 'Adatta intera timeline'; + + @override + String get modify => 'Modify'; + + @override + String get projectSettings => 'Project settings'; + + @override + String get projectSettingsDescription => + 'Change project output settings while keeping clip timing and speed.'; + + @override + String get projectColorSpace => 'Color space'; + + @override + String get projectWidth => 'Width (px)'; + + @override + String get projectHeight => 'Height (px)'; + + @override + String get projectResolutionInvalid => 'Enter a whole number from 1 to 16384'; + + @override + String get previewFullscreen => 'Anteprima a schermo intero'; + + @override + String get exitPreviewFullscreen => 'Esci da schermo intero'; + + @override + String get previewGoToStart => 'Vai all’inizio'; + + @override + String get previewPreviousFrame => 'Fotogramma precedente'; + + @override + String get previewNextFrame => 'Fotogramma successivo'; + + @override + String get softwareUpdates => 'Aggiornamenti'; + + @override + String get checkForUpdates => 'Cerca aggiornamenti'; + + @override + String get automaticallyCheckUpdates => 'Cerca aggiornamenti automaticamente'; + + @override + String get updatesUnavailable => + 'Aggiornamenti non disponibili per questa build.'; + + @override + String get updateCheckFailed => 'Impossibile cercare aggiornamenti. Riprova.'; + + @override + String get removeBackground => 'Rimuovi sfondo'; + + @override + String get startBackgroundRemoval => 'Rimuovi sfondo'; + + @override + String get backgroundRemovalResourceRequired => + 'La rimozione dello sfondo richiede un modello locale. Si avvia automaticamente dopo il download.'; + + @override + String get backgroundRemovalDownloadTask => + 'Scarica la risorsa per la rimozione dello sfondo'; + + @override + String get backgroundRemovalResourceName => + 'Modello di rimozione dello sfondo'; + + @override + String get backgroundRemovalDestructiveHint => + 'Il contenuto trasparente generato sostituirà questo clip. Puoi usare Annulla per ripristinare il clip originale.'; + + @override + String get backgroundRemovalTaskStarted => 'Rimozione dello sfondo avviata'; + + @override + String get startBackgroundRemovalFailed => + 'Impossibile avviare la rimozione dello sfondo. Controlla il contenuto o attendi il completamento dell’elaborazione corrente.'; + + @override + String get backgroundRemovalComplete => 'Rimozione dello sfondo completata'; + + @override + String get backgroundRemovalApplying => 'Sostituzione del contenuto del clip'; + + @override + String get backgroundRemovalFailed => 'Rimozione dello sfondo non riuscita'; + + @override + String get agentSettings => 'Agent'; + + @override + String get agentSaveSettingsFailed => + 'Impossibile salvare le impostazioni dell’Agent.'; + + @override + String get agentDeleteProviderTitle => 'Eliminare il provider?'; + + @override + String agentDeleteProviderDescription(String providerName) { + return '“$providerName” e la relativa chiave API salvata verranno rimossi da questo dispositivo.'; + } + + @override + String get agentProviderRequired => + 'Aggiungi un provider prima di attivare l’assistente.'; + + @override + String get agentUseSelectedModel => + 'Le nuove richieste dell’Agent useranno il modello selezionato.'; + + @override + String get agentEnable => 'Attiva Agent'; + + @override + String get agentDefaultModel => 'Modello predefinito'; + + @override + String get agentConfigureModel => 'Configura modelli'; + + @override + String get agentSelectModel => 'Seleziona modello'; + + @override + String get agentModelUnavailable => + 'Il modello di questa conversazione non è disponibile. Seleziona un altro modello per iniziare una nuova conversazione.'; + + @override + String get agentModelChangeSession => + 'La modifica del modello avvia una nuova sessione dell’Agent.'; + + @override + String get agentCustomProviders => 'Provider personalizzati'; + + @override + String get agentProviderStorageDescription => + 'I metadati del provider vengono salvati localmente. Le chiavi API vengono conservate nell’archivio credenziali di sistema.'; + + @override + String get agentAddProvider => 'Aggiungi provider'; + + @override + String get agentBackToProviders => 'Torna ai provider'; + + @override + String get agentLoadSettingsFailed => + 'Impossibile caricare le impostazioni dell’Agent. Riprova'; + + @override + String get agentEnableProvider => 'Abilita provider'; + + @override + String get agentEditProvider => 'Modifica provider'; + + @override + String get agentDeleteProvider => 'Elimina provider'; + + @override + String get agentModelIdsUnique => 'Gli ID modello devono essere univoci.'; + + @override + String get agentEditProviderTitle => 'Modifica provider'; + + @override + String get agentProviderEndpointDescription => + 'Configura un endpoint Chat Completions compatibile con OpenAI.'; + + @override + String get agentSaveProvider => 'Salva provider'; + + @override + String get agentProviderConfiguration => 'Configurazione del provider'; + + @override + String get agentAuthenticationAndModels => 'Autenticazione e modelli'; + + @override + String get agentApiType => 'Tipo di API'; + + @override + String get agentOpenAiChatCompletions => 'OpenAI Completions'; + + @override + String get agentBaseUrl => 'URL di base'; + + @override + String get agentApiKey => 'Chiave API'; + + @override + String get agentProviderNameHint => 'Il mio provider'; + + @override + String get agentApiKeyOptional => + 'Facoltativa per gli endpoint che non richiedono autenticazione.'; + + @override + String get agentApiKeyKeep => 'Lascia vuoto per mantenere la chiave salvata.'; + + @override + String get agentOptional => 'Facoltativo'; + + @override + String get agentApiKeyOneLine => + 'La chiave API deve essere su una sola riga.'; + + @override + String get agentRemoveSavedApiKey => 'Rimuovi la chiave API salvata'; + + @override + String get agentModels => 'Modelli'; + + @override + String get agentAddModel => 'Aggiungi modello'; + + @override + String get agentRequiredField => 'Questo campo è obbligatorio.'; + + @override + String get agentInvalidBaseUrl => + 'Inserisci un URL di base HTTP(S) senza credenziali, query o frammento.'; + + @override + String get agentModelId => 'ID modello'; + + @override + String get agentContextWindow => 'Finestra di contesto'; + + @override + String get agentMaxOutputTokens => 'Output massimo'; + + @override + String get agentMaxOutputBelowContext => + 'Deve essere inferiore alla finestra di contesto.'; + + @override + String get agentDeleteModel => 'Elimina modello'; + + @override + String get agentPositiveInteger => 'Inserisci un numero intero positivo.'; + + @override + String get agentConfigurationReadFailed => + 'Impossibile leggere la configurazione dell’Agent. Controlla le impostazioni e riprova.'; + + @override + String get agentConfigurationRequired => + 'Prima configura e attiva l’Agent nelle Impostazioni.'; + + @override + String get agentSessionRestoreFailed => + 'Impossibile ripristinare la sessione dell’Agent. Riprova più tardi.'; + + @override + String get agentContextBudgetExceeded => + 'Spazio di input insufficiente per istruzioni, strumenti e messaggio. Aumenta il contesto o riduci l’output massimo.'; + + @override + String get agentAuthenticationFailed => + 'Autenticazione non riuscita. Controlla API Key e autorizzazioni.'; + + @override + String get agentConnectionFailed => + 'Connessione non riuscita o scaduta. Controlla Base URL e rete.'; + + @override + String get agentProtocolFailed => + 'La risposta non corrisponde al tipo API scelto o il flusso è incompleto.'; + + @override + String get agentContextBudgetTooSmall => + 'Riserva più spazio per le istruzioni. Aumenta il contesto o riduci l’output massimo.'; + + @override + String get agentCompacting => 'Organizzazione del contesto…'; + + @override + String get agentEditing => 'Modifica in corso…'; + + @override + String get agentVerifying => 'Verifica dei risultati…'; + + @override + String get agentTurnLimitReached => + 'La procedura ha raggiunto il limite di esecuzione. Le modifiche sono state salvate. Invia «Continua» per riprendere.'; + + @override + String get agentRecoveryRequired => + 'Il risultato precedente non è confermato. Riprendi per verificare i dati salvati; le modifiche non confermate non verranno ripetute.'; + + @override + String get agentExportReplyFailed => + 'Video esportato. La risposta di riepilogo non è riuscita. Riprova senza ripetere modifiche o esportazione.'; + + @override + String get agentRetrySummary => 'Riprova riepilogo'; + + @override + String get agentResumeTask => 'Riprendi attività'; + + @override + String get agentTaskInterrupted => + 'L’attività è stata interrotta. Riprendi dai progressi salvati.'; + + @override + String get downloadSubtitleModel => 'Scarica il modello per i sottotitoli'; + + @override + String get downloadModelAction => 'Scarica'; + + @override + String get subtitleEngineUnavailable => + 'Il modello è installato, ma il motore dei sottotitoli non si è avviato. Ripara il motore; non occorre scaricare nuovamente il modello.'; + + @override + String get backgroundTaskDetails => 'Dettagli attività'; + + @override + String get backgroundTaskFailed => 'Non riuscita'; + + @override + String get backgroundTaskCompleted => 'Completata'; + + @override + String get captionWrapLines => 'A capo automatico dei sottotitoli'; + + @override + String get captionSingleLine => 'Mostra sottotitoli su una riga'; + + @override + String get noMatchingCaptions => 'Nessun sottotitolo corrispondente'; + + @override + String get subtitleResourcesRequired => + 'Queste risorse sono necessarie per i sottotitoli. La generazione inizierà automaticamente dopo il download.'; + + @override + String subtitleResourcesDownloadSize(String size) { + return 'Da scaricare: $size'; + } + + @override + String get pauseDownload => 'Pausa'; + + @override + String get resumeDownload => 'Riprendi'; + + @override + String get downloadPaused => 'In pausa'; + + @override + String get cancelResourceDownloadTitle => 'Annullare il download?'; + + @override + String get cancelResourceDownloadMessage => + 'Il download si interromperà. I progressi della risorsa corrente potrebbero andare persi.'; + + @override + String get continueDownload => 'Continua il download'; + + @override + String get cancelDownload => 'Annulla il download'; + + @override + String get speechResourceStage => 'Risorsa di riconoscimento vocale'; + + @override + String get translationResourceStage => 'Risorsa di traduzione'; + + @override + String get subtitleResourceDownloadTask => + 'Scarica risorse vocali e di traduzione'; + + @override + String get downloadingSpeechModel => 'Download del modello vocale'; + + @override + String get downloadingTranslationModel => + 'Download del modello di traduzione'; + + @override + String get checkingForUpdates => 'Ricerca aggiornamenti…'; + + @override + String get appIsUpToDate => 'L’app è aggiornata.'; + + @override + String downloadingUpdate(int progress) { + return 'Download aggiornamento: $progress%'; + } + + @override + String updateAvailable(String version) { + return 'È disponibile la versione $version.'; + } + + @override + String get downloadUpdate => 'Scarica aggiornamento'; + + @override + String get restartToUpdate => 'Riavvia e aggiorna'; + + @override + String get updateOperationFailed => + 'Aggiornamento non riuscito. Completa le attività in corso e riprova.'; + + @override + String get windowMinimize => 'Riduci a icona'; + + @override + String get windowMaximize => 'Ingrandisci'; + + @override + String get windowRestore => 'Ripristina'; + + @override + String get workspaceAgent => 'Assistente'; + + @override + String get workspaceCut => 'Montaggio'; + + @override + String get noAvailableOptions => 'Nessuna opzione disponibile'; + + @override + String get composerReferenceInvalid => + 'Un riferimento non è più valido. Torna al suo progetto o rimuovilo.'; + + @override + String durationSeconds(int seconds) { + return '$seconds s'; + } + + @override + String durationMinutesSeconds(int minutes, int seconds) { + return '$minutes min $seconds s'; + } + + @override + String get projectNameInvalid => 'Nome del progetto non valido'; + + @override + String get projectLocationDefaultUnavailable => + 'Impossibile accedere alla posizione predefinita dei progetti. Selezionala di nuovo nelle impostazioni.'; + + @override + String get chooseProjectLocation => + 'Seleziona prima una posizione di salvataggio dei progetti nelle impostazioni.'; + + @override + String get untitledTimeline => 'Timeline senza titolo'; + + @override + String get primarySequence => 'Sequenza principale'; + + @override + String get primaryStoryline => 'Linea principale'; + + @override + String get projectSessionClosed => + 'La sessione del progetto è chiusa. Riapri il progetto.'; + + @override + String get timelineSessionClosed => + 'La sessione della timeline è chiusa. Riapri la timeline.'; + + @override + String get timelineMissing => 'La timeline non esiste o è stata eliminata.'; + + @override + String get timelineInUse => + 'La timeline è in uso e non può ancora essere eliminata.'; + + @override + String get timelineHasBackgroundTasks => + 'Completa le attività in background della timeline prima di eliminarla.'; + + @override + String get timelineRequired => + 'Un progetto deve mantenere almeno una timeline.'; + + @override + String get mediaReadFailed => 'Impossibile leggere il file multimediale'; + + @override + String get mediaImportFailed => 'Impossibile importare il file multimediale'; + + @override + String get unsupportedMediaType => + 'È possibile importare solo file video, audio e immagini.'; + + @override + String get mediaNoVideoTracks => + 'Il file multimediale non contiene una traccia video utilizzabile'; + + @override + String get mediaDurationOutOfRange => + 'La durata del file multimediale supera l’intervallo della timeline'; + + @override + String resourceDownloadHttpFailed(String statusCode) { + return 'Download non riuscito (HTTP $statusCode)'; + } + + @override + String get resourceChecksumFailed => + 'Verifica del file del modello non riuscita. Scarica di nuovo la risorsa.'; + + @override + String get subtitleLanguageAf => 'afrikaans'; + + @override + String get subtitleLanguageAm => 'amarico'; + + @override + String get subtitleLanguageAr => 'arabo'; + + @override + String get subtitleLanguageAst => 'asturiano'; + + @override + String get subtitleLanguageAz => 'azerbaigiano'; + + @override + String get subtitleLanguageBa => 'baschiro'; + + @override + String get subtitleLanguageBe => 'bielorusso'; + + @override + String get subtitleLanguageBg => 'bulgaro'; + + @override + String get subtitleLanguageBn => 'bengalese'; + + @override + String get subtitleLanguageBr => 'bretone'; + + @override + String get subtitleLanguageBs => 'bosniaco'; + + @override + String get subtitleLanguageCa => 'catalano'; + + @override + String get subtitleLanguageCeb => 'cebuano'; + + @override + String get subtitleLanguageCs => 'ceco'; + + @override + String get subtitleLanguageCy => 'gallese'; + + @override + String get subtitleLanguageDa => 'danese'; + + @override + String get subtitleLanguageDe => 'tedesco'; + + @override + String get subtitleLanguageEl => 'greco'; + + @override + String get subtitleLanguageEn => 'inglese'; + + @override + String get subtitleLanguageEs => 'spagnolo'; + + @override + String get subtitleLanguageEt => 'estone'; + + @override + String get subtitleLanguageFa => 'persiano'; + + @override + String get subtitleLanguageFf => 'fulah'; + + @override + String get subtitleLanguageFi => 'finlandese'; + + @override + String get subtitleLanguageFr => 'francese'; + + @override + String get subtitleLanguageFy => 'frisone occidentale'; + + @override + String get subtitleLanguageGa => 'irlandese'; + + @override + String get subtitleLanguageGd => 'gaelico scozzese'; + + @override + String get subtitleLanguageGl => 'galiziano'; + + @override + String get subtitleLanguageGu => 'gujarati'; + + @override + String get subtitleLanguageHa => 'hausa'; + + @override + String get subtitleLanguageHe => 'ebraico'; + + @override + String get subtitleLanguageHi => 'hindi'; + + @override + String get subtitleLanguageHr => 'croato'; + + @override + String get subtitleLanguageHt => 'creolo haitiano'; + + @override + String get subtitleLanguageHu => 'ungherese'; + + @override + String get subtitleLanguageHy => 'armeno'; + + @override + String get subtitleLanguageId => 'indonesiano'; + + @override + String get subtitleLanguageIg => 'igbo'; + + @override + String get subtitleLanguageIlo => 'ilocano'; + + @override + String get subtitleLanguageIs => 'islandese'; + + @override + String get subtitleLanguageIt => 'italiano'; + + @override + String get subtitleLanguageJa => 'giapponese'; + + @override + String get subtitleLanguageJv => 'giavanese'; + + @override + String get subtitleLanguageKa => 'georgiano'; + + @override + String get subtitleLanguageKk => 'kazako'; + + @override + String get subtitleLanguageKm => 'khmer'; + + @override + String get subtitleLanguageKn => 'kannada'; + + @override + String get subtitleLanguageKo => 'coreano'; + + @override + String get subtitleLanguageLb => 'lussemburghese'; + + @override + String get subtitleLanguageLg => 'ganda'; + + @override + String get subtitleLanguageLn => 'lingala'; + + @override + String get subtitleLanguageLo => 'lao'; + + @override + String get subtitleLanguageLt => 'lituano'; + + @override + String get subtitleLanguageLv => 'lettone'; + + @override + String get subtitleLanguageMg => 'malgascio'; + + @override + String get subtitleLanguageMk => 'macedone'; + + @override + String get subtitleLanguageMl => 'malayalam'; + + @override + String get subtitleLanguageMn => 'mongolo'; + + @override + String get subtitleLanguageMr => 'marathi'; + + @override + String get subtitleLanguageMs => 'malese'; + + @override + String get subtitleLanguageMy => 'birmano'; + + @override + String get subtitleLanguageNe => 'nepalese'; + + @override + String get subtitleLanguageNl => 'olandese'; + + @override + String get subtitleLanguageNo => 'norvegese'; + + @override + String get subtitleLanguageNs => 'sotho del nord'; + + @override + String get subtitleLanguageOc => 'occitano'; + + @override + String get subtitleLanguageOr => 'odia'; + + @override + String get subtitleLanguagePa => 'punjabi'; + + @override + String get subtitleLanguagePl => 'polacco'; + + @override + String get subtitleLanguagePs => 'pashto'; + + @override + String get subtitleLanguagePt => 'portoghese'; + + @override + String get subtitleLanguageRo => 'rumeno'; + + @override + String get subtitleLanguageRu => 'russo'; + + @override + String get subtitleLanguageSd => 'sindhi'; + + @override + String get subtitleLanguageSi => 'singalese'; + + @override + String get subtitleLanguageSk => 'slovacco'; + + @override + String get subtitleLanguageSl => 'sloveno'; + + @override + String get subtitleLanguageSo => 'somalo'; + + @override + String get subtitleLanguageSq => 'albanese'; + + @override + String get subtitleLanguageSr => 'serbo'; + + @override + String get subtitleLanguageSs => 'swati'; + + @override + String get subtitleLanguageSu => 'sundanese'; + + @override + String get subtitleLanguageSv => 'svedese'; + + @override + String get subtitleLanguageSw => 'swahili'; + + @override + String get subtitleLanguageTa => 'tamil'; + + @override + String get subtitleLanguageTh => 'thailandese'; + + @override + String get subtitleLanguageTl => 'tagalog'; + + @override + String get subtitleLanguageTn => 'tswana'; + + @override + String get subtitleLanguageTr => 'turco'; + + @override + String get subtitleLanguageUk => 'ucraino'; + + @override + String get subtitleLanguageUr => 'urdu'; + + @override + String get subtitleLanguageUz => 'uzbeco'; + + @override + String get subtitleLanguageVi => 'vietnamita'; + + @override + String get subtitleLanguageWo => 'wolof'; + + @override + String get subtitleLanguageXh => 'xhosa'; + + @override + String get subtitleLanguageYi => 'yiddish'; + + @override + String get subtitleLanguageYo => 'yoruba'; + + @override + String get subtitleLanguageYue => 'cantonese'; + + @override + String get subtitleLanguageZh => 'cinese'; + + @override + String get subtitleLanguageZu => 'zulu'; + + @override + String get linearRec2020 => 'Rec.2020 lineare'; + + @override + String get diagnostics => 'Diagnostica'; + + @override + String get exportDiagnostics => 'Esporta pacchetto diagnostico'; + + @override + String get exportDiagnosticsFailed => + 'Impossibile esportare la diagnostica. Riprova.'; + + @override + String get exportDiagnosticsSucceeded => 'Pacchetto diagnostico salvato.'; +} diff --git a/lib/l10n/app_localizations_ja.dart b/lib/l10n/app_localizations_ja.dart new file mode 100644 index 0000000..e02fd46 --- /dev/null +++ b/lib/l10n/app_localizations_ja.dart @@ -0,0 +1,2133 @@ +// ignore: unused_import +import 'package:intl/intl.dart' as intl; + +import 'app_localizations.dart'; + +// ignore_for_file: type=lint + +/// The translations for Japanese (`ja`). +class AppLocalizationsJa extends AppLocalizations { + AppLocalizationsJa([String locale = 'ja']) : super(locale); + + @override + String get selectProject => 'プロジェクトを選択'; + + @override + String get searchProjects => 'プロジェクトを検索'; + + @override + String get noMatchingProjects => '一致するプロジェクトがありません'; + + @override + String get projectsNone => 'プロジェクトがありません'; + + @override + String get projectLocationMissing => 'フォルダが存在しません。プロジェクト作成時に作成されます。'; + + @override + String get projectLocationUnavailable => + 'プロジェクトの保存先を利用できません。ディスクやネットワークを確認して再試行するか、保存先を変更してください。'; + + @override + String get projectLocationNotWritable => + 'プロジェクトの保存先に書き込めません。アクセス権を確認するか、保存先を変更してください。'; + + @override + String get projectLocationCreateFailed => + 'プロジェクト保存フォルダの作成または書き込みに失敗しました。アクセス権を確認するか、保存先を変更してください。'; + + @override + String get removeProjectFromSidebar => 'サイドバーから削除'; + + @override + String get projectRemoved => 'プロジェクトを一覧から削除しました。ローカルファイルと会話は保持されます。'; + + @override + String get agentNoConversations => 'まだ会話がありません'; + + @override + String get renameConversationTitle => 'チャットの名前を変更'; + + @override + String get renameConversationDescription => '短く分かりやすい名前にしてください。'; + + @override + String get collapseProject => 'プロジェクトを折りたたむ'; + + @override + String get expandProject => 'プロジェクトを展開'; + + @override + String agentDeleteConfirmation(String title) { + return '「$title」とすべてのメッセージを完全に削除しますか?この操作は取り消せません。ローカルのプロジェクトファイルには影響しません。'; + } + + @override + String get agentEmptyTrashConfirmation => + 'ゴミ箱内のすべての会話を完全に削除しますか?この操作は取り消せません。ローカルのプロジェクトファイルには影響しません。'; + + @override + String get agentConversations => '会話'; + + @override + String get showMoreConversations => 'さらに表示'; + + @override + String get showFewerConversations => '表示を減らす'; + + @override + String get agentNewConversation => '新しい会話'; + + @override + String agentElapsedTime(String duration) { + return '所要時間 $duration'; + } + + @override + String get agentConversationActions => '会話の操作'; + + @override + String get agentMoveToTrash => 'ゴミ箱に移動'; + + @override + String get agentTrash => 'ゴミ箱'; + + @override + String get agentRestore => '復元'; + + @override + String get agentEmptyTrash => 'ゴミ箱を空にする'; + + @override + String get agentDeleteForever => '完全に削除'; + + @override + String get agentConversationLocation => '会話の保存先'; + + @override + String get agentChooseExistingConversations => '既存の会話を選択'; + + @override + String get agentMoveConversations => '会話を移動'; + + @override + String get agentLocationUnavailable => '会話の保存先を利用できません'; + + @override + String get agentLocationBusy => '実行中の会話が終了してから移動してください'; + + @override + String get agentRelinkProvider => 'プロバイダーを再関連付け'; + + @override + String get settings => '設定'; + + @override + String get closeSettings => '設定を閉じる'; + + @override + String get general => '一般'; + + @override + String get appearance => '外観'; + + @override + String get theme => 'テーマ'; + + @override + String get system => 'システムに合わせる'; + + @override + String get light => 'ライト'; + + @override + String get dark => 'ダーク'; + + @override + String get saveAppearanceFailed => '外観を保存できませんでした。もう一度試してください。'; + + @override + String get loadAppearanceFailed => '外観を読み込めませんでした。テーマを再度選択してください。'; + + @override + String get cancel => 'キャンセル'; + + @override + String get save => '保存'; + + @override + String get create => '作成'; + + @override + String get close => '閉じる'; + + @override + String get retry => '再試行'; + + @override + String get select => '選択'; + + @override + String get name => '名前'; + + @override + String get enterName => '名前を入力してください'; + + @override + String get invalidName => '名前にパス区切り文字や制御文字を含めることはできません'; + + @override + String get projects => 'プロジェクト'; + + @override + String get projectName => 'プロジェクト名'; + + @override + String get projectLocation => 'プロジェクトの保存先'; + + @override + String get projectLocationNotSet => '未設定'; + + @override + String get loadProjectLocationFailed => 'プロジェクトの保存先を読み込めませんでした。'; + + @override + String get saveProjectLocationFailed => 'プロジェクトの保存先を保存できませんでした。'; + + @override + String get resourceLocation => 'リソースの保存先'; + + @override + String get resourceLocationNotSet => '未設定'; + + @override + String get loadResourceLocationFailed => 'リソースの保存先を読み込めませんでした。'; + + @override + String get saveResourceLocationFailed => 'リソースの保存先を保存できませんでした。'; + + @override + String get transcriptionResourceRequired => + '字幕を生成するには、まず音声認識モデルをダウンロードする必要があります。'; + + @override + String get downloadAndContinue => 'ダウンロードして続行'; + + @override + String get downloadingResource => 'ダウンロード中…'; + + @override + String get downloadInBackground => 'バックグラウンドでダウンロード'; + + @override + String get processingResourceDownloadFailed => + '音声認識リソースをダウンロードできませんでした。もう一度お試しください。'; + + @override + String get newProject => '新規プロジェクト'; + + @override + String get openProject => 'プロジェクトを開く'; + + @override + String get openProjectMore => '別のプロジェクトを開く'; + + @override + String get saveHere => 'ここに保存'; + + @override + String get selectDirectoryFailed => 'ディレクトリを選択できませんでした。システム権限を確認してください。'; + + @override + String get openingWorkspace => 'ワークスペースを開いています…'; + + @override + String get loadProjectsFailed => 'プロジェクトを読み込めませんでした'; + + @override + String get projectsEmpty => 'プロジェクトがありません'; + + @override + String get backToProjects => '編集に戻る'; + + @override + String get timelines => 'タイムライン'; + + @override + String timelineLimitReached(int count) { + return '1つのプロジェクトに作成できるタイムラインは最大$count件です。'; + } + + @override + String get timelineName => 'タイムライン名'; + + @override + String defaultTimelineName(int index) { + return 'タイムライン $index'; + } + + @override + String get newTimeline => '新規タイムライン'; + + @override + String get noTimelines => 'タイムラインがありません'; + + @override + String get activeTimeline => '現在のタイムライン'; + + @override + String get timelineUnavailable => 'タイムラインを利用できません'; + + @override + String get projectNoTimelines => 'このプロジェクトにはタイムラインがありません'; + + @override + String get createTimelineHint => '左側の「タイムライン」から新しいタイムラインを作成して編集を開始します。'; + + @override + String get createTimelineChat => 'タイムラインを作成するとチャットを開始できます'; + + @override + String get operationFailed => '操作が失敗しました。もう一度試してください。'; + + @override + String get collapseSidebar => 'サイドバーを折りたたむ'; + + @override + String get expandSidebar => 'サイドバーを展開する'; + + @override + String get expandEditor => '編集エリアを展開'; + + @override + String get collapseProperties => 'プロパティを折りたたむ'; + + @override + String get expandProperties => 'プロパティを展開する'; + + @override + String get layout => 'レイアウト'; + + @override + String get editingFirstLayout => '編集優先'; + + @override + String get agentEditingLayout => 'エージェントと編集'; + + @override + String get agentLayoutDescription => '計画、共同作業、実行'; + + @override + String get editingLayoutDescription => 'プレビュー、編集、調整'; + + @override + String get materials => 'メディア'; + + @override + String get all => 'すべて'; + + @override + String get video => 'ビデオ'; + + @override + String get audio => 'オーディオ'; + + @override + String get image => '画像'; + + @override + String get picture => '画像'; + + @override + String get captions => '字幕'; + + @override + String get text => '文章'; + + @override + String get noMedia => 'メディアがありません'; + + @override + String get mediaCategory => 'メディアの種類'; + + @override + String get captionTasks => '字幕タスク'; + + @override + String get listLayout => 'リストビュー'; + + @override + String get gridLayout => 'グリッドビュー'; + + @override + String get addToTimeline => 'タイムラインに追加'; + + @override + String get rename => '名前を変更'; + + @override + String get renameMedia => 'メディアの名前を変更'; + + @override + String get removeMedia => 'メディアを削除'; + + @override + String get remove => '削除'; + + @override + String get revealFinder => 'Finderで表示'; + + @override + String get revealFileManager => 'ファイルマネージャーで表示'; + + @override + String get dropToAdd => '離して追加'; + + @override + String get timelineDropToStart => 'メディアをここにドラッグして開始します。'; + + @override + String get dragMediaHint => 'ビデオ、オーディオ、または画像をここにドラッグします\n元のファイルは現在の場所に残ります'; + + @override + String get transcribe => '文字起こし'; + + @override + String get generateCaptions => '字幕を生成'; + + @override + String get play => '再生'; + + @override + String get pause => '一時停止'; + + @override + String get retryPreview => 'プレビューを再試行する'; + + @override + String get canvasRatio => 'キャンバスの縦横比'; + + @override + String get noPreviewContent => 'タイムラインにプレビューするコンテンツがありません'; + + @override + String get nativePreviewUnsupported => 'このプラットフォームではネイティブ プレビューを利用できません'; + + @override + String get canvasTransformFailed => 'キャンバスを変形できませんでした。もう一度試してください。'; + + @override + String get undo => '元に戻す'; + + @override + String get redo => 'やり直す'; + + @override + String get deleteSelectedClips => '選択したクリップを削除します'; + + @override + String get splitAtPlayhead => '再生ヘッドで分割'; + + @override + String get trimLeft => '左側をトリム'; + + @override + String get trimRight => '右側をトリム'; + + @override + String get trimLeftTooltip => '再生ヘッドの左側を削除し、右側を保持'; + + @override + String get trimRightTooltip => '再生ヘッドの右側を削除し、左側を保持'; + + @override + String get currentSequence => '現在のシーケンス'; + + @override + String get projectProperties => 'プロジェクトのプロパティ'; + + @override + String get canvasSize => 'キャンバスサイズ'; + + @override + String get frameRate => 'フレームレート'; + + @override + String get duration => '間隔'; + + @override + String get totalDuration => '合計期間'; + + @override + String get clipDuration => 'クリップの長さ'; + + @override + String get seconds => '秒'; + + @override + String get clip => 'クリップ'; + + @override + String get unnamedClip => '名称未設定のクリップ'; + + @override + String get gap => 'ギャップ'; + + @override + String get compoundClip => '複合クリップ'; + + @override + String get textClip => 'テキストクリップ'; + + @override + String get pictureProperties => '映像'; + + @override + String get position => '位置'; + + @override + String get rotation => '回転'; + + @override + String get scale => '拡大縮小'; + + @override + String get size => 'サイズ'; + + @override + String get transform => '変形'; + + @override + String get resetPosition => '位置をリセット'; + + @override + String get keepAspectRatio => 'アスペクト比をロックする'; + + @override + String get alignment => '配置'; + + @override + String get alignLeft => '左揃え'; + + @override + String get alignRight => '右揃え'; + + @override + String get alignTop => '上揃え'; + + @override + String get alignBottom => '下揃え'; + + @override + String get alignHorizontalCenter => '水平方向に中央揃え'; + + @override + String get alignVerticalCenter => '垂直方向に中央揃え'; + + @override + String get volume => '音量'; + + @override + String get gain => 'ゲイン'; + + @override + String get mute => 'ミュート'; + + @override + String get unmute => 'ミュート解除'; + + @override + String get resetVolume => '音量をリセットする'; + + @override + String get invalidGain => '-90 ~ +12 の値を入力してください'; + + @override + String get animation => 'アニメーション'; + + @override + String get keyframes => 'キーフレーム'; + + @override + String get removeAllKeyframes => 'すべてのキーフレームを削除します'; + + @override + String get linear => 'リニア'; + + @override + String get easeIn => 'イーズイン'; + + @override + String get easeOut => 'イーズアウト'; + + @override + String get easeInOut => 'イーズインアウト'; + + @override + String get basic => '基本'; + + @override + String get mask => 'マスク'; + + @override + String get addMask => 'マスクの追加'; + + @override + String get deleteMask => 'マスクの削除'; + + @override + String get resetMask => 'マスクをリセット'; + + @override + String get enableMask => 'マスクを有効にする'; + + @override + String get disableMask => 'マスクを無効にする'; + + @override + String get moveMaskUp => 'マスクを上に移動します'; + + @override + String get moveMaskDown => 'マスクを下に移動します'; + + @override + String get rectangle => '長方形'; + + @override + String get ellipse => '楕円'; + + @override + String get invert => '反転'; + + @override + String get feather => 'ぼかし'; + + @override + String get add => '加算'; + + @override + String get subtract => '減算'; + + @override + String get intersect => '交差'; + + @override + String get initialRegion => '初期領域'; + + @override + String get none => 'なし'; + + @override + String get color => '色'; + + @override + String get fontSize => 'フォントサイズ'; + + @override + String get outlineWidth => '縁取りの幅'; + + @override + String get outlineColor => '縁取りの色'; + + @override + String get captionBaseline => '字幕のベースライン'; + + @override + String get content => 'テキスト'; + + @override + String get start => '開始'; + + @override + String get time => '時間'; + + @override + String get speed => 'スピード'; + + @override + String speedSegmentCount(int count) { + return '速度区間:$count'; + } + + @override + String get splitSpeedAtPlayhead => '再生ヘッドで速度を分割'; + + @override + String get speedChange => 'スピード'; + + @override + String get speedMode => '速度モード'; + + @override + String get constantSpeed => '一定速度'; + + @override + String get segmentedSpeed => '分割速度'; + + @override + String get speedNotAvailable => '速度制御はまだ利用できません'; + + @override + String get custom => 'カスタム'; + + @override + String get invalidNumber => '無効な値'; + + @override + String get mediaUnavailable => 'メディアが利用できません'; + + @override + String get mediaMissing => 'メディアが見つかりません'; + + @override + String get mediaColorSpace => 'メディアの色空間'; + + @override + String get mediaColorInterpretation => 'メディアの色の解釈'; + + @override + String get colorInfoNotLoaded => 'カラー情報が読み込まれていません'; + + @override + String get unknownColorSpace => '不明な色空間。 Rec.709として表示されます。'; + + @override + String get colorBackendUnsupported => '現在のバックエンドはメディアの色の解釈をサポートしていません。'; + + @override + String get loadClipPropertiesFailed => 'クリップのプロパティを読み取れませんでした'; + + @override + String get updatePictureFailed => '画像のプロパティを更新できませんでした'; + + @override + String get updateVolumeFailed => 'ボリュームを更新できませんでした'; + + @override + String get updateMaskFailed => 'マスクを更新できませんでした'; + + @override + String get updateKeyframesFailed => 'キーフレームを更新できませんでした'; + + @override + String get maskPreviewFailed => 'マスクのプレビューを準備できませんでした'; + + @override + String get alignClipFailed => + 'クリップを位置合わせできませんでした。プレビューが表示されるまで待ってから、もう一度試してください。'; + + @override + String get invalidTransform => + 'スケールは 1% ~ 10000% である必要があります。位置と角度は有効な数値でなければなりません。'; + + @override + String get editFailed => '編集できませんでした。入力と時間範囲を確認してください。'; + + @override + String get addMediaFailed => 'メディアを追加できませんでした。もう一度試してください。'; + + @override + String get deleteCaption => '字幕を削除'; + + @override + String get mergeCaptions => '字幕を結合'; + + @override + String get captionDeleted => '字幕を削除しました'; + + @override + String get captionChanged => '字幕が変更されました。もう一度試してください。'; + + @override + String get captionEditChanged => '字幕が変更されました。再度編集してください。'; + + @override + String get assistantHint => '編集のアイデアを説明してください'; + + @override + String get configureAgentHint => 'チャットを開始するようにエージェント サービスを構成する'; + + @override + String get agentRestartHint => 'エージェント サービスを構成し、アプリを再起動します。'; + + @override + String get replyInterrupted => '応答が中断されました'; + + @override + String get replying => '応答中…'; + + @override + String get stopReply => '応答を停止'; + + @override + String get sendMessage => 'メッセージを送信'; + + @override + String get addAttachment => '添付ファイルを追加します (まだ利用できません)'; + + @override + String get replyFailed => '応答に失敗しました。接続を確認するか、後でもう一度試してください。'; + + @override + String get mcpService => 'MCPサービス'; + + @override + String get listenPort => 'ポート'; + + @override + String get accessToken => 'アクセストークン'; + + @override + String get copyAccessToken => 'アクセストークンをコピーする'; + + @override + String get accessTokenCopied => 'アクセストークンがコピーされました'; + + @override + String get loadMcpFailed => 'MCP 設定をロードできませんでした。リトライ'; + + @override + String get saveMcpFailed => 'MCP設定を保存できませんでした。もう一度試してください。'; + + @override + String get retryStart => 'リトライスタート'; + + @override + String get invalidPort => 'ポートは 1 ~ 65535 でなければなりません'; + + @override + String get loadingSettings => '設定を読み込み中…'; + + @override + String get starting => '起動中…'; + + @override + String get stopping => '停止中…'; + + @override + String get disabled => '無効'; + + @override + String get running => '実行中'; + + @override + String get startFailed => '開始に失敗しました'; + + @override + String get saved => '保存済み'; + + @override + String get unsaved => '未保存'; + + @override + String get saving => '保存中…'; + + @override + String get pendingSave => '保存保留中'; + + @override + String get notApplied => '未適用'; + + @override + String get enable => '有効にする'; + + @override + String get disable => '無効にする'; + + @override + String get type => '種類'; + + @override + String get status => '状態'; + + @override + String get file => 'ファイル'; + + @override + String get unboundMedia => 'メディア未設定'; + + @override + String get unboundAudio => '音声トラック未設定'; + + @override + String get vertical => '垂直'; + + @override + String get language => '言語'; + + @override + String get saveLanguageFailed => '言語を保存できませんでした。もう一度試してください。'; + + @override + String get loadLanguageFailed => '言語をロードできませんでした。再度選択してください。'; + + @override + String get propertiesFirstLayout => '最初にプロパティ'; + + @override + String get defaultLayout => 'デフォルトのレイアウト'; + + @override + String get separateVocals => 'ボーカルを分離'; + + @override + String get detachAudio => '音声を分離'; + + @override + String get restoreAudio => '音声を復元'; + + @override + String get audioDetached => '音声は分離済みです'; + + @override + String get addAll => 'すべて追加'; + + @override + String get preparingMedia => 'メディアを準備中…'; + + @override + String get cancelling => 'キャンセル中…'; + + @override + String get cancelled => 'キャンセル済み'; + + @override + String get interruptedTask => 'タスクが中断されました。続行するには再起動してください'; + + @override + String get auto => '自動'; + + @override + String get autoDetect => '自動検出'; + + @override + String get noTranslation => '翻訳しない'; + + @override + String get sourceLanguage => '元の言語'; + + @override + String get translationLanguage => '翻訳先の言語'; + + @override + String get transcriptionNotConfigured => + '文字起こしが設定されていません。認識コンポーネントと Whisper Turbo モデルをインストールします。'; + + @override + String get translationNotConfigured => '字幕翻訳が設定されていません。ソース言語で字幕を生成できます。'; + + @override + String get sourceLanguageUnknown => '翻訳のソース言語を決定できませんでした。'; + + @override + String get startTranscriptionFailed => + '文字起こしを開始できませんでした。メディアを確認するか、現在のタスクが完了するまで待ちます。'; + + @override + String get placeMediaFirst => '字幕を適用する前に、このメディアをタイムライン上に配置します。'; + + @override + String get placeTranslationMediaFirst => + '翻訳された字幕を適用する前に、対応するメディアをタイムライン上に配置します。'; + + @override + String get selectTargetClip => 'ターゲットクリップを選択'; + + @override + String get timelineChanged => 'タイムラインが変わりました。対象のクリップを再度選択してください。'; + + @override + String get transcriptionAccessFailed => + '転写に失敗しました: コンポーネント、モデル、またはソース メディアにアクセスできません (notConfigured)'; + + @override + String get transcriptionNoAudio => + '文字起こしに失敗しました: 選択したメディアまたはトラックに認識可能な音声がありません (noAudio)'; + + @override + String get transcriptionInvalidResult => + '文字起こしに失敗しました: 無効な字幕 ファイルが返されました (invalidResult)'; + + @override + String get transcriptionWorkerExited => + '転写に失敗しました: 認識コンポーネントが予期せず終了しました (workerExited)'; + + @override + String get transcriptionProcessingFailed => + '転写に失敗しました: ネイティブ処理に失敗しました (processingFailed)'; + + @override + String get transcriptionFailed => + '転写に失敗しました。コンポーネント、モデル、オーディオトラック、およびデュレーションを確認してください'; + + @override + String get transcribing => '文字起こし中…'; + + @override + String get captionsGenerated => '字幕を生成しました'; + + @override + String get cancelTranscription => '文字起こしをキャンセル'; + + @override + String get applyCaptions => '字幕を適用'; + + @override + String get preparingTranslation => '翻訳を準備中…'; + + @override + String get translatingCaptions => '字幕を翻訳中…'; + + @override + String get cancellingTranslation => '翻訳をキャンセル中…'; + + @override + String get translatedCaptionsGenerated => '翻訳字幕を生成しました'; + + @override + String get translationCancelled => '翻訳をキャンセルしました'; + + @override + String get translationInterrupted => '翻訳が中断されました'; + + @override + String get cancelTranslation => '翻訳をキャンセル'; + + @override + String get editorServiceUnavailable => '編集サービスは利用できません。プロジェクトを再度開きます。'; + + @override + String get mcpUnavailable => 'MCP 接続が利用できません。ローカルポートとトークンを確認してください。'; + + @override + String get openTimelineFailed => 'タイムラインを開けませんでした'; + + @override + String get noTimelineSequence => 'このタイムラインにはシーケンスがありません。'; + + @override + String get waitingForProject => 'プロジェクトが開くのを待っています'; + + @override + String get hold => 'ホールド'; + + @override + String get noImportableFiles => 'インポート可能なファイルを受信しませんでした'; + + @override + String get virtualFilesUnsupported => + 'ファイルマネージャーから元のファイルをドラッグします。仮想ファイルはまだサポートされていません。'; + + @override + String get editorSessionStartFailed => 'タイムラインエディターを開けませんでした'; + + @override + String get previewStartFailed => 'ネイティブ プレビューを開始できませんでした'; + + @override + String get previewInvalidTrack => '選択したオーディオまたはビデオ トラックがメディアに存在しません。'; + + @override + String get previewMissingBinding => + 'メディア バインディングがありません。このタイムラインをプレビューできませんでした。'; + + @override + String get previewUnsupportedEdits => + 'このタイムラインには、プレビューでまだ​​サポートされていない編集が含まれています。'; + + @override + String get previewUnsupportedConfiguration => + 'このプレビュー構成は、現在のプラットフォームまたはシステム バージョンではサポートされていません。'; + + @override + String get previewHdrUnsupported => + 'HDR メディアには、SDR プレビュー用のトーン マッピングが必要です。現在のシステムまたはプレビュー構成はこれをサポートしていません。'; + + @override + String get previewAudioOutOfRange => + 'オーディオ クリップはソース トラックの範囲を超えているため、プレビューできません。'; + + @override + String get previewResourceMissing => 'プレビュー メディアは存在しません。元のファイルを再度見つけます。'; + + @override + String get previewInvalidComposition => 'ビデオ構成設定が無効です。プレビューを作成できませんでした。'; + + @override + String get previewInvalidData => '無効なプレビュー データです。もう一度試してください。'; + + @override + String get previewFailed => 'プレビューに失敗しました。メディアアクセスを確認して、再試行してください。'; + + @override + String get chatFailed => '会話を完了できませんでした。サービス構成を確認するか、後で再試行してください。'; + + @override + String get delete => '削除'; + + @override + String get pinTimeline => 'タイムラインをピン留め'; + + @override + String get unpinTimeline => 'ピン留めを解除'; + + @override + String deleteTimelineConfirmation(String name) { + return '「$name」と編集履歴を削除しますか?この操作は元に戻せません。'; + } + + @override + String get processingFailed => '処理に失敗しました'; + + @override + String get noMatchingOptions => '一致する項目がありません'; + + @override + String removeMediaConfirmation(String name) { + return '「$name」をライブラリから削除しますか?既存のクリップ、履歴、元のファイルは保持されます。'; + } + + @override + String mediaAdded(int count) { + return 'メディア参照を$count件追加しました'; + } + + @override + String duplicatesSkipped(int count) { + return '$count 重複ファイルをスキップしました'; + } + + @override + String mediaCount(int count) { + return 'メディア$count件'; + } + + @override + String get importMedia => '読み込む'; + + @override + String noMediaOfType(String type) { + return '$type メディアがありません'; + } + + @override + String captionsImported(String count) { + return 'インポートされた $count 字幕'; + } + + @override + String editCaptionError(String message) { + return '字幕を編集できませんでした: $message'; + } + + @override + String mcpStartError(String message) { + return 'MCP を開始できませんでした: $message'; + } + + @override + String manualColorSpace(String name) { + return '手動で選択: $name'; + } + + @override + String detectedColorSpace(String name) { + return '検出されました: $name'; + } + + @override + String keyframeLabel(String channel) { + return '$channelのキーフレーム'; + } + + @override + String maskMode(String mode) { + return '組み合わせモード: $mode'; + } + + @override + String keyframeCount(int count) { + return 'キーフレーム$count個'; + } + + @override + String toggleKeyframe(String action, String channel) { + return '$channelのキーフレームを$action'; + } + + @override + String previousKeyframe(String channel) { + return '前の$channelキーフレーム'; + } + + @override + String nextKeyframe(String channel) { + return '次の$channelキーフレーム'; + } + + @override + String keyframeSettings(String channel) { + return '$channelのキーフレーム設定'; + } + + @override + String selectedClipsHint(int count) { + return '$count クリップが選択されました\nクリップを 1 つ選択してそのプロパティを表示します'; + } + + @override + String transcriptionError(String code) { + return '転写に失敗しました。コンポーネント、モデル、オーディオ トラック、およびデュレーションを確認します ($code)'; + } + + @override + String captionsAdded(String count) { + return '$count 字幕を追加しました。プロパティ パネルで編集します。'; + } + + @override + String translatedCaptionsAdded(String count) { + return '$count 翻訳字幕を追加しました。プロパティ パネルで編集します。'; + } + + @override + String applyCaptionsError(String message) { + return '字幕を適用できませんでした: $message'; + } + + @override + String applyTranslatedCaptionsError(String message) { + return '翻訳された字幕を適用できませんでした: $message'; + } + + @override + String recognizedCaptions(int count) { + return '字幕を$count件認識しました'; + } + + @override + String captionCount(int count) { + return '字幕$count件'; + } + + @override + String translationFailed(String message) { + return '翻訳に失敗しました: $message'; + } + + @override + String translatedCaptionCount(int count, String language) { + return '$languageの字幕$count件'; + } + + @override + String previewParameterError(String message) { + return '無効なプレビューパラメータ: $message'; + } + + @override + String mediaOffline(String names) { + return 'メディアがオフラインまたは利用不可: $names'; + } + + @override + String searchOptions(String label) { + return '$labelを検索…'; + } + + @override + String get loadRecentProjectsFailed => + '最近のライブラリをロードできませんでした。ライブラリを手動で開くこともできます。'; + + @override + String get projectAccessFailed => 'プロジェクトを利用できません'; + + @override + String get projectMissingDirectory => 'プロジェクトが見つかりません'; + + @override + String get recentProjectSaveFailed => + 'ライブラリは開きましたが、最近のライブラリ レコードを保存できませんでした。'; + + @override + String get lastProjectSaveFailed => + 'プロジェクトは開きましたが、最後のプロジェクト レコードを保存できませんでした。'; + + @override + String get enterProjectName => 'プロジェクト名を入力してください'; + + @override + String get projectSwitched => 'プロジェクトが変更されました。メディアを再度ドラッグします。'; + + @override + String get notLocalMedia => 'このメディアはローカル ファイルではありません'; + + @override + String get revealMediaFailed => 'ファイルマネージャーでメディアを表示できませんでした'; + + @override + String get openMatchingProject => 'まず対応するプロジェクトを開きます'; + + @override + String get projectMismatch => 'この場所のライブラリはレコードと一致しません。 「ライブラリを開く」で再度選択します。'; + + @override + String get openProjectFirst => 'まずライブラリを開いてください'; + + @override + String get localFilesOnly => 'ファイルマネージャーからローカルファイルをドラッグ'; + + @override + String get foldersUnsupported => 'ファイルを選択します。フォルダーのドラッグはまだサポートされていません。'; + + @override + String get mediaImportCancelled => 'メディアのインポートがキャンセルされました'; + + @override + String get fileAccessFailed => 'ファイルが見つからないか、読み取ることができません。場所と権限を確認してください'; + + @override + String get registerMediaFailed => 'メディアを登録できませんでした。もう一度試してください'; + + @override + String get mediaNoLongerExists => 'メディアはもう存在しません'; + + @override + String get mediaNoTracks => 'メディアに使用可能なビデオまたはオーディオ トラックがありません'; + + @override + String get invalidMediaDuration => 'メディアの長さが無効です'; + + @override + String get mediaInfoUnsupported => 'このプラットフォームではメディア情報の読み取りがまだサポートされていません'; + + @override + String get mediaInfoFailed => 'メディア情報を読み取れませんでした。ファイルとアクセス許可を確認してください'; + + @override + String get saveTimelineFailed => + 'タイムラインを保存できませんでした。もう一度やり直してください。保存されていない編集内容はこのセッションに残ります。'; + + @override + String get addKeyframeAction => '追加'; + + @override + String get backgroundTasks => 'バックグラウンドタスク'; + + @override + String get noBackgroundTasks => 'バックグラウンドタスクはありません'; + + @override + String get retryTask => '再試行'; + + @override + String get applyOriginalCaptions => '原文字幕を適用'; + + @override + String get applyTranslatedCaptions => '翻訳字幕を適用'; + + @override + String get subtitleTaskStarted => '字幕タスクを開始しました'; + + @override + String get fitTimeline => 'タイムライン全体を表示'; + + @override + String get modify => 'Modify'; + + @override + String get projectSettings => 'Project settings'; + + @override + String get projectSettingsDescription => + 'Change project output settings while keeping clip timing and speed.'; + + @override + String get projectColorSpace => 'Color space'; + + @override + String get projectWidth => 'Width (px)'; + + @override + String get projectHeight => 'Height (px)'; + + @override + String get projectResolutionInvalid => 'Enter a whole number from 1 to 16384'; + + @override + String get previewFullscreen => '全画面プレビュー'; + + @override + String get exitPreviewFullscreen => '全画面表示を終了'; + + @override + String get previewGoToStart => '先頭へ移動'; + + @override + String get previewPreviousFrame => '前のフレーム'; + + @override + String get previewNextFrame => '次のフレーム'; + + @override + String get softwareUpdates => 'ソフトウェア更新'; + + @override + String get checkForUpdates => '更新を確認'; + + @override + String get automaticallyCheckUpdates => '更新を自動的に確認'; + + @override + String get updatesUnavailable => 'このビルドでは更新を利用できません。'; + + @override + String get updateCheckFailed => '更新を確認できませんでした。もう一度お試しください。'; + + @override + String get removeBackground => '背景を削除'; + + @override + String get startBackgroundRemoval => '背景を削除'; + + @override + String get backgroundRemovalResourceRequired => + '背景削除にはローカルモデルが必要です。ダウンロード後に自動で開始します。'; + + @override + String get backgroundRemovalDownloadTask => '背景削除リソースをダウンロード'; + + @override + String get backgroundRemovalResourceName => '背景削除モデル'; + + @override + String get backgroundRemovalDestructiveHint => + '生成された透過メディアでこのクリップを置き換えます。元に戻すを使用して元のクリップを復元できます。'; + + @override + String get backgroundRemovalTaskStarted => '背景削除を開始しました'; + + @override + String get startBackgroundRemovalFailed => + '背景削除を開始できませんでした。メディアを確認するか、現在の処理タスクが完了するまでお待ちください。'; + + @override + String get backgroundRemovalComplete => '背景削除が完了しました'; + + @override + String get backgroundRemovalApplying => 'クリップのメディアを置き換えています'; + + @override + String get backgroundRemovalFailed => '背景削除に失敗しました'; + + @override + String get agentSettings => 'Agent'; + + @override + String get agentSaveSettingsFailed => 'Agent設定を保存できませんでした。'; + + @override + String get agentDeleteProviderTitle => 'プロバイダーを削除しますか?'; + + @override + String agentDeleteProviderDescription(String providerName) { + return '「$providerName」と保存済みのAPIキーがこのデバイスから削除されます。'; + } + + @override + String get agentProviderRequired => 'アシスタントを有効にする前にプロバイダーを追加してください。'; + + @override + String get agentUseSelectedModel => '新しいAgentリクエストには選択したモデルが使用されます。'; + + @override + String get agentEnable => 'Agentを有効にする'; + + @override + String get agentDefaultModel => 'デフォルトモデル'; + + @override + String get agentConfigureModel => 'モデルを設定'; + + @override + String get agentSelectModel => 'モデルを選択'; + + @override + String get agentModelUnavailable => + 'この会話のモデルは利用できません。別のモデルを選択して新しい会話を開始してください。'; + + @override + String get agentModelChangeSession => 'モデルを変更すると、新しいAgentセッションが開始されます。'; + + @override + String get agentCustomProviders => 'カスタムプロバイダー'; + + @override + String get agentProviderStorageDescription => + 'プロバイダーのメタデータはローカルに保存されます。APIキーはシステムの資格情報ストアに保管されます。'; + + @override + String get agentAddProvider => 'プロバイダーを追加'; + + @override + String get agentBackToProviders => 'プロバイダー一覧に戻る'; + + @override + String get agentLoadSettingsFailed => 'Agent設定を読み込めませんでした。再試行'; + + @override + String get agentEnableProvider => 'Provider を有効にする'; + + @override + String get agentEditProvider => 'プロバイダーを編集'; + + @override + String get agentDeleteProvider => 'プロバイダーを削除'; + + @override + String get agentModelIdsUnique => 'モデルIDは一意である必要があります。'; + + @override + String get agentEditProviderTitle => 'プロバイダーを編集'; + + @override + String get agentProviderEndpointDescription => + 'OpenAI互換のChat Completionsエンドポイントを設定します。'; + + @override + String get agentSaveProvider => 'プロバイダーを保存'; + + @override + String get agentProviderConfiguration => 'Provider 設定'; + + @override + String get agentAuthenticationAndModels => '認証とモデル'; + + @override + String get agentApiType => 'APIタイプ'; + + @override + String get agentOpenAiChatCompletions => 'OpenAI Completions'; + + @override + String get agentBaseUrl => 'ベースURL'; + + @override + String get agentApiKey => 'APIキー'; + + @override + String get agentProviderNameHint => 'マイプロバイダー'; + + @override + String get agentApiKeyOptional => '認証を必要としないエンドポイントでは省略できます。'; + + @override + String get agentApiKeyKeep => '保存済みのキーを保持する場合は空欄にしてください。'; + + @override + String get agentOptional => '任意'; + + @override + String get agentApiKeyOneLine => 'APIキーは1行で入力してください。'; + + @override + String get agentRemoveSavedApiKey => '保存済みのAPIキーを削除'; + + @override + String get agentModels => 'モデル'; + + @override + String get agentAddModel => 'モデルを追加'; + + @override + String get agentRequiredField => 'この項目は必須です。'; + + @override + String get agentInvalidBaseUrl => + '資格情報、クエリ、フラグメントを含まないHTTP(S)ベースURLを入力してください。'; + + @override + String get agentModelId => 'モデルID'; + + @override + String get agentContextWindow => 'コンテキストウィンドウ'; + + @override + String get agentMaxOutputTokens => '最大出力'; + + @override + String get agentMaxOutputBelowContext => 'コンテキストウィンドウより小さい値を指定してください。'; + + @override + String get agentDeleteModel => 'モデルを削除'; + + @override + String get agentPositiveInteger => '正の整数を入力してください。'; + + @override + String get agentConfigurationReadFailed => + 'Agent設定を読み込めませんでした。設定を確認してもう一度お試しください。'; + + @override + String get agentConfigurationRequired => '先に設定でAgentを構成して有効にしてください。'; + + @override + String get agentSessionRestoreFailed => + 'Agentセッションを復元できませんでした。しばらくしてからもう一度お試しください。'; + + @override + String get agentContextBudgetExceeded => + 'システム指示、ツール、メッセージに必要な入力容量が不足しています。コンテキストを増やすか最大出力を減らしてください。'; + + @override + String get agentAuthenticationFailed => '認証に失敗しました。API Key と権限を確認してください。'; + + @override + String get agentConnectionFailed => + '接続に失敗したかタイムアウトしました。Base URL とネットワークを確認してください。'; + + @override + String get agentProtocolFailed => '応答が選択した API タイプと一致しないか、ストリームが不完全です。'; + + @override + String get agentContextBudgetTooSmall => + 'システム指示用の入力容量を確保してください。コンテキストを増やすか最大出力を減らしてください。'; + + @override + String get agentCompacting => 'コンテキストを整理中…'; + + @override + String get agentEditing => '編集中…'; + + @override + String get agentVerifying => '結果を確認中…'; + + @override + String get agentTurnLimitReached => + '実行回数の上限に達しました。編集内容は保存されています。「続けて」と送信すると再開します。'; + + @override + String get agentRecoveryRequired => + '前回の操作結果は未確認です。続行して保存済みの記録を確認できます。未確認の編集は繰り返しません。'; + + @override + String get agentExportReplyFailed => + '動画は書き出し済みですが、要約の返信に失敗しました。編集や書き出しを繰り返さず要約を再試行できます。'; + + @override + String get agentRetrySummary => '要約を再試行'; + + @override + String get agentResumeTask => 'タスクを続行'; + + @override + String get agentTaskInterrupted => 'タスクが中断されました。保存済みの進行状況から続行できます。'; + + @override + String get downloadSubtitleModel => '字幕モデルをダウンロード'; + + @override + String get downloadModelAction => 'ダウンロード'; + + @override + String get subtitleEngineUnavailable => + 'モデルはインストール済みですが、字幕処理エンジンを起動できませんでした。エンジンを修復してください。モデルの再ダウンロードは不要です。'; + + @override + String get backgroundTaskDetails => 'タスクの詳細'; + + @override + String get backgroundTaskFailed => '失敗'; + + @override + String get backgroundTaskCompleted => '完了'; + + @override + String get captionWrapLines => '字幕を折り返して表示'; + + @override + String get captionSingleLine => '字幕を1行で表示'; + + @override + String get noMatchingCaptions => '一致する字幕がありません'; + + @override + String get subtitleResourcesRequired => + '字幕の生成に必要なリソースです。ダウンロード後、自動的に生成を開始します。'; + + @override + String subtitleResourcesDownloadSize(String size) { + return 'ダウンロード容量: $size'; + } + + @override + String get pauseDownload => '一時停止'; + + @override + String get resumeDownload => '再開'; + + @override + String get downloadPaused => '一時停止中'; + + @override + String get cancelResourceDownloadTitle => 'ダウンロードをキャンセルしますか?'; + + @override + String get cancelResourceDownloadMessage => + 'ダウンロードを停止します。現在のリソースの進行状況は失われる場合があります。'; + + @override + String get continueDownload => 'ダウンロードを続ける'; + + @override + String get cancelDownload => 'ダウンロードをキャンセル'; + + @override + String get speechResourceStage => '音声認識リソース'; + + @override + String get translationResourceStage => '翻訳リソース'; + + @override + String get subtitleResourceDownloadTask => '音声・翻訳リソースをダウンロード'; + + @override + String get downloadingSpeechModel => '音声モデルをダウンロード中'; + + @override + String get downloadingTranslationModel => '翻訳モデルをダウンロード中'; + + @override + String get checkingForUpdates => '更新を確認中…'; + + @override + String get appIsUpToDate => '最新バージョンです。'; + + @override + String downloadingUpdate(int progress) { + return '更新をダウンロード中:$progress%'; + } + + @override + String updateAvailable(String version) { + return 'バージョン $version が利用可能です。'; + } + + @override + String get downloadUpdate => '更新をダウンロード'; + + @override + String get restartToUpdate => '再起動して更新'; + + @override + String get updateOperationFailed => '更新できませんでした。実行中のタスクを完了してから再試行してください。'; + + @override + String get windowMinimize => '最小化'; + + @override + String get windowMaximize => '最大化'; + + @override + String get windowRestore => '元に戻す'; + + @override + String get workspaceAgent => 'アシスタント'; + + @override + String get workspaceCut => '編集'; + + @override + String get noAvailableOptions => '利用できる項目がありません'; + + @override + String get composerReferenceInvalid => '参照が無効です。元のプロジェクトに戻るか、参照を削除してください。'; + + @override + String durationSeconds(int seconds) { + return '$seconds秒'; + } + + @override + String durationMinutesSeconds(int minutes, int seconds) { + return '$minutes分$seconds秒'; + } + + @override + String get projectNameInvalid => 'プロジェクト名が無効です'; + + @override + String get projectLocationDefaultUnavailable => + '既定のプロジェクト保存先にアクセスできません。設定で選び直してください。'; + + @override + String get chooseProjectLocation => '先に設定でプロジェクトの保存先を選択してください。'; + + @override + String get untitledTimeline => '無題のタイムライン'; + + @override + String get primarySequence => 'メインシーケンス'; + + @override + String get primaryStoryline => 'メインストーリーライン'; + + @override + String get projectSessionClosed => 'プロジェクトのセッションが終了しました。開き直してください。'; + + @override + String get timelineSessionClosed => 'タイムラインのセッションが終了しました。開き直してください。'; + + @override + String get timelineMissing => 'タイムラインが存在しないか、削除されています。'; + + @override + String get timelineInUse => 'タイムラインは使用中のため削除できません。'; + + @override + String get timelineHasBackgroundTasks => '削除する前にタイムラインのバックグラウンドタスクを完了してください。'; + + @override + String get timelineRequired => 'プロジェクトには少なくとも1つのタイムラインが必要です。'; + + @override + String get mediaReadFailed => 'メディアを読み込めませんでした'; + + @override + String get mediaImportFailed => 'メディアを読み込めませんでした'; + + @override + String get unsupportedMediaType => '動画、音声、画像ファイルのみ読み込めます。'; + + @override + String get mediaNoVideoTracks => 'メディアに利用できる映像トラックがありません'; + + @override + String get mediaDurationOutOfRange => 'メディアの長さがタイムラインの範囲を超えています'; + + @override + String resourceDownloadHttpFailed(String statusCode) { + return 'ダウンロードに失敗しました(HTTP $statusCode)'; + } + + @override + String get resourceChecksumFailed => 'モデルファイルの検証に失敗しました。リソースを再ダウンロードしてください。'; + + @override + String get subtitleLanguageAf => 'アフリカーンス語'; + + @override + String get subtitleLanguageAm => 'アムハラ語'; + + @override + String get subtitleLanguageAr => 'アラビア語'; + + @override + String get subtitleLanguageAst => 'アストゥリアス語'; + + @override + String get subtitleLanguageAz => 'アゼルバイジャン語'; + + @override + String get subtitleLanguageBa => 'バシキール語'; + + @override + String get subtitleLanguageBe => 'ベラルーシ語'; + + @override + String get subtitleLanguageBg => 'ブルガリア語'; + + @override + String get subtitleLanguageBn => 'ベンガル語'; + + @override + String get subtitleLanguageBr => 'ブルトン語'; + + @override + String get subtitleLanguageBs => 'ボスニア語'; + + @override + String get subtitleLanguageCa => 'カタロニア語'; + + @override + String get subtitleLanguageCeb => 'セブアノ語'; + + @override + String get subtitleLanguageCs => 'チェコ語'; + + @override + String get subtitleLanguageCy => 'ウェールズ語'; + + @override + String get subtitleLanguageDa => 'デンマーク語'; + + @override + String get subtitleLanguageDe => 'ドイツ語'; + + @override + String get subtitleLanguageEl => 'ギリシャ語'; + + @override + String get subtitleLanguageEn => '英語'; + + @override + String get subtitleLanguageEs => 'スペイン語'; + + @override + String get subtitleLanguageEt => 'エストニア語'; + + @override + String get subtitleLanguageFa => 'ペルシア語'; + + @override + String get subtitleLanguageFf => 'フラ語'; + + @override + String get subtitleLanguageFi => 'フィンランド語'; + + @override + String get subtitleLanguageFr => 'フランス語'; + + @override + String get subtitleLanguageFy => '西フリジア語'; + + @override + String get subtitleLanguageGa => 'アイルランド語'; + + @override + String get subtitleLanguageGd => 'スコットランド・ゲール語'; + + @override + String get subtitleLanguageGl => 'ガリシア語'; + + @override + String get subtitleLanguageGu => 'グジャラート語'; + + @override + String get subtitleLanguageHa => 'ハウサ語'; + + @override + String get subtitleLanguageHe => 'ヘブライ語'; + + @override + String get subtitleLanguageHi => 'ヒンディー語'; + + @override + String get subtitleLanguageHr => 'クロアチア語'; + + @override + String get subtitleLanguageHt => 'ハイチ・クレオール語'; + + @override + String get subtitleLanguageHu => 'ハンガリー語'; + + @override + String get subtitleLanguageHy => 'アルメニア語'; + + @override + String get subtitleLanguageId => 'インドネシア語'; + + @override + String get subtitleLanguageIg => 'イボ語'; + + @override + String get subtitleLanguageIlo => 'イロカノ語'; + + @override + String get subtitleLanguageIs => 'アイスランド語'; + + @override + String get subtitleLanguageIt => 'イタリア語'; + + @override + String get subtitleLanguageJa => '日本語'; + + @override + String get subtitleLanguageJv => 'ジャワ語'; + + @override + String get subtitleLanguageKa => 'ジョージア語'; + + @override + String get subtitleLanguageKk => 'カザフ語'; + + @override + String get subtitleLanguageKm => 'クメール語'; + + @override + String get subtitleLanguageKn => 'カンナダ語'; + + @override + String get subtitleLanguageKo => '韓国語'; + + @override + String get subtitleLanguageLb => 'ルクセンブルク語'; + + @override + String get subtitleLanguageLg => 'ガンダ語'; + + @override + String get subtitleLanguageLn => 'リンガラ語'; + + @override + String get subtitleLanguageLo => 'ラオ語'; + + @override + String get subtitleLanguageLt => 'リトアニア語'; + + @override + String get subtitleLanguageLv => 'ラトビア語'; + + @override + String get subtitleLanguageMg => 'マダガスカル語'; + + @override + String get subtitleLanguageMk => 'マケドニア語'; + + @override + String get subtitleLanguageMl => 'マラヤーラム語'; + + @override + String get subtitleLanguageMn => 'モンゴル語'; + + @override + String get subtitleLanguageMr => 'マラーティー語'; + + @override + String get subtitleLanguageMs => 'マレー語'; + + @override + String get subtitleLanguageMy => 'ミャンマー語'; + + @override + String get subtitleLanguageNe => 'ネパール語'; + + @override + String get subtitleLanguageNl => 'オランダ語'; + + @override + String get subtitleLanguageNo => 'ノルウェー語'; + + @override + String get subtitleLanguageNs => '北部ソト語'; + + @override + String get subtitleLanguageOc => 'オック語'; + + @override + String get subtitleLanguageOr => 'オディア語'; + + @override + String get subtitleLanguagePa => 'パンジャブ語'; + + @override + String get subtitleLanguagePl => 'ポーランド語'; + + @override + String get subtitleLanguagePs => 'パシュトゥー語'; + + @override + String get subtitleLanguagePt => 'ポルトガル語'; + + @override + String get subtitleLanguageRo => 'ルーマニア語'; + + @override + String get subtitleLanguageRu => 'ロシア語'; + + @override + String get subtitleLanguageSd => 'シンド語'; + + @override + String get subtitleLanguageSi => 'シンハラ語'; + + @override + String get subtitleLanguageSk => 'スロバキア語'; + + @override + String get subtitleLanguageSl => 'スロベニア語'; + + @override + String get subtitleLanguageSo => 'ソマリ語'; + + @override + String get subtitleLanguageSq => 'アルバニア語'; + + @override + String get subtitleLanguageSr => 'セルビア語'; + + @override + String get subtitleLanguageSs => 'スワジ語'; + + @override + String get subtitleLanguageSu => 'スンダ語'; + + @override + String get subtitleLanguageSv => 'スウェーデン語'; + + @override + String get subtitleLanguageSw => 'スワヒリ語'; + + @override + String get subtitleLanguageTa => 'タミル語'; + + @override + String get subtitleLanguageTh => 'タイ語'; + + @override + String get subtitleLanguageTl => 'タガログ語'; + + @override + String get subtitleLanguageTn => 'ツワナ語'; + + @override + String get subtitleLanguageTr => 'トルコ語'; + + @override + String get subtitleLanguageUk => 'ウクライナ語'; + + @override + String get subtitleLanguageUr => 'ウルドゥー語'; + + @override + String get subtitleLanguageUz => 'ウズベク語'; + + @override + String get subtitleLanguageVi => 'ベトナム語'; + + @override + String get subtitleLanguageWo => 'ウォロフ語'; + + @override + String get subtitleLanguageXh => 'コサ語'; + + @override + String get subtitleLanguageYi => 'イディッシュ語'; + + @override + String get subtitleLanguageYo => 'ヨルバ語'; + + @override + String get subtitleLanguageYue => '広東語'; + + @override + String get subtitleLanguageZh => '中国語'; + + @override + String get subtitleLanguageZu => 'ズールー語'; + + @override + String get linearRec2020 => 'リニア Rec.2020'; + + @override + String get diagnostics => '診断'; + + @override + String get exportDiagnostics => '診断パッケージをエクスポート'; + + @override + String get exportDiagnosticsFailed => '診断をエクスポートできませんでした。もう一度お試しください。'; + + @override + String get exportDiagnosticsSucceeded => '診断パッケージを保存しました。'; +} diff --git a/lib/l10n/app_localizations_ko.dart b/lib/l10n/app_localizations_ko.dart new file mode 100644 index 0000000..fba52a2 --- /dev/null +++ b/lib/l10n/app_localizations_ko.dart @@ -0,0 +1,2133 @@ +// ignore: unused_import +import 'package:intl/intl.dart' as intl; + +import 'app_localizations.dart'; + +// ignore_for_file: type=lint + +/// The translations for Korean (`ko`). +class AppLocalizationsKo extends AppLocalizations { + AppLocalizationsKo([String locale = 'ko']) : super(locale); + + @override + String get selectProject => '프로젝트 선택'; + + @override + String get searchProjects => '프로젝트 검색'; + + @override + String get noMatchingProjects => '일치하는 프로젝트가 없습니다'; + + @override + String get projectsNone => '프로젝트가 없습니다'; + + @override + String get projectLocationMissing => '폴더가 없습니다. 프로젝트를 만들 때 생성됩니다.'; + + @override + String get projectLocationUnavailable => + '프로젝트 저장 위치를 사용할 수 없습니다. 디스크나 네트워크를 확인하고 다시 시도하거나 위치를 변경하세요.'; + + @override + String get projectLocationNotWritable => + '프로젝트 저장 위치에 쓸 수 없습니다. 권한을 확인하거나 위치를 변경하세요.'; + + @override + String get projectLocationCreateFailed => + '프로젝트 저장 폴더를 만들거나 쓸 수 없습니다. 권한을 확인하거나 위치를 변경하세요.'; + + @override + String get removeProjectFromSidebar => '사이드바에서 제거'; + + @override + String get projectRemoved => '프로젝트를 목록에서 제거했습니다. 로컬 파일과 대화는 유지됩니다.'; + + @override + String get agentNoConversations => '아직 대화가 없습니다'; + + @override + String get renameConversationTitle => '채팅 이름 변경'; + + @override + String get renameConversationDescription => '짧고 알아보기 쉬운 이름을 사용하세요.'; + + @override + String get collapseProject => '프로젝트 접기'; + + @override + String get expandProject => '프로젝트 펼치기'; + + @override + String agentDeleteConfirmation(String title) { + return '“$title” 및 모든 메시지를 영구적으로 삭제할까요? 이 작업은 취소할 수 없습니다. 로컬 프로젝트 파일에는 영향을 주지 않습니다.'; + } + + @override + String get agentEmptyTrashConfirmation => + '휴지통의 모든 대화를 영구적으로 삭제할까요? 이 작업은 취소할 수 없습니다. 로컬 프로젝트 파일에는 영향을 주지 않습니다.'; + + @override + String get agentConversations => '대화'; + + @override + String get showMoreConversations => '더 보기'; + + @override + String get showFewerConversations => '접기'; + + @override + String get agentNewConversation => '새 대화'; + + @override + String agentElapsedTime(String duration) { + return '소요 시간 $duration'; + } + + @override + String get agentConversationActions => '대화 작업'; + + @override + String get agentMoveToTrash => '휴지통으로 이동'; + + @override + String get agentTrash => '휴지통'; + + @override + String get agentRestore => '복원'; + + @override + String get agentEmptyTrash => '휴지통 비우기'; + + @override + String get agentDeleteForever => '영구 삭제'; + + @override + String get agentConversationLocation => '대화 저장 위치'; + + @override + String get agentChooseExistingConversations => '기존 대화 선택'; + + @override + String get agentMoveConversations => '대화 이동'; + + @override + String get agentLocationUnavailable => '대화 저장 위치를 사용할 수 없습니다'; + + @override + String get agentLocationBusy => '실행 중인 대화가 끝난 후 이동하세요'; + + @override + String get agentRelinkProvider => '제공자 다시 연결'; + + @override + String get settings => '설정'; + + @override + String get closeSettings => '설정 닫기'; + + @override + String get general => '일반'; + + @override + String get appearance => '외관'; + + @override + String get theme => '테마'; + + @override + String get system => '시스템 설정 따르기'; + + @override + String get light => '라이트'; + + @override + String get dark => '다크'; + + @override + String get saveAppearanceFailed => '외모를 저장할 수 없습니다. 다시 시도해 주세요.'; + + @override + String get loadAppearanceFailed => '화면 설정을 불러올 수 없습니다. 테마를 다시 선택해 주세요.'; + + @override + String get cancel => '취소'; + + @override + String get save => '저장'; + + @override + String get create => '만들기'; + + @override + String get close => '닫기'; + + @override + String get retry => '다시 시도'; + + @override + String get select => '선택'; + + @override + String get name => '이름'; + + @override + String get enterName => '이름을 입력하세요'; + + @override + String get invalidName => '이름에는 경로 구분 기호나 제어 문자를 포함할 수 없습니다.'; + + @override + String get projects => '프로젝트'; + + @override + String get projectName => '프로젝트 이름'; + + @override + String get projectLocation => '프로젝트 저장 위치'; + + @override + String get projectLocationNotSet => '설정되지 않음'; + + @override + String get loadProjectLocationFailed => '프로젝트 저장 위치를 불러올 수 없습니다.'; + + @override + String get saveProjectLocationFailed => '프로젝트 저장 위치를 저장할 수 없습니다.'; + + @override + String get resourceLocation => '리소스 저장 위치'; + + @override + String get resourceLocationNotSet => '설정되지 않음'; + + @override + String get loadResourceLocationFailed => '리소스 저장 위치를 불러올 수 없습니다.'; + + @override + String get saveResourceLocationFailed => '리소스 저장 위치를 저장할 수 없습니다.'; + + @override + String get transcriptionResourceRequired => + '자막을 생성하려면 먼저 음성 인식 모델을 다운로드해야 합니다.'; + + @override + String get downloadAndContinue => '다운로드 후 계속'; + + @override + String get downloadingResource => '다운로드 중…'; + + @override + String get downloadInBackground => '백그라운드에서 다운로드'; + + @override + String get processingResourceDownloadFailed => + '음성 인식 리소스를 다운로드할 수 없습니다. 다시 시도해 주세요.'; + + @override + String get newProject => '새 프로젝트'; + + @override + String get openProject => '프로젝트 열기'; + + @override + String get openProjectMore => '다른 프로젝트 열기'; + + @override + String get saveHere => '여기에 저장'; + + @override + String get selectDirectoryFailed => '디렉터리를 선택할 수 없습니다. 시스템 권한을 확인하세요.'; + + @override + String get openingWorkspace => '작업 공간을 여는 중…'; + + @override + String get loadProjectsFailed => '프로젝트를 불러오지 못했습니다'; + + @override + String get projectsEmpty => '프로젝트가 없습니다'; + + @override + String get backToProjects => '편집으로 돌아가기'; + + @override + String get timelines => '타임라인'; + + @override + String timelineLimitReached(int count) { + return '프로젝트마다 타임라인을 최대 $count개까지 만들 수 있습니다.'; + } + + @override + String get timelineName => '타임라인 이름'; + + @override + String defaultTimelineName(int index) { + return '타임라인 $index'; + } + + @override + String get newTimeline => '새 타임라인'; + + @override + String get noTimelines => '타임라인이 없습니다'; + + @override + String get activeTimeline => '현재 타임라인'; + + @override + String get timelineUnavailable => '타임라인을 사용할 수 없습니다'; + + @override + String get projectNoTimelines => '이 프로젝트에는 타임라인이 없습니다'; + + @override + String get createTimelineHint => '왼쪽의 ‘타임라인’에서 새 타임라인을 만들어 편집을 시작하세요.'; + + @override + String get createTimelineChat => '타임라인을 만들면 채팅을 시작할 수 있습니다'; + + @override + String get operationFailed => '작업이 실패했습니다. 다시 시도해 주세요.'; + + @override + String get collapseSidebar => '사이드바 접기'; + + @override + String get expandSidebar => '사이드바 확장'; + + @override + String get expandEditor => '편집 영역 펼치기'; + + @override + String get collapseProperties => '속성 축소'; + + @override + String get expandProperties => '속성 확장'; + + @override + String get layout => '레이아웃'; + + @override + String get editingFirstLayout => '편집 우선'; + + @override + String get agentEditingLayout => '에이전트와 편집'; + + @override + String get agentLayoutDescription => '계획, 협업 및 실행'; + + @override + String get editingLayoutDescription => '미리보기, 편집 및 다듬기'; + + @override + String get materials => '미디어'; + + @override + String get all => '전체'; + + @override + String get video => '동영상'; + + @override + String get audio => '오디오'; + + @override + String get image => '영상'; + + @override + String get picture => '영상'; + + @override + String get captions => '자막'; + + @override + String get text => '텍스트'; + + @override + String get noMedia => '미디어 없음'; + + @override + String get mediaCategory => '미디어 분류'; + + @override + String get captionTasks => '자막 작업'; + + @override + String get listLayout => '목록 보기'; + + @override + String get gridLayout => '그리드 보기'; + + @override + String get addToTimeline => '타임라인에 추가'; + + @override + String get rename => '이름 바꾸기'; + + @override + String get renameMedia => '미디어 이름 바꾸기'; + + @override + String get removeMedia => '미디어 제거'; + + @override + String get remove => '제거'; + + @override + String get revealFinder => 'Finder에서 보기'; + + @override + String get revealFileManager => '파일 관리자에서 보기'; + + @override + String get dropToAdd => '놓으면 추가됩니다'; + + @override + String get timelineDropToStart => '시작하려면 미디어를 여기로 드래그하세요.'; + + @override + String get dragMediaHint => + '비디오, 오디오, 이미지를 여기로 드래그하세요.\n원본 파일은 현재 위치에 유지됩니다.'; + + @override + String get transcribe => '음성 받아쓰기'; + + @override + String get generateCaptions => '자막 생성'; + + @override + String get play => '재생'; + + @override + String get pause => '일시 정지'; + + @override + String get retryPreview => '미리보기 재시도'; + + @override + String get canvasRatio => '캔버스 종횡비'; + + @override + String get noPreviewContent => '타임라인에서 미리 볼 콘텐츠가 없습니다.'; + + @override + String get nativePreviewUnsupported => '이 플랫폼에서는 기본 미리보기를 사용할 수 없습니다.'; + + @override + String get canvasTransformFailed => '캔버스를 변환할 수 없습니다. 다시 시도해 주세요.'; + + @override + String get undo => '실행 취소'; + + @override + String get redo => '다시 실행'; + + @override + String get deleteSelectedClips => '선택한 클립 삭제'; + + @override + String get splitAtPlayhead => '플레이헤드에서 분할'; + + @override + String get trimLeft => '왼쪽 자르기'; + + @override + String get trimRight => '오른쪽 자르기'; + + @override + String get trimLeftTooltip => '재생 헤드 왼쪽을 제거하고 오른쪽 유지'; + + @override + String get trimRightTooltip => '재생 헤드 오른쪽을 제거하고 왼쪽 유지'; + + @override + String get currentSequence => '현재 시퀀스'; + + @override + String get projectProperties => '프로젝트 속성'; + + @override + String get canvasSize => '캔버스 크기'; + + @override + String get frameRate => '프레임 속도'; + + @override + String get duration => '지속'; + + @override + String get totalDuration => '총 기간'; + + @override + String get clipDuration => '클립 길이'; + + @override + String get seconds => '초'; + + @override + String get clip => '클립'; + + @override + String get unnamedClip => '이름 없는 클립'; + + @override + String get gap => '간격'; + + @override + String get compoundClip => '복합 클립'; + + @override + String get textClip => '텍스트 클립'; + + @override + String get pictureProperties => '영상'; + + @override + String get position => '위치'; + + @override + String get rotation => '회전'; + + @override + String get scale => '배율'; + + @override + String get size => '크기'; + + @override + String get transform => '변환'; + + @override + String get resetPosition => '위치 초기화'; + + @override + String get keepAspectRatio => '가로 세로 비율 잠금'; + + @override + String get alignment => '정렬'; + + @override + String get alignLeft => '왼쪽 정렬'; + + @override + String get alignRight => '오른쪽 정렬'; + + @override + String get alignTop => '상단 정렬'; + + @override + String get alignBottom => '하단 정렬'; + + @override + String get alignHorizontalCenter => '가로 가운데 정렬'; + + @override + String get alignVerticalCenter => '세로 가운데 정렬'; + + @override + String get volume => '볼륨'; + + @override + String get gain => '게인'; + + @override + String get mute => '음소거'; + + @override + String get unmute => '음소거 해제'; + + @override + String get resetVolume => '볼륨 재설정'; + + @override + String get invalidGain => '-90에서 +12 사이의 값을 입력하세요.'; + + @override + String get animation => '애니메이션'; + + @override + String get keyframes => '키프레임'; + + @override + String get removeAllKeyframes => '모든 키프레임 제거'; + + @override + String get linear => '선형'; + + @override + String get easeIn => '서서히 가속'; + + @override + String get easeOut => '서서히 감속'; + + @override + String get easeInOut => '서서히 가속 및 감속'; + + @override + String get basic => '기본'; + + @override + String get mask => '마스크'; + + @override + String get addMask => '마스크 추가'; + + @override + String get deleteMask => '마스크 삭제'; + + @override + String get resetMask => '마스크 재설정'; + + @override + String get enableMask => '마스크 활성화'; + + @override + String get disableMask => '마스크 비활성화'; + + @override + String get moveMaskUp => '마스크를 위로 이동'; + + @override + String get moveMaskDown => '마스크를 아래로 이동'; + + @override + String get rectangle => '사각형'; + + @override + String get ellipse => '타원'; + + @override + String get invert => '반전'; + + @override + String get feather => '페더'; + + @override + String get add => '더하기'; + + @override + String get subtract => '빼기'; + + @override + String get intersect => '교차'; + + @override + String get initialRegion => '초기 영역'; + + @override + String get none => '없음'; + + @override + String get color => '색상'; + + @override + String get fontSize => '글꼴 크기'; + + @override + String get outlineWidth => '외곽선 두께'; + + @override + String get outlineColor => '외곽선 색상'; + + @override + String get captionBaseline => '자막 기준선'; + + @override + String get content => '텍스트'; + + @override + String get start => '시작'; + + @override + String get time => '시간'; + + @override + String get speed => '속도'; + + @override + String speedSegmentCount(int count) { + return '속도 구간 $count개'; + } + + @override + String get splitSpeedAtPlayhead => '재생 헤드에서 속도 분할'; + + @override + String get speedChange => '속도'; + + @override + String get speedMode => '속도 모드'; + + @override + String get constantSpeed => '일정한 속도'; + + @override + String get segmentedSpeed => '분할 속도'; + + @override + String get speedNotAvailable => '속도 제어는 아직 사용할 수 없습니다.'; + + @override + String get custom => '사용자 지정'; + + @override + String get invalidNumber => '잘못된 값'; + + @override + String get mediaUnavailable => '미디어를 사용할 수 없음'; + + @override + String get mediaMissing => '미디어 누락'; + + @override + String get mediaColorSpace => '미디어 색 공간'; + + @override + String get mediaColorInterpretation => '미디어 색상 해석'; + + @override + String get colorInfoNotLoaded => '색상 정보가 로드되지 않았습니다.'; + + @override + String get unknownColorSpace => '알 수 없는 색상 공간입니다. Rec.709로 표시됩니다.'; + + @override + String get colorBackendUnsupported => '현재 백엔드는 미디어 색상 해석을 지원하지 않습니다.'; + + @override + String get loadClipPropertiesFailed => '클립 속성을 읽을 수 없습니다.'; + + @override + String get updatePictureFailed => '사진 속성을 업데이트할 수 없습니다.'; + + @override + String get updateVolumeFailed => '볼륨을 업데이트할 수 없습니다.'; + + @override + String get updateMaskFailed => '마스크를 업데이트할 수 없습니다.'; + + @override + String get updateKeyframesFailed => '키프레임을 업데이트할 수 없습니다.'; + + @override + String get maskPreviewFailed => '마스크 미리보기를 준비할 수 없습니다.'; + + @override + String get alignClipFailed => '클립을 정렬할 수 없습니다. 미리보기를 기다린 후 다시 시도해 보세요.'; + + @override + String get invalidTransform => '배율은 1%~10000%여야 합니다. 위치와 각도는 유효한 숫자여야 합니다.'; + + @override + String get editFailed => '편집할 수 없습니다. 입력 및 시간 범위를 확인하세요.'; + + @override + String get addMediaFailed => '미디어를 추가할 수 없습니다. 다시 시도해 주세요.'; + + @override + String get deleteCaption => '자막 삭제'; + + @override + String get mergeCaptions => '자막 병합'; + + @override + String get captionDeleted => '자막이 삭제되었습니다'; + + @override + String get captionChanged => '자막이 변경되었습니다. 다시 시도해 주세요.'; + + @override + String get captionEditChanged => '자막이 변경되었습니다. 다시 수정해 주세요.'; + + @override + String get assistantHint => '편집 아이디어를 설명해주세요'; + + @override + String get configureAgentHint => '채팅을 시작하도록 에이전트 서비스 구성'; + + @override + String get agentRestartHint => '에이전트 서비스를 구성한 후 앱을 다시 시작하세요.'; + + @override + String get replyInterrupted => '응답이 중단되었습니다.'; + + @override + String get replying => '응답 중…'; + + @override + String get stopReply => '응답 중지'; + + @override + String get sendMessage => '메시지 보내기'; + + @override + String get addAttachment => '첨부파일 추가(아직 사용할 수 없음)'; + + @override + String get replyFailed => '응답에 실패했습니다. 연결을 확인하거나 나중에 다시 시도하세요.'; + + @override + String get mcpService => 'MCP 서비스'; + + @override + String get listenPort => '포트'; + + @override + String get accessToken => '액세스 토큰'; + + @override + String get copyAccessToken => '액세스 토큰 복사'; + + @override + String get accessTokenCopied => '액세스 토큰이 복사되었습니다.'; + + @override + String get loadMcpFailed => 'MCP 설정을 로드할 수 없습니다. 다시 해 보다'; + + @override + String get saveMcpFailed => 'MCP 설정을 저장할 수 없습니다. 다시 시도해 주세요.'; + + @override + String get retryStart => '다시 시작해 보세요.'; + + @override + String get invalidPort => '포트는 1에서 65535 사이여야 합니다.'; + + @override + String get loadingSettings => '설정 불러오는 중…'; + + @override + String get starting => '시작 중…'; + + @override + String get stopping => '중지 중…'; + + @override + String get disabled => '비활성화됨'; + + @override + String get running => '실행 중'; + + @override + String get startFailed => '시작하지 못했습니다.'; + + @override + String get saved => '저장됨'; + + @override + String get unsaved => '저장되지 않음'; + + @override + String get saving => '저장 중…'; + + @override + String get pendingSave => '저장 대기 중'; + + @override + String get notApplied => '적용되지 않음'; + + @override + String get enable => '활성화'; + + @override + String get disable => '비활성화'; + + @override + String get type => '유형'; + + @override + String get status => '상태'; + + @override + String get file => '파일'; + + @override + String get unboundMedia => '연결된 미디어 없음'; + + @override + String get unboundAudio => '연결된 오디오 트랙 없음'; + + @override + String get vertical => '세로'; + + @override + String get language => '언어'; + + @override + String get saveLanguageFailed => '언어를 저장할 수 없습니다. 다시 시도해 주세요.'; + + @override + String get loadLanguageFailed => '언어를 로드할 수 없습니다. 다시 선택해 주세요.'; + + @override + String get propertiesFirstLayout => '속성 우선'; + + @override + String get defaultLayout => '기본 레이아웃'; + + @override + String get separateVocals => '보컬 분리'; + + @override + String get detachAudio => '오디오 분리'; + + @override + String get restoreAudio => '오디오 복원'; + + @override + String get audioDetached => '오디오가 분리되었습니다'; + + @override + String get addAll => '모두 추가'; + + @override + String get preparingMedia => '미디어 준비 중…'; + + @override + String get cancelling => '취소 중…'; + + @override + String get cancelled => '취소됨'; + + @override + String get interruptedTask => '작업이 중단되었습니다. 계속하려면 다시 시작하세요.'; + + @override + String get auto => '자동'; + + @override + String get autoDetect => '자동 감지'; + + @override + String get noTranslation => '번역 안 함'; + + @override + String get sourceLanguage => '원본 언어'; + + @override + String get translationLanguage => '번역 언어'; + + @override + String get transcriptionNotConfigured => + '전사가 구성되지 않았습니다. 인식 구성요소와 Whisper Turbo 모델을 설치합니다.'; + + @override + String get translationNotConfigured => + '자막 번역이 구성되지 않았습니다. 소스 언어로 자막을 생성할 수 있습니다.'; + + @override + String get sourceLanguageUnknown => '번역할 소스 언어를 결정할 수 없습니다.'; + + @override + String get startTranscriptionFailed => + '스크립트 작성을 시작할 수 없습니다. 미디어를 확인하거나 현재 작업이 완료될 때까지 기다리세요.'; + + @override + String get placeMediaFirst => '자막을 적용하기 전에 이 미디어를 타임라인에 배치하세요.'; + + @override + String get placeTranslationMediaFirst => + '번역된 자막을 적용하기 전에 해당 미디어를 타임라인에 배치하세요.'; + + @override + String get selectTargetClip => '대상 클립 선택'; + + @override + String get timelineChanged => '타임라인이 변경되었습니다. 대상 클립을 다시 선택하십시오.'; + + @override + String get transcriptionAccessFailed => + '기록 실패: 구성 요소, 모델 또는 소스 미디어에 액세스할 수 없음(notConfigured)'; + + @override + String get transcriptionNoAudio => + '녹음 실패: 선택한 미디어 또는 트랙에서 인식할 수 있는 오디오가 없습니다(noAudio).'; + + @override + String get transcriptionInvalidResult => + '스크립트 작성 실패: 잘못된 자막 파일이 반환되었습니다(invalidResult).'; + + @override + String get transcriptionWorkerExited => + '기록 실패: 인식 구성 요소가 예기치 않게 종료되었습니다(workerExited).'; + + @override + String get transcriptionProcessingFailed => + '전사 실패: 기본 처리 실패(processingFailed)'; + + @override + String get transcriptionFailed => + '전사에 실패했습니다. 구성 요소, 모델, 오디오 트랙 및 지속 시간을 확인하세요.'; + + @override + String get transcribing => '받아쓰는 중…'; + + @override + String get captionsGenerated => '자막이 생성되었습니다'; + + @override + String get cancelTranscription => '받아쓰기 취소'; + + @override + String get applyCaptions => '자막 적용'; + + @override + String get preparingTranslation => '번역 준비 중…'; + + @override + String get translatingCaptions => '자막 번역 중…'; + + @override + String get cancellingTranslation => '번역 취소 중…'; + + @override + String get translatedCaptionsGenerated => '번역 자막이 생성되었습니다'; + + @override + String get translationCancelled => '번역이 취소되었습니다'; + + @override + String get translationInterrupted => '번역이 중단되었습니다'; + + @override + String get cancelTranslation => '번역 취소'; + + @override + String get editorServiceUnavailable => '편집 서비스를 이용할 수 없습니다. 프로젝트를 다시 엽니다.'; + + @override + String get mcpUnavailable => 'MCP 연결을 사용할 수 없습니다. 로컬 포트와 토큰을 확인하세요.'; + + @override + String get openTimelineFailed => '타임라인을 열 수 없습니다.'; + + @override + String get noTimelineSequence => '이 타임라인에는 시퀀스가 없습니다.'; + + @override + String get waitingForProject => '프로젝트가 열리기를 기다리는 중'; + + @override + String get hold => '유지'; + + @override + String get noImportableFiles => '가져올 수 있는 파일이 수신되지 않았습니다.'; + + @override + String get virtualFilesUnsupported => + '파일 관리자에서 원본 파일을 드래그하세요. 가상 파일은 아직 지원되지 않습니다.'; + + @override + String get editorSessionStartFailed => '타임라인 편집기를 열 수 없습니다'; + + @override + String get previewStartFailed => '기본 미리보기를 시작할 수 없습니다.'; + + @override + String get previewInvalidTrack => '선택한 오디오 또는 비디오 트랙이 미디어에 존재하지 않습니다.'; + + @override + String get previewMissingBinding => '미디어 바인딩이 누락되었습니다. 이 타임라인을 미리 볼 수 없습니다.'; + + @override + String get previewUnsupportedEdits => + '이 타임라인에는 아직 미리보기에서 지원되지 않는 수정사항이 포함되어 있습니다.'; + + @override + String get previewUnsupportedConfiguration => + '이 미리보기 구성은 현재 플랫폼 또는 시스템 버전에서 지원되지 않습니다.'; + + @override + String get previewHdrUnsupported => + 'HDR 미디어에는 SDR 미리 보기를 위한 톤 매핑이 필요합니다. 현재 시스템이나 미리보기 구성에서는 이를 지원하지 않습니다.'; + + @override + String get previewAudioOutOfRange => '오디오 클립이 소스 트랙 범위를 초과하여 미리 볼 수 없습니다.'; + + @override + String get previewResourceMissing => + '미리보기 미디어가 더 이상 존재하지 않습니다. 원본 파일을 다시 찾으세요.'; + + @override + String get previewInvalidComposition => + '동영상 구성 구성이 잘못되었습니다. 미리보기를 만들 수 없습니다.'; + + @override + String get previewInvalidData => '미리보기 데이터가 잘못되었습니다. 다시 시도해 주세요.'; + + @override + String get previewFailed => '미리보기에 실패했습니다. 미디어 액세스를 확인하고 다시 시도하세요.'; + + @override + String get chatFailed => '대화를 완료할 수 없습니다. 서비스 구성을 확인하거나 나중에 다시 시도하세요.'; + + @override + String get delete => '삭제'; + + @override + String get pinTimeline => '타임라인 고정'; + + @override + String get unpinTimeline => '타임라인 고정 해제'; + + @override + String deleteTimelineConfirmation(String name) { + return '“$name” 및 편집 기록을 삭제할까요? 이 작업은 되돌릴 수 없습니다.'; + } + + @override + String get processingFailed => '처리 실패'; + + @override + String get noMatchingOptions => '일치하는 옵션 없음'; + + @override + String removeMediaConfirmation(String name) { + return '라이브러리에서 “$name”를 제거하시겠습니까? 기존 클립, 히스토리, 원본 파일은 그대로 유지됩니다.'; + } + + @override + String mediaAdded(int count) { + return '미디어 참조 $count개가 추가되었습니다'; + } + + @override + String duplicatesSkipped(int count) { + return '$count 중복 파일을 건너뛰었습니다.'; + } + + @override + String mediaCount(int count) { + return '미디어 $count개'; + } + + @override + String get importMedia => '가져오기'; + + @override + String noMediaOfType(String type) { + return '$type 미디어 없음'; + } + + @override + String captionsImported(String count) { + return '가져온 $count 자막'; + } + + @override + String editCaptionError(String message) { + return '자막을 편집할 수 없습니다: $message'; + } + + @override + String mcpStartError(String message) { + return 'MCP를 시작할 수 없습니다: $message'; + } + + @override + String manualColorSpace(String name) { + return '수동 선택: $name'; + } + + @override + String detectedColorSpace(String name) { + return '감지됨: $name'; + } + + @override + String keyframeLabel(String channel) { + return '$channel 키프레임'; + } + + @override + String maskMode(String mode) { + return '조합 모드: $mode'; + } + + @override + String keyframeCount(int count) { + return '키프레임 $count개'; + } + + @override + String toggleKeyframe(String action, String channel) { + return '$channel 키프레임 $action'; + } + + @override + String previousKeyframe(String channel) { + return '이전 $channel 키프레임'; + } + + @override + String nextKeyframe(String channel) { + return '다음 $channel 키프레임'; + } + + @override + String keyframeSettings(String channel) { + return '$channel 키프레임 설정'; + } + + @override + String selectedClipsHint(int count) { + return '$count 클립이 선택됨\n해당 속성을 보려면 클립 하나를 선택하세요.'; + } + + @override + String transcriptionError(String code) { + return '전사에 실패했습니다. 구성 요소, 모델, 오디오 트랙 및 지속 시간 확인($code)'; + } + + @override + String captionsAdded(String count) { + return '$count 자막을 추가했습니다. 속성 패널에서 편집하세요.'; + } + + @override + String translatedCaptionsAdded(String count) { + return '$count 번역된 자막을 추가했습니다. 속성 패널에서 편집하세요.'; + } + + @override + String applyCaptionsError(String message) { + return '자막을 적용할 수 없습니다: $message'; + } + + @override + String applyTranslatedCaptionsError(String message) { + return '번역된 자막을 적용할 수 없습니다: $message'; + } + + @override + String recognizedCaptions(int count) { + return '자막 $count개 인식됨'; + } + + @override + String captionCount(int count) { + return '자막 $count개'; + } + + @override + String translationFailed(String message) { + return '번역 실패: $message'; + } + + @override + String translatedCaptionCount(int count, String language) { + return '$language 자막 $count개'; + } + + @override + String previewParameterError(String message) { + return '잘못된 미리보기 매개변수: $message'; + } + + @override + String mediaOffline(String names) { + return '미디어가 오프라인이거나 사용할 수 없음: $names'; + } + + @override + String searchOptions(String label) { + return '$label 검색…'; + } + + @override + String get loadRecentProjectsFailed => + '최근 라이브러리를 로드할 수 없습니다. 여전히 수동으로 라이브러리를 열 수 있습니다.'; + + @override + String get projectAccessFailed => '프로젝트를 사용할 수 없음'; + + @override + String get projectMissingDirectory => '프로젝트를 찾을 수 없음'; + + @override + String get recentProjectSaveFailed => '라이브러리가 열렸지만 최근 라이브러리 기록을 저장할 수 없습니다.'; + + @override + String get lastProjectSaveFailed => '프로젝트가 열렸지만 마지막 프로젝트 기록을 저장할 수 없습니다.'; + + @override + String get enterProjectName => '프로젝트 이름을 입력하세요.'; + + @override + String get projectSwitched => '프로젝트가 변경되었습니다. 미디어를 다시 드래그하세요.'; + + @override + String get notLocalMedia => '이 미디어는 로컬 파일이 아닙니다.'; + + @override + String get revealMediaFailed => '파일 관리자에 미디어를 표시할 수 없습니다.'; + + @override + String get openMatchingProject => '먼저 해당 프로젝트를 엽니다.'; + + @override + String get projectMismatch => + '이 위치에 있는 라이브러리는 기록과 일치하지 않습니다. 라이브러리 열기로 다시 선택하세요.'; + + @override + String get openProjectFirst => '먼저 라이브러리를 열어보세요'; + + @override + String get localFilesOnly => '파일 관리자에서 로컬 파일 드래그'; + + @override + String get foldersUnsupported => '파일을 선택합니다. 폴더 드래그는 아직 지원되지 않습니다.'; + + @override + String get mediaImportCancelled => '미디어 가져오기가 취소되었습니다.'; + + @override + String get fileAccessFailed => '파일이 없거나 읽을 수 없습니다. 위치와 권한을 확인하세요'; + + @override + String get registerMediaFailed => '미디어를 등록할 수 없습니다. 다시 시도해 주세요'; + + @override + String get mediaNoLongerExists => '미디어가 더 이상 존재하지 않습니다.'; + + @override + String get mediaNoTracks => '미디어에 사용 가능한 비디오 또는 오디오 트랙이 없습니다.'; + + @override + String get invalidMediaDuration => '잘못된 미디어 기간'; + + @override + String get mediaInfoUnsupported => '이 플랫폼에서는 아직 미디어 정보 읽기가 지원되지 않습니다.'; + + @override + String get mediaInfoFailed => '미디어 정보를 읽을 수 없습니다. 파일 및 접근권한을 확인하세요'; + + @override + String get saveTimelineFailed => + '타임라인을 저장할 수 없습니다. 다시 시도해 보세요. 저장되지 않은 수정사항은 이 세션에 남아 있습니다.'; + + @override + String get addKeyframeAction => '추가'; + + @override + String get backgroundTasks => '백그라운드 작업'; + + @override + String get noBackgroundTasks => '백그라운드 작업이 없습니다'; + + @override + String get retryTask => '다시 시도'; + + @override + String get applyOriginalCaptions => '원문 자막 적용'; + + @override + String get applyTranslatedCaptions => '번역 자막 적용'; + + @override + String get subtitleTaskStarted => '자막 작업을 시작했습니다'; + + @override + String get fitTimeline => '전체 타임라인 맞춤'; + + @override + String get modify => 'Modify'; + + @override + String get projectSettings => 'Project settings'; + + @override + String get projectSettingsDescription => + 'Change project output settings while keeping clip timing and speed.'; + + @override + String get projectColorSpace => 'Color space'; + + @override + String get projectWidth => 'Width (px)'; + + @override + String get projectHeight => 'Height (px)'; + + @override + String get projectResolutionInvalid => 'Enter a whole number from 1 to 16384'; + + @override + String get previewFullscreen => '전체 화면 미리보기'; + + @override + String get exitPreviewFullscreen => '전체 화면 종료'; + + @override + String get previewGoToStart => '처음으로 이동'; + + @override + String get previewPreviousFrame => '이전 프레임'; + + @override + String get previewNextFrame => '다음 프레임'; + + @override + String get softwareUpdates => '소프트웨어 업데이트'; + + @override + String get checkForUpdates => '업데이트 확인'; + + @override + String get automaticallyCheckUpdates => '자동으로 업데이트 확인'; + + @override + String get updatesUnavailable => '이 빌드에서는 업데이트를 사용할 수 없습니다.'; + + @override + String get updateCheckFailed => '업데이트를 확인할 수 없습니다. 다시 시도해 주세요.'; + + @override + String get removeBackground => '배경 제거'; + + @override + String get startBackgroundRemoval => '배경 제거'; + + @override + String get backgroundRemovalResourceRequired => + '배경 제거에는 로컬 모델이 필요합니다. 다운로드가 완료되면 자동으로 시작됩니다.'; + + @override + String get backgroundRemovalDownloadTask => '배경 제거 리소스 다운로드'; + + @override + String get backgroundRemovalResourceName => '배경 제거 모델'; + + @override + String get backgroundRemovalDestructiveHint => + '생성된 투명 미디어가 이 클립을 대체합니다. 실행 취소로 원본 클립을 복원할 수 있습니다.'; + + @override + String get backgroundRemovalTaskStarted => '배경 제거를 시작했습니다'; + + @override + String get startBackgroundRemovalFailed => + '배경 제거를 시작할 수 없습니다. 미디어를 확인하거나 현재 처리 작업이 끝날 때까지 기다려 주세요.'; + + @override + String get backgroundRemovalComplete => '배경 제거 완료'; + + @override + String get backgroundRemovalApplying => '클립 미디어 교체 중'; + + @override + String get backgroundRemovalFailed => '배경 제거 실패'; + + @override + String get agentSettings => 'Agent'; + + @override + String get agentSaveSettingsFailed => 'Agent 설정을 저장할 수 없습니다.'; + + @override + String get agentDeleteProviderTitle => '공급자를 삭제할까요?'; + + @override + String agentDeleteProviderDescription(String providerName) { + return '‘$providerName’ 및 저장된 API 키가 이 기기에서 삭제됩니다.'; + } + + @override + String get agentProviderRequired => '도우미를 활성화하기 전에 공급자를 추가하세요.'; + + @override + String get agentUseSelectedModel => '새 Agent 요청에는 선택한 모델이 사용됩니다.'; + + @override + String get agentEnable => 'Agent 활성화'; + + @override + String get agentDefaultModel => '기본 모델'; + + @override + String get agentConfigureModel => '모델 설정'; + + @override + String get agentSelectModel => '모델 선택'; + + @override + String get agentModelUnavailable => + '이 대화의 모델을 사용할 수 없습니다. 다른 모델을 선택하여 새 대화를 시작하세요.'; + + @override + String get agentModelChangeSession => '모델을 변경하면 새 Agent 세션이 시작됩니다.'; + + @override + String get agentCustomProviders => '사용자 지정 공급자'; + + @override + String get agentProviderStorageDescription => + '공급자 메타데이터는 로컬에 저장됩니다. API 키는 시스템 자격 증명 저장소에 보관됩니다.'; + + @override + String get agentAddProvider => '공급자 추가'; + + @override + String get agentBackToProviders => 'Provider 목록으로 돌아가기'; + + @override + String get agentLoadSettingsFailed => 'Agent 설정을 불러올 수 없습니다. 다시 시도'; + + @override + String get agentEnableProvider => 'Provider 활성화'; + + @override + String get agentEditProvider => '공급자 편집'; + + @override + String get agentDeleteProvider => '공급자 삭제'; + + @override + String get agentModelIdsUnique => '모델 ID는 고유해야 합니다.'; + + @override + String get agentEditProviderTitle => '공급자 편집'; + + @override + String get agentProviderEndpointDescription => + 'OpenAI 호환 Chat Completions 엔드포인트를 구성합니다.'; + + @override + String get agentSaveProvider => '공급자 저장'; + + @override + String get agentProviderConfiguration => 'Provider 설정'; + + @override + String get agentAuthenticationAndModels => '인증 및 모델'; + + @override + String get agentApiType => 'API 유형'; + + @override + String get agentOpenAiChatCompletions => 'OpenAI Completions'; + + @override + String get agentBaseUrl => '기본 URL'; + + @override + String get agentApiKey => 'API 키'; + + @override + String get agentProviderNameHint => '내 공급자'; + + @override + String get agentApiKeyOptional => '인증이 필요하지 않은 엔드포인트에서는 선택 사항입니다.'; + + @override + String get agentApiKeyKeep => '저장된 키를 유지하려면 비워 두세요.'; + + @override + String get agentOptional => '선택 사항'; + + @override + String get agentApiKeyOneLine => 'API 키는 한 줄이어야 합니다.'; + + @override + String get agentRemoveSavedApiKey => '저장된 API 키 제거'; + + @override + String get agentModels => '모델'; + + @override + String get agentAddModel => '모델 추가'; + + @override + String get agentRequiredField => '필수 입력 항목입니다.'; + + @override + String get agentInvalidBaseUrl => + '자격 증명, 쿼리 또는 프래그먼트가 없는 HTTP(S) 기본 URL을 입력하세요.'; + + @override + String get agentModelId => '모델 ID'; + + @override + String get agentContextWindow => '컨텍스트 창'; + + @override + String get agentMaxOutputTokens => '최대 출력'; + + @override + String get agentMaxOutputBelowContext => '컨텍스트 창보다 작아야 합니다.'; + + @override + String get agentDeleteModel => '모델 삭제'; + + @override + String get agentPositiveInteger => '양의 정수를 입력하세요.'; + + @override + String get agentConfigurationReadFailed => + 'Agent 구성을 읽을 수 없습니다. 설정을 확인하고 다시 시도하세요.'; + + @override + String get agentConfigurationRequired => '먼저 설정에서 Agent를 구성하고 활성화하세요.'; + + @override + String get agentSessionRestoreFailed => + 'Agent 세션을 복원할 수 없습니다. 나중에 다시 시도해 주세요.'; + + @override + String get agentContextBudgetExceeded => + '시스템 지침, 도구 및 메시지를 위한 입력 공간이 부족합니다. 컨텍스트를 늘리거나 최대 출력을 줄이세요.'; + + @override + String get agentAuthenticationFailed => '인증에 실패했습니다. API Key와 권한을 확인하세요.'; + + @override + String get agentConnectionFailed => + '연결에 실패했거나 시간이 초과되었습니다. Base URL과 네트워크를 확인하세요.'; + + @override + String get agentProtocolFailed => '응답이 선택한 API 유형과 다르거나 스트림이 불완전합니다.'; + + @override + String get agentContextBudgetTooSmall => + '시스템 지침용 입력 공간을 확보하세요. 컨텍스트를 늘리거나 최대 출력을 줄이세요.'; + + @override + String get agentCompacting => '컨텍스트 정리 중…'; + + @override + String get agentEditing => '편집 중…'; + + @override + String get agentVerifying => '결과 확인 중…'; + + @override + String get agentTurnLimitReached => + '작업 실행 한도에 도달했습니다. 편집 내용은 저장되었습니다. “계속”을 보내면 이어서 진행합니다.'; + + @override + String get agentRecoveryRequired => + '이전 작업 결과가 확인되지 않았습니다. 계속하여 저장된 기록을 확인하세요. 확인되지 않은 편집은 반복하지 않습니다.'; + + @override + String get agentExportReplyFailed => + '동영상 내보내기는 완료되었지만 요약 응답에 실패했습니다. 편집이나 내보내기를 반복하지 않고 요약을 다시 시도할 수 있습니다.'; + + @override + String get agentRetrySummary => '요약 재시도'; + + @override + String get agentResumeTask => '작업 계속'; + + @override + String get agentTaskInterrupted => '작업이 중단되었습니다. 저장된 진행 상태에서 계속할 수 있습니다.'; + + @override + String get downloadSubtitleModel => '자막 모델 다운로드'; + + @override + String get downloadModelAction => '다운로드'; + + @override + String get subtitleEngineUnavailable => + '모델은 설치되었지만 자막 처리 엔진을 시작하지 못했습니다. 엔진을 복구하세요. 모델을 다시 다운로드할 필요는 없습니다.'; + + @override + String get backgroundTaskDetails => '작업 상세'; + + @override + String get backgroundTaskFailed => '실패'; + + @override + String get backgroundTaskCompleted => '완료'; + + @override + String get captionWrapLines => '자막 줄바꿈'; + + @override + String get captionSingleLine => '자막을 한 줄로 표시'; + + @override + String get noMatchingCaptions => '일치하는 자막 없음'; + + @override + String get subtitleResourcesRequired => + '자막 생성에 필요한 리소스입니다. 다운로드가 끝나면 자동으로 생성이 시작됩니다.'; + + @override + String subtitleResourcesDownloadSize(String size) { + return '다운로드할 용량: $size'; + } + + @override + String get pauseDownload => '일시 중지'; + + @override + String get resumeDownload => '계속'; + + @override + String get downloadPaused => '일시 중지됨'; + + @override + String get cancelResourceDownloadTitle => '다운로드를 취소할까요?'; + + @override + String get cancelResourceDownloadMessage => + '다운로드가 중지됩니다. 현재 리소스의 다운로드 진행 내용이 손실될 수 있습니다.'; + + @override + String get continueDownload => '다운로드 계속'; + + @override + String get cancelDownload => '다운로드 취소'; + + @override + String get speechResourceStage => '음성 인식 리소스'; + + @override + String get translationResourceStage => '번역 리소스'; + + @override + String get subtitleResourceDownloadTask => '음성 및 번역 리소스 다운로드'; + + @override + String get downloadingSpeechModel => '음성 모델 다운로드 중'; + + @override + String get downloadingTranslationModel => '번역 모델 다운로드 중'; + + @override + String get checkingForUpdates => '업데이트 확인 중…'; + + @override + String get appIsUpToDate => '최신 버전입니다.'; + + @override + String downloadingUpdate(int progress) { + return '업데이트 다운로드 중: $progress%'; + } + + @override + String updateAvailable(String version) { + return '버전 $version을 사용할 수 있습니다.'; + } + + @override + String get downloadUpdate => '업데이트 다운로드'; + + @override + String get restartToUpdate => '다시 시작하여 업데이트'; + + @override + String get updateOperationFailed => '업데이트하지 못했습니다. 실행 중인 작업을 완료한 후 다시 시도하세요.'; + + @override + String get windowMinimize => '최소화'; + + @override + String get windowMaximize => '최대화'; + + @override + String get windowRestore => '복원'; + + @override + String get workspaceAgent => '도우미'; + + @override + String get workspaceCut => '편집'; + + @override + String get noAvailableOptions => '사용 가능한 옵션이 없습니다'; + + @override + String get composerReferenceInvalid => + '참조가 만료되었습니다. 원래 프로젝트로 돌아가거나 참조를 제거하세요.'; + + @override + String durationSeconds(int seconds) { + return '$seconds초'; + } + + @override + String durationMinutesSeconds(int minutes, int seconds) { + return '$minutes분 $seconds초'; + } + + @override + String get projectNameInvalid => '잘못된 프로젝트 이름입니다'; + + @override + String get projectLocationDefaultUnavailable => + '기본 프로젝트 위치에 접근할 수 없습니다. 설정에서 다시 선택하세요.'; + + @override + String get chooseProjectLocation => '먼저 설정에서 프로젝트 저장 위치를 선택하세요.'; + + @override + String get untitledTimeline => '제목 없는 타임라인'; + + @override + String get primarySequence => '주 시퀀스'; + + @override + String get primaryStoryline => '주 스토리라인'; + + @override + String get projectSessionClosed => '프로젝트 세션이 닫혔습니다. 프로젝트를 다시 여세요.'; + + @override + String get timelineSessionClosed => '타임라인 세션이 닫혔습니다. 타임라인을 다시 여세요.'; + + @override + String get timelineMissing => '타임라인이 없거나 삭제되었습니다.'; + + @override + String get timelineInUse => '사용 중인 타임라인은 삭제할 수 없습니다.'; + + @override + String get timelineHasBackgroundTasks => '타임라인의 백그라운드 작업을 완료한 후 삭제하세요.'; + + @override + String get timelineRequired => '프로젝트에 타임라인이 하나 이상 있어야 합니다.'; + + @override + String get mediaReadFailed => '미디어를 읽을 수 없습니다'; + + @override + String get mediaImportFailed => '미디어를 가져올 수 없습니다'; + + @override + String get unsupportedMediaType => '동영상, 오디오 및 이미지 파일만 가져올 수 있습니다.'; + + @override + String get mediaNoVideoTracks => '미디어에 사용 가능한 동영상 트랙이 없습니다'; + + @override + String get mediaDurationOutOfRange => '미디어 길이가 타임라인 범위를 초과합니다'; + + @override + String resourceDownloadHttpFailed(String statusCode) { + return '다운로드 실패 (HTTP $statusCode)'; + } + + @override + String get resourceChecksumFailed => '모델 파일 검증에 실패했습니다. 리소스를 다시 다운로드하세요.'; + + @override + String get subtitleLanguageAf => '아프리칸스어'; + + @override + String get subtitleLanguageAm => '암하라어'; + + @override + String get subtitleLanguageAr => '아랍어'; + + @override + String get subtitleLanguageAst => '아스투리아어'; + + @override + String get subtitleLanguageAz => '아제르바이잔어'; + + @override + String get subtitleLanguageBa => '바슈키르어'; + + @override + String get subtitleLanguageBe => '벨라루스어'; + + @override + String get subtitleLanguageBg => '불가리아어'; + + @override + String get subtitleLanguageBn => '벵골어'; + + @override + String get subtitleLanguageBr => '브르타뉴어'; + + @override + String get subtitleLanguageBs => '보스니아어'; + + @override + String get subtitleLanguageCa => '카탈로니아어'; + + @override + String get subtitleLanguageCeb => '세부아노어'; + + @override + String get subtitleLanguageCs => '체코어'; + + @override + String get subtitleLanguageCy => '웨일스어'; + + @override + String get subtitleLanguageDa => '덴마크어'; + + @override + String get subtitleLanguageDe => '독일어'; + + @override + String get subtitleLanguageEl => '그리스어'; + + @override + String get subtitleLanguageEn => '영어'; + + @override + String get subtitleLanguageEs => '스페인어'; + + @override + String get subtitleLanguageEt => '에스토니아어'; + + @override + String get subtitleLanguageFa => '페르시아어'; + + @override + String get subtitleLanguageFf => '풀라어'; + + @override + String get subtitleLanguageFi => '핀란드어'; + + @override + String get subtitleLanguageFr => '프랑스어'; + + @override + String get subtitleLanguageFy => '서부 프리지아어'; + + @override + String get subtitleLanguageGa => '아일랜드어'; + + @override + String get subtitleLanguageGd => '스코틀랜드 게일어'; + + @override + String get subtitleLanguageGl => '갈리시아어'; + + @override + String get subtitleLanguageGu => '구자라트어'; + + @override + String get subtitleLanguageHa => '하우사어'; + + @override + String get subtitleLanguageHe => '히브리어'; + + @override + String get subtitleLanguageHi => '힌디어'; + + @override + String get subtitleLanguageHr => '크로아티아어'; + + @override + String get subtitleLanguageHt => '아이티어'; + + @override + String get subtitleLanguageHu => '헝가리어'; + + @override + String get subtitleLanguageHy => '아르메니아어'; + + @override + String get subtitleLanguageId => '인도네시아어'; + + @override + String get subtitleLanguageIg => '이그보어'; + + @override + String get subtitleLanguageIlo => '이로코어'; + + @override + String get subtitleLanguageIs => '아이슬란드어'; + + @override + String get subtitleLanguageIt => '이탈리아어'; + + @override + String get subtitleLanguageJa => '일본어'; + + @override + String get subtitleLanguageJv => '자바어'; + + @override + String get subtitleLanguageKa => '조지아어'; + + @override + String get subtitleLanguageKk => '카자흐어'; + + @override + String get subtitleLanguageKm => '크메르어'; + + @override + String get subtitleLanguageKn => '칸나다어'; + + @override + String get subtitleLanguageKo => '한국어'; + + @override + String get subtitleLanguageLb => '룩셈부르크어'; + + @override + String get subtitleLanguageLg => '간다어'; + + @override + String get subtitleLanguageLn => '링갈라어'; + + @override + String get subtitleLanguageLo => '라오어'; + + @override + String get subtitleLanguageLt => '리투아니아어'; + + @override + String get subtitleLanguageLv => '라트비아어'; + + @override + String get subtitleLanguageMg => '말라가시어'; + + @override + String get subtitleLanguageMk => '마케도니아어'; + + @override + String get subtitleLanguageMl => '말라얄람어'; + + @override + String get subtitleLanguageMn => '몽골어'; + + @override + String get subtitleLanguageMr => '마라티어'; + + @override + String get subtitleLanguageMs => '말레이어'; + + @override + String get subtitleLanguageMy => '버마어'; + + @override + String get subtitleLanguageNe => '네팔어'; + + @override + String get subtitleLanguageNl => '네덜란드어'; + + @override + String get subtitleLanguageNo => '노르웨이어'; + + @override + String get subtitleLanguageNs => '북부 소토어'; + + @override + String get subtitleLanguageOc => '오크어'; + + @override + String get subtitleLanguageOr => '오리야어'; + + @override + String get subtitleLanguagePa => '펀자브어'; + + @override + String get subtitleLanguagePl => '폴란드어'; + + @override + String get subtitleLanguagePs => '파슈토어'; + + @override + String get subtitleLanguagePt => '포르투갈어'; + + @override + String get subtitleLanguageRo => '루마니아어'; + + @override + String get subtitleLanguageRu => '러시아어'; + + @override + String get subtitleLanguageSd => '신디어'; + + @override + String get subtitleLanguageSi => '싱할라어'; + + @override + String get subtitleLanguageSk => '슬로바키아어'; + + @override + String get subtitleLanguageSl => '슬로베니아어'; + + @override + String get subtitleLanguageSo => '소말리아어'; + + @override + String get subtitleLanguageSq => '알바니아어'; + + @override + String get subtitleLanguageSr => '세르비아어'; + + @override + String get subtitleLanguageSs => '시스와티어'; + + @override + String get subtitleLanguageSu => '순다어'; + + @override + String get subtitleLanguageSv => '스웨덴어'; + + @override + String get subtitleLanguageSw => '스와힐리어'; + + @override + String get subtitleLanguageTa => '타밀어'; + + @override + String get subtitleLanguageTh => '태국어'; + + @override + String get subtitleLanguageTl => '타갈로그어'; + + @override + String get subtitleLanguageTn => '츠와나어'; + + @override + String get subtitleLanguageTr => '튀르키예어'; + + @override + String get subtitleLanguageUk => '우크라이나어'; + + @override + String get subtitleLanguageUr => '우르두어'; + + @override + String get subtitleLanguageUz => '우즈베크어'; + + @override + String get subtitleLanguageVi => '베트남어'; + + @override + String get subtitleLanguageWo => '월로프어'; + + @override + String get subtitleLanguageXh => '코사어'; + + @override + String get subtitleLanguageYi => '이디시어'; + + @override + String get subtitleLanguageYo => '요루바어'; + + @override + String get subtitleLanguageYue => '광둥어'; + + @override + String get subtitleLanguageZh => '중국어'; + + @override + String get subtitleLanguageZu => '줄루어'; + + @override + String get linearRec2020 => '선형 Rec.2020'; + + @override + String get diagnostics => '진단'; + + @override + String get exportDiagnostics => '진단 패키지 내보내기'; + + @override + String get exportDiagnosticsFailed => '진단을 내보낼 수 없습니다. 다시 시도해 주세요.'; + + @override + String get exportDiagnosticsSucceeded => '진단 패키지가 저장되었습니다.'; +} diff --git a/lib/l10n/app_localizations_pt.dart b/lib/l10n/app_localizations_pt.dart new file mode 100644 index 0000000..7830825 --- /dev/null +++ b/lib/l10n/app_localizations_pt.dart @@ -0,0 +1,2225 @@ +// ignore: unused_import +import 'package:intl/intl.dart' as intl; + +import 'app_localizations.dart'; + +// ignore_for_file: type=lint + +/// The translations for Portuguese (`pt`). +class AppLocalizationsPt extends AppLocalizations { + AppLocalizationsPt([String locale = 'pt']) : super(locale); + + @override + String get selectProject => 'Selecionar projeto'; + + @override + String get searchProjects => 'Pesquisar projetos'; + + @override + String get noMatchingProjects => 'Nenhum projeto correspondente'; + + @override + String get projectsNone => 'Nenhum projeto'; + + @override + String get projectLocationMissing => + 'A pasta não existe. Será criada ao criar um projeto.'; + + @override + String get projectLocationUnavailable => + 'O local de armazenamento está indisponível. Conecte o disco ou verifique a rede e tente novamente, ou altere o local.'; + + @override + String get projectLocationNotWritable => + 'Não é possível gravar no local de armazenamento. Verifique as permissões ou altere o local.'; + + @override + String get projectLocationCreateFailed => + 'Não foi possível criar a pasta do projeto ou gravar nela. Verifique as permissões ou altere o local.'; + + @override + String get removeProjectFromSidebar => 'Remover da barra lateral'; + + @override + String get projectRemoved => + 'Projeto removido. Os arquivos locais e as conversas foram preservados.'; + + @override + String get agentNoConversations => 'Ainda não há conversas'; + + @override + String get renameConversationTitle => 'Renomear conversa'; + + @override + String get renameConversationDescription => + 'Use um nome curto e fácil de reconhecer.'; + + @override + String get collapseProject => 'Recolher projeto'; + + @override + String get expandProject => 'Expandir projeto'; + + @override + String agentDeleteConfirmation(String title) { + return 'Excluir permanentemente “$title” e todas as mensagens? Esta ação não pode ser desfeita. Os arquivos locais do projeto não serão afetados.'; + } + + @override + String get agentEmptyTrashConfirmation => + 'Excluir permanentemente todas as conversas da lixeira? Esta ação não pode ser desfeita. Os arquivos locais do projeto não serão afetados.'; + + @override + String get agentConversations => 'Conversas'; + + @override + String get showMoreConversations => 'Mostrar mais'; + + @override + String get showFewerConversations => 'Mostrar menos'; + + @override + String get agentNewConversation => 'Nova conversa'; + + @override + String agentElapsedTime(String duration) { + return 'Duração $duration'; + } + + @override + String get agentConversationActions => 'Ações da conversa'; + + @override + String get agentMoveToTrash => 'Mover para a lixeira'; + + @override + String get agentTrash => 'Lixeira'; + + @override + String get agentRestore => 'Restaurar'; + + @override + String get agentEmptyTrash => 'Esvaziar lixeira'; + + @override + String get agentDeleteForever => 'Excluir permanentemente'; + + @override + String get agentConversationLocation => 'Local das conversas'; + + @override + String get agentChooseExistingConversations => + 'Escolher conversas existentes'; + + @override + String get agentMoveConversations => 'Mover conversas'; + + @override + String get agentLocationUnavailable => + 'O local das conversas está indisponível'; + + @override + String get agentLocationBusy => + 'Aguarde as conversas em andamento terminarem'; + + @override + String get agentRelinkProvider => 'Vincular provedor novamente'; + + @override + String get settings => 'Configurações'; + + @override + String get closeSettings => 'Fechar configurações'; + + @override + String get general => 'Geral'; + + @override + String get appearance => 'Aparência'; + + @override + String get theme => 'Tema'; + + @override + String get system => 'Seguir o sistema'; + + @override + String get light => 'Claro'; + + @override + String get dark => 'Escuro'; + + @override + String get saveAppearanceFailed => + 'Não foi possível salvar a aparência. Por favor, tente novamente.'; + + @override + String get loadAppearanceFailed => + 'Não foi possível carregar a aparência. Selecione um tema novamente.'; + + @override + String get cancel => 'Cancelar'; + + @override + String get save => 'Salvar'; + + @override + String get create => 'Criar'; + + @override + String get close => 'Fechar'; + + @override + String get retry => 'Tentar novamente'; + + @override + String get select => 'Selecionar'; + + @override + String get name => 'Nome'; + + @override + String get enterName => 'Digite um nome'; + + @override + String get invalidName => + 'Os nomes não podem conter separadores de caminho ou caracteres de controle'; + + @override + String get projects => 'Projetos'; + + @override + String get projectName => 'Nome do projeto'; + + @override + String get projectLocation => 'Local de salvamento dos projetos'; + + @override + String get projectLocationNotSet => 'Não definido'; + + @override + String get loadProjectLocationFailed => + 'Não foi possível carregar o local de salvamento dos projetos.'; + + @override + String get saveProjectLocationFailed => + 'Não foi possível salvar o local dos projetos.'; + + @override + String get resourceLocation => 'Local de armazenamento dos recursos'; + + @override + String get resourceLocationNotSet => 'Não definido'; + + @override + String get loadResourceLocationFailed => + 'Não foi possível carregar o local de armazenamento dos recursos.'; + + @override + String get saveResourceLocationFailed => + 'Não foi possível salvar o local dos recursos.'; + + @override + String get transcriptionResourceRequired => + 'Para gerar legendas, primeiro é necessário baixar um modelo de reconhecimento de fala.'; + + @override + String get downloadAndContinue => 'Baixar e continuar'; + + @override + String get downloadingResource => 'Baixando…'; + + @override + String get downloadInBackground => 'Baixar em segundo plano'; + + @override + String get processingResourceDownloadFailed => + 'Não foi possível baixar o recurso de reconhecimento de fala. Tente novamente.'; + + @override + String get newProject => 'Novo projeto'; + + @override + String get openProject => 'Abrir projeto'; + + @override + String get openProjectMore => 'Abrir outro projeto'; + + @override + String get saveHere => 'Salvar aqui'; + + @override + String get selectDirectoryFailed => + 'Não foi possível selecionar um diretório. Verifique as permissões do sistema.'; + + @override + String get openingWorkspace => 'Abrindo o espaço de trabalho…'; + + @override + String get loadProjectsFailed => 'Não foi possível carregar os projetos'; + + @override + String get projectsEmpty => 'Nenhum projeto'; + + @override + String get backToProjects => 'Voltar à edição'; + + @override + String get timelines => 'Linhas do tempo'; + + @override + String timelineLimitReached(int count) { + return 'Cada projeto pode conter até $count linhas do tempo.'; + } + + @override + String get timelineName => 'Nome da linha do tempo'; + + @override + String defaultTimelineName(int index) { + return 'Linha do tempo $index'; + } + + @override + String get newTimeline => 'Nova linha do tempo'; + + @override + String get noTimelines => 'Nenhuma linha do tempo'; + + @override + String get activeTimeline => 'Linha do tempo atual'; + + @override + String get timelineUnavailable => 'Linha do tempo indisponível'; + + @override + String get projectNoTimelines => 'Este projeto ainda não tem linhas do tempo'; + + @override + String get createTimelineHint => + 'Crie uma linha do tempo na seção “Linhas do tempo” à esquerda para começar a editar.'; + + @override + String get createTimelineChat => + 'Crie uma linha do tempo para iniciar a conversa'; + + @override + String get operationFailed => + 'A operação falhou. Por favor, tente novamente.'; + + @override + String get collapseSidebar => 'Recolher barra lateral'; + + @override + String get expandSidebar => 'Expandir barra lateral'; + + @override + String get expandEditor => 'Expandir área de edição'; + + @override + String get collapseProperties => 'Recolher propriedades'; + + @override + String get expandProperties => 'Expandir propriedades'; + + @override + String get layout => 'Layout'; + + @override + String get editingFirstLayout => 'Edição em primeiro lugar'; + + @override + String get agentEditingLayout => 'Agente e edição'; + + @override + String get agentLayoutDescription => 'Planejar, colaborar e executar'; + + @override + String get editingLayoutDescription => 'Pré-visualizar, editar e refinar'; + + @override + String get materials => 'Mídia'; + + @override + String get all => 'Todos'; + + @override + String get video => 'Vídeo'; + + @override + String get audio => 'Áudio'; + + @override + String get image => 'Imagem'; + + @override + String get picture => 'Imagem'; + + @override + String get captions => 'Legendas'; + + @override + String get text => 'Texto'; + + @override + String get noMedia => 'Sem mídia'; + + @override + String get mediaCategory => 'Categoria de mídia'; + + @override + String get captionTasks => 'Tarefas de legendas'; + + @override + String get listLayout => 'Visualização de lista'; + + @override + String get gridLayout => 'Visualização em grade'; + + @override + String get addToTimeline => 'Adicionar à linha do tempo'; + + @override + String get rename => 'Renomear'; + + @override + String get renameMedia => 'Renomear mídia'; + + @override + String get removeMedia => 'Remover mídia'; + + @override + String get remove => 'Remover'; + + @override + String get revealFinder => 'Mostrar no Finder'; + + @override + String get revealFileManager => 'Mostrar no gerenciador de arquivos'; + + @override + String get dropToAdd => 'Solte para adicionar'; + + @override + String get timelineDropToStart => 'Arraste a mídia aqui para começar.'; + + @override + String get dragMediaHint => + 'Arraste vídeo, áudio ou imagens aqui\nOs arquivos originais permanecem em seu local atual'; + + @override + String get transcribe => 'Transcrever'; + + @override + String get generateCaptions => 'Gerar legendas'; + + @override + String get play => 'Reproduzir'; + + @override + String get pause => 'Pausar'; + + @override + String get retryPreview => 'Tentar visualizar novamente'; + + @override + String get canvasRatio => 'Proporção da tela'; + + @override + String get noPreviewContent => + 'Nenhum conteúdo para visualizar na linha do tempo'; + + @override + String get nativePreviewUnsupported => + 'A visualização nativa não está disponível nesta plataforma'; + + @override + String get canvasTransformFailed => + 'Não foi possível transformar a tela. Por favor, tente novamente.'; + + @override + String get undo => 'Desfazer'; + + @override + String get redo => 'Refazer'; + + @override + String get deleteSelectedClips => 'Excluir clipes selecionados'; + + @override + String get splitAtPlayhead => 'Dividir no playhead'; + + @override + String get trimLeft => 'Aparar à esquerda'; + + @override + String get trimRight => 'Aparar à direita'; + + @override + String get trimLeftTooltip => + 'Remover à esquerda do cursor e manter a direita'; + + @override + String get trimRightTooltip => + 'Remover à direita do cursor e manter a esquerda'; + + @override + String get currentSequence => 'Sequência atual'; + + @override + String get projectProperties => 'Propriedades do projeto'; + + @override + String get canvasSize => 'Tamanho da tela'; + + @override + String get frameRate => 'Taxa de quadros'; + + @override + String get duration => 'Duração'; + + @override + String get totalDuration => 'Duração total'; + + @override + String get clipDuration => 'Duração do clipe'; + + @override + String get seconds => 'segundos'; + + @override + String get clip => 'Clipe'; + + @override + String get unnamedClip => 'Clipe sem nome'; + + @override + String get gap => 'Espaço vazio'; + + @override + String get compoundClip => 'Clipe composto'; + + @override + String get textClip => 'Clipe de texto'; + + @override + String get pictureProperties => 'Imagem'; + + @override + String get position => 'Posição'; + + @override + String get rotation => 'Rotação'; + + @override + String get scale => 'Escala'; + + @override + String get size => 'Tamanho'; + + @override + String get transform => 'Transformação'; + + @override + String get resetPosition => 'Redefinir posição'; + + @override + String get keepAspectRatio => 'Bloquear proporção de aspecto'; + + @override + String get alignment => 'Alinhamento'; + + @override + String get alignLeft => 'Alinhar à esquerda'; + + @override + String get alignRight => 'Alinhar à direita'; + + @override + String get alignTop => 'Alinhar topo'; + + @override + String get alignBottom => 'Alinhar parte inferior'; + + @override + String get alignHorizontalCenter => 'Centralizar horizontalmente'; + + @override + String get alignVerticalCenter => 'Centralizar verticalmente'; + + @override + String get volume => 'Volume'; + + @override + String get gain => 'Ganho'; + + @override + String get mute => 'Silenciar'; + + @override + String get unmute => 'Ativar som'; + + @override + String get resetVolume => 'Redefinir volume'; + + @override + String get invalidGain => 'Insira um valor entre -90 e +12'; + + @override + String get animation => 'Animação'; + + @override + String get keyframes => 'Quadros-chave'; + + @override + String get removeAllKeyframes => 'Remover todos os quadros-chave'; + + @override + String get linear => 'Linear'; + + @override + String get easeIn => 'Entrada suave'; + + @override + String get easeOut => 'Saída suave'; + + @override + String get easeInOut => 'Entrada e saída suaves'; + + @override + String get basic => 'Básico'; + + @override + String get mask => 'Máscara'; + + @override + String get addMask => 'Adicionar máscara'; + + @override + String get deleteMask => 'Excluir máscara'; + + @override + String get resetMask => 'Redefinir máscara'; + + @override + String get enableMask => 'Habilitar máscara'; + + @override + String get disableMask => 'Desativar máscara'; + + @override + String get moveMaskUp => 'Mova a máscara para cima'; + + @override + String get moveMaskDown => 'Mover máscara para baixo'; + + @override + String get rectangle => 'Retângulo'; + + @override + String get ellipse => 'Elipse'; + + @override + String get invert => 'Inverter'; + + @override + String get feather => 'Suavização'; + + @override + String get add => 'Adicionar'; + + @override + String get subtract => 'Subtrair'; + + @override + String get intersect => 'Interseção'; + + @override + String get initialRegion => 'Região inicial'; + + @override + String get none => 'Nenhum'; + + @override + String get color => 'Cor'; + + @override + String get fontSize => 'Tamanho da fonte'; + + @override + String get outlineWidth => 'Largura do contorno'; + + @override + String get outlineColor => 'Cor do contorno'; + + @override + String get captionBaseline => 'Linha de base das legendas'; + + @override + String get content => 'Texto'; + + @override + String get start => 'Início'; + + @override + String get time => 'Tempo'; + + @override + String get speed => 'Velocidade'; + + @override + String speedSegmentCount(int count) { + return '$count segmentos de velocidade'; + } + + @override + String get splitSpeedAtPlayhead => 'Dividir velocidade no cursor'; + + @override + String get speedChange => 'Velocidade'; + + @override + String get speedMode => 'Modo de velocidade'; + + @override + String get constantSpeed => 'Velocidade constante'; + + @override + String get segmentedSpeed => 'Velocidade segmentada'; + + @override + String get speedNotAvailable => + 'Os controles de velocidade ainda não estão disponíveis'; + + @override + String get custom => 'Personalizado'; + + @override + String get invalidNumber => 'Valor inválido'; + + @override + String get mediaUnavailable => 'Mídia indisponível'; + + @override + String get mediaMissing => 'Mídia ausente'; + + @override + String get mediaColorSpace => 'Espaço de cores da mídia'; + + @override + String get mediaColorInterpretation => 'Interpretação de cores da mídia'; + + @override + String get colorInfoNotLoaded => 'Informações de cor não carregadas'; + + @override + String get unknownColorSpace => + 'Espaço de cores desconhecido. Exibindo como Rec.709.'; + + @override + String get colorBackendUnsupported => + 'O back-end atual não oferece suporte à interpretação de cores de mídia.'; + + @override + String get loadClipPropertiesFailed => + 'Não foi possível ler as propriedades do clipe'; + + @override + String get updatePictureFailed => + 'Não foi possível atualizar as propriedades da imagem'; + + @override + String get updateVolumeFailed => 'Não foi possível atualizar o volume'; + + @override + String get updateMaskFailed => 'Não foi possível atualizar a máscara'; + + @override + String get updateKeyframesFailed => + 'Não foi possível atualizar os quadros-chave'; + + @override + String get maskPreviewFailed => + 'Não foi possível preparar a visualização da máscara'; + + @override + String get alignClipFailed => + 'Não foi possível alinhar o clipe. Aguarde a visualização e tente novamente.'; + + @override + String get invalidTransform => + 'A escala deve ser de 1% a 10.000%. A posição e o ângulo devem ser números válidos.'; + + @override + String get editFailed => + 'Não foi possível editar. Verifique a entrada e o intervalo de tempo.'; + + @override + String get addMediaFailed => + 'Não foi possível adicionar mídia. Por favor, tente novamente.'; + + @override + String get deleteCaption => 'Excluir legenda'; + + @override + String get mergeCaptions => 'Mesclar legendas'; + + @override + String get captionDeleted => 'Legenda excluída'; + + @override + String get captionChanged => + 'As legendas mudaram. Por favor, tente novamente.'; + + @override + String get captionEditChanged => 'As legendas mudaram. Edite novamente.'; + + @override + String get assistantHint => 'Descreva sua ideia de edição'; + + @override + String get configureAgentHint => + 'Configure o serviço do agente para iniciar o bate-papo'; + + @override + String get agentRestartHint => + 'Configure o serviço do agente e reinicie o aplicativo.'; + + @override + String get replyInterrupted => 'Resposta interrompida'; + + @override + String get replying => 'Respondendo…'; + + @override + String get stopReply => 'Parar resposta'; + + @override + String get sendMessage => 'Enviar mensagem'; + + @override + String get addAttachment => 'Adicionar anexo (ainda não disponível)'; + + @override + String get replyFailed => + 'A resposta falhou. Verifique a conexão ou tente novamente mais tarde.'; + + @override + String get mcpService => 'Serviço MCP'; + + @override + String get listenPort => 'Porta'; + + @override + String get accessToken => 'Token de acesso'; + + @override + String get copyAccessToken => 'Copiar token de acesso'; + + @override + String get accessTokenCopied => 'Token de acesso copiado'; + + @override + String get loadMcpFailed => + 'Não foi possível carregar as configurações do MCP. Tentar novamente'; + + @override + String get saveMcpFailed => + 'Não foi possível salvar as configurações do MCP. Por favor, tente novamente.'; + + @override + String get retryStart => 'Tentar iniciar novamente'; + + @override + String get invalidPort => 'A porta deve estar entre 1 e 65535'; + + @override + String get loadingSettings => 'Carregando configurações…'; + + @override + String get starting => 'Iniciando…'; + + @override + String get stopping => 'Parando…'; + + @override + String get disabled => 'Desativado'; + + @override + String get running => 'Em execução'; + + @override + String get startFailed => 'Falha ao iniciar'; + + @override + String get saved => 'Salvo'; + + @override + String get unsaved => 'Não salvo'; + + @override + String get saving => 'Salvando…'; + + @override + String get pendingSave => 'Salvamento pendente'; + + @override + String get notApplied => 'Não aplicado'; + + @override + String get enable => 'Ativar'; + + @override + String get disable => 'Desativar'; + + @override + String get type => 'Tipo'; + + @override + String get status => 'Status'; + + @override + String get file => 'Arquivo'; + + @override + String get unboundMedia => 'Nenhuma mídia vinculada'; + + @override + String get unboundAudio => 'Nenhuma faixa de áudio vinculada'; + + @override + String get vertical => 'Vertical'; + + @override + String get language => 'Idioma'; + + @override + String get saveLanguageFailed => + 'Não foi possível salvar o idioma. Por favor, tente novamente.'; + + @override + String get loadLanguageFailed => + 'Não foi possível carregar o idioma. Selecione novamente.'; + + @override + String get propertiesFirstLayout => 'Propriedades primeiro'; + + @override + String get defaultLayout => 'Layout padrão'; + + @override + String get separateVocals => 'Separar vocais'; + + @override + String get detachAudio => 'Separar áudio'; + + @override + String get restoreAudio => 'Restaurar áudio'; + + @override + String get audioDetached => 'Áudio separado'; + + @override + String get addAll => 'Adicionar tudo'; + + @override + String get preparingMedia => 'Preparando mídia…'; + + @override + String get cancelling => 'Cancelando…'; + + @override + String get cancelled => 'Cancelado'; + + @override + String get interruptedTask => 'Tarefa interrompida. Reinicie para continuar'; + + @override + String get auto => 'Automático'; + + @override + String get autoDetect => 'Detecção automática'; + + @override + String get noTranslation => 'Não traduzir'; + + @override + String get sourceLanguage => 'Idioma de origem'; + + @override + String get translationLanguage => 'Idioma de destino'; + + @override + String get transcriptionNotConfigured => + 'A transcrição não está configurada. Instale o componente de reconhecimento e o modelo Whisper Turbo.'; + + @override + String get translationNotConfigured => + 'A tradução de legendas não está configurada. Você pode gerar legendas no idioma de origem.'; + + @override + String get sourceLanguageUnknown => + 'Não foi possível determinar um idioma de origem para tradução.'; + + @override + String get startTranscriptionFailed => + 'Não foi possível iniciar a transcrição. Verifique a mídia ou aguarde a conclusão da tarefa atual.'; + + @override + String get placeMediaFirst => + 'Coloque esta mídia na linha do tempo antes de aplicar as legendas.'; + + @override + String get placeTranslationMediaFirst => + 'Coloque a mídia correspondente na linha do tempo antes de aplicar as legendas traduzidas.'; + + @override + String get selectTargetClip => 'Selecione o clipe alvo'; + + @override + String get timelineChanged => + 'A linha do tempo mudou. Selecione o clipe de destino novamente.'; + + @override + String get transcriptionAccessFailed => + 'Falha na transcrição: componente, modelo ou mídia de origem inacessível (notConfigured)'; + + @override + String get transcriptionNoAudio => + 'Falha na transcrição: nenhum áudio reconhecível na mídia ou faixa selecionada (noAudio)'; + + @override + String get transcriptionInvalidResult => + 'Falha na transcrição: arquivo de legenda inválido retornado (invalidResult)'; + + @override + String get transcriptionWorkerExited => + 'Falha na transcrição: o componente de reconhecimento foi encerrado inesperadamente (workerExited)'; + + @override + String get transcriptionProcessingFailed => + 'Falha na transcrição: falha no processamento nativo (processingFailed)'; + + @override + String get transcriptionFailed => + 'Falha na transcrição. Verifique o componente, modelo, trilha de áudio e duração'; + + @override + String get transcribing => 'Transcrevendo…'; + + @override + String get captionsGenerated => 'Legendas geradas'; + + @override + String get cancelTranscription => 'Cancelar transcrição'; + + @override + String get applyCaptions => 'Aplicar legendas'; + + @override + String get preparingTranslation => 'Preparando tradução…'; + + @override + String get translatingCaptions => 'Traduzindo legendas…'; + + @override + String get cancellingTranslation => 'Cancelando tradução…'; + + @override + String get translatedCaptionsGenerated => 'Legendas traduzidas geradas'; + + @override + String get translationCancelled => 'Tradução cancelada'; + + @override + String get translationInterrupted => 'Tradução interrompida'; + + @override + String get cancelTranslation => 'Cancelar tradução'; + + @override + String get editorServiceUnavailable => + 'Serviço de edição indisponível. Reabra o projeto.'; + + @override + String get mcpUnavailable => + 'Conexão MCP indisponível. Verifique a porta local e o token.'; + + @override + String get openTimelineFailed => 'Não foi possível abrir a linha do tempo'; + + @override + String get noTimelineSequence => 'Esta linha do tempo não tem sequência.'; + + @override + String get waitingForProject => 'Aguardando a abertura de um projeto'; + + @override + String get hold => 'Manter'; + + @override + String get noImportableFiles => 'Nenhum arquivo importável recebido'; + + @override + String get virtualFilesUnsupported => + 'Arraste os arquivos originais do gerenciador de arquivos. Arquivos virtuais ainda não são suportados.'; + + @override + String get editorSessionStartFailed => + 'Não foi possível abrir o editor da linha do tempo'; + + @override + String get previewStartFailed => + 'Não foi possível iniciar a visualização nativa'; + + @override + String get previewInvalidTrack => + 'A trilha de áudio ou vídeo selecionada não existe na mídia.'; + + @override + String get previewMissingBinding => + 'As vinculações de mídia estão faltando. Não foi possível visualizar esta linha do tempo.'; + + @override + String get previewUnsupportedEdits => + 'Esta linha do tempo contém edições que ainda não são suportadas pela visualização.'; + + @override + String get previewUnsupportedConfiguration => + 'Esta configuração de visualização não é compatível com a plataforma ou versão do sistema atual.'; + + @override + String get previewHdrUnsupported => + 'A mídia HDR requer mapeamento de tons para visualização SDR. O sistema atual ou a configuração de visualização não oferece suporte para isso.'; + + @override + String get previewAudioOutOfRange => + 'O clipe de áudio excede o intervalo da trilha de origem e não pode ser visualizado.'; + + @override + String get previewResourceMissing => + 'A mídia de visualização não existe mais. Localize o arquivo original novamente.'; + + @override + String get previewInvalidComposition => + 'Configuração de composição de vídeo inválida. Não foi possível criar a visualização.'; + + @override + String get previewInvalidData => + 'Dados de visualização inválidos. Por favor, tente novamente.'; + + @override + String get previewFailed => + 'Falha na visualização. Verifique o acesso à mídia e tente novamente.'; + + @override + String get chatFailed => + 'Não foi possível concluir a conversa. Verifique a configuração do serviço ou tente novamente mais tarde.'; + + @override + String get delete => 'Excluir'; + + @override + String get pinTimeline => 'Fixar linha do tempo'; + + @override + String get unpinTimeline => 'Desafixar linha do tempo'; + + @override + String deleteTimelineConfirmation(String name) { + return 'Excluir “$name” e seu histórico de edição? Esta ação não pode ser desfeita.'; + } + + @override + String get processingFailed => 'Falha no processamento'; + + @override + String get noMatchingOptions => 'Nenhuma opção correspondente'; + + @override + String removeMediaConfirmation(String name) { + return 'Remover “$name” da biblioteca? Os clipes existentes, o histórico e o arquivo original serão mantidos.'; + } + + @override + String mediaAdded(int count) { + return '$count referências de mídia adicionadas'; + } + + @override + String duplicatesSkipped(int count) { + return 'Arquivos duplicados $count ignorados'; + } + + @override + String mediaCount(int count) { + return '$count itens de mídia'; + } + + @override + String get importMedia => 'Importar'; + + @override + String noMediaOfType(String type) { + return 'Nenhuma mídia $type'; + } + + @override + String captionsImported(String count) { + return 'Legendas $count importadas'; + } + + @override + String editCaptionError(String message) { + return 'Não foi possível editar as legendas: $message'; + } + + @override + String mcpStartError(String message) { + return 'Não foi possível iniciar o MCP: $message'; + } + + @override + String manualColorSpace(String name) { + return 'Selecionado manualmente: $name'; + } + + @override + String detectedColorSpace(String name) { + return 'Detectado: $name'; + } + + @override + String keyframeLabel(String channel) { + return 'Quadro-chave de $channel'; + } + + @override + String maskMode(String mode) { + return 'Modo de combinação: $mode'; + } + + @override + String keyframeCount(int count) { + return '$count quadros-chave'; + } + + @override + String toggleKeyframe(String action, String channel) { + return '$action quadro-chave de $channel'; + } + + @override + String previousKeyframe(String channel) { + return 'Quadro-chave anterior de $channel'; + } + + @override + String nextKeyframe(String channel) { + return 'Próximo quadro-chave de $channel'; + } + + @override + String keyframeSettings(String channel) { + return 'Configurações de quadros-chave de $channel'; + } + + @override + String selectedClipsHint(int count) { + return 'Clipes $count selecionados\nSelecione um clipe para ver suas propriedades'; + } + + @override + String transcriptionError(String code) { + return 'Falha na transcrição. Verifique o componente, modelo, trilha de áudio e duração ($code)'; + } + + @override + String captionsAdded(String count) { + return 'Adicionadas legendas $count. Edite-os no painel de propriedades.'; + } + + @override + String translatedCaptionsAdded(String count) { + return 'Adicionadas legendas traduzidas $count. Edite-os no painel de propriedades.'; + } + + @override + String applyCaptionsError(String message) { + return 'Não foi possível aplicar legendas: $message'; + } + + @override + String applyTranslatedCaptionsError(String message) { + return 'Não foi possível aplicar legendas traduzidas: $message'; + } + + @override + String recognizedCaptions(int count) { + return '$count legendas reconhecidas'; + } + + @override + String captionCount(int count) { + return '$count legendas'; + } + + @override + String translationFailed(String message) { + return 'Falha na tradução: $message'; + } + + @override + String translatedCaptionCount(int count, String language) { + return '$count legendas em $language'; + } + + @override + String previewParameterError(String message) { + return 'Parâmetros de visualização inválidos: $message'; + } + + @override + String mediaOffline(String names) { + return 'Mídia offline ou indisponível: $names'; + } + + @override + String searchOptions(String label) { + return 'Procurar $label…'; + } + + @override + String get loadRecentProjectsFailed => + 'Não foi possível carregar bibliotecas recentes. Você ainda pode abrir uma biblioteca manualmente.'; + + @override + String get projectAccessFailed => 'Projeto indisponível'; + + @override + String get projectMissingDirectory => 'Projeto não encontrado'; + + @override + String get recentProjectSaveFailed => + 'Biblioteca aberta, mas não foi possível salvar o registro recente da biblioteca.'; + + @override + String get lastProjectSaveFailed => + 'Projeto aberto, mas não foi possível salvar o último registro do projeto.'; + + @override + String get enterProjectName => 'Insira um nome de projeto'; + + @override + String get projectSwitched => 'O projeto mudou. Arraste a mídia novamente.'; + + @override + String get notLocalMedia => 'Esta mídia não é um arquivo local'; + + @override + String get revealMediaFailed => + 'Não foi possível mostrar a mídia no gerenciador de arquivos'; + + @override + String get openMatchingProject => 'Abra o projeto correspondente primeiro'; + + @override + String get projectMismatch => + 'A biblioteca neste local não corresponde ao registro. Selecione-o novamente com Abrir biblioteca.'; + + @override + String get openProjectFirst => 'Abra uma biblioteca primeiro'; + + @override + String get localFilesOnly => + 'Arraste arquivos locais do gerenciador de arquivos'; + + @override + String get foldersUnsupported => + 'Selecione os arquivos. Arrastar pastas ainda não é compatível.'; + + @override + String get mediaImportCancelled => 'Importação de mídia cancelada'; + + @override + String get fileAccessFailed => + 'O arquivo está ausente ou ilegível. Verifique sua localização e permissões'; + + @override + String get registerMediaFailed => + 'Não foi possível registrar a mídia. Por favor, tente novamente'; + + @override + String get mediaNoLongerExists => 'A mídia não existe mais'; + + @override + String get mediaNoTracks => + 'A mídia não tem faixas de vídeo ou áudio utilizáveis'; + + @override + String get invalidMediaDuration => 'Duração de mídia inválida'; + + @override + String get mediaInfoUnsupported => + 'A leitura de informações de mídia ainda não é compatível com esta plataforma'; + + @override + String get mediaInfoFailed => + 'Não foi possível ler as informações da mídia. Verifique o arquivo e as permissões de acesso'; + + @override + String get saveTimelineFailed => + 'Não foi possível salvar a linha do tempo. Tente novamente. As edições não salvas permanecem nesta sessão.'; + + @override + String get addKeyframeAction => 'Adicionar'; + + @override + String get backgroundTasks => 'Tarefas em segundo plano'; + + @override + String get noBackgroundTasks => 'Nenhuma tarefa em segundo plano'; + + @override + String get retryTask => 'Tentar novamente'; + + @override + String get applyOriginalCaptions => 'Aplicar legendas originais'; + + @override + String get applyTranslatedCaptions => 'Aplicar legendas traduzidas'; + + @override + String get subtitleTaskStarted => 'Tarefa de legendas iniciada'; + + @override + String get fitTimeline => 'Ajustar toda a linha do tempo'; + + @override + String get modify => 'Modify'; + + @override + String get projectSettings => 'Project settings'; + + @override + String get projectSettingsDescription => + 'Change project output settings while keeping clip timing and speed.'; + + @override + String get projectColorSpace => 'Color space'; + + @override + String get projectWidth => 'Width (px)'; + + @override + String get projectHeight => 'Height (px)'; + + @override + String get projectResolutionInvalid => 'Enter a whole number from 1 to 16384'; + + @override + String get previewFullscreen => 'Prévia em tela cheia'; + + @override + String get exitPreviewFullscreen => 'Sair da tela cheia'; + + @override + String get previewGoToStart => 'Ir para o início'; + + @override + String get previewPreviousFrame => 'Quadro anterior'; + + @override + String get previewNextFrame => 'Próximo quadro'; + + @override + String get softwareUpdates => 'Atualizações'; + + @override + String get checkForUpdates => 'Verificar atualizações'; + + @override + String get automaticallyCheckUpdates => + 'Verificar atualizações automaticamente'; + + @override + String get updatesUnavailable => + 'Atualizações indisponíveis nesta compilação.'; + + @override + String get updateCheckFailed => + 'Não foi possível verificar atualizações. Tente novamente.'; + + @override + String get removeBackground => 'Remover fundo'; + + @override + String get startBackgroundRemoval => 'Remover fundo'; + + @override + String get backgroundRemovalResourceRequired => + 'A remoção de fundo precisa de um modelo local. Ela começa automaticamente após o download.'; + + @override + String get backgroundRemovalDownloadTask => + 'Baixar recurso de remoção de fundo'; + + @override + String get backgroundRemovalResourceName => 'Modelo de remoção de fundo'; + + @override + String get backgroundRemovalDestructiveHint => + 'A mídia transparente gerada substituirá este clipe. Você ainda pode usar Desfazer para restaurar o clipe original.'; + + @override + String get backgroundRemovalTaskStarted => 'Remoção de fundo iniciada'; + + @override + String get startBackgroundRemovalFailed => + 'Não foi possível iniciar a remoção de fundo. Verifique a mídia ou aguarde a conclusão da tarefa de processamento atual.'; + + @override + String get backgroundRemovalComplete => 'Remoção de fundo concluída'; + + @override + String get backgroundRemovalApplying => 'Substituindo a mídia do clipe'; + + @override + String get backgroundRemovalFailed => 'Falha ao remover o fundo'; + + @override + String get agentSettings => 'Agente'; + + @override + String get agentSaveSettingsFailed => + 'Não foi possível salvar as configurações do agente.'; + + @override + String get agentDeleteProviderTitle => 'Excluir provedor?'; + + @override + String agentDeleteProviderDescription(String providerName) { + return '“$providerName” e a chave de API salva serão removidos deste dispositivo.'; + } + + @override + String get agentProviderRequired => + 'Adicione um provedor antes de ativar o assistente.'; + + @override + String get agentUseSelectedModel => + 'As novas solicitações do agente usarão o modelo selecionado.'; + + @override + String get agentEnable => 'Ativar agente'; + + @override + String get agentDefaultModel => 'Modelo padrão'; + + @override + String get agentConfigureModel => 'Configurar modelos'; + + @override + String get agentSelectModel => 'Selecionar modelo'; + + @override + String get agentModelUnavailable => + 'O modelo desta conversa está indisponível. Selecione outro modelo para iniciar uma nova conversa.'; + + @override + String get agentModelChangeSession => + 'Alterar o modelo inicia uma nova sessão do agente.'; + + @override + String get agentCustomProviders => 'Provedores personalizados'; + + @override + String get agentProviderStorageDescription => + 'Os metadados do provedor são armazenados localmente. As chaves de API ficam no armazenamento de credenciais do sistema.'; + + @override + String get agentAddProvider => 'Adicionar provedor'; + + @override + String get agentBackToProviders => 'Voltar aos provedores'; + + @override + String get agentLoadSettingsFailed => + 'Não foi possível carregar as configurações do agente. Tentar novamente'; + + @override + String get agentEnableProvider => 'Ativar provedor'; + + @override + String get agentEditProvider => 'Editar provedor'; + + @override + String get agentDeleteProvider => 'Excluir provedor'; + + @override + String get agentModelIdsUnique => 'Os IDs de modelo devem ser exclusivos.'; + + @override + String get agentEditProviderTitle => 'Editar provedor'; + + @override + String get agentProviderEndpointDescription => + 'Configure um endpoint de Chat Completions compatível com OpenAI.'; + + @override + String get agentSaveProvider => 'Salvar provedor'; + + @override + String get agentProviderConfiguration => 'Configuração do provedor'; + + @override + String get agentAuthenticationAndModels => 'Autenticação e modelos'; + + @override + String get agentApiType => 'Tipo de API'; + + @override + String get agentOpenAiChatCompletions => 'OpenAI Completions'; + + @override + String get agentBaseUrl => 'URL base'; + + @override + String get agentApiKey => 'Chave de API'; + + @override + String get agentProviderNameHint => 'Meu provedor'; + + @override + String get agentApiKeyOptional => + 'Opcional para endpoints que não exigem autenticação.'; + + @override + String get agentApiKeyKeep => 'Deixe em branco para manter a chave salva.'; + + @override + String get agentOptional => 'Opcional'; + + @override + String get agentApiKeyOneLine => 'A chave de API deve ter apenas uma linha.'; + + @override + String get agentRemoveSavedApiKey => 'Remover chave de API salva'; + + @override + String get agentModels => 'Modelos'; + + @override + String get agentAddModel => 'Adicionar modelo'; + + @override + String get agentRequiredField => 'Este campo é obrigatório.'; + + @override + String get agentInvalidBaseUrl => + 'Insira uma URL base HTTP(S) sem credenciais, consulta ou fragmento.'; + + @override + String get agentModelId => 'ID do modelo'; + + @override + String get agentContextWindow => 'Janela de contexto'; + + @override + String get agentMaxOutputTokens => 'Saída máxima'; + + @override + String get agentMaxOutputBelowContext => + 'Deve ser menor que a janela de contexto.'; + + @override + String get agentDeleteModel => 'Excluir modelo'; + + @override + String get agentPositiveInteger => 'Insira um número inteiro positivo.'; + + @override + String get agentConfigurationReadFailed => + 'Não foi possível ler a configuração do agente. Verifique as configurações e tente novamente.'; + + @override + String get agentConfigurationRequired => + 'Primeiro configure e ative o agente em Configurações.'; + + @override + String get agentSessionRestoreFailed => + 'Não foi possível restaurar a sessão do agente. Tente novamente mais tarde.'; + + @override + String get agentContextBudgetExceeded => + 'O orçamento de entrada é insuficiente para instruções, ferramentas e mensagem. Aumente o contexto ou reduza a saída máxima.'; + + @override + String get agentAuthenticationFailed => + 'Falha na autenticação. Verifique a API Key e as permissões.'; + + @override + String get agentConnectionFailed => + 'Falha de conexão ou tempo esgotado. Verifique a Base URL e a rede.'; + + @override + String get agentProtocolFailed => + 'A resposta não corresponde ao tipo de API selecionado ou o fluxo está incompleto.'; + + @override + String get agentContextBudgetTooSmall => + 'Reserve mais espaço para instruções. Aumente o contexto ou reduza a saída máxima.'; + + @override + String get agentCompacting => 'Organizando o contexto…'; + + @override + String get agentEditing => 'Editando…'; + + @override + String get agentVerifying => 'Verificando resultados…'; + + @override + String get agentTurnLimitReached => + 'A tarefa atingiu o limite de execução. As alterações foram salvas. Envie “Continuar” para retomar.'; + + @override + String get agentRecoveryRequired => + 'O resultado anterior não foi confirmado. Continue para verificar os registros salvos; edições não confirmadas não serão repetidas.'; + + @override + String get agentExportReplyFailed => + 'Vídeo exportado. A resposta de resumo falhou. Tente novamente sem repetir a edição ou exportação.'; + + @override + String get agentRetrySummary => 'Tentar resumo novamente'; + + @override + String get agentResumeTask => 'Continuar tarefa'; + + @override + String get agentTaskInterrupted => + 'A tarefa foi interrompida. Continue a partir do progresso salvo.'; + + @override + String get downloadSubtitleModel => 'Baixar modelo de legendas'; + + @override + String get downloadModelAction => 'Baixar'; + + @override + String get subtitleEngineUnavailable => + 'O modelo está instalado, mas o mecanismo de legendas não iniciou. Repare o mecanismo; não é necessário baixar o modelo novamente.'; + + @override + String get backgroundTaskDetails => 'Detalhes da tarefa'; + + @override + String get backgroundTaskFailed => 'Falhou'; + + @override + String get backgroundTaskCompleted => 'Concluída'; + + @override + String get captionWrapLines => 'Quebrar linhas das legendas'; + + @override + String get captionSingleLine => 'Mostrar legendas numa linha'; + + @override + String get noMatchingCaptions => 'Nenhuma legenda correspondente'; + + @override + String get subtitleResourcesRequired => + 'Estes recursos são necessários para as legendas. A geração começará automaticamente após o download.'; + + @override + String subtitleResourcesDownloadSize(String size) { + return 'Para baixar: $size'; + } + + @override + String get pauseDownload => 'Pausar'; + + @override + String get resumeDownload => 'Retomar'; + + @override + String get downloadPaused => 'Pausado'; + + @override + String get cancelResourceDownloadTitle => 'Cancelar download?'; + + @override + String get cancelResourceDownloadMessage => + 'O download será interrompido. O progresso do recurso atual pode ser perdido.'; + + @override + String get continueDownload => 'Continuar download'; + + @override + String get cancelDownload => 'Cancelar download'; + + @override + String get speechResourceStage => 'Recurso de reconhecimento de voz'; + + @override + String get translationResourceStage => 'Recurso de tradução'; + + @override + String get subtitleResourceDownloadTask => + 'Baixar recursos de voz e tradução'; + + @override + String get downloadingSpeechModel => 'A transferir o modelo de voz'; + + @override + String get downloadingTranslationModel => 'A transferir o modelo de tradução'; + + @override + String get checkingForUpdates => 'Verificando atualizações…'; + + @override + String get appIsUpToDate => 'O aplicativo está atualizado.'; + + @override + String downloadingUpdate(int progress) { + return 'Baixando atualização: $progress%'; + } + + @override + String updateAvailable(String version) { + return 'A versão $version está disponível.'; + } + + @override + String get downloadUpdate => 'Baixar atualização'; + + @override + String get restartToUpdate => 'Reiniciar para atualizar'; + + @override + String get updateOperationFailed => + 'Não foi possível atualizar. Conclua as tarefas ativas e tente novamente.'; + + @override + String get windowMinimize => 'Minimizar'; + + @override + String get windowMaximize => 'Maximizar'; + + @override + String get windowRestore => 'Restaurar'; + + @override + String get workspaceAgent => 'Assistente'; + + @override + String get workspaceCut => 'Edição'; + + @override + String get noAvailableOptions => 'Nenhuma opção disponível'; + + @override + String get composerReferenceInvalid => + 'Uma referência não é mais válida. Volte ao projeto dela ou remova-a.'; + + @override + String durationSeconds(int seconds) { + return '$seconds s'; + } + + @override + String durationMinutesSeconds(int minutes, int seconds) { + return '$minutes min $seconds s'; + } + + @override + String get projectNameInvalid => 'Nome de projeto inválido'; + + @override + String get projectLocationDefaultUnavailable => + 'Não foi possível acessar o local padrão dos projetos. Selecione-o novamente nas configurações.'; + + @override + String get chooseProjectLocation => + 'Selecione primeiro um local para salvar projetos nas configurações.'; + + @override + String get untitledTimeline => 'Linha do tempo sem título'; + + @override + String get primarySequence => 'Sequência principal'; + + @override + String get primaryStoryline => 'Linha principal'; + + @override + String get projectSessionClosed => + 'A sessão do projeto foi fechada. Reabra o projeto.'; + + @override + String get timelineSessionClosed => + 'A sessão da linha do tempo foi fechada. Reabra a linha do tempo.'; + + @override + String get timelineMissing => 'A linha do tempo não existe ou foi excluída.'; + + @override + String get timelineInUse => + 'A linha do tempo está em uso e ainda não pode ser excluída.'; + + @override + String get timelineHasBackgroundTasks => + 'Conclua as tarefas em segundo plano da linha do tempo antes de excluí-la.'; + + @override + String get timelineRequired => + 'Um projeto deve manter pelo menos uma linha do tempo.'; + + @override + String get mediaReadFailed => 'Não foi possível ler a mídia'; + + @override + String get mediaImportFailed => 'Não foi possível importar a mídia'; + + @override + String get unsupportedMediaType => + 'Somente arquivos de vídeo, áudio e imagem podem ser importados.'; + + @override + String get mediaNoVideoTracks => + 'A mídia não tem uma faixa de vídeo utilizável'; + + @override + String get mediaDurationOutOfRange => + 'A duração da mídia excede o intervalo da linha do tempo'; + + @override + String resourceDownloadHttpFailed(String statusCode) { + return 'Falha no download (HTTP $statusCode)'; + } + + @override + String get resourceChecksumFailed => + 'A verificação do arquivo do modelo falhou. Baixe o recurso novamente.'; + + @override + String get subtitleLanguageAf => 'africâner'; + + @override + String get subtitleLanguageAm => 'amárico'; + + @override + String get subtitleLanguageAr => 'árabe'; + + @override + String get subtitleLanguageAst => 'asturiano'; + + @override + String get subtitleLanguageAz => 'azerbaijano'; + + @override + String get subtitleLanguageBa => 'bashkir'; + + @override + String get subtitleLanguageBe => 'bielorrusso'; + + @override + String get subtitleLanguageBg => 'búlgaro'; + + @override + String get subtitleLanguageBn => 'bengali'; + + @override + String get subtitleLanguageBr => 'bretão'; + + @override + String get subtitleLanguageBs => 'bósnio'; + + @override + String get subtitleLanguageCa => 'catalão'; + + @override + String get subtitleLanguageCeb => 'cebuano'; + + @override + String get subtitleLanguageCs => 'tcheco'; + + @override + String get subtitleLanguageCy => 'galês'; + + @override + String get subtitleLanguageDa => 'dinamarquês'; + + @override + String get subtitleLanguageDe => 'alemão'; + + @override + String get subtitleLanguageEl => 'grego'; + + @override + String get subtitleLanguageEn => 'inglês'; + + @override + String get subtitleLanguageEs => 'espanhol'; + + @override + String get subtitleLanguageEt => 'estoniano'; + + @override + String get subtitleLanguageFa => 'persa'; + + @override + String get subtitleLanguageFf => 'fula'; + + @override + String get subtitleLanguageFi => 'finlandês'; + + @override + String get subtitleLanguageFr => 'francês'; + + @override + String get subtitleLanguageFy => 'frísio ocidental'; + + @override + String get subtitleLanguageGa => 'irlandês'; + + @override + String get subtitleLanguageGd => 'gaélico escocês'; + + @override + String get subtitleLanguageGl => 'galego'; + + @override + String get subtitleLanguageGu => 'guzerate'; + + @override + String get subtitleLanguageHa => 'hauçá'; + + @override + String get subtitleLanguageHe => 'hebraico'; + + @override + String get subtitleLanguageHi => 'hindi'; + + @override + String get subtitleLanguageHr => 'croata'; + + @override + String get subtitleLanguageHt => 'haitiano'; + + @override + String get subtitleLanguageHu => 'húngaro'; + + @override + String get subtitleLanguageHy => 'armênio'; + + @override + String get subtitleLanguageId => 'indonésio'; + + @override + String get subtitleLanguageIg => 'igbo'; + + @override + String get subtitleLanguageIlo => 'ilocano'; + + @override + String get subtitleLanguageIs => 'islandês'; + + @override + String get subtitleLanguageIt => 'italiano'; + + @override + String get subtitleLanguageJa => 'japonês'; + + @override + String get subtitleLanguageJv => 'javanês'; + + @override + String get subtitleLanguageKa => 'georgiano'; + + @override + String get subtitleLanguageKk => 'cazaque'; + + @override + String get subtitleLanguageKm => 'khmer'; + + @override + String get subtitleLanguageKn => 'canarim'; + + @override + String get subtitleLanguageKo => 'coreano'; + + @override + String get subtitleLanguageLb => 'luxemburguês'; + + @override + String get subtitleLanguageLg => 'luganda'; + + @override + String get subtitleLanguageLn => 'lingala'; + + @override + String get subtitleLanguageLo => 'laosiano'; + + @override + String get subtitleLanguageLt => 'lituano'; + + @override + String get subtitleLanguageLv => 'letão'; + + @override + String get subtitleLanguageMg => 'malgaxe'; + + @override + String get subtitleLanguageMk => 'macedônio'; + + @override + String get subtitleLanguageMl => 'malaiala'; + + @override + String get subtitleLanguageMn => 'mongol'; + + @override + String get subtitleLanguageMr => 'marati'; + + @override + String get subtitleLanguageMs => 'malaio'; + + @override + String get subtitleLanguageMy => 'birmanês'; + + @override + String get subtitleLanguageNe => 'nepalês'; + + @override + String get subtitleLanguageNl => 'holandês'; + + @override + String get subtitleLanguageNo => 'norueguês'; + + @override + String get subtitleLanguageNs => 'soto setentrional'; + + @override + String get subtitleLanguageOc => 'occitânico'; + + @override + String get subtitleLanguageOr => 'oriá'; + + @override + String get subtitleLanguagePa => 'panjabi'; + + @override + String get subtitleLanguagePl => 'polonês'; + + @override + String get subtitleLanguagePs => 'pashto'; + + @override + String get subtitleLanguagePt => 'português'; + + @override + String get subtitleLanguageRo => 'romeno'; + + @override + String get subtitleLanguageRu => 'russo'; + + @override + String get subtitleLanguageSd => 'sindi'; + + @override + String get subtitleLanguageSi => 'cingalês'; + + @override + String get subtitleLanguageSk => 'eslovaco'; + + @override + String get subtitleLanguageSl => 'esloveno'; + + @override + String get subtitleLanguageSo => 'somali'; + + @override + String get subtitleLanguageSq => 'albanês'; + + @override + String get subtitleLanguageSr => 'sérvio'; + + @override + String get subtitleLanguageSs => 'suázi'; + + @override + String get subtitleLanguageSu => 'sundanês'; + + @override + String get subtitleLanguageSv => 'sueco'; + + @override + String get subtitleLanguageSw => 'suaíli'; + + @override + String get subtitleLanguageTa => 'tâmil'; + + @override + String get subtitleLanguageTh => 'tailandês'; + + @override + String get subtitleLanguageTl => 'tagalo'; + + @override + String get subtitleLanguageTn => 'tswana'; + + @override + String get subtitleLanguageTr => 'turco'; + + @override + String get subtitleLanguageUk => 'ucraniano'; + + @override + String get subtitleLanguageUr => 'urdu'; + + @override + String get subtitleLanguageUz => 'uzbeque'; + + @override + String get subtitleLanguageVi => 'vietnamita'; + + @override + String get subtitleLanguageWo => 'uolofe'; + + @override + String get subtitleLanguageXh => 'xhosa'; + + @override + String get subtitleLanguageYi => 'iídiche'; + + @override + String get subtitleLanguageYo => 'iorubá'; + + @override + String get subtitleLanguageYue => 'cantonês'; + + @override + String get subtitleLanguageZh => 'chinês'; + + @override + String get subtitleLanguageZu => 'zulu'; + + @override + String get linearRec2020 => 'Rec.2020 linear'; + + @override + String get diagnostics => 'Diagnóstico'; + + @override + String get exportDiagnostics => 'Exportar pacote de diagnóstico'; + + @override + String get exportDiagnosticsFailed => + 'Não foi possível exportar o diagnóstico. Tente novamente.'; + + @override + String get exportDiagnosticsSucceeded => 'Pacote de diagnóstico salvo.'; +} diff --git a/lib/l10n/app_localizations_ru.dart b/lib/l10n/app_localizations_ru.dart new file mode 100644 index 0000000..4b9fbbe --- /dev/null +++ b/lib/l10n/app_localizations_ru.dart @@ -0,0 +1,2218 @@ +// ignore: unused_import +import 'package:intl/intl.dart' as intl; + +import 'app_localizations.dart'; + +// ignore_for_file: type=lint + +/// The translations for Russian (`ru`). +class AppLocalizationsRu extends AppLocalizations { + AppLocalizationsRu([String locale = 'ru']) : super(locale); + + @override + String get selectProject => 'Выбрать проект'; + + @override + String get searchProjects => 'Поиск проектов'; + + @override + String get noMatchingProjects => 'Подходящих проектов нет'; + + @override + String get projectsNone => 'Нет проектов'; + + @override + String get projectLocationMissing => + 'Папка не существует. Она будет создана при создании проекта.'; + + @override + String get projectLocationUnavailable => + 'Место сохранения проекта недоступно. Подключите диск или проверьте сеть и повторите попытку либо выберите другое место.'; + + @override + String get projectLocationNotWritable => + 'Запись в место сохранения проекта невозможна. Проверьте разрешения или выберите другое место.'; + + @override + String get projectLocationCreateFailed => + 'Не удалось создать папку проекта или записать в неё данные. Проверьте разрешения или выберите другое место.'; + + @override + String get removeProjectFromSidebar => 'Убрать с боковой панели'; + + @override + String get projectRemoved => + 'Проект убран. Локальные файлы и беседы сохранены.'; + + @override + String get agentNoConversations => 'Бесед пока нет'; + + @override + String get renameConversationTitle => 'Переименовать чат'; + + @override + String get renameConversationDescription => + 'Выберите короткое и узнаваемое название.'; + + @override + String get collapseProject => 'Свернуть проект'; + + @override + String get expandProject => 'Развернуть проект'; + + @override + String agentDeleteConfirmation(String title) { + return 'Навсегда удалить «$title» и все сообщения? Это действие нельзя отменить. Локальные файлы проекта не будут затронуты.'; + } + + @override + String get agentEmptyTrashConfirmation => + 'Навсегда удалить все беседы из корзины? Это действие нельзя отменить. Локальные файлы проекта не будут затронуты.'; + + @override + String get agentConversations => 'Диалоги'; + + @override + String get showMoreConversations => 'Показать ещё'; + + @override + String get showFewerConversations => 'Показать меньше'; + + @override + String get agentNewConversation => 'Новый диалог'; + + @override + String agentElapsedTime(String duration) { + return 'Время $duration'; + } + + @override + String get agentConversationActions => 'Действия с диалогом'; + + @override + String get agentMoveToTrash => 'Переместить в корзину'; + + @override + String get agentTrash => 'Корзина'; + + @override + String get agentRestore => 'Восстановить'; + + @override + String get agentEmptyTrash => 'Очистить корзину'; + + @override + String get agentDeleteForever => 'Удалить навсегда'; + + @override + String get agentConversationLocation => 'Расположение диалогов'; + + @override + String get agentChooseExistingConversations => 'Выбрать существующие диалоги'; + + @override + String get agentMoveConversations => 'Переместить диалоги'; + + @override + String get agentLocationUnavailable => 'Расположение диалогов недоступно'; + + @override + String get agentLocationBusy => 'Дождитесь завершения активных диалогов'; + + @override + String get agentRelinkProvider => 'Повторно связать провайдера'; + + @override + String get settings => 'Настройки'; + + @override + String get closeSettings => 'Закрыть настройки'; + + @override + String get general => 'Общие'; + + @override + String get appearance => 'Оформление'; + + @override + String get theme => 'Тема'; + + @override + String get system => 'Как в системе'; + + @override + String get light => 'Светлая'; + + @override + String get dark => 'Тёмная'; + + @override + String get saveAppearanceFailed => + 'Не удалось сохранить внешний вид. Пожалуйста, попробуйте еще раз.'; + + @override + String get loadAppearanceFailed => + 'Не удалось загрузить внешний вид. Пожалуйста, выберите тему еще раз.'; + + @override + String get cancel => 'Отмена'; + + @override + String get save => 'Сохранить'; + + @override + String get create => 'Создать'; + + @override + String get close => 'Закрыть'; + + @override + String get retry => 'Повторить'; + + @override + String get select => 'Выбрать'; + + @override + String get name => 'Имя'; + + @override + String get enterName => 'Введите имя'; + + @override + String get invalidName => + 'Имена не могут содержать разделители путей или управляющие символы.'; + + @override + String get projects => 'Проекты'; + + @override + String get projectName => 'Название проекта'; + + @override + String get projectLocation => 'Место сохранения проектов'; + + @override + String get projectLocationNotSet => 'Не задано'; + + @override + String get loadProjectLocationFailed => + 'Не удалось загрузить место сохранения проектов.'; + + @override + String get saveProjectLocationFailed => + 'Не удалось сохранить место для проектов.'; + + @override + String get resourceLocation => 'Место хранения ресурсов'; + + @override + String get resourceLocationNotSet => 'Не задано'; + + @override + String get loadResourceLocationFailed => + 'Не удалось загрузить место хранения ресурсов.'; + + @override + String get saveResourceLocationFailed => + 'Не удалось сохранить место для ресурсов.'; + + @override + String get transcriptionResourceRequired => + 'Для создания субтитров сначала необходимо скачать модель распознавания речи.'; + + @override + String get downloadAndContinue => 'Скачать и продолжить'; + + @override + String get downloadingResource => 'Скачивание…'; + + @override + String get downloadInBackground => 'Скачать в фоновом режиме'; + + @override + String get processingResourceDownloadFailed => + 'Не удалось скачать ресурс распознавания речи. Повторите попытку.'; + + @override + String get newProject => 'Новый проект'; + + @override + String get openProject => 'Открыть проект'; + + @override + String get openProjectMore => 'Открыть другой проект'; + + @override + String get saveHere => 'Сохранить здесь'; + + @override + String get selectDirectoryFailed => + 'Не удалось выбрать каталог. Проверьте системные разрешения.'; + + @override + String get openingWorkspace => 'Открытие рабочего пространства…'; + + @override + String get loadProjectsFailed => 'Не удалось загрузить проекты'; + + @override + String get projectsEmpty => 'Нет проектов'; + + @override + String get backToProjects => 'Вернуться к монтажу'; + + @override + String get timelines => 'Таймлайны'; + + @override + String timelineLimitReached(int count) { + return 'В каждом проекте может быть не более $count таймлайнов.'; + } + + @override + String get timelineName => 'Название таймлайна'; + + @override + String defaultTimelineName(int index) { + return 'Таймлайн $index'; + } + + @override + String get newTimeline => 'Новый таймлайн'; + + @override + String get noTimelines => 'Нет таймлайнов'; + + @override + String get activeTimeline => 'Текущий таймлайн'; + + @override + String get timelineUnavailable => 'Таймлайн недоступен'; + + @override + String get projectNoTimelines => 'В этом проекте пока нет таймлайнов'; + + @override + String get createTimelineHint => + 'Создайте таймлайн в разделе «Таймлайны» слева, чтобы начать монтаж.'; + + @override + String get createTimelineChat => 'Создайте таймлайн, чтобы начать чат'; + + @override + String get operationFailed => + 'Операция не удалась. Пожалуйста, попробуйте еще раз.'; + + @override + String get collapseSidebar => 'Свернуть боковую панель'; + + @override + String get expandSidebar => 'Развернуть боковую панель'; + + @override + String get expandEditor => 'Развернуть область монтажа'; + + @override + String get collapseProperties => 'Свернуть свойства'; + + @override + String get expandProperties => 'Развернуть свойства'; + + @override + String get layout => 'Компоновка'; + + @override + String get editingFirstLayout => 'Монтаж в приоритете'; + + @override + String get agentEditingLayout => 'Агент и монтаж'; + + @override + String get agentLayoutDescription => + 'Планирование, совместная работа и выполнение'; + + @override + String get editingLayoutDescription => 'Просмотр, монтаж и доработка'; + + @override + String get materials => 'Медиа'; + + @override + String get all => 'Все'; + + @override + String get video => 'Видео'; + + @override + String get audio => 'Аудио'; + + @override + String get image => 'Изображение'; + + @override + String get picture => 'Изображение'; + + @override + String get captions => 'Субтитры'; + + @override + String get text => 'Текст'; + + @override + String get noMedia => 'Нет медиа'; + + @override + String get mediaCategory => 'Категория медиа'; + + @override + String get captionTasks => 'Задачи субтитров'; + + @override + String get listLayout => 'Просмотр списка'; + + @override + String get gridLayout => 'Представление в виде сетки'; + + @override + String get addToTimeline => 'Добавить на таймлайн'; + + @override + String get rename => 'Переименовать'; + + @override + String get renameMedia => 'Переименовать медиа'; + + @override + String get removeMedia => 'Удалить медиа'; + + @override + String get remove => 'Удалить'; + + @override + String get revealFinder => 'Показать в Finder'; + + @override + String get revealFileManager => 'Показать в файловом менеджере'; + + @override + String get dropToAdd => 'Отпустите, чтобы добавить'; + + @override + String get timelineDropToStart => 'Перетащите медиафайлы сюда, чтобы начать.'; + + @override + String get dragMediaHint => + 'Перетащите сюда видео, аудио или изображения.\nИсходные файлы остаются в своем текущем местоположении.'; + + @override + String get transcribe => 'Транскрибировать'; + + @override + String get generateCaptions => 'Создать субтитры'; + + @override + String get play => 'Воспроизвести'; + + @override + String get pause => 'Пауза'; + + @override + String get retryPreview => 'Повторить предварительный просмотр'; + + @override + String get canvasRatio => 'Соотношение сторон'; + + @override + String get noPreviewContent => + 'На временной шкале нет контента для предварительного просмотра.'; + + @override + String get nativePreviewUnsupported => + 'Нативная предварительная версия недоступна на этой платформе.'; + + @override + String get canvasTransformFailed => + 'Не удалось трансформировать полотно. Пожалуйста, попробуйте еще раз.'; + + @override + String get undo => 'Отменить'; + + @override + String get redo => 'Повторить'; + + @override + String get deleteSelectedClips => 'Удалить выбранные клипы'; + + @override + String get splitAtPlayhead => 'Разделить по точке воспроизведения'; + + @override + String get trimLeft => 'Обрезать слева'; + + @override + String get trimRight => 'Обрезать справа'; + + @override + String get trimLeftTooltip => + 'Удалить слева от курсора, сохранив правую часть'; + + @override + String get trimRightTooltip => + 'Удалить справа от курсора, сохранив левую часть'; + + @override + String get currentSequence => 'Текущая секвенция'; + + @override + String get projectProperties => 'Свойства проекта'; + + @override + String get canvasSize => 'Размер холста'; + + @override + String get frameRate => 'Частота кадров'; + + @override + String get duration => 'Продолжительность'; + + @override + String get totalDuration => 'Общая продолжительность'; + + @override + String get clipDuration => 'Продолжительность клипа'; + + @override + String get seconds => 'сек.'; + + @override + String get clip => 'Клип'; + + @override + String get unnamedClip => 'Безымянный клип'; + + @override + String get gap => 'Промежуток'; + + @override + String get compoundClip => 'Составной клип'; + + @override + String get textClip => 'Текстовый клип'; + + @override + String get pictureProperties => 'Изображение'; + + @override + String get position => 'Позиция'; + + @override + String get rotation => 'Вращение'; + + @override + String get scale => 'Масштаб'; + + @override + String get size => 'Размер'; + + @override + String get transform => 'Преобразование'; + + @override + String get resetPosition => 'Сбросить позицию'; + + @override + String get keepAspectRatio => 'Блокировка соотношения сторон'; + + @override + String get alignment => 'Выравнивание'; + + @override + String get alignLeft => 'Выровнять по левому краю'; + + @override + String get alignRight => 'Выровнять справа'; + + @override + String get alignTop => 'Выровнять по верху'; + + @override + String get alignBottom => 'Выровнять низ'; + + @override + String get alignHorizontalCenter => 'Центрировать по горизонтали'; + + @override + String get alignVerticalCenter => 'Центрировать по вертикали'; + + @override + String get volume => 'Громкость'; + + @override + String get gain => 'Усиление'; + + @override + String get mute => 'Отключить звук'; + + @override + String get unmute => 'Включить звук'; + + @override + String get resetVolume => 'Сбросить громкость'; + + @override + String get invalidGain => 'Введите значение от -90 до +12.'; + + @override + String get animation => 'Анимация'; + + @override + String get keyframes => 'Ключевые кадры'; + + @override + String get removeAllKeyframes => 'Удалить все ключевые кадры'; + + @override + String get linear => 'Линейная'; + + @override + String get easeIn => 'Плавное ускорение'; + + @override + String get easeOut => 'Плавное замедление'; + + @override + String get easeInOut => 'Плавное ускорение и замедление'; + + @override + String get basic => 'Основные'; + + @override + String get mask => 'Маска'; + + @override + String get addMask => 'Добавить маску'; + + @override + String get deleteMask => 'Удалить маску'; + + @override + String get resetMask => 'Сбросить маску'; + + @override + String get enableMask => 'Включить маску'; + + @override + String get disableMask => 'Отключить маску'; + + @override + String get moveMaskUp => 'Переместить маску вверх'; + + @override + String get moveMaskDown => 'Переместить маску вниз'; + + @override + String get rectangle => 'Прямоугольник'; + + @override + String get ellipse => 'Эллипс'; + + @override + String get invert => 'Инвертировать'; + + @override + String get feather => 'Растушёвка'; + + @override + String get add => 'Сложение'; + + @override + String get subtract => 'Вычитание'; + + @override + String get intersect => 'Пересечение'; + + @override + String get initialRegion => 'Начальная область'; + + @override + String get none => 'Нет'; + + @override + String get color => 'Цвет'; + + @override + String get fontSize => 'Размер шрифта'; + + @override + String get outlineWidth => 'Толщина контура'; + + @override + String get outlineColor => 'Цвет контура'; + + @override + String get captionBaseline => 'Базовая линия субтитров'; + + @override + String get content => 'Текст'; + + @override + String get start => 'Начало'; + + @override + String get time => 'Время'; + + @override + String get speed => 'Скорость'; + + @override + String speedSegmentCount(int count) { + return 'Сегментов скорости: $count'; + } + + @override + String get splitSpeedAtPlayhead => 'Разделить скорость на позиции указателя'; + + @override + String get speedChange => 'Скорость'; + + @override + String get speedMode => 'Режим скорости'; + + @override + String get constantSpeed => 'Постоянная скорость'; + + @override + String get segmentedSpeed => 'Сегментированная скорость'; + + @override + String get speedNotAvailable => 'Регулировка скорости пока недоступна.'; + + @override + String get custom => 'Настраиваемый'; + + @override + String get invalidNumber => 'Недопустимое значение'; + + @override + String get mediaUnavailable => 'Медиа недоступно'; + + @override + String get mediaMissing => 'Медиа отсутствует'; + + @override + String get mediaColorSpace => 'Цветовое пространство мультимедиа'; + + @override + String get mediaColorInterpretation => 'Интерпретация цвета медиа'; + + @override + String get colorInfoNotLoaded => 'Информация о цвете не загружена'; + + @override + String get unknownColorSpace => + 'Неизвестное цветовое пространство. Отображается как Rec.709.'; + + @override + String get colorBackendUnsupported => + 'Текущая серверная часть не поддерживает интерпретацию цвета мультимедиа.'; + + @override + String get loadClipPropertiesFailed => 'Не удалось прочитать свойства клипа.'; + + @override + String get updatePictureFailed => 'Не удалось обновить свойства изображения.'; + + @override + String get updateVolumeFailed => 'Не удалось изменить громкость'; + + @override + String get updateMaskFailed => 'Не удалось обновить маску'; + + @override + String get updateKeyframesFailed => 'Не удалось обновить ключевые кадры'; + + @override + String get maskPreviewFailed => + 'Не удалось подготовить предварительный просмотр маски.'; + + @override + String get alignClipFailed => + 'Не удалось выровнять клип. Подождите предварительного просмотра и повторите попытку.'; + + @override + String get invalidTransform => + 'Масштаб должен быть 1–10 000 %. Позиция и угол должны быть допустимыми числами.'; + + @override + String get editFailed => + 'Не удалось отредактировать. Проверьте ввод и временной диапазон.'; + + @override + String get addMediaFailed => + 'Не удалось добавить медиа. Пожалуйста, попробуйте еще раз.'; + + @override + String get deleteCaption => 'Удалить субтитр'; + + @override + String get mergeCaptions => 'Объединить субтитры'; + + @override + String get captionDeleted => 'Субтитр удалён'; + + @override + String get captionChanged => + 'Субтитры изменились. Пожалуйста, попробуйте еще раз.'; + + @override + String get captionEditChanged => + 'Субтитры изменились. Пожалуйста, отредактируйте еще раз.'; + + @override + String get assistantHint => 'Опишите свою идею редактирования'; + + @override + String get configureAgentHint => + 'Настройте службу агента, чтобы начать общение'; + + @override + String get agentRestartHint => + 'Настройте службу агента, затем перезапустите приложение.'; + + @override + String get replyInterrupted => 'Ответ прерван'; + + @override + String get replying => 'Подготовка ответа…'; + + @override + String get stopReply => 'Остановить ответ'; + + @override + String get sendMessage => 'Отправить сообщение'; + + @override + String get addAttachment => 'Добавить вложение (пока недоступно)'; + + @override + String get replyFailed => + 'Ответ не удался. Проверьте соединение или повторите попытку позже.'; + + @override + String get mcpService => 'MCP-сервис'; + + @override + String get listenPort => 'Порт'; + + @override + String get accessToken => 'Токен доступа'; + + @override + String get copyAccessToken => 'Копировать токен доступа'; + + @override + String get accessTokenCopied => 'Токен доступа скопирован.'; + + @override + String get loadMcpFailed => + 'Не удалось загрузить настройки MCP. Повторить попытку'; + + @override + String get saveMcpFailed => + 'Не удалось сохранить настройки MCP. Пожалуйста, попробуйте еще раз.'; + + @override + String get retryStart => 'Повторить попытку запуска'; + + @override + String get invalidPort => 'Порт должен быть в диапазоне от 1 до 65535.'; + + @override + String get loadingSettings => 'Загрузка настроек…'; + + @override + String get starting => 'Запуск…'; + + @override + String get stopping => 'Остановка…'; + + @override + String get disabled => 'Отключено'; + + @override + String get running => 'Работает'; + + @override + String get startFailed => 'Не удалось запустить'; + + @override + String get saved => 'Сохранено'; + + @override + String get unsaved => 'несохраненный'; + + @override + String get saving => 'Сохранение…'; + + @override + String get pendingSave => 'Ожидание сохранения'; + + @override + String get notApplied => 'Не применено'; + + @override + String get enable => 'Включить'; + + @override + String get disable => 'Отключить'; + + @override + String get type => 'Тип'; + + @override + String get status => 'Статус'; + + @override + String get file => 'Файл'; + + @override + String get unboundMedia => 'Медиа не привязано'; + + @override + String get unboundAudio => 'Аудиодорожка не привязана'; + + @override + String get vertical => 'Вертикально'; + + @override + String get language => 'Язык'; + + @override + String get saveLanguageFailed => + 'Не удалось сохранить язык. Пожалуйста, попробуйте еще раз.'; + + @override + String get loadLanguageFailed => + 'Не удалось загрузить язык. Пожалуйста, выберите еще раз.'; + + @override + String get propertiesFirstLayout => 'Свойства в первую очередь'; + + @override + String get defaultLayout => 'Макет по умолчанию'; + + @override + String get separateVocals => 'Отделить вокал'; + + @override + String get detachAudio => 'Отделить аудио'; + + @override + String get restoreAudio => 'Восстановить аудио'; + + @override + String get audioDetached => 'Аудио отделено'; + + @override + String get addAll => 'Добавить всё'; + + @override + String get preparingMedia => 'Подготовка медиа…'; + + @override + String get cancelling => 'Отмена…'; + + @override + String get cancelled => 'Отменено'; + + @override + String get interruptedTask => + 'Задача прервана. Перезапустите, чтобы продолжить'; + + @override + String get auto => 'Автоматически'; + + @override + String get autoDetect => 'Определить автоматически'; + + @override + String get noTranslation => 'Не переводить'; + + @override + String get sourceLanguage => 'Исходный язык'; + + @override + String get translationLanguage => 'Язык перевода'; + + @override + String get transcriptionNotConfigured => + 'Транскрипция не настроена. Установите компонент распознавания и модель Whisper Turbo.'; + + @override + String get translationNotConfigured => + 'Перевод титров не настроен. Вы можете создавать субтитры на исходном языке.'; + + @override + String get sourceLanguageUnknown => + 'Не удалось определить исходный язык для перевода.'; + + @override + String get startTranscriptionFailed => + 'Не удалось начать транскрипцию. Проверьте носитель или дождитесь завершения текущей задачи.'; + + @override + String get placeMediaFirst => + 'Поместите этот медиафайл на временную шкалу перед применением субтитров.'; + + @override + String get placeTranslationMediaFirst => + 'Прежде чем применять переведенные субтитры, поместите соответствующие медиафайлы на временную шкалу.'; + + @override + String get selectTargetClip => 'Выберите целевой клип'; + + @override + String get timelineChanged => + 'Временная шкала изменилась. Снова выберите целевой клип.'; + + @override + String get transcriptionAccessFailed => + 'Ошибка транскрипции: компонент, модель или исходный носитель недоступны (notConfigured)'; + + @override + String get transcriptionNoAudio => + 'Ошибка транскрипции: на выбранном носителе или дорожке нет распознаваемого звука (noAudio)'; + + @override + String get transcriptionInvalidResult => + 'Ошибка транскрипции: возвращен недопустимый файл субтитров (invalidResult)'; + + @override + String get transcriptionWorkerExited => + 'Транскрипция не удалась: компонент распознавания неожиданно завершил работу (workerExited)'; + + @override + String get transcriptionProcessingFailed => + 'Ошибка транскрипции: ошибка встроенной обработки (processingFailed)'; + + @override + String get transcriptionFailed => + 'Транскрипция не удалась. Проверьте компонент, модель, звуковую дорожку и продолжительность.'; + + @override + String get transcribing => 'Транскрибирование…'; + + @override + String get captionsGenerated => 'Субтитры созданы'; + + @override + String get cancelTranscription => 'Отменить транскрибирование'; + + @override + String get applyCaptions => 'Применить субтитры'; + + @override + String get preparingTranslation => 'Подготовка перевода…'; + + @override + String get translatingCaptions => 'Перевод субтитров…'; + + @override + String get cancellingTranslation => 'Отмена перевода…'; + + @override + String get translatedCaptionsGenerated => 'Переведённые субтитры созданы'; + + @override + String get translationCancelled => 'Перевод отменён'; + + @override + String get translationInterrupted => 'Перевод прерван'; + + @override + String get cancelTranslation => 'Отменить перевод'; + + @override + String get editorServiceUnavailable => + 'Сервис редактирования недоступен. Снова откройте проект.'; + + @override + String get mcpUnavailable => + 'Соединение MCP недоступно. Проверьте локальный порт и токен.'; + + @override + String get openTimelineFailed => 'Не удалось открыть хронологию'; + + @override + String get noTimelineSequence => 'В этом таймлайне нет секвенции.'; + + @override + String get waitingForProject => 'Ждем открытия проекта'; + + @override + String get hold => 'Удержание'; + + @override + String get noImportableFiles => 'Импортируемые файлы не получены'; + + @override + String get virtualFilesUnsupported => + 'Перетащите оригинальные файлы из файлового менеджера. Виртуальные файлы пока не поддерживаются.'; + + @override + String get editorSessionStartFailed => + 'Не удалось открыть редактор таймлайна'; + + @override + String get previewStartFailed => + 'Не удалось запустить встроенный предварительный просмотр.'; + + @override + String get previewInvalidTrack => + 'Выбранная аудио- или видеодорожка не существует на носителе.'; + + @override + String get previewMissingBinding => + 'Привязки мультимедиа отсутствуют. Не удалось просмотреть эту хронологию.'; + + @override + String get previewUnsupportedEdits => + 'Эта временная шкала содержит изменения, которые еще не поддерживаются предварительной версией.'; + + @override + String get previewUnsupportedConfiguration => + 'Эта предварительная конфигурация не поддерживается на текущей платформе или версии системы.'; + + @override + String get previewHdrUnsupported => + 'Для мультимедиа HDR требуется тональная компрессия для предварительного просмотра SDR. Текущая система или предварительная конфигурация не поддерживают его.'; + + @override + String get previewAudioOutOfRange => + 'Аудиоклип выходит за пределы диапазона исходной дорожки и не может быть просмотрен.'; + + @override + String get previewResourceMissing => + 'Предварительный просмотр носителя больше не существует. Снова найдите исходный файл.'; + + @override + String get previewInvalidComposition => + 'Неверная конфигурация композиции видео. Не удалось создать предварительный просмотр.'; + + @override + String get previewInvalidData => + 'Неверные данные предварительного просмотра. Пожалуйста, попробуйте еще раз.'; + + @override + String get previewFailed => + 'Предварительный просмотр не удался. Проверьте доступ к мультимедиа и повторите попытку.'; + + @override + String get chatFailed => + 'Не удалось завершить разговор. Проверьте конфигурацию службы или повторите попытку позже.'; + + @override + String get delete => 'Удалить'; + + @override + String get pinTimeline => 'Закрепить таймлайн'; + + @override + String get unpinTimeline => 'Открепить таймлайн'; + + @override + String deleteTimelineConfirmation(String name) { + return 'Удалить «$name» и историю изменений? Это действие нельзя отменить.'; + } + + @override + String get processingFailed => 'Ошибка обработки'; + + @override + String get noMatchingOptions => 'Нет подходящих вариантов'; + + @override + String removeMediaConfirmation(String name) { + return 'Удалить «$name» из библиотеки? Существующие клипы, история и исходный файл будут сохранены.'; + } + + @override + String mediaAdded(int count) { + return 'Добавлено ссылок на медиа: $count'; + } + + @override + String duplicatesSkipped(int count) { + return 'Пропущены дубликаты файлов $count.'; + } + + @override + String mediaCount(int count) { + return 'Медиа: $count'; + } + + @override + String get importMedia => 'Импортировать'; + + @override + String noMediaOfType(String type) { + return 'Нет носителя $type'; + } + + @override + String captionsImported(String count) { + return 'Импортированные субтитры $count.'; + } + + @override + String editCaptionError(String message) { + return 'Не удалось редактировать субтитры: $message.'; + } + + @override + String mcpStartError(String message) { + return 'Не удалось запустить MCP: $message.'; + } + + @override + String manualColorSpace(String name) { + return 'Выбрано вручную: $name'; + } + + @override + String detectedColorSpace(String name) { + return 'Обнаружено: $name'; + } + + @override + String keyframeLabel(String channel) { + return 'Ключевой кадр: $channel'; + } + + @override + String maskMode(String mode) { + return 'Комбинированный режим: $mode'; + } + + @override + String keyframeCount(int count) { + return 'Ключевых кадров: $count'; + } + + @override + String toggleKeyframe(String action, String channel) { + return '$action ключевой кадр: $channel'; + } + + @override + String previousKeyframe(String channel) { + return 'Предыдущий ключевой кадр: $channel'; + } + + @override + String nextKeyframe(String channel) { + return 'Следующий ключевой кадр: $channel'; + } + + @override + String keyframeSettings(String channel) { + return 'Настройки ключевых кадров: $channel'; + } + + @override + String selectedClipsHint(int count) { + return 'Выбраны клипы $count.\nВыберите один клип, чтобы просмотреть его свойства.'; + } + + @override + String transcriptionError(String code) { + return 'Транскрипция не удалась. Проверьте компонент, модель, звуковую дорожку и продолжительность ($code)'; + } + + @override + String captionsAdded(String count) { + return 'Добавлены субтитры $count. Отредактируйте их на панели свойств.'; + } + + @override + String translatedCaptionsAdded(String count) { + return 'Добавлены переведенные субтитры $count. Отредактируйте их на панели свойств.'; + } + + @override + String applyCaptionsError(String message) { + return 'Не удалось применить субтитры: $message.'; + } + + @override + String applyTranslatedCaptionsError(String message) { + return 'Не удалось применить переведенные субтитры: $message.'; + } + + @override + String recognizedCaptions(int count) { + return 'Распознано субтитров: $count'; + } + + @override + String captionCount(int count) { + return 'Субтитров: $count'; + } + + @override + String translationFailed(String message) { + return 'Ошибка перевода: $message'; + } + + @override + String translatedCaptionCount(int count, String language) { + return 'Субтитров: $count ($language)'; + } + + @override + String previewParameterError(String message) { + return 'Неверные параметры предварительного просмотра: $message.'; + } + + @override + String mediaOffline(String names) { + return 'Мультимедиа не в сети или недоступно: $names'; + } + + @override + String searchOptions(String label) { + return 'Поиск $label…'; + } + + @override + String get loadRecentProjectsFailed => + 'Не удалось загрузить последние библиотеки. Вы по-прежнему можете открыть библиотеку вручную.'; + + @override + String get projectAccessFailed => 'Проект недоступен'; + + @override + String get projectMissingDirectory => 'Проект не найден'; + + @override + String get recentProjectSaveFailed => + 'Библиотека открылась, но недавнюю запись библиотеки сохранить не удалось.'; + + @override + String get lastProjectSaveFailed => + 'Проект открыт, но последнюю запись проекта сохранить не удалось.'; + + @override + String get enterProjectName => 'Введите название проекта'; + + @override + String get projectSwitched => 'Проект изменился. Перетащите медиа снова.'; + + @override + String get notLocalMedia => 'Этот носитель не является локальным файлом'; + + @override + String get revealMediaFailed => + 'Не удалось отобразить медиафайлы в файловом менеджере.'; + + @override + String get openMatchingProject => 'Сначала откройте соответствующий проект'; + + @override + String get projectMismatch => + 'Библиотека по этому адресу не соответствует записи. Выберите его еще раз с помощью команды «Открыть библиотеку».'; + + @override + String get openProjectFirst => 'Сначала откройте библиотеку'; + + @override + String get localFilesOnly => + 'Перетащите локальные файлы из файлового менеджера'; + + @override + String get foldersUnsupported => + 'Выберите файлы. Перетаскивание папок пока не поддерживается.'; + + @override + String get mediaImportCancelled => 'Импорт мультимедиа отменен'; + + @override + String get fileAccessFailed => + 'Файл отсутствует или не читается. Проверьте его местоположение и разрешения'; + + @override + String get registerMediaFailed => + 'Не удалось зарегистрировать носитель. Пожалуйста, попробуйте еще раз'; + + @override + String get mediaNoLongerExists => 'медиа больше не существует'; + + @override + String get mediaNoTracks => + 'В медиафайле нет пригодных для использования видео- или аудиодорожек.'; + + @override + String get invalidMediaDuration => 'Неверная продолжительность медиа.'; + + @override + String get mediaInfoUnsupported => + 'Чтение медиаинформации пока не поддерживается на этой платформе.'; + + @override + String get mediaInfoFailed => + 'Не удалось прочитать медиа-информацию. Проверьте файл и права доступа'; + + @override + String get saveTimelineFailed => + 'Не удалось сохранить хронологию. Попробуйте еще раз. Несохраненные изменения остаются в этом сеансе.'; + + @override + String get addKeyframeAction => 'Добавить'; + + @override + String get backgroundTasks => 'Фоновые задачи'; + + @override + String get noBackgroundTasks => 'Нет фоновых задач'; + + @override + String get retryTask => 'Повторить'; + + @override + String get applyOriginalCaptions => 'Применить исходные субтитры'; + + @override + String get applyTranslatedCaptions => 'Применить переведённые субтитры'; + + @override + String get subtitleTaskStarted => 'Создание субтитров начато'; + + @override + String get fitTimeline => 'Показать всю временную шкалу'; + + @override + String get modify => 'Modify'; + + @override + String get projectSettings => 'Project settings'; + + @override + String get projectSettingsDescription => + 'Change project output settings while keeping clip timing and speed.'; + + @override + String get projectColorSpace => 'Color space'; + + @override + String get projectWidth => 'Width (px)'; + + @override + String get projectHeight => 'Height (px)'; + + @override + String get projectResolutionInvalid => 'Enter a whole number from 1 to 16384'; + + @override + String get previewFullscreen => 'Полноэкранный просмотр'; + + @override + String get exitPreviewFullscreen => 'Выйти из полноэкранного режима'; + + @override + String get previewGoToStart => 'В начало'; + + @override + String get previewPreviousFrame => 'Предыдущий кадр'; + + @override + String get previewNextFrame => 'Следующий кадр'; + + @override + String get softwareUpdates => 'Обновления'; + + @override + String get checkForUpdates => 'Проверить обновления'; + + @override + String get automaticallyCheckUpdates => 'Проверять обновления автоматически'; + + @override + String get updatesUnavailable => 'В этой сборке обновления недоступны.'; + + @override + String get updateCheckFailed => + 'Не удалось проверить обновления. Повторите попытку.'; + + @override + String get removeBackground => 'Удалить фон'; + + @override + String get startBackgroundRemoval => 'Удалить фон'; + + @override + String get backgroundRemovalResourceRequired => + 'Для удаления фона нужна локальная модель. После загрузки обработка начнётся автоматически.'; + + @override + String get backgroundRemovalDownloadTask => 'Загрузить ресурс удаления фона'; + + @override + String get backgroundRemovalResourceName => 'Модель удаления фона'; + + @override + String get backgroundRemovalDestructiveHint => + 'Созданный медиафайл с прозрачным фоном заменит этот клип. Исходный клип можно восстановить командой «Отменить».'; + + @override + String get backgroundRemovalTaskStarted => 'Удаление фона запущено'; + + @override + String get startBackgroundRemovalFailed => + 'Не удалось начать удаление фона. Проверьте медиафайл или дождитесь завершения текущей задачи обработки.'; + + @override + String get backgroundRemovalComplete => 'Удаление фона завершено'; + + @override + String get backgroundRemovalApplying => 'Замена медиафайла клипа'; + + @override + String get backgroundRemovalFailed => 'Не удалось удалить фон'; + + @override + String get agentSettings => 'Агент'; + + @override + String get agentSaveSettingsFailed => + 'Не удалось сохранить настройки агента.'; + + @override + String get agentDeleteProviderTitle => 'Удалить провайдера?'; + + @override + String agentDeleteProviderDescription(String providerName) { + return '«$providerName» и сохранённый ключ API будут удалены с этого устройства.'; + } + + @override + String get agentProviderRequired => + 'Добавьте провайдера, прежде чем включать помощника.'; + + @override + String get agentUseSelectedModel => + 'Новые запросы агента будут использовать выбранную модель.'; + + @override + String get agentEnable => 'Включить агента'; + + @override + String get agentDefaultModel => 'Модель по умолчанию'; + + @override + String get agentConfigureModel => 'Настроить модели'; + + @override + String get agentSelectModel => 'Выбрать модель'; + + @override + String get agentModelUnavailable => + 'Модель этого диалога недоступна. Выберите другую модель, чтобы начать новый диалог.'; + + @override + String get agentModelChangeSession => + 'При смене модели начинается новый сеанс агента.'; + + @override + String get agentCustomProviders => 'Пользовательские провайдеры'; + + @override + String get agentProviderStorageDescription => + 'Метаданные провайдера хранятся локально. Ключи API сохраняются в системном хранилище учётных данных.'; + + @override + String get agentAddProvider => 'Добавить провайдера'; + + @override + String get agentBackToProviders => 'Назад к провайдерам'; + + @override + String get agentLoadSettingsFailed => + 'Не удалось загрузить настройки агента. Повторить'; + + @override + String get agentEnableProvider => 'Включить провайдера'; + + @override + String get agentEditProvider => 'Изменить провайдера'; + + @override + String get agentDeleteProvider => 'Удалить провайдера'; + + @override + String get agentModelIdsUnique => + 'Идентификаторы моделей должны быть уникальными.'; + + @override + String get agentEditProviderTitle => 'Изменить провайдера'; + + @override + String get agentProviderEndpointDescription => + 'Настройте конечную точку Chat Completions, совместимую с OpenAI.'; + + @override + String get agentSaveProvider => 'Сохранить провайдера'; + + @override + String get agentProviderConfiguration => 'Настройка провайдера'; + + @override + String get agentAuthenticationAndModels => 'Аутентификация и модели'; + + @override + String get agentApiType => 'Тип API'; + + @override + String get agentOpenAiChatCompletions => 'OpenAI Completions'; + + @override + String get agentBaseUrl => 'Базовый URL'; + + @override + String get agentApiKey => 'Ключ API'; + + @override + String get agentProviderNameHint => 'Мой провайдер'; + + @override + String get agentApiKeyOptional => + 'Необязательно для конечных точек без аутентификации.'; + + @override + String get agentApiKeyKeep => + 'Оставьте поле пустым, чтобы сохранить текущий ключ.'; + + @override + String get agentOptional => 'Необязательно'; + + @override + String get agentApiKeyOneLine => 'Ключ API должен занимать одну строку.'; + + @override + String get agentRemoveSavedApiKey => 'Удалить сохранённый ключ API'; + + @override + String get agentModels => 'Модели'; + + @override + String get agentAddModel => 'Добавить модель'; + + @override + String get agentRequiredField => 'Это поле обязательно.'; + + @override + String get agentInvalidBaseUrl => + 'Введите базовый URL HTTP(S) без учётных данных, строки запроса и фрагмента.'; + + @override + String get agentModelId => 'Идентификатор модели'; + + @override + String get agentContextWindow => 'Контекстное окно'; + + @override + String get agentMaxOutputTokens => 'Максимальный вывод'; + + @override + String get agentMaxOutputBelowContext => + 'Значение должно быть меньше контекстного окна.'; + + @override + String get agentDeleteModel => 'Удалить модель'; + + @override + String get agentPositiveInteger => 'Введите положительное целое число.'; + + @override + String get agentConfigurationReadFailed => + 'Не удалось прочитать конфигурацию агента. Проверьте настройки и повторите попытку.'; + + @override + String get agentConfigurationRequired => + 'Сначала настройте и включите агента в настройках.'; + + @override + String get agentSessionRestoreFailed => + 'Не удалось восстановить сеанс агента. Повторите попытку позже.'; + + @override + String get agentContextBudgetExceeded => + 'Недостаточно места для системных инструкций, инструментов и сообщения. Увеличьте контекст или уменьшите максимальный вывод.'; + + @override + String get agentAuthenticationFailed => + 'Ошибка авторизации. Проверьте API Key и разрешения.'; + + @override + String get agentConnectionFailed => + 'Ошибка подключения или тайм-аут. Проверьте Base URL и сеть.'; + + @override + String get agentProtocolFailed => + 'Ответ не соответствует выбранному типу API или поток неполный.'; + + @override + String get agentContextBudgetTooSmall => + 'Оставьте больше места для инструкций. Увеличьте контекст или уменьшите максимальный вывод.'; + + @override + String get agentCompacting => 'Упорядочивание контекста…'; + + @override + String get agentEditing => 'Редактирование…'; + + @override + String get agentVerifying => 'Проверка результатов…'; + + @override + String get agentTurnLimitReached => + 'Достигнут лимит выполнения задачи. Изменения сохранены. Отправьте «Продолжить», чтобы возобновить.'; + + @override + String get agentRecoveryRequired => + 'Результат предыдущей операции не подтверждён. Продолжите для проверки сохранённых записей; неподтверждённые изменения не будут повторены.'; + + @override + String get agentExportReplyFailed => + 'Видео экспортировано. Не удалось получить итоговый ответ. Повторите запрос итога без повторного монтажа или экспорта.'; + + @override + String get agentRetrySummary => 'Повторить итог'; + + @override + String get agentResumeTask => 'Продолжить задачу'; + + @override + String get agentTaskInterrupted => + 'Задача прервана. Продолжите с сохранённого состояния.'; + + @override + String get downloadSubtitleModel => 'Скачать модель субтитров'; + + @override + String get downloadModelAction => 'Скачать'; + + @override + String get subtitleEngineUnavailable => + 'Модель установлена, но движок субтитров не запустился. Исправьте движок; повторно скачивать модель не нужно.'; + + @override + String get backgroundTaskDetails => 'Сведения о задаче'; + + @override + String get backgroundTaskFailed => 'Ошибка'; + + @override + String get backgroundTaskCompleted => 'Завершено'; + + @override + String get captionWrapLines => 'Переносить текст субтитров'; + + @override + String get captionSingleLine => 'Показывать субтитры в одну строку'; + + @override + String get noMatchingCaptions => 'Нет подходящих субтитров'; + + @override + String get subtitleResourcesRequired => + 'Эти ресурсы нужны для субтитров. После загрузки создание начнётся автоматически.'; + + @override + String subtitleResourcesDownloadSize(String size) { + return 'Объём загрузки: $size'; + } + + @override + String get pauseDownload => 'Пауза'; + + @override + String get resumeDownload => 'Продолжить'; + + @override + String get downloadPaused => 'Приостановлено'; + + @override + String get cancelResourceDownloadTitle => 'Отменить загрузку?'; + + @override + String get cancelResourceDownloadMessage => + 'Загрузка остановится. Прогресс загрузки текущего ресурса может быть потерян.'; + + @override + String get continueDownload => 'Продолжить загрузку'; + + @override + String get cancelDownload => 'Отменить загрузку'; + + @override + String get speechResourceStage => 'Ресурс распознавания речи'; + + @override + String get translationResourceStage => 'Ресурс перевода'; + + @override + String get subtitleResourceDownloadTask => + 'Загрузить ресурсы распознавания речи и перевода'; + + @override + String get downloadingSpeechModel => 'Загрузка речевой модели'; + + @override + String get downloadingTranslationModel => 'Загрузка модели перевода'; + + @override + String get checkingForUpdates => 'Проверка обновлений…'; + + @override + String get appIsUpToDate => 'Установлена последняя версия.'; + + @override + String downloadingUpdate(int progress) { + return 'Загрузка обновления: $progress%'; + } + + @override + String updateAvailable(String version) { + return 'Доступна версия $version.'; + } + + @override + String get downloadUpdate => 'Скачать обновление'; + + @override + String get restartToUpdate => 'Перезапустить и обновить'; + + @override + String get updateOperationFailed => + 'Не удалось обновить. Завершите активные задачи и повторите попытку.'; + + @override + String get windowMinimize => 'Свернуть'; + + @override + String get windowMaximize => 'Развернуть'; + + @override + String get windowRestore => 'Восстановить'; + + @override + String get workspaceAgent => 'Ассистент'; + + @override + String get workspaceCut => 'Монтаж'; + + @override + String get noAvailableOptions => 'Нет доступных вариантов'; + + @override + String get composerReferenceInvalid => + 'Ссылка больше недействительна. Вернитесь к её проекту или удалите её.'; + + @override + String durationSeconds(int seconds) { + return '$seconds с'; + } + + @override + String durationMinutesSeconds(int minutes, int seconds) { + return '$minutes мин $seconds с'; + } + + @override + String get projectNameInvalid => 'Недопустимое имя проекта'; + + @override + String get projectLocationDefaultUnavailable => + 'Нет доступа к папке проектов по умолчанию. Выберите её заново в настройках.'; + + @override + String get chooseProjectLocation => + 'Сначала выберите папку для сохранения проектов в настройках.'; + + @override + String get untitledTimeline => 'Таймлайн без названия'; + + @override + String get primarySequence => 'Основная последовательность'; + + @override + String get primaryStoryline => 'Основная линия'; + + @override + String get projectSessionClosed => + 'Сеанс проекта закрыт. Откройте проект заново.'; + + @override + String get timelineSessionClosed => + 'Сеанс таймлайна закрыт. Откройте таймлайн заново.'; + + @override + String get timelineMissing => 'Таймлайн не существует или был удалён.'; + + @override + String get timelineInUse => + 'Таймлайн используется и пока не может быть удалён.'; + + @override + String get timelineHasBackgroundTasks => + 'Завершите фоновые задачи таймлайна перед удалением.'; + + @override + String get timelineRequired => + 'В проекте должен оставаться хотя бы один таймлайн.'; + + @override + String get mediaReadFailed => 'Не удалось прочитать медиафайл'; + + @override + String get mediaImportFailed => 'Не удалось импортировать медиафайл'; + + @override + String get unsupportedMediaType => + 'Можно импортировать только видео, аудио и изображения.'; + + @override + String get mediaNoVideoTracks => 'В медиафайле нет доступной видеодорожки'; + + @override + String get mediaDurationOutOfRange => + 'Длительность медиафайла превышает диапазон таймлайна'; + + @override + String resourceDownloadHttpFailed(String statusCode) { + return 'Ошибка загрузки (HTTP $statusCode)'; + } + + @override + String get resourceChecksumFailed => + 'Проверка файла модели не пройдена. Загрузите ресурс заново.'; + + @override + String get subtitleLanguageAf => 'африкаанс'; + + @override + String get subtitleLanguageAm => 'амхарский'; + + @override + String get subtitleLanguageAr => 'арабский'; + + @override + String get subtitleLanguageAst => 'астурийский'; + + @override + String get subtitleLanguageAz => 'азербайджанский'; + + @override + String get subtitleLanguageBa => 'башкирский'; + + @override + String get subtitleLanguageBe => 'белорусский'; + + @override + String get subtitleLanguageBg => 'болгарский'; + + @override + String get subtitleLanguageBn => 'бенгальский'; + + @override + String get subtitleLanguageBr => 'бретонский'; + + @override + String get subtitleLanguageBs => 'боснийский'; + + @override + String get subtitleLanguageCa => 'каталанский'; + + @override + String get subtitleLanguageCeb => 'себуано'; + + @override + String get subtitleLanguageCs => 'чешский'; + + @override + String get subtitleLanguageCy => 'валлийский'; + + @override + String get subtitleLanguageDa => 'датский'; + + @override + String get subtitleLanguageDe => 'немецкий'; + + @override + String get subtitleLanguageEl => 'греческий'; + + @override + String get subtitleLanguageEn => 'английский'; + + @override + String get subtitleLanguageEs => 'испанский'; + + @override + String get subtitleLanguageEt => 'эстонский'; + + @override + String get subtitleLanguageFa => 'персидский'; + + @override + String get subtitleLanguageFf => 'фулах'; + + @override + String get subtitleLanguageFi => 'финский'; + + @override + String get subtitleLanguageFr => 'французский'; + + @override + String get subtitleLanguageFy => 'западнофризский'; + + @override + String get subtitleLanguageGa => 'ирландский'; + + @override + String get subtitleLanguageGd => 'гэльский'; + + @override + String get subtitleLanguageGl => 'галисийский'; + + @override + String get subtitleLanguageGu => 'гуджарати'; + + @override + String get subtitleLanguageHa => 'хауса'; + + @override + String get subtitleLanguageHe => 'иврит'; + + @override + String get subtitleLanguageHi => 'хинди'; + + @override + String get subtitleLanguageHr => 'хорватский'; + + @override + String get subtitleLanguageHt => 'гаитянский'; + + @override + String get subtitleLanguageHu => 'венгерский'; + + @override + String get subtitleLanguageHy => 'армянский'; + + @override + String get subtitleLanguageId => 'индонезийский'; + + @override + String get subtitleLanguageIg => 'игбо'; + + @override + String get subtitleLanguageIlo => 'илоко'; + + @override + String get subtitleLanguageIs => 'исландский'; + + @override + String get subtitleLanguageIt => 'итальянский'; + + @override + String get subtitleLanguageJa => 'японский'; + + @override + String get subtitleLanguageJv => 'яванский'; + + @override + String get subtitleLanguageKa => 'грузинский'; + + @override + String get subtitleLanguageKk => 'казахский'; + + @override + String get subtitleLanguageKm => 'кхмерский'; + + @override + String get subtitleLanguageKn => 'каннада'; + + @override + String get subtitleLanguageKo => 'корейский'; + + @override + String get subtitleLanguageLb => 'люксембургский'; + + @override + String get subtitleLanguageLg => 'ганда'; + + @override + String get subtitleLanguageLn => 'лингала'; + + @override + String get subtitleLanguageLo => 'лаосский'; + + @override + String get subtitleLanguageLt => 'литовский'; + + @override + String get subtitleLanguageLv => 'латышский'; + + @override + String get subtitleLanguageMg => 'малагасийский'; + + @override + String get subtitleLanguageMk => 'македонский'; + + @override + String get subtitleLanguageMl => 'малаялам'; + + @override + String get subtitleLanguageMn => 'монгольский'; + + @override + String get subtitleLanguageMr => 'маратхи'; + + @override + String get subtitleLanguageMs => 'малайский'; + + @override + String get subtitleLanguageMy => 'бирманский'; + + @override + String get subtitleLanguageNe => 'непальский'; + + @override + String get subtitleLanguageNl => 'нидерландский'; + + @override + String get subtitleLanguageNo => 'норвежский'; + + @override + String get subtitleLanguageNs => 'северный сото'; + + @override + String get subtitleLanguageOc => 'окситанский'; + + @override + String get subtitleLanguageOr => 'ория'; + + @override + String get subtitleLanguagePa => 'панджаби'; + + @override + String get subtitleLanguagePl => 'польский'; + + @override + String get subtitleLanguagePs => 'пушту'; + + @override + String get subtitleLanguagePt => 'португальский'; + + @override + String get subtitleLanguageRo => 'румынский'; + + @override + String get subtitleLanguageRu => 'русский'; + + @override + String get subtitleLanguageSd => 'синдхи'; + + @override + String get subtitleLanguageSi => 'сингальский'; + + @override + String get subtitleLanguageSk => 'словацкий'; + + @override + String get subtitleLanguageSl => 'словенский'; + + @override + String get subtitleLanguageSo => 'сомали'; + + @override + String get subtitleLanguageSq => 'албанский'; + + @override + String get subtitleLanguageSr => 'сербский'; + + @override + String get subtitleLanguageSs => 'свази'; + + @override + String get subtitleLanguageSu => 'сунданский'; + + @override + String get subtitleLanguageSv => 'шведский'; + + @override + String get subtitleLanguageSw => 'суахили'; + + @override + String get subtitleLanguageTa => 'тамильский'; + + @override + String get subtitleLanguageTh => 'тайский'; + + @override + String get subtitleLanguageTl => 'тагалог'; + + @override + String get subtitleLanguageTn => 'тсвана'; + + @override + String get subtitleLanguageTr => 'турецкий'; + + @override + String get subtitleLanguageUk => 'украинский'; + + @override + String get subtitleLanguageUr => 'урду'; + + @override + String get subtitleLanguageUz => 'узбекский'; + + @override + String get subtitleLanguageVi => 'вьетнамский'; + + @override + String get subtitleLanguageWo => 'волоф'; + + @override + String get subtitleLanguageXh => 'коса'; + + @override + String get subtitleLanguageYi => 'идиш'; + + @override + String get subtitleLanguageYo => 'йоруба'; + + @override + String get subtitleLanguageYue => 'кантонский'; + + @override + String get subtitleLanguageZh => 'китайский'; + + @override + String get subtitleLanguageZu => 'зулу'; + + @override + String get linearRec2020 => 'Линейный Rec.2020'; + + @override + String get diagnostics => 'Диагностика'; + + @override + String get exportDiagnostics => 'Экспортировать пакет диагностики'; + + @override + String get exportDiagnosticsFailed => + 'Не удалось экспортировать диагностику. Повторите попытку.'; + + @override + String get exportDiagnosticsSucceeded => 'Пакет диагностики сохранён.'; +} diff --git a/lib/l10n/app_localizations_zh.dart b/lib/l10n/app_localizations_zh.dart new file mode 100644 index 0000000..ad9fa1c --- /dev/null +++ b/lib/l10n/app_localizations_zh.dart @@ -0,0 +1,6261 @@ +// ignore: unused_import +import 'package:intl/intl.dart' as intl; + +import 'app_localizations.dart'; + +// ignore_for_file: type=lint + +/// The translations for Chinese (`zh`). +class AppLocalizationsZh extends AppLocalizations { + AppLocalizationsZh([String locale = 'zh']) : super(locale); + + @override + String get selectProject => '选择项目'; + + @override + String get searchProjects => '搜索项目'; + + @override + String get noMatchingProjects => '没有匹配的项目'; + + @override + String get projectsNone => '暂无项目'; + + @override + String get projectLocationMissing => '目录不存在,创建项目时将自动创建。'; + + @override + String get projectLocationUnavailable => '项目保存位置不可用,请连接磁盘或检查网络后重试,也可以更改位置。'; + + @override + String get projectLocationNotWritable => '项目保存位置没有写入权限,请检查权限或更改位置。'; + + @override + String get projectLocationCreateFailed => '无法创建或写入项目保存目录,请检查权限或更改位置。'; + + @override + String get removeProjectFromSidebar => '从侧边栏移除'; + + @override + String get projectRemoved => '已移除项目,本地文件和聊天记录已保留。'; + + @override + String get agentNoConversations => '暂无聊天'; + + @override + String get renameConversationTitle => '重命名聊天'; + + @override + String get renameConversationDescription => '保持简短且易于识别'; + + @override + String get collapseProject => '收起项目'; + + @override + String get expandProject => '展开项目'; + + @override + String agentDeleteConfirmation(String title) { + return '聊天“$title”及其消息记录将被永久删除,无法恢复。本地项目文件不受影响。'; + } + + @override + String get agentEmptyTrashConfirmation => '回收站中的所有聊天将被永久删除,无法恢复。本地项目文件不受影响。'; + + @override + String get agentConversations => '对话'; + + @override + String get showMoreConversations => '展开显示'; + + @override + String get showFewerConversations => '收起显示'; + + @override + String get agentNewConversation => '新建对话'; + + @override + String agentElapsedTime(String duration) { + return '用时 $duration'; + } + + @override + String get agentConversationActions => '对话操作'; + + @override + String get agentMoveToTrash => '移至回收区'; + + @override + String get agentTrash => '回收区'; + + @override + String get agentRestore => '恢复'; + + @override + String get agentEmptyTrash => '清空回收区'; + + @override + String get agentDeleteForever => '永久删除'; + + @override + String get agentConversationLocation => '对话存储位置'; + + @override + String get agentChooseExistingConversations => '选择已有对话目录'; + + @override + String get agentMoveConversations => '移动对话'; + + @override + String get agentLocationUnavailable => '对话存储位置不可用'; + + @override + String get agentLocationBusy => '请等待当前对话运行结束后再移动'; + + @override + String get agentRelinkProvider => '重新关联 Provider'; + + @override + String get settings => '设置'; + + @override + String get closeSettings => '关闭设置'; + + @override + String get general => '通用'; + + @override + String get appearance => '外观'; + + @override + String get theme => '主题'; + + @override + String get system => '跟随系统'; + + @override + String get light => '明亮'; + + @override + String get dark => '深色'; + + @override + String get saveAppearanceFailed => '无法保存外观设置,请重试'; + + @override + String get loadAppearanceFailed => '无法读取外观设置,请重新选择主题'; + + @override + String get cancel => '取消'; + + @override + String get save => '保存'; + + @override + String get create => '创建'; + + @override + String get close => '关闭'; + + @override + String get retry => '重试'; + + @override + String get select => '选择'; + + @override + String get name => '名称'; + + @override + String get enterName => '请输入名称'; + + @override + String get invalidName => '名称不能包含路径分隔符或控制字符'; + + @override + String get projects => '项目'; + + @override + String get projectName => '项目名称'; + + @override + String get projectLocation => '项目保存位置'; + + @override + String get projectLocationNotSet => '未设置'; + + @override + String get loadProjectLocationFailed => '无法读取项目保存位置。'; + + @override + String get saveProjectLocationFailed => '无法保存项目保存位置。'; + + @override + String get resourceLocation => '资源存储位置'; + + @override + String get resourceLocationNotSet => '未设置'; + + @override + String get loadResourceLocationFailed => '无法读取资源存储位置。'; + + @override + String get saveResourceLocationFailed => '无法保存资源存储位置。'; + + @override + String get transcriptionResourceRequired => '生成字幕需要先下载语音识别模型。'; + + @override + String get downloadAndContinue => '下载并继续'; + + @override + String get downloadingResource => '正在下载…'; + + @override + String get downloadInBackground => '后台下载'; + + @override + String get processingResourceDownloadFailed => '语音识别资源下载失败,请重试。'; + + @override + String get newProject => '新建项目'; + + @override + String get openProject => '打开项目'; + + @override + String get openProjectMore => '打开项目…'; + + @override + String get saveHere => '保存到这里'; + + @override + String get selectDirectoryFailed => '无法选择目录,请检查系统权限。'; + + @override + String get openingWorkspace => '正在打开工作区…'; + + @override + String get loadProjectsFailed => '无法加载项目列表'; + + @override + String get projectsEmpty => '新建或打开项目,开始剪辑。'; + + @override + String get backToProjects => '返回剪辑'; + + @override + String get timelines => '时间线'; + + @override + String timelineLimitReached(int count) { + return '每个项目最多可创建 $count 条时间线。'; + } + + @override + String get timelineName => '时间线名称'; + + @override + String defaultTimelineName(int index) { + return '时间线 $index'; + } + + @override + String get newTimeline => '新建时间线'; + + @override + String get noTimelines => '暂无时间线'; + + @override + String get activeTimeline => '当前时间线'; + + @override + String get timelineUnavailable => '时间线不可用'; + + @override + String get projectNoTimelines => '项目中还没有时间线'; + + @override + String get createTimelineHint => '在左侧“时间线”分组中新建时间线,开始剪辑。'; + + @override + String get createTimelineChat => '新建时间线后即可开始对话'; + + @override + String get operationFailed => '操作失败,请重试'; + + @override + String get collapseSidebar => '收起侧边栏'; + + @override + String get expandSidebar => '展开侧边栏'; + + @override + String get expandEditor => '展开剪辑区'; + + @override + String get collapseProperties => '收起属性面板'; + + @override + String get expandProperties => '展开属性面板'; + + @override + String get layout => '布局'; + + @override + String get editingFirstLayout => '剪辑优先'; + + @override + String get agentEditingLayout => 'Agent + 剪辑'; + + @override + String get agentLayoutDescription => '规划、协作和执行'; + + @override + String get editingLayoutDescription => '预览、剪辑和调整'; + + @override + String get materials => '素材'; + + @override + String get all => '全部'; + + @override + String get video => '视频'; + + @override + String get audio => '音频'; + + @override + String get image => '图像'; + + @override + String get picture => '图片'; + + @override + String get captions => '字幕'; + + @override + String get text => '文字'; + + @override + String get noMedia => '暂无素材'; + + @override + String get mediaCategory => '素材分类'; + + @override + String get captionTasks => '字幕任务'; + + @override + String get listLayout => '列表布局'; + + @override + String get gridLayout => '宫格布局'; + + @override + String get addToTimeline => '添加到时间线'; + + @override + String get rename => '重命名'; + + @override + String get renameMedia => '重命名素材'; + + @override + String get removeMedia => '移除素材'; + + @override + String get remove => '移除'; + + @override + String get revealFinder => '在访达中显示'; + + @override + String get revealFileManager => '在文件管理器中显示'; + + @override + String get dropToAdd => '松手即可添加'; + + @override + String get timelineDropToStart => '将媒体拖到此处以开始。'; + + @override + String get dragMediaHint => '将视频、音频或图像拖到这里\n原文件保留在原位置'; + + @override + String get transcribe => '转字幕'; + + @override + String get generateCaptions => '生成字幕'; + + @override + String get play => '播放'; + + @override + String get pause => '暂停播放'; + + @override + String get retryPreview => '重试预览'; + + @override + String get canvasRatio => '画布比例'; + + @override + String get noPreviewContent => '时间线中暂无可预览内容'; + + @override + String get nativePreviewUnsupported => '当前平台尚未实现原生预览'; + + @override + String get canvasTransformFailed => '无法完成画布变换,请重试。'; + + @override + String get undo => '撤销'; + + @override + String get redo => '重做'; + + @override + String get deleteSelectedClips => '删除所选片段'; + + @override + String get splitAtPlayhead => '在播放头处分割'; + + @override + String get trimLeft => '向左裁剪'; + + @override + String get trimRight => '向右裁剪'; + + @override + String get trimLeftTooltip => '裁掉播放头左侧,保留右侧'; + + @override + String get trimRightTooltip => '裁掉播放头右侧,保留左侧'; + + @override + String get currentSequence => '当前序列'; + + @override + String get projectProperties => '项目属性'; + + @override + String get canvasSize => '画布尺寸'; + + @override + String get frameRate => '帧率'; + + @override + String get duration => '时长'; + + @override + String get totalDuration => '总时长'; + + @override + String get clipDuration => '片段时长'; + + @override + String get seconds => '秒'; + + @override + String get clip => '片段'; + + @override + String get unnamedClip => '未命名片段'; + + @override + String get gap => '空隙'; + + @override + String get compoundClip => '复合片段'; + + @override + String get textClip => '文字片段'; + + @override + String get pictureProperties => '画面'; + + @override + String get position => '位置'; + + @override + String get rotation => '旋转'; + + @override + String get scale => '缩放'; + + @override + String get size => '尺寸'; + + @override + String get transform => '变换'; + + @override + String get resetPosition => '重置位置'; + + @override + String get keepAspectRatio => '等比缩放'; + + @override + String get alignment => '对齐'; + + @override + String get alignLeft => '左对齐'; + + @override + String get alignRight => '右对齐'; + + @override + String get alignTop => '顶部对齐'; + + @override + String get alignBottom => '底部对齐'; + + @override + String get alignHorizontalCenter => '水平居中'; + + @override + String get alignVerticalCenter => '垂直居中'; + + @override + String get volume => '音量'; + + @override + String get gain => '增益'; + + @override + String get mute => '静音'; + + @override + String get unmute => '取消静音'; + + @override + String get resetVolume => '重置音量'; + + @override + String get invalidGain => '请输入 -90 到 +12 之间的数值'; + + @override + String get animation => '动画'; + + @override + String get keyframes => '关键帧'; + + @override + String get removeAllKeyframes => '移除全部关键帧'; + + @override + String get linear => '线性'; + + @override + String get easeIn => '缓入'; + + @override + String get easeOut => '缓出'; + + @override + String get easeInOut => '缓入缓出'; + + @override + String get basic => '基本'; + + @override + String get mask => '蒙版'; + + @override + String get addMask => '添加蒙版'; + + @override + String get deleteMask => '删除蒙版'; + + @override + String get resetMask => '重置蒙版'; + + @override + String get enableMask => '启用蒙版'; + + @override + String get disableMask => '停用蒙版'; + + @override + String get moveMaskUp => '上移蒙版'; + + @override + String get moveMaskDown => '下移蒙版'; + + @override + String get rectangle => '矩形'; + + @override + String get ellipse => '椭圆'; + + @override + String get invert => '反转'; + + @override + String get feather => '羽化'; + + @override + String get add => '相加'; + + @override + String get subtract => '相减'; + + @override + String get intersect => '相交'; + + @override + String get initialRegion => '初始区域'; + + @override + String get none => '无'; + + @override + String get color => '颜色'; + + @override + String get fontSize => '字号'; + + @override + String get outlineWidth => '描边宽度'; + + @override + String get outlineColor => '描边颜色'; + + @override + String get captionBaseline => '字幕基线'; + + @override + String get content => '文本'; + + @override + String get start => '开始'; + + @override + String get time => '时间'; + + @override + String get speed => '速度'; + + @override + String speedSegmentCount(int count) { + return '$count 个速度区间'; + } + + @override + String get splitSpeedAtPlayhead => '在播放头分割速度区间'; + + @override + String get speedChange => '变速'; + + @override + String get speedMode => '变速模式'; + + @override + String get constantSpeed => '恒定速度'; + + @override + String get segmentedSpeed => '分段变速'; + + @override + String get speedNotAvailable => '变速调节控件尚未接入'; + + @override + String get custom => '自定义'; + + @override + String get invalidNumber => '无效数值'; + + @override + String get mediaUnavailable => '素材不可用'; + + @override + String get mediaMissing => '素材缺失'; + + @override + String get mediaColorSpace => '素材色彩空间'; + + @override + String get mediaColorInterpretation => '素材色彩解释'; + + @override + String get colorInfoNotLoaded => '色彩信息未读取'; + + @override + String get unknownColorSpace => '色彩空间未知,暂按 Rec.709 显示'; + + @override + String get colorBackendUnsupported => '当前后端不支持素材色彩解释。'; + + @override + String get loadClipPropertiesFailed => '无法读取片段属性'; + + @override + String get updatePictureFailed => '无法更新画面属性'; + + @override + String get updateVolumeFailed => '无法更新音量'; + + @override + String get updateMaskFailed => '无法更新蒙版'; + + @override + String get updateKeyframesFailed => '无法更新关键帧'; + + @override + String get maskPreviewFailed => '无法准备蒙版预览'; + + @override + String get alignClipFailed => '无法对齐片段,请等待预览就绪后重试'; + + @override + String get invalidTransform => '缩放范围为 1%–10000%,位置和角度必须为有效数值'; + + @override + String get editFailed => '无法修改,请检查输入和时间范围。'; + + @override + String get addMediaFailed => '无法添加素材,请重试'; + + @override + String get deleteCaption => '删除字幕'; + + @override + String get mergeCaptions => '合并字幕'; + + @override + String get captionDeleted => '字幕已删除'; + + @override + String get captionChanged => '字幕已变化,请重试。'; + + @override + String get captionEditChanged => '字幕已变化,请重新编辑。'; + + @override + String get assistantHint => '描述你的剪辑想法'; + + @override + String get configureAgentHint => '配置 Agent 服务后开始对话'; + + @override + String get agentRestartHint => '请配置 Agent 服务后重新启动应用。'; + + @override + String get replyInterrupted => '回复已中断'; + + @override + String get replying => '正在回复…'; + + @override + String get stopReply => '停止回复'; + + @override + String get sendMessage => '发送消息'; + + @override + String get addAttachment => '添加附件(暂未接入)'; + + @override + String get replyFailed => '回复失败,请检查服务连接或稍后重试。'; + + @override + String get mcpService => 'MCP 服务'; + + @override + String get listenPort => '监听端口'; + + @override + String get accessToken => '访问令牌'; + + @override + String get copyAccessToken => '复制访问令牌'; + + @override + String get accessTokenCopied => '访问令牌已复制'; + + @override + String get loadMcpFailed => '无法读取 MCP 设置,重试'; + + @override + String get saveMcpFailed => '无法保存 MCP 设置,请重试'; + + @override + String get retryStart => '重试启动'; + + @override + String get invalidPort => '端口必须为 1–65535'; + + @override + String get loadingSettings => '正在读取设置…'; + + @override + String get starting => '正在启动…'; + + @override + String get stopping => '正在停止…'; + + @override + String get disabled => '已停用'; + + @override + String get running => '运行中'; + + @override + String get startFailed => '启动失败'; + + @override + String get saved => '已保存'; + + @override + String get unsaved => '未保存'; + + @override + String get saving => '保存中…'; + + @override + String get pendingSave => '待保存'; + + @override + String get notApplied => '未应用'; + + @override + String get enable => '启用'; + + @override + String get disable => '停用'; + + @override + String get type => '类型'; + + @override + String get status => '状态'; + + @override + String get file => '文件'; + + @override + String get unboundMedia => '未绑定素材'; + + @override + String get unboundAudio => '未绑定音轨'; + + @override + String get vertical => '垂直'; + + @override + String get language => '语言'; + + @override + String get saveLanguageFailed => '无法保存语言设置,请重试'; + + @override + String get loadLanguageFailed => '无法读取语言设置,请重新选择'; + + @override + String get propertiesFirstLayout => '属性优先布局'; + + @override + String get defaultLayout => '默认布局'; + + @override + String get separateVocals => '分离人声'; + + @override + String get detachAudio => '分离音频'; + + @override + String get restoreAudio => '恢复音频'; + + @override + String get audioDetached => '音频已分离'; + + @override + String get addAll => '全部添加'; + + @override + String get preparingMedia => '准备素材…'; + + @override + String get cancelling => '正在取消…'; + + @override + String get cancelled => '已取消'; + + @override + String get interruptedTask => '任务已中断,可重新启动并继续'; + + @override + String get auto => '自动'; + + @override + String get autoDetect => '自动识别'; + + @override + String get noTranslation => '不翻译'; + + @override + String get sourceLanguage => '源语言'; + + @override + String get translationLanguage => '翻译语言'; + + @override + String get transcriptionNotConfigured => '转字幕尚未配置,请安装识别组件和 Whisper Turbo 模型。'; + + @override + String get translationNotConfigured => '字幕翻译尚未配置,目前可生成源语言字幕。'; + + @override + String get sourceLanguageUnknown => '无法确定可翻译的源语言。'; + + @override + String get startTranscriptionFailed => '无法启动识别,请检查素材,或等待当前任务完成。'; + + @override + String get placeMediaFirst => '请先将这份素材放到时间线,再应用字幕。'; + + @override + String get placeTranslationMediaFirst => '请先将对应素材放到时间线,再应用翻译字幕。'; + + @override + String get selectTargetClip => '选择目标片段'; + + @override + String get timelineChanged => '时间线已变化,请重新选择目标片段。'; + + @override + String get transcriptionAccessFailed => '识别失败:无法访问识别组件、模型或源素材(notConfigured)'; + + @override + String get transcriptionNoAudio => '识别失败:所选素材或音轨没有可识别的音频(noAudio)'; + + @override + String get transcriptionInvalidResult => '识别失败:组件返回的字幕文件无效(invalidResult)'; + + @override + String get transcriptionWorkerExited => '识别失败:识别组件意外退出(workerExited)'; + + @override + String get transcriptionProcessingFailed => '识别失败:原生识别处理失败(processingFailed)'; + + @override + String get transcriptionFailed => '识别失败,请检查组件、模型、音轨和时长'; + + @override + String get transcribing => '正在识别…'; + + @override + String get captionsGenerated => '字幕已生成'; + + @override + String get cancelTranscription => '取消识别'; + + @override + String get applyCaptions => '应用为字幕'; + + @override + String get preparingTranslation => '准备翻译…'; + + @override + String get translatingCaptions => '正在翻译字幕…'; + + @override + String get cancellingTranslation => '正在取消翻译…'; + + @override + String get translatedCaptionsGenerated => '翻译字幕已生成'; + + @override + String get translationCancelled => '翻译已取消'; + + @override + String get translationInterrupted => '翻译任务已中断'; + + @override + String get cancelTranslation => '取消翻译'; + + @override + String get editorServiceUnavailable => '编辑工具服务不可用,请重新打开项目。'; + + @override + String get mcpUnavailable => 'MCP 连接不可用,请检查本地端口和令牌配置。'; + + @override + String get openTimelineFailed => '无法打开时间线'; + + @override + String get noTimelineSequence => '时间线中没有序列'; + + @override + String get waitingForProject => '等待打开工程'; + + @override + String get hold => '保持'; + + @override + String get noImportableFiles => '未收到可导入的文件'; + + @override + String get virtualFilesUnsupported => '请从文件管理器拖入原文件,暂不支持虚拟文件'; + + @override + String get editorSessionStartFailed => '无法打开时间线编辑器'; + + @override + String get previewStartFailed => '无法启动原生预览'; + + @override + String get previewInvalidTrack => '素材中不存在所选音视频轨道。'; + + @override + String get previewMissingBinding => '缺少素材绑定,无法预览当前时间线。'; + + @override + String get previewUnsupportedEdits => '当前时间线包含尚不支持预览的编辑。'; + + @override + String get previewUnsupportedConfiguration => '当前平台或系统版本尚不支持此预览配置。'; + + @override + String get previewHdrUnsupported => 'HDR 素材需要色调映射才能在 SDR 预览中显示,当前系统或预览配置不支持。'; + + @override + String get previewAudioOutOfRange => '音频片段超出了素材音轨的有效范围,无法预览。'; + + @override + String get previewResourceMissing => '预览素材已不存在,请重新定位原文件。'; + + @override + String get previewInvalidComposition => '视频合成配置无效,无法创建预览。'; + + @override + String get previewInvalidData => '预览数据无效,请重试。'; + + @override + String get previewFailed => '预览失败,请检查素材是否可访问后重试。'; + + @override + String get chatFailed => '无法完成对话,请检查服务配置或稍后重试。'; + + @override + String get delete => '删除'; + + @override + String get pinTimeline => '置顶时间线'; + + @override + String get unpinTimeline => '取消置顶'; + + @override + String deleteTimelineConfirmation(String name) { + return '删除“$name”及其编辑历史?此操作无法撤销。'; + } + + @override + String get processingFailed => '处理失败'; + + @override + String get noMatchingOptions => '没有匹配的选项'; + + @override + String removeMediaConfirmation(String name) { + return '从项目移除“$name”?已有片段、历史版本和原文件会保留。'; + } + + @override + String mediaAdded(int count) { + return '已添加 $count 个素材引用'; + } + + @override + String duplicatesSkipped(int count) { + return '跳过 $count 个重复文件'; + } + + @override + String mediaCount(int count) { + return '$count 个素材'; + } + + @override + String get importMedia => '导入'; + + @override + String noMediaOfType(String type) { + return '暂无$type素材'; + } + + @override + String captionsImported(String count) { + return '已导入 $count 条字幕'; + } + + @override + String editCaptionError(String message) { + return '无法修改字幕:$message'; + } + + @override + String mcpStartError(String message) { + return '无法启动 MCP:$message'; + } + + @override + String manualColorSpace(String name) { + return '手动指定:$name'; + } + + @override + String detectedColorSpace(String name) { + return '已识别:$name'; + } + + @override + String keyframeLabel(String channel) { + return '$channel关键帧'; + } + + @override + String maskMode(String mode) { + return '组合方式:$mode'; + } + + @override + String keyframeCount(int count) { + return '$count 个关键帧'; + } + + @override + String toggleKeyframe(String action, String channel) { + return '$action$channel关键帧'; + } + + @override + String previousKeyframe(String channel) { + return '上一个$channel关键帧'; + } + + @override + String nextKeyframe(String channel) { + return '下一个$channel关键帧'; + } + + @override + String keyframeSettings(String channel) { + return '$channel关键帧设置'; + } + + @override + String selectedClipsHint(int count) { + return '已选择 $count 个片段\n请选择单个片段查看属性'; + } + + @override + String transcriptionError(String code) { + return '识别失败,请检查组件、模型、音轨和时长($code)'; + } + + @override + String captionsAdded(String count) { + return '已添加 $count 条字幕,可在属性面板编辑。'; + } + + @override + String translatedCaptionsAdded(String count) { + return '已添加 $count 条翻译字幕,可在属性面板编辑。'; + } + + @override + String applyCaptionsError(String message) { + return '无法应用字幕:$message'; + } + + @override + String applyTranslatedCaptionsError(String message) { + return '无法应用翻译字幕:$message'; + } + + @override + String recognizedCaptions(int count) { + return '已识别 $count 条'; + } + + @override + String captionCount(int count) { + return '$count 条字幕'; + } + + @override + String translationFailed(String message) { + return '翻译失败:$message'; + } + + @override + String translatedCaptionCount(int count, String language) { + return '$count 条$language字幕'; + } + + @override + String previewParameterError(String message) { + return '预览参数无效:$message'; + } + + @override + String mediaOffline(String names) { + return '素材离线或不可用:$names'; + } + + @override + String searchOptions(String label) { + return '搜索$label…'; + } + + @override + String get loadRecentProjectsFailed => '无法读取最近项目记录,仍可手动打开项目。'; + + @override + String get projectAccessFailed => '项目不可用'; + + @override + String get projectMissingDirectory => '项目不存在'; + + @override + String get recentProjectSaveFailed => '项目已打开,但最近使用记录未能保存。'; + + @override + String get lastProjectSaveFailed => '项目已打开,但上次项目记录未能保存。'; + + @override + String get enterProjectName => '请输入项目名称'; + + @override + String get projectSwitched => '项目已切换,请重新拖入素材'; + + @override + String get notLocalMedia => '该素材不是本地文件'; + + @override + String get revealMediaFailed => '无法在文件管理器中显示素材'; + + @override + String get openMatchingProject => '请先打开对应项目'; + + @override + String get projectMismatch => '此位置的项目与记录不一致,请使用“打开项目”重新选择。'; + + @override + String get openProjectFirst => '请先打开项目'; + + @override + String get localFilesOnly => '请从文件管理器拖入本地文件'; + + @override + String get foldersUnsupported => '请选择文件,暂不支持拖入文件夹'; + + @override + String get mediaImportCancelled => '素材导入已取消'; + + @override + String get fileAccessFailed => '文件不存在或无法读取,请检查位置与权限'; + + @override + String get registerMediaFailed => '无法登记素材,请重试'; + + @override + String get mediaNoLongerExists => '素材已不存在'; + + @override + String get mediaNoTracks => '素材没有可用的视频或音频轨道'; + + @override + String get invalidMediaDuration => '素材时长无效'; + + @override + String get mediaInfoUnsupported => '当前平台尚未支持素材信息读取'; + + @override + String get mediaInfoFailed => '无法读取素材信息,请检查文件与访问权限'; + + @override + String get saveTimelineFailed => '时间线保存失败,请重试。未保存的编辑仍保留在当前会话。'; + + @override + String get addKeyframeAction => '添加'; + + @override + String get backgroundTasks => '后台任务'; + + @override + String get noBackgroundTasks => '暂无后台任务'; + + @override + String get retryTask => '重试'; + + @override + String get applyOriginalCaptions => '应用原文字幕'; + + @override + String get applyTranslatedCaptions => '应用翻译字幕'; + + @override + String get subtitleTaskStarted => '字幕任务已开始'; + + @override + String get fitTimeline => '适合整个时间线'; + + @override + String get modify => '修改'; + + @override + String get projectSettings => '项目设置'; + + @override + String get projectSettingsDescription => '修改项目输出规格,保留片段的实际时长和速度。'; + + @override + String get projectColorSpace => '色彩空间'; + + @override + String get projectWidth => '宽度(px)'; + + @override + String get projectHeight => '高度(px)'; + + @override + String get projectResolutionInvalid => '请输入 1–16384 的整数'; + + @override + String get previewFullscreen => '全屏预览'; + + @override + String get exitPreviewFullscreen => '退出全屏'; + + @override + String get previewGoToStart => '回到开头'; + + @override + String get previewPreviousFrame => '上一帧'; + + @override + String get previewNextFrame => '下一帧'; + + @override + String get softwareUpdates => '软件更新'; + + @override + String get checkForUpdates => '检查更新'; + + @override + String get automaticallyCheckUpdates => '自动检查更新'; + + @override + String get updatesUnavailable => '此构建暂不提供更新。'; + + @override + String get updateCheckFailed => '无法检查更新,请重试。'; + + @override + String get removeBackground => '抠像'; + + @override + String get startBackgroundRemoval => '开始抠像'; + + @override + String get backgroundRemovalResourceRequired => '抠像需要下载本地模型。下载完成后会自动开始抠像。'; + + @override + String get backgroundRemovalDownloadTask => '下载抠像资源'; + + @override + String get backgroundRemovalResourceName => '抠像模型'; + + @override + String get backgroundRemovalDestructiveHint => + '生成的透明素材会直接替换当前片段;仍可通过撤销恢复原片段。'; + + @override + String get backgroundRemovalTaskStarted => '抠像任务已开始'; + + @override + String get startBackgroundRemovalFailed => '无法启动抠像,请检查素材,或等待当前处理任务完成。'; + + @override + String get backgroundRemovalComplete => '抠像完成'; + + @override + String get backgroundRemovalApplying => '正在替换片段素材'; + + @override + String get backgroundRemovalFailed => '抠像失败'; + + @override + String get agentSettings => 'Agent'; + + @override + String get agentSaveSettingsFailed => '无法保存 Agent 设置。'; + + @override + String get agentDeleteProviderTitle => '删除 Provider?'; + + @override + String agentDeleteProviderDescription(String providerName) { + return '将从此设备移除“$providerName”及其保存的 API Key。'; + } + + @override + String get agentProviderRequired => '请先添加 Provider,再启用助手。'; + + @override + String get agentUseSelectedModel => '新的 Agent 请求将使用所选模型。'; + + @override + String get agentEnable => '启用 Agent'; + + @override + String get agentDefaultModel => '默认模型'; + + @override + String get agentConfigureModel => '配置模型'; + + @override + String get agentSelectModel => '选择模型'; + + @override + String get agentModelUnavailable => '此对话的模型已不可用,请选择其他模型开始新对话。'; + + @override + String get agentModelChangeSession => '切换模型后会开始新的 Agent 会话。'; + + @override + String get agentCustomProviders => '自定义 Provider'; + + @override + String get agentProviderStorageDescription => + 'Provider 元数据保存在本机,API Key 保存在系统凭据存储中。'; + + @override + String get agentAddProvider => '添加 Provider'; + + @override + String get agentBackToProviders => '返回 Provider 列表'; + + @override + String get agentLoadSettingsFailed => '无法读取 Agent 设置,重试'; + + @override + String get agentEnableProvider => '启用 Provider'; + + @override + String get agentEditProvider => '编辑 Provider'; + + @override + String get agentDeleteProvider => '删除 Provider'; + + @override + String get agentModelIdsUnique => 'Model ID 不能重复。'; + + @override + String get agentEditProviderTitle => '编辑 Provider'; + + @override + String get agentProviderEndpointDescription => + '配置 OpenAI-compatible Chat Completions 服务。'; + + @override + String get agentSaveProvider => '保存 Provider'; + + @override + String get agentProviderConfiguration => 'Provider 配置'; + + @override + String get agentAuthenticationAndModels => '认证与模型'; + + @override + String get agentApiType => 'API 类型'; + + @override + String get agentOpenAiChatCompletions => 'OpenAI Completions'; + + @override + String get agentBaseUrl => 'Base URL'; + + @override + String get agentApiKey => 'API Key'; + + @override + String get agentProviderNameHint => '我的 Provider'; + + @override + String get agentApiKeyOptional => '不需要鉴权的服务可以留空。'; + + @override + String get agentApiKeyKeep => '留空将保留已保存的 Key。'; + + @override + String get agentOptional => '可选'; + + @override + String get agentApiKeyOneLine => 'API Key 必须为单行文本。'; + + @override + String get agentRemoveSavedApiKey => '移除已保存的 API Key'; + + @override + String get agentModels => '模型'; + + @override + String get agentAddModel => '添加模型'; + + @override + String get agentRequiredField => '此项为必填项。'; + + @override + String get agentInvalidBaseUrl => '请输入不含凭据、查询参数或片段的 HTTP(S) Base URL。'; + + @override + String get agentModelId => 'Model ID'; + + @override + String get agentContextWindow => '上下文窗口'; + + @override + String get agentMaxOutputTokens => '最大输出'; + + @override + String get agentMaxOutputBelowContext => '必须小于上下文窗口。'; + + @override + String get agentDeleteModel => '删除模型'; + + @override + String get agentPositiveInteger => '请输入正整数。'; + + @override + String get agentConfigurationReadFailed => '无法读取 Agent 配置,请检查设置后重试。'; + + @override + String get agentConfigurationRequired => '请先在设置中配置并启用 Agent。'; + + @override + String get agentSessionRestoreFailed => '无法恢复 Agent 会话,请稍后重试。'; + + @override + String get agentContextBudgetExceeded => + '输入预算不足,无法容纳系统指令、工具和消息。请增大上下文窗口或降低最大输出 tokens。'; + + @override + String get agentAuthenticationFailed => '鉴权失败,请检查 Provider 的 API Key 和访问权限。'; + + @override + String get agentConnectionFailed => '模型服务连接失败或请求超时,请检查 Base URL 和网络。'; + + @override + String get agentProtocolFailed => '服务返回内容不符合所选 API 类型,或响应流不完整。'; + + @override + String get agentContextBudgetTooSmall => + '需要为系统指令保留更多输入空间,请增大上下文窗口或降低最大输出 tokens。'; + + @override + String get agentCompacting => '整理上下文…'; + + @override + String get agentEditing => '编辑中…'; + + @override + String get agentVerifying => '核对结果…'; + + @override + String get agentTurnLimitReached => '本轮任务已达到执行上限,已完成的编辑已保存。发送“继续”可接着执行。'; + + @override + String get agentRecoveryRequired => '上次操作的结果尚未确认。可继续任务核对已保存回执;未确认的编辑不会重复执行。'; + + @override + String get agentExportReplyFailed => '视频已成功导出,总结回复失败。可重试总结,不会重复剪辑或导出。'; + + @override + String get agentRetrySummary => '重试总结'; + + @override + String get agentResumeTask => '继续任务'; + + @override + String get agentTaskInterrupted => '任务已中断,可从已保存的进度继续。'; + + @override + String get downloadSubtitleModel => '下载字幕模型'; + + @override + String get downloadModelAction => '下载'; + + @override + String get subtitleEngineUnavailable => '模型已安装,但字幕处理引擎未能启动。请修复处理引擎,无需重新下载模型。'; + + @override + String get backgroundTaskDetails => '任务详情'; + + @override + String get backgroundTaskFailed => '失败'; + + @override + String get backgroundTaskCompleted => '已完成'; + + @override + String get captionWrapLines => '换行显示字幕'; + + @override + String get captionSingleLine => '单行显示字幕'; + + @override + String get noMatchingCaptions => '没有匹配的字幕'; + + @override + String get subtitleResourcesRequired => '生成字幕需要这些资源。下载完成后会自动开始处理。'; + + @override + String subtitleResourcesDownloadSize(String size) { + return '需下载 $size'; + } + + @override + String get pauseDownload => '暂停'; + + @override + String get resumeDownload => '继续'; + + @override + String get downloadPaused => '已暂停'; + + @override + String get cancelResourceDownloadTitle => '取消下载?'; + + @override + String get cancelResourceDownloadMessage => '下载任务将停止,当前资源的下载进度可能丢失。'; + + @override + String get continueDownload => '继续下载'; + + @override + String get cancelDownload => '取消下载'; + + @override + String get speechResourceStage => '语音识别资源'; + + @override + String get translationResourceStage => '翻译资源'; + + @override + String get subtitleResourceDownloadTask => '下载语音与翻译资源'; + + @override + String get downloadingSpeechModel => '正在下载语音模型'; + + @override + String get downloadingTranslationModel => '正在下载翻译模型'; + + @override + String get checkingForUpdates => '正在检查更新…'; + + @override + String get appIsUpToDate => '当前已是最新版本。'; + + @override + String downloadingUpdate(int progress) { + return '正在下载更新:$progress%'; + } + + @override + String updateAvailable(String version) { + return '发现新版本 $version。'; + } + + @override + String get downloadUpdate => '下载更新'; + + @override + String get restartToUpdate => '重启并更新'; + + @override + String get updateOperationFailed => '无法更新,请完成正在运行的任务后重试。'; + + @override + String get windowMinimize => '最小化'; + + @override + String get windowMaximize => '最大化'; + + @override + String get windowRestore => '还原'; + + @override + String get workspaceAgent => '助手'; + + @override + String get workspaceCut => '剪辑'; + + @override + String get noAvailableOptions => '暂无可用选项'; + + @override + String get composerReferenceInvalid => '引用已失效,请切回原项目或移除引用'; + + @override + String durationSeconds(int seconds) { + return '$seconds秒'; + } + + @override + String durationMinutesSeconds(int minutes, int seconds) { + return '$minutes分钟 $seconds秒'; + } + + @override + String get projectNameInvalid => '项目名称无效。'; + + @override + String get projectLocationDefaultUnavailable => '无法访问默认项目位置,请在设置中重新选择。'; + + @override + String get chooseProjectLocation => '请先在设置中选择项目保存位置。'; + + @override + String get untitledTimeline => '未命名时间线'; + + @override + String get primarySequence => '主序列'; + + @override + String get primaryStoryline => '主线'; + + @override + String get projectSessionClosed => '项目会话已关闭,请重新打开项目。'; + + @override + String get timelineSessionClosed => '时间线会话已关闭,请重新打开时间线。'; + + @override + String get timelineMissing => '时间线不存在或已被删除'; + + @override + String get timelineInUse => '时间线正在使用中,暂时无法删除'; + + @override + String get timelineHasBackgroundTasks => '时间线有正在进行的后台任务,暂时无法删除'; + + @override + String get timelineRequired => '项目至少需要保留一条时间线'; + + @override + String get mediaReadFailed => '无法读取素材'; + + @override + String get mediaImportFailed => '无法导入素材'; + + @override + String get unsupportedMediaType => '仅支持导入视频、音频和图像文件'; + + @override + String get mediaNoVideoTracks => '素材没有可用的视频轨道'; + + @override + String get mediaDurationOutOfRange => '素材时长超出时间线范围'; + + @override + String resourceDownloadHttpFailed(String statusCode) { + return '下载失败(HTTP $statusCode)'; + } + + @override + String get resourceChecksumFailed => '模型文件校验失败,请重新下载资源。'; + + @override + String get subtitleLanguageAf => '南非荷兰语'; + + @override + String get subtitleLanguageAm => '阿姆哈拉语'; + + @override + String get subtitleLanguageAr => '阿拉伯语'; + + @override + String get subtitleLanguageAst => '阿斯图里亚斯语'; + + @override + String get subtitleLanguageAz => '阿塞拜疆语'; + + @override + String get subtitleLanguageBa => '巴什基尔语'; + + @override + String get subtitleLanguageBe => '白俄罗斯语'; + + @override + String get subtitleLanguageBg => '保加利亚语'; + + @override + String get subtitleLanguageBn => '孟加拉语'; + + @override + String get subtitleLanguageBr => '布列塔尼语'; + + @override + String get subtitleLanguageBs => '波斯尼亚语'; + + @override + String get subtitleLanguageCa => '加泰罗尼亚语'; + + @override + String get subtitleLanguageCeb => '宿务语'; + + @override + String get subtitleLanguageCs => '捷克语'; + + @override + String get subtitleLanguageCy => '威尔士语'; + + @override + String get subtitleLanguageDa => '丹麦语'; + + @override + String get subtitleLanguageDe => '德语'; + + @override + String get subtitleLanguageEl => '希腊语'; + + @override + String get subtitleLanguageEn => '英语'; + + @override + String get subtitleLanguageEs => '西班牙语'; + + @override + String get subtitleLanguageEt => '爱沙尼亚语'; + + @override + String get subtitleLanguageFa => '波斯语'; + + @override + String get subtitleLanguageFf => '富拉语'; + + @override + String get subtitleLanguageFi => '芬兰语'; + + @override + String get subtitleLanguageFr => '法语'; + + @override + String get subtitleLanguageFy => '西弗里斯语'; + + @override + String get subtitleLanguageGa => '爱尔兰语'; + + @override + String get subtitleLanguageGd => '苏格兰盖尔语'; + + @override + String get subtitleLanguageGl => '加利西亚语'; + + @override + String get subtitleLanguageGu => '古吉拉特语'; + + @override + String get subtitleLanguageHa => '豪萨语'; + + @override + String get subtitleLanguageHe => '希伯来语'; + + @override + String get subtitleLanguageHi => '印地语'; + + @override + String get subtitleLanguageHr => '克罗地亚语'; + + @override + String get subtitleLanguageHt => '海地克里奥尔语'; + + @override + String get subtitleLanguageHu => '匈牙利语'; + + @override + String get subtitleLanguageHy => '亚美尼亚语'; + + @override + String get subtitleLanguageId => '印度尼西亚语'; + + @override + String get subtitleLanguageIg => '伊博语'; + + @override + String get subtitleLanguageIlo => '伊洛卡诺语'; + + @override + String get subtitleLanguageIs => '冰岛语'; + + @override + String get subtitleLanguageIt => '意大利语'; + + @override + String get subtitleLanguageJa => '日语'; + + @override + String get subtitleLanguageJv => '爪哇语'; + + @override + String get subtitleLanguageKa => '格鲁吉亚语'; + + @override + String get subtitleLanguageKk => '哈萨克语'; + + @override + String get subtitleLanguageKm => '高棉语'; + + @override + String get subtitleLanguageKn => '卡纳达语'; + + @override + String get subtitleLanguageKo => '韩语'; + + @override + String get subtitleLanguageLb => '卢森堡语'; + + @override + String get subtitleLanguageLg => '卢干达语'; + + @override + String get subtitleLanguageLn => '林加拉语'; + + @override + String get subtitleLanguageLo => '老挝语'; + + @override + String get subtitleLanguageLt => '立陶宛语'; + + @override + String get subtitleLanguageLv => '拉脱维亚语'; + + @override + String get subtitleLanguageMg => '马拉加斯语'; + + @override + String get subtitleLanguageMk => '马其顿语'; + + @override + String get subtitleLanguageMl => '马拉雅拉姆语'; + + @override + String get subtitleLanguageMn => '蒙古语'; + + @override + String get subtitleLanguageMr => '马拉地语'; + + @override + String get subtitleLanguageMs => '马来语'; + + @override + String get subtitleLanguageMy => '缅甸语'; + + @override + String get subtitleLanguageNe => '尼泊尔语'; + + @override + String get subtitleLanguageNl => '荷兰语'; + + @override + String get subtitleLanguageNo => '挪威语'; + + @override + String get subtitleLanguageNs => '北索托语'; + + @override + String get subtitleLanguageOc => '奥克语'; + + @override + String get subtitleLanguageOr => '奥里亚语'; + + @override + String get subtitleLanguagePa => '旁遮普语'; + + @override + String get subtitleLanguagePl => '波兰语'; + + @override + String get subtitleLanguagePs => '普什图语'; + + @override + String get subtitleLanguagePt => '葡萄牙语'; + + @override + String get subtitleLanguageRo => '罗马尼亚语'; + + @override + String get subtitleLanguageRu => '俄语'; + + @override + String get subtitleLanguageSd => '信德语'; + + @override + String get subtitleLanguageSi => '僧伽罗语'; + + @override + String get subtitleLanguageSk => '斯洛伐克语'; + + @override + String get subtitleLanguageSl => '斯洛文尼亚语'; + + @override + String get subtitleLanguageSo => '索马里语'; + + @override + String get subtitleLanguageSq => '阿尔巴尼亚语'; + + @override + String get subtitleLanguageSr => '塞尔维亚语'; + + @override + String get subtitleLanguageSs => '斯瓦蒂语'; + + @override + String get subtitleLanguageSu => '巽他语'; + + @override + String get subtitleLanguageSv => '瑞典语'; + + @override + String get subtitleLanguageSw => '斯瓦希里语'; + + @override + String get subtitleLanguageTa => '泰米尔语'; + + @override + String get subtitleLanguageTh => '泰语'; + + @override + String get subtitleLanguageTl => '他加禄语'; + + @override + String get subtitleLanguageTn => '茨瓦纳语'; + + @override + String get subtitleLanguageTr => '土耳其语'; + + @override + String get subtitleLanguageUk => '乌克兰语'; + + @override + String get subtitleLanguageUr => '乌尔都语'; + + @override + String get subtitleLanguageUz => '乌兹别克语'; + + @override + String get subtitleLanguageVi => '越南语'; + + @override + String get subtitleLanguageWo => '沃洛夫语'; + + @override + String get subtitleLanguageXh => '科萨语'; + + @override + String get subtitleLanguageYi => '意第绪语'; + + @override + String get subtitleLanguageYo => '约鲁巴语'; + + @override + String get subtitleLanguageYue => '粤语'; + + @override + String get subtitleLanguageZh => '中文'; + + @override + String get subtitleLanguageZu => '祖鲁语'; + + @override + String get linearRec2020 => '线性 Rec.2020'; + + @override + String get diagnostics => '诊断'; + + @override + String get exportDiagnostics => '导出诊断包'; + + @override + String get exportDiagnosticsFailed => '无法导出诊断包,请重试。'; + + @override + String get exportDiagnosticsSucceeded => '诊断包已保存。'; +} + +/// The translations for Chinese, using the Han script (`zh_Hans`). +class AppLocalizationsZhHans extends AppLocalizationsZh { + AppLocalizationsZhHans() : super('zh_Hans'); + + @override + String get selectProject => '选择项目'; + + @override + String get searchProjects => '搜索项目'; + + @override + String get noMatchingProjects => '没有匹配的项目'; + + @override + String get projectsNone => '暂无项目'; + + @override + String get projectLocationMissing => '目录不存在,创建项目时将自动创建。'; + + @override + String get projectLocationUnavailable => '项目保存位置不可用,请连接磁盘或检查网络后重试,也可以更改位置。'; + + @override + String get projectLocationNotWritable => '项目保存位置没有写入权限,请检查权限或更改位置。'; + + @override + String get projectLocationCreateFailed => '无法创建或写入项目保存目录,请检查权限或更改位置。'; + + @override + String get removeProjectFromSidebar => '从侧边栏移除'; + + @override + String get projectRemoved => '已移除项目,本地文件和聊天记录已保留。'; + + @override + String get agentNoConversations => '暂无聊天'; + + @override + String get renameConversationTitle => '重命名聊天'; + + @override + String get renameConversationDescription => '保持简短且易于识别'; + + @override + String get collapseProject => '收起项目'; + + @override + String get expandProject => '展开项目'; + + @override + String agentDeleteConfirmation(String title) { + return '聊天“$title”及其消息记录将被永久删除,无法恢复。本地项目文件不受影响。'; + } + + @override + String get agentEmptyTrashConfirmation => '回收站中的所有聊天将被永久删除,无法恢复。本地项目文件不受影响。'; + + @override + String get agentConversations => '对话'; + + @override + String get showMoreConversations => '展开显示'; + + @override + String get showFewerConversations => '收起显示'; + + @override + String get agentNewConversation => '新建对话'; + + @override + String agentElapsedTime(String duration) { + return '用时 $duration'; + } + + @override + String get agentConversationActions => '对话操作'; + + @override + String get agentMoveToTrash => '移至回收区'; + + @override + String get agentTrash => '回收区'; + + @override + String get agentRestore => '恢复'; + + @override + String get agentEmptyTrash => '清空回收区'; + + @override + String get agentDeleteForever => '永久删除'; + + @override + String get agentConversationLocation => '对话存储位置'; + + @override + String get agentChooseExistingConversations => '选择已有对话目录'; + + @override + String get agentMoveConversations => '移动对话'; + + @override + String get agentLocationUnavailable => '对话存储位置不可用'; + + @override + String get agentLocationBusy => '请等待当前对话运行结束后再移动'; + + @override + String get agentRelinkProvider => '重新关联 Provider'; + + @override + String get settings => '设置'; + + @override + String get closeSettings => '关闭设置'; + + @override + String get general => '通用'; + + @override + String get appearance => '外观'; + + @override + String get theme => '主题'; + + @override + String get system => '跟随系统'; + + @override + String get light => '明亮'; + + @override + String get dark => '深色'; + + @override + String get saveAppearanceFailed => '无法保存外观设置,请重试'; + + @override + String get loadAppearanceFailed => '无法读取外观设置,请重新选择主题'; + + @override + String get cancel => '取消'; + + @override + String get save => '保存'; + + @override + String get create => '创建'; + + @override + String get close => '关闭'; + + @override + String get retry => '重试'; + + @override + String get select => '选择'; + + @override + String get name => '名称'; + + @override + String get enterName => '请输入名称'; + + @override + String get invalidName => '名称不能包含路径分隔符或控制字符'; + + @override + String get projects => '项目'; + + @override + String get projectName => '项目名称'; + + @override + String get projectLocation => '项目保存位置'; + + @override + String get projectLocationNotSet => '未设置'; + + @override + String get loadProjectLocationFailed => '无法读取项目保存位置。'; + + @override + String get saveProjectLocationFailed => '无法保存项目保存位置。'; + + @override + String get resourceLocation => '资源存储位置'; + + @override + String get resourceLocationNotSet => '未设置'; + + @override + String get loadResourceLocationFailed => '无法读取资源存储位置。'; + + @override + String get saveResourceLocationFailed => '无法保存资源存储位置。'; + + @override + String get transcriptionResourceRequired => '生成字幕需要先下载语音识别模型。'; + + @override + String get downloadAndContinue => '下载并继续'; + + @override + String get downloadingResource => '正在下载…'; + + @override + String get downloadInBackground => '后台下载'; + + @override + String get processingResourceDownloadFailed => '语音识别资源下载失败,请重试。'; + + @override + String get newProject => '新建项目'; + + @override + String get openProject => '打开项目'; + + @override + String get openProjectMore => '打开项目…'; + + @override + String get saveHere => '保存到这里'; + + @override + String get selectDirectoryFailed => '无法选择目录,请检查系统权限。'; + + @override + String get openingWorkspace => '正在打开工作区…'; + + @override + String get loadProjectsFailed => '无法加载项目列表'; + + @override + String get projectsEmpty => '新建或打开项目,开始剪辑。'; + + @override + String get backToProjects => '返回剪辑'; + + @override + String get timelines => '时间线'; + + @override + String timelineLimitReached(int count) { + return '每个项目最多可创建 $count 条时间线。'; + } + + @override + String get timelineName => '时间线名称'; + + @override + String defaultTimelineName(int index) { + return '时间线 $index'; + } + + @override + String get newTimeline => '新建时间线'; + + @override + String get noTimelines => '暂无时间线'; + + @override + String get activeTimeline => '当前时间线'; + + @override + String get timelineUnavailable => '时间线不可用'; + + @override + String get projectNoTimelines => '项目中还没有时间线'; + + @override + String get createTimelineHint => '在左侧“时间线”分组中新建时间线,开始剪辑。'; + + @override + String get createTimelineChat => '新建时间线后即可开始对话'; + + @override + String get operationFailed => '操作失败,请重试'; + + @override + String get collapseSidebar => '收起侧边栏'; + + @override + String get expandSidebar => '展开侧边栏'; + + @override + String get expandEditor => '展开剪辑区'; + + @override + String get collapseProperties => '收起属性面板'; + + @override + String get expandProperties => '展开属性面板'; + + @override + String get layout => '布局'; + + @override + String get editingFirstLayout => '剪辑优先'; + + @override + String get agentEditingLayout => 'Agent + 剪辑'; + + @override + String get agentLayoutDescription => '规划、协作和执行'; + + @override + String get editingLayoutDescription => '预览、剪辑和调整'; + + @override + String get materials => '素材'; + + @override + String get all => '全部'; + + @override + String get video => '视频'; + + @override + String get audio => '音频'; + + @override + String get image => '图像'; + + @override + String get picture => '图片'; + + @override + String get captions => '字幕'; + + @override + String get text => '文字'; + + @override + String get noMedia => '暂无素材'; + + @override + String get mediaCategory => '素材分类'; + + @override + String get captionTasks => '字幕任务'; + + @override + String get listLayout => '列表布局'; + + @override + String get gridLayout => '宫格布局'; + + @override + String get addToTimeline => '添加到时间线'; + + @override + String get rename => '重命名'; + + @override + String get renameMedia => '重命名素材'; + + @override + String get removeMedia => '移除素材'; + + @override + String get remove => '移除'; + + @override + String get revealFinder => '在访达中显示'; + + @override + String get revealFileManager => '在文件管理器中显示'; + + @override + String get dropToAdd => '松手即可添加'; + + @override + String get timelineDropToStart => '将媒体拖到此处以开始。'; + + @override + String get dragMediaHint => '将视频、音频或图像拖到这里\n原文件保留在原位置'; + + @override + String get transcribe => '转字幕'; + + @override + String get generateCaptions => '生成字幕'; + + @override + String get play => '播放'; + + @override + String get pause => '暂停播放'; + + @override + String get retryPreview => '重试预览'; + + @override + String get canvasRatio => '画布比例'; + + @override + String get noPreviewContent => '时间线中暂无可预览内容'; + + @override + String get nativePreviewUnsupported => '当前平台尚未实现原生预览'; + + @override + String get canvasTransformFailed => '无法完成画布变换,请重试。'; + + @override + String get undo => '撤销'; + + @override + String get redo => '重做'; + + @override + String get deleteSelectedClips => '删除所选片段'; + + @override + String get splitAtPlayhead => '在播放头处分割'; + + @override + String get trimLeft => '向左裁剪'; + + @override + String get trimRight => '向右裁剪'; + + @override + String get trimLeftTooltip => '裁掉播放头左侧,保留右侧'; + + @override + String get trimRightTooltip => '裁掉播放头右侧,保留左侧'; + + @override + String get currentSequence => '当前序列'; + + @override + String get projectProperties => '项目属性'; + + @override + String get canvasSize => '画布尺寸'; + + @override + String get frameRate => '帧率'; + + @override + String get duration => '时长'; + + @override + String get totalDuration => '总时长'; + + @override + String get clipDuration => '片段时长'; + + @override + String get seconds => '秒'; + + @override + String get clip => '片段'; + + @override + String get unnamedClip => '未命名片段'; + + @override + String get gap => '空隙'; + + @override + String get compoundClip => '复合片段'; + + @override + String get textClip => '文字片段'; + + @override + String get pictureProperties => '画面'; + + @override + String get position => '位置'; + + @override + String get rotation => '旋转'; + + @override + String get scale => '缩放'; + + @override + String get size => '尺寸'; + + @override + String get transform => '变换'; + + @override + String get resetPosition => '重置位置'; + + @override + String get keepAspectRatio => '等比缩放'; + + @override + String get alignment => '对齐'; + + @override + String get alignLeft => '左对齐'; + + @override + String get alignRight => '右对齐'; + + @override + String get alignTop => '顶部对齐'; + + @override + String get alignBottom => '底部对齐'; + + @override + String get alignHorizontalCenter => '水平居中'; + + @override + String get alignVerticalCenter => '垂直居中'; + + @override + String get volume => '音量'; + + @override + String get gain => '增益'; + + @override + String get mute => '静音'; + + @override + String get unmute => '取消静音'; + + @override + String get resetVolume => '重置音量'; + + @override + String get invalidGain => '请输入 -90 到 +12 之间的数值'; + + @override + String get animation => '动画'; + + @override + String get keyframes => '关键帧'; + + @override + String get removeAllKeyframes => '移除全部关键帧'; + + @override + String get linear => '线性'; + + @override + String get easeIn => '缓入'; + + @override + String get easeOut => '缓出'; + + @override + String get easeInOut => '缓入缓出'; + + @override + String get basic => '基本'; + + @override + String get mask => '蒙版'; + + @override + String get addMask => '添加蒙版'; + + @override + String get deleteMask => '删除蒙版'; + + @override + String get resetMask => '重置蒙版'; + + @override + String get enableMask => '启用蒙版'; + + @override + String get disableMask => '停用蒙版'; + + @override + String get moveMaskUp => '上移蒙版'; + + @override + String get moveMaskDown => '下移蒙版'; + + @override + String get rectangle => '矩形'; + + @override + String get ellipse => '椭圆'; + + @override + String get invert => '反转'; + + @override + String get feather => '羽化'; + + @override + String get add => '相加'; + + @override + String get subtract => '相减'; + + @override + String get intersect => '相交'; + + @override + String get initialRegion => '初始区域'; + + @override + String get none => '无'; + + @override + String get color => '颜色'; + + @override + String get fontSize => '字号'; + + @override + String get outlineWidth => '描边宽度'; + + @override + String get outlineColor => '描边颜色'; + + @override + String get captionBaseline => '字幕基线'; + + @override + String get content => '文本'; + + @override + String get start => '开始'; + + @override + String get time => '时间'; + + @override + String get speed => '速度'; + + @override + String speedSegmentCount(int count) { + return '$count 个速度区间'; + } + + @override + String get splitSpeedAtPlayhead => '在播放头分割速度区间'; + + @override + String get speedChange => '变速'; + + @override + String get speedMode => '变速模式'; + + @override + String get constantSpeed => '恒定速度'; + + @override + String get segmentedSpeed => '分段变速'; + + @override + String get speedNotAvailable => '变速调节控件尚未接入'; + + @override + String get custom => '自定义'; + + @override + String get invalidNumber => '无效数值'; + + @override + String get mediaUnavailable => '素材不可用'; + + @override + String get mediaMissing => '素材缺失'; + + @override + String get mediaColorSpace => '素材色彩空间'; + + @override + String get mediaColorInterpretation => '素材色彩解释'; + + @override + String get colorInfoNotLoaded => '色彩信息未读取'; + + @override + String get unknownColorSpace => '色彩空间未知,暂按 Rec.709 显示'; + + @override + String get colorBackendUnsupported => '当前后端不支持素材色彩解释。'; + + @override + String get loadClipPropertiesFailed => '无法读取片段属性'; + + @override + String get updatePictureFailed => '无法更新画面属性'; + + @override + String get updateVolumeFailed => '无法更新音量'; + + @override + String get updateMaskFailed => '无法更新蒙版'; + + @override + String get updateKeyframesFailed => '无法更新关键帧'; + + @override + String get maskPreviewFailed => '无法准备蒙版预览'; + + @override + String get alignClipFailed => '无法对齐片段,请等待预览就绪后重试'; + + @override + String get invalidTransform => '缩放范围为 1%–10000%,位置和角度必须为有效数值'; + + @override + String get editFailed => '无法修改,请检查输入和时间范围。'; + + @override + String get addMediaFailed => '无法添加素材,请重试'; + + @override + String get deleteCaption => '删除字幕'; + + @override + String get mergeCaptions => '合并字幕'; + + @override + String get captionDeleted => '字幕已删除'; + + @override + String get captionChanged => '字幕已变化,请重试。'; + + @override + String get captionEditChanged => '字幕已变化,请重新编辑。'; + + @override + String get assistantHint => '描述你的剪辑想法'; + + @override + String get configureAgentHint => '配置 Agent 服务后开始对话'; + + @override + String get agentRestartHint => '请配置 Agent 服务后重新启动应用。'; + + @override + String get replyInterrupted => '回复已中断'; + + @override + String get replying => '正在回复…'; + + @override + String get stopReply => '停止回复'; + + @override + String get sendMessage => '发送消息'; + + @override + String get addAttachment => '添加附件(暂未接入)'; + + @override + String get replyFailed => '回复失败,请检查服务连接或稍后重试。'; + + @override + String get mcpService => 'MCP 服务'; + + @override + String get listenPort => '监听端口'; + + @override + String get accessToken => '访问令牌'; + + @override + String get copyAccessToken => '复制访问令牌'; + + @override + String get accessTokenCopied => '访问令牌已复制'; + + @override + String get loadMcpFailed => '无法读取 MCP 设置,重试'; + + @override + String get saveMcpFailed => '无法保存 MCP 设置,请重试'; + + @override + String get retryStart => '重试启动'; + + @override + String get invalidPort => '端口必须为 1–65535'; + + @override + String get loadingSettings => '正在读取设置…'; + + @override + String get starting => '正在启动…'; + + @override + String get stopping => '正在停止…'; + + @override + String get disabled => '已停用'; + + @override + String get running => '运行中'; + + @override + String get startFailed => '启动失败'; + + @override + String get saved => '已保存'; + + @override + String get unsaved => '未保存'; + + @override + String get saving => '保存中…'; + + @override + String get pendingSave => '待保存'; + + @override + String get notApplied => '未应用'; + + @override + String get enable => '启用'; + + @override + String get disable => '停用'; + + @override + String get type => '类型'; + + @override + String get status => '状态'; + + @override + String get file => '文件'; + + @override + String get unboundMedia => '未绑定素材'; + + @override + String get unboundAudio => '未绑定音轨'; + + @override + String get vertical => '垂直'; + + @override + String get language => '语言'; + + @override + String get saveLanguageFailed => '无法保存语言设置,请重试'; + + @override + String get loadLanguageFailed => '无法读取语言设置,请重新选择'; + + @override + String get propertiesFirstLayout => '属性优先布局'; + + @override + String get defaultLayout => '默认布局'; + + @override + String get separateVocals => '分离人声'; + + @override + String get detachAudio => '分离音频'; + + @override + String get restoreAudio => '恢复音频'; + + @override + String get audioDetached => '音频已分离'; + + @override + String get addAll => '全部添加'; + + @override + String get preparingMedia => '准备素材…'; + + @override + String get cancelling => '正在取消…'; + + @override + String get cancelled => '已取消'; + + @override + String get interruptedTask => '任务已中断,可重新启动并继续'; + + @override + String get auto => '自动'; + + @override + String get autoDetect => '自动识别'; + + @override + String get noTranslation => '不翻译'; + + @override + String get sourceLanguage => '源语言'; + + @override + String get translationLanguage => '翻译语言'; + + @override + String get transcriptionNotConfigured => '转字幕尚未配置,请安装识别组件和 Whisper Turbo 模型。'; + + @override + String get translationNotConfigured => '字幕翻译尚未配置,目前可生成源语言字幕。'; + + @override + String get sourceLanguageUnknown => '无法确定可翻译的源语言。'; + + @override + String get startTranscriptionFailed => '无法启动识别,请检查素材,或等待当前任务完成。'; + + @override + String get placeMediaFirst => '请先将这份素材放到时间线,再应用字幕。'; + + @override + String get placeTranslationMediaFirst => '请先将对应素材放到时间线,再应用翻译字幕。'; + + @override + String get selectTargetClip => '选择目标片段'; + + @override + String get timelineChanged => '时间线已变化,请重新选择目标片段。'; + + @override + String get transcriptionAccessFailed => '识别失败:无法访问识别组件、模型或源素材(notConfigured)'; + + @override + String get transcriptionNoAudio => '识别失败:所选素材或音轨没有可识别的音频(noAudio)'; + + @override + String get transcriptionInvalidResult => '识别失败:组件返回的字幕文件无效(invalidResult)'; + + @override + String get transcriptionWorkerExited => '识别失败:识别组件意外退出(workerExited)'; + + @override + String get transcriptionProcessingFailed => '识别失败:原生识别处理失败(processingFailed)'; + + @override + String get transcriptionFailed => '识别失败,请检查组件、模型、音轨和时长'; + + @override + String get transcribing => '正在识别…'; + + @override + String get captionsGenerated => '字幕已生成'; + + @override + String get cancelTranscription => '取消识别'; + + @override + String get applyCaptions => '应用为字幕'; + + @override + String get preparingTranslation => '准备翻译…'; + + @override + String get translatingCaptions => '正在翻译字幕…'; + + @override + String get cancellingTranslation => '正在取消翻译…'; + + @override + String get translatedCaptionsGenerated => '翻译字幕已生成'; + + @override + String get translationCancelled => '翻译已取消'; + + @override + String get translationInterrupted => '翻译任务已中断'; + + @override + String get cancelTranslation => '取消翻译'; + + @override + String get editorServiceUnavailable => '编辑工具服务不可用,请重新打开项目。'; + + @override + String get mcpUnavailable => 'MCP 连接不可用,请检查本地端口和令牌配置。'; + + @override + String get openTimelineFailed => '无法打开时间线'; + + @override + String get noTimelineSequence => '时间线中没有序列'; + + @override + String get waitingForProject => '等待打开工程'; + + @override + String get hold => '保持'; + + @override + String get noImportableFiles => '未收到可导入的文件'; + + @override + String get virtualFilesUnsupported => '请从文件管理器拖入原文件,暂不支持虚拟文件'; + + @override + String get editorSessionStartFailed => '无法打开时间线编辑器'; + + @override + String get previewStartFailed => '无法启动原生预览'; + + @override + String get previewInvalidTrack => '素材中不存在所选音视频轨道。'; + + @override + String get previewMissingBinding => '缺少素材绑定,无法预览当前时间线。'; + + @override + String get previewUnsupportedEdits => '当前时间线包含尚不支持预览的编辑。'; + + @override + String get previewUnsupportedConfiguration => '当前平台或系统版本尚不支持此预览配置。'; + + @override + String get previewHdrUnsupported => 'HDR 素材需要色调映射才能在 SDR 预览中显示,当前系统或预览配置不支持。'; + + @override + String get previewAudioOutOfRange => '音频片段超出了素材音轨的有效范围,无法预览。'; + + @override + String get previewResourceMissing => '预览素材已不存在,请重新定位原文件。'; + + @override + String get previewInvalidComposition => '视频合成配置无效,无法创建预览。'; + + @override + String get previewInvalidData => '预览数据无效,请重试。'; + + @override + String get previewFailed => '预览失败,请检查素材是否可访问后重试。'; + + @override + String get chatFailed => '无法完成对话,请检查服务配置或稍后重试。'; + + @override + String get delete => '删除'; + + @override + String get pinTimeline => '置顶时间线'; + + @override + String get unpinTimeline => '取消置顶'; + + @override + String deleteTimelineConfirmation(String name) { + return '删除“$name”及其编辑历史?此操作无法撤销。'; + } + + @override + String get processingFailed => '处理失败'; + + @override + String get noMatchingOptions => '没有匹配的选项'; + + @override + String removeMediaConfirmation(String name) { + return '从项目移除“$name”?已有片段、历史版本和原文件会保留。'; + } + + @override + String mediaAdded(int count) { + return '已添加 $count 个素材引用'; + } + + @override + String duplicatesSkipped(int count) { + return '跳过 $count 个重复文件'; + } + + @override + String mediaCount(int count) { + return '$count 个素材'; + } + + @override + String get importMedia => '导入'; + + @override + String noMediaOfType(String type) { + return '暂无$type素材'; + } + + @override + String captionsImported(String count) { + return '已导入 $count 条字幕'; + } + + @override + String editCaptionError(String message) { + return '无法修改字幕:$message'; + } + + @override + String mcpStartError(String message) { + return '无法启动 MCP:$message'; + } + + @override + String manualColorSpace(String name) { + return '手动指定:$name'; + } + + @override + String detectedColorSpace(String name) { + return '已识别:$name'; + } + + @override + String keyframeLabel(String channel) { + return '$channel关键帧'; + } + + @override + String maskMode(String mode) { + return '组合方式:$mode'; + } + + @override + String keyframeCount(int count) { + return '$count 个关键帧'; + } + + @override + String toggleKeyframe(String action, String channel) { + return '$action$channel关键帧'; + } + + @override + String previousKeyframe(String channel) { + return '上一个$channel关键帧'; + } + + @override + String nextKeyframe(String channel) { + return '下一个$channel关键帧'; + } + + @override + String keyframeSettings(String channel) { + return '$channel关键帧设置'; + } + + @override + String selectedClipsHint(int count) { + return '已选择 $count 个片段\n请选择单个片段查看属性'; + } + + @override + String transcriptionError(String code) { + return '识别失败,请检查组件、模型、音轨和时长($code)'; + } + + @override + String captionsAdded(String count) { + return '已添加 $count 条字幕,可在属性面板编辑。'; + } + + @override + String translatedCaptionsAdded(String count) { + return '已添加 $count 条翻译字幕,可在属性面板编辑。'; + } + + @override + String applyCaptionsError(String message) { + return '无法应用字幕:$message'; + } + + @override + String applyTranslatedCaptionsError(String message) { + return '无法应用翻译字幕:$message'; + } + + @override + String recognizedCaptions(int count) { + return '已识别 $count 条'; + } + + @override + String captionCount(int count) { + return '$count 条字幕'; + } + + @override + String translationFailed(String message) { + return '翻译失败:$message'; + } + + @override + String translatedCaptionCount(int count, String language) { + return '$count 条$language字幕'; + } + + @override + String previewParameterError(String message) { + return '预览参数无效:$message'; + } + + @override + String mediaOffline(String names) { + return '素材离线或不可用:$names'; + } + + @override + String searchOptions(String label) { + return '搜索$label…'; + } + + @override + String get loadRecentProjectsFailed => '无法读取最近项目记录,仍可手动打开项目。'; + + @override + String get projectAccessFailed => '项目不可用'; + + @override + String get projectMissingDirectory => '项目不存在'; + + @override + String get recentProjectSaveFailed => '项目已打开,但最近使用记录未能保存。'; + + @override + String get lastProjectSaveFailed => '项目已打开,但上次项目记录未能保存。'; + + @override + String get enterProjectName => '请输入项目名称'; + + @override + String get projectSwitched => '项目已切换,请重新拖入素材'; + + @override + String get notLocalMedia => '该素材不是本地文件'; + + @override + String get revealMediaFailed => '无法在文件管理器中显示素材'; + + @override + String get openMatchingProject => '请先打开对应项目'; + + @override + String get projectMismatch => '此位置的项目与记录不一致,请使用“打开项目”重新选择。'; + + @override + String get openProjectFirst => '请先打开项目'; + + @override + String get localFilesOnly => '请从文件管理器拖入本地文件'; + + @override + String get foldersUnsupported => '请选择文件,暂不支持拖入文件夹'; + + @override + String get mediaImportCancelled => '素材导入已取消'; + + @override + String get fileAccessFailed => '文件不存在或无法读取,请检查位置与权限'; + + @override + String get registerMediaFailed => '无法登记素材,请重试'; + + @override + String get mediaNoLongerExists => '素材已不存在'; + + @override + String get mediaNoTracks => '素材没有可用的视频或音频轨道'; + + @override + String get invalidMediaDuration => '素材时长无效'; + + @override + String get mediaInfoUnsupported => '当前平台尚未支持素材信息读取'; + + @override + String get mediaInfoFailed => '无法读取素材信息,请检查文件与访问权限'; + + @override + String get saveTimelineFailed => '时间线保存失败,请重试。未保存的编辑仍保留在当前会话。'; + + @override + String get addKeyframeAction => '添加'; + + @override + String get backgroundTasks => '后台任务'; + + @override + String get noBackgroundTasks => '暂无后台任务'; + + @override + String get retryTask => '重试'; + + @override + String get applyOriginalCaptions => '应用原文字幕'; + + @override + String get applyTranslatedCaptions => '应用翻译字幕'; + + @override + String get subtitleTaskStarted => '字幕任务已开始'; + + @override + String get fitTimeline => '适合整个时间线'; + + @override + String get modify => '修改'; + + @override + String get projectSettings => '项目设置'; + + @override + String get projectSettingsDescription => '修改项目输出规格,保留片段的实际时长和速度。'; + + @override + String get projectColorSpace => '色彩空间'; + + @override + String get projectWidth => '宽度(px)'; + + @override + String get projectHeight => '高度(px)'; + + @override + String get projectResolutionInvalid => '请输入 1–16384 的整数'; + + @override + String get previewFullscreen => '全屏预览'; + + @override + String get exitPreviewFullscreen => '退出全屏'; + + @override + String get previewGoToStart => '回到开头'; + + @override + String get previewPreviousFrame => '上一帧'; + + @override + String get previewNextFrame => '下一帧'; + + @override + String get softwareUpdates => '软件更新'; + + @override + String get checkForUpdates => '检查更新'; + + @override + String get automaticallyCheckUpdates => '自动检查更新'; + + @override + String get updatesUnavailable => '此构建暂不提供更新。'; + + @override + String get updateCheckFailed => '无法检查更新,请重试。'; + + @override + String get removeBackground => '抠像'; + + @override + String get startBackgroundRemoval => '开始抠像'; + + @override + String get backgroundRemovalResourceRequired => '抠像需要下载本地模型。下载完成后会自动开始抠像。'; + + @override + String get backgroundRemovalDownloadTask => '下载抠像资源'; + + @override + String get backgroundRemovalResourceName => '抠像模型'; + + @override + String get backgroundRemovalDestructiveHint => + '生成的透明素材会直接替换当前片段;仍可通过撤销恢复原片段。'; + + @override + String get backgroundRemovalTaskStarted => '抠像任务已开始'; + + @override + String get startBackgroundRemovalFailed => '无法启动抠像,请检查素材,或等待当前处理任务完成。'; + + @override + String get backgroundRemovalComplete => '抠像完成'; + + @override + String get backgroundRemovalApplying => '正在替换片段素材'; + + @override + String get backgroundRemovalFailed => '抠像失败'; + + @override + String get agentSettings => 'Agent'; + + @override + String get agentSaveSettingsFailed => '无法保存 Agent 设置。'; + + @override + String get agentDeleteProviderTitle => '删除 Provider?'; + + @override + String agentDeleteProviderDescription(String providerName) { + return '将从此设备移除“$providerName”及其保存的 API Key。'; + } + + @override + String get agentProviderRequired => '请先添加 Provider,再启用助手。'; + + @override + String get agentUseSelectedModel => '新的 Agent 请求将使用所选模型。'; + + @override + String get agentEnable => '启用 Agent'; + + @override + String get agentDefaultModel => '默认模型'; + + @override + String get agentConfigureModel => '配置模型'; + + @override + String get agentSelectModel => '选择模型'; + + @override + String get agentModelUnavailable => '此对话的模型已不可用,请选择其他模型开始新对话。'; + + @override + String get agentModelChangeSession => '切换模型后会开始新的 Agent 会话。'; + + @override + String get agentCustomProviders => '自定义 Provider'; + + @override + String get agentProviderStorageDescription => + 'Provider 元数据保存在本机,API Key 保存在系统凭据存储中。'; + + @override + String get agentAddProvider => '添加 Provider'; + + @override + String get agentBackToProviders => '返回 Provider 列表'; + + @override + String get agentLoadSettingsFailed => '无法读取 Agent 设置,重试'; + + @override + String get agentEnableProvider => '启用 Provider'; + + @override + String get agentEditProvider => '编辑 Provider'; + + @override + String get agentDeleteProvider => '删除 Provider'; + + @override + String get agentModelIdsUnique => 'Model ID 不能重复。'; + + @override + String get agentEditProviderTitle => '编辑 Provider'; + + @override + String get agentProviderEndpointDescription => + '配置 OpenAI-compatible Chat Completions 服务。'; + + @override + String get agentSaveProvider => '保存 Provider'; + + @override + String get agentProviderConfiguration => 'Provider 配置'; + + @override + String get agentAuthenticationAndModels => '认证与模型'; + + @override + String get agentApiType => 'API 类型'; + + @override + String get agentOpenAiChatCompletions => 'OpenAI Completions'; + + @override + String get agentBaseUrl => 'Base URL'; + + @override + String get agentApiKey => 'API Key'; + + @override + String get agentProviderNameHint => '我的 Provider'; + + @override + String get agentApiKeyOptional => '不需要鉴权的服务可以留空。'; + + @override + String get agentApiKeyKeep => '留空将保留已保存的 Key。'; + + @override + String get agentOptional => '可选'; + + @override + String get agentApiKeyOneLine => 'API Key 必须为单行文本。'; + + @override + String get agentRemoveSavedApiKey => '移除已保存的 API Key'; + + @override + String get agentModels => '模型'; + + @override + String get agentAddModel => '添加模型'; + + @override + String get agentRequiredField => '此项为必填项。'; + + @override + String get agentInvalidBaseUrl => '请输入不含凭据、查询参数或片段的 HTTP(S) Base URL。'; + + @override + String get agentModelId => 'Model ID'; + + @override + String get agentContextWindow => '上下文窗口'; + + @override + String get agentMaxOutputTokens => '最大输出'; + + @override + String get agentMaxOutputBelowContext => '必须小于上下文窗口。'; + + @override + String get agentDeleteModel => '删除模型'; + + @override + String get agentPositiveInteger => '请输入正整数。'; + + @override + String get agentConfigurationReadFailed => '无法读取 Agent 配置,请检查设置后重试。'; + + @override + String get agentConfigurationRequired => '请先在设置中配置并启用 Agent。'; + + @override + String get agentSessionRestoreFailed => '无法恢复 Agent 会话,请稍后重试。'; + + @override + String get agentContextBudgetExceeded => + '输入预算不足,无法容纳系统指令、工具和消息。请增大上下文窗口或降低最大输出 tokens。'; + + @override + String get agentAuthenticationFailed => '鉴权失败,请检查 Provider 的 API Key 和访问权限。'; + + @override + String get agentConnectionFailed => '模型服务连接失败或请求超时,请检查 Base URL 和网络。'; + + @override + String get agentProtocolFailed => '服务返回内容不符合所选 API 类型,或响应流不完整。'; + + @override + String get agentContextBudgetTooSmall => + '需要为系统指令保留更多输入空间,请增大上下文窗口或降低最大输出 tokens。'; + + @override + String get agentCompacting => '整理上下文…'; + + @override + String get agentEditing => '编辑中…'; + + @override + String get agentVerifying => '核对结果…'; + + @override + String get agentTurnLimitReached => '本轮任务已达到执行上限,已完成的编辑已保存。发送“继续”可接着执行。'; + + @override + String get agentRecoveryRequired => '上次操作的结果尚未确认。可继续任务核对已保存回执;未确认的编辑不会重复执行。'; + + @override + String get agentExportReplyFailed => '视频已成功导出,总结回复失败。可重试总结,不会重复剪辑或导出。'; + + @override + String get agentRetrySummary => '重试总结'; + + @override + String get agentResumeTask => '继续任务'; + + @override + String get agentTaskInterrupted => '任务已中断,可从已保存的进度继续。'; + + @override + String get downloadSubtitleModel => '下载字幕模型'; + + @override + String get downloadModelAction => '下载'; + + @override + String get subtitleEngineUnavailable => '模型已安装,但字幕处理引擎未能启动。请修复处理引擎,无需重新下载模型。'; + + @override + String get backgroundTaskDetails => '任务详情'; + + @override + String get backgroundTaskFailed => '失败'; + + @override + String get backgroundTaskCompleted => '已完成'; + + @override + String get captionWrapLines => '换行显示字幕'; + + @override + String get captionSingleLine => '单行显示字幕'; + + @override + String get noMatchingCaptions => '没有匹配的字幕'; + + @override + String get subtitleResourcesRequired => '生成字幕需要这些资源。下载完成后会自动开始处理。'; + + @override + String subtitleResourcesDownloadSize(String size) { + return '需下载 $size'; + } + + @override + String get pauseDownload => '暂停'; + + @override + String get resumeDownload => '继续'; + + @override + String get downloadPaused => '已暂停'; + + @override + String get cancelResourceDownloadTitle => '取消下载?'; + + @override + String get cancelResourceDownloadMessage => '下载任务将停止,当前资源的下载进度可能丢失。'; + + @override + String get continueDownload => '继续下载'; + + @override + String get cancelDownload => '取消下载'; + + @override + String get speechResourceStage => '语音识别资源'; + + @override + String get translationResourceStage => '翻译资源'; + + @override + String get subtitleResourceDownloadTask => '下载语音与翻译资源'; + + @override + String get downloadingSpeechModel => '正在下载语音模型'; + + @override + String get downloadingTranslationModel => '正在下载翻译模型'; + + @override + String get checkingForUpdates => '正在检查更新…'; + + @override + String get appIsUpToDate => '当前已是最新版本。'; + + @override + String downloadingUpdate(int progress) { + return '正在下载更新:$progress%'; + } + + @override + String updateAvailable(String version) { + return '发现新版本 $version。'; + } + + @override + String get downloadUpdate => '下载更新'; + + @override + String get restartToUpdate => '重启并更新'; + + @override + String get updateOperationFailed => '无法更新,请完成正在运行的任务后重试。'; + + @override + String get windowMinimize => '最小化'; + + @override + String get windowMaximize => '最大化'; + + @override + String get windowRestore => '还原'; + + @override + String get workspaceAgent => '助手'; + + @override + String get workspaceCut => '剪辑'; + + @override + String get noAvailableOptions => '暂无可用选项'; + + @override + String get composerReferenceInvalid => '引用已失效,请切回原项目或移除引用'; + + @override + String durationSeconds(int seconds) { + return '$seconds秒'; + } + + @override + String durationMinutesSeconds(int minutes, int seconds) { + return '$minutes分钟 $seconds秒'; + } + + @override + String get projectNameInvalid => '项目名称无效。'; + + @override + String get projectLocationDefaultUnavailable => '无法访问默认项目位置,请在设置中重新选择。'; + + @override + String get chooseProjectLocation => '请先在设置中选择项目保存位置。'; + + @override + String get untitledTimeline => '未命名时间线'; + + @override + String get primarySequence => '主序列'; + + @override + String get primaryStoryline => '主线'; + + @override + String get projectSessionClosed => '项目会话已关闭,请重新打开项目。'; + + @override + String get timelineSessionClosed => '时间线会话已关闭,请重新打开时间线。'; + + @override + String get timelineMissing => '时间线不存在或已被删除'; + + @override + String get timelineInUse => '时间线正在使用中,暂时无法删除'; + + @override + String get timelineHasBackgroundTasks => '时间线有正在进行的后台任务,暂时无法删除'; + + @override + String get timelineRequired => '项目至少需要保留一条时间线'; + + @override + String get mediaReadFailed => '无法读取素材'; + + @override + String get mediaImportFailed => '无法导入素材'; + + @override + String get unsupportedMediaType => '仅支持导入视频、音频和图像文件'; + + @override + String get mediaNoVideoTracks => '素材没有可用的视频轨道'; + + @override + String get mediaDurationOutOfRange => '素材时长超出时间线范围'; + + @override + String resourceDownloadHttpFailed(String statusCode) { + return '下载失败(HTTP $statusCode)'; + } + + @override + String get resourceChecksumFailed => '模型文件校验失败,请重新下载资源。'; + + @override + String get subtitleLanguageAf => '南非荷兰语'; + + @override + String get subtitleLanguageAm => '阿姆哈拉语'; + + @override + String get subtitleLanguageAr => '阿拉伯语'; + + @override + String get subtitleLanguageAst => '阿斯图里亚斯语'; + + @override + String get subtitleLanguageAz => '阿塞拜疆语'; + + @override + String get subtitleLanguageBa => '巴什基尔语'; + + @override + String get subtitleLanguageBe => '白俄罗斯语'; + + @override + String get subtitleLanguageBg => '保加利亚语'; + + @override + String get subtitleLanguageBn => '孟加拉语'; + + @override + String get subtitleLanguageBr => '布列塔尼语'; + + @override + String get subtitleLanguageBs => '波斯尼亚语'; + + @override + String get subtitleLanguageCa => '加泰罗尼亚语'; + + @override + String get subtitleLanguageCeb => '宿务语'; + + @override + String get subtitleLanguageCs => '捷克语'; + + @override + String get subtitleLanguageCy => '威尔士语'; + + @override + String get subtitleLanguageDa => '丹麦语'; + + @override + String get subtitleLanguageDe => '德语'; + + @override + String get subtitleLanguageEl => '希腊语'; + + @override + String get subtitleLanguageEn => '英语'; + + @override + String get subtitleLanguageEs => '西班牙语'; + + @override + String get subtitleLanguageEt => '爱沙尼亚语'; + + @override + String get subtitleLanguageFa => '波斯语'; + + @override + String get subtitleLanguageFf => '富拉语'; + + @override + String get subtitleLanguageFi => '芬兰语'; + + @override + String get subtitleLanguageFr => '法语'; + + @override + String get subtitleLanguageFy => '西弗里斯语'; + + @override + String get subtitleLanguageGa => '爱尔兰语'; + + @override + String get subtitleLanguageGd => '苏格兰盖尔语'; + + @override + String get subtitleLanguageGl => '加利西亚语'; + + @override + String get subtitleLanguageGu => '古吉拉特语'; + + @override + String get subtitleLanguageHa => '豪萨语'; + + @override + String get subtitleLanguageHe => '希伯来语'; + + @override + String get subtitleLanguageHi => '印地语'; + + @override + String get subtitleLanguageHr => '克罗地亚语'; + + @override + String get subtitleLanguageHt => '海地克里奥尔语'; + + @override + String get subtitleLanguageHu => '匈牙利语'; + + @override + String get subtitleLanguageHy => '亚美尼亚语'; + + @override + String get subtitleLanguageId => '印度尼西亚语'; + + @override + String get subtitleLanguageIg => '伊博语'; + + @override + String get subtitleLanguageIlo => '伊洛卡诺语'; + + @override + String get subtitleLanguageIs => '冰岛语'; + + @override + String get subtitleLanguageIt => '意大利语'; + + @override + String get subtitleLanguageJa => '日语'; + + @override + String get subtitleLanguageJv => '爪哇语'; + + @override + String get subtitleLanguageKa => '格鲁吉亚语'; + + @override + String get subtitleLanguageKk => '哈萨克语'; + + @override + String get subtitleLanguageKm => '高棉语'; + + @override + String get subtitleLanguageKn => '卡纳达语'; + + @override + String get subtitleLanguageKo => '韩语'; + + @override + String get subtitleLanguageLb => '卢森堡语'; + + @override + String get subtitleLanguageLg => '卢干达语'; + + @override + String get subtitleLanguageLn => '林加拉语'; + + @override + String get subtitleLanguageLo => '老挝语'; + + @override + String get subtitleLanguageLt => '立陶宛语'; + + @override + String get subtitleLanguageLv => '拉脱维亚语'; + + @override + String get subtitleLanguageMg => '马拉加斯语'; + + @override + String get subtitleLanguageMk => '马其顿语'; + + @override + String get subtitleLanguageMl => '马拉雅拉姆语'; + + @override + String get subtitleLanguageMn => '蒙古语'; + + @override + String get subtitleLanguageMr => '马拉地语'; + + @override + String get subtitleLanguageMs => '马来语'; + + @override + String get subtitleLanguageMy => '缅甸语'; + + @override + String get subtitleLanguageNe => '尼泊尔语'; + + @override + String get subtitleLanguageNl => '荷兰语'; + + @override + String get subtitleLanguageNo => '挪威语'; + + @override + String get subtitleLanguageNs => '北索托语'; + + @override + String get subtitleLanguageOc => '奥克语'; + + @override + String get subtitleLanguageOr => '奥里亚语'; + + @override + String get subtitleLanguagePa => '旁遮普语'; + + @override + String get subtitleLanguagePl => '波兰语'; + + @override + String get subtitleLanguagePs => '普什图语'; + + @override + String get subtitleLanguagePt => '葡萄牙语'; + + @override + String get subtitleLanguageRo => '罗马尼亚语'; + + @override + String get subtitleLanguageRu => '俄语'; + + @override + String get subtitleLanguageSd => '信德语'; + + @override + String get subtitleLanguageSi => '僧伽罗语'; + + @override + String get subtitleLanguageSk => '斯洛伐克语'; + + @override + String get subtitleLanguageSl => '斯洛文尼亚语'; + + @override + String get subtitleLanguageSo => '索马里语'; + + @override + String get subtitleLanguageSq => '阿尔巴尼亚语'; + + @override + String get subtitleLanguageSr => '塞尔维亚语'; + + @override + String get subtitleLanguageSs => '斯瓦蒂语'; + + @override + String get subtitleLanguageSu => '巽他语'; + + @override + String get subtitleLanguageSv => '瑞典语'; + + @override + String get subtitleLanguageSw => '斯瓦希里语'; + + @override + String get subtitleLanguageTa => '泰米尔语'; + + @override + String get subtitleLanguageTh => '泰语'; + + @override + String get subtitleLanguageTl => '他加禄语'; + + @override + String get subtitleLanguageTn => '茨瓦纳语'; + + @override + String get subtitleLanguageTr => '土耳其语'; + + @override + String get subtitleLanguageUk => '乌克兰语'; + + @override + String get subtitleLanguageUr => '乌尔都语'; + + @override + String get subtitleLanguageUz => '乌兹别克语'; + + @override + String get subtitleLanguageVi => '越南语'; + + @override + String get subtitleLanguageWo => '沃洛夫语'; + + @override + String get subtitleLanguageXh => '科萨语'; + + @override + String get subtitleLanguageYi => '意第绪语'; + + @override + String get subtitleLanguageYo => '约鲁巴语'; + + @override + String get subtitleLanguageYue => '粤语'; + + @override + String get subtitleLanguageZh => '中文'; + + @override + String get subtitleLanguageZu => '祖鲁语'; + + @override + String get linearRec2020 => '线性 Rec.2020'; + + @override + String get diagnostics => '诊断'; + + @override + String get exportDiagnostics => '导出诊断包'; + + @override + String get exportDiagnosticsFailed => '无法导出诊断包,请重试。'; + + @override + String get exportDiagnosticsSucceeded => '诊断包已保存。'; +} + +/// The translations for Chinese, using the Han script (`zh_Hant`). +class AppLocalizationsZhHant extends AppLocalizationsZh { + AppLocalizationsZhHant() : super('zh_Hant'); + + @override + String get selectProject => '選擇專案'; + + @override + String get searchProjects => '搜尋專案'; + + @override + String get noMatchingProjects => '沒有符合的專案'; + + @override + String get projectsNone => '暫無專案'; + + @override + String get projectLocationMissing => '目錄不存在,建立專案時將自動建立。'; + + @override + String get projectLocationUnavailable => '專案儲存位置無法使用,請連接磁碟或檢查網路後重試,也可以變更位置。'; + + @override + String get projectLocationNotWritable => '專案儲存位置沒有寫入權限,請檢查權限或變更位置。'; + + @override + String get projectLocationCreateFailed => '無法建立或寫入專案儲存目錄,請檢查權限或變更位置。'; + + @override + String get removeProjectFromSidebar => '從側邊欄移除'; + + @override + String get projectRemoved => '已移除專案,本機檔案和聊天記錄已保留。'; + + @override + String get agentNoConversations => '暫無聊天'; + + @override + String get renameConversationTitle => '重新命名聊天'; + + @override + String get renameConversationDescription => '保持簡短且易於辨識'; + + @override + String get collapseProject => '收合專案'; + + @override + String get expandProject => '展開專案'; + + @override + String agentDeleteConfirmation(String title) { + return '聊天「$title」及其訊息記錄將被永久刪除,無法復原。本機專案檔案不受影響。'; + } + + @override + String get agentEmptyTrashConfirmation => '垃圾桶中的所有聊天將被永久刪除,無法復原。本機專案檔案不受影響。'; + + @override + String get agentConversations => '對話'; + + @override + String get showMoreConversations => '展開顯示'; + + @override + String get showFewerConversations => '收起顯示'; + + @override + String get agentNewConversation => '新增對話'; + + @override + String agentElapsedTime(String duration) { + return '耗時 $duration'; + } + + @override + String get agentConversationActions => '對話操作'; + + @override + String get agentMoveToTrash => '移至資源回收桶'; + + @override + String get agentTrash => '資源回收桶'; + + @override + String get agentRestore => '還原'; + + @override + String get agentEmptyTrash => '清空資源回收桶'; + + @override + String get agentDeleteForever => '永久刪除'; + + @override + String get agentConversationLocation => '對話儲存位置'; + + @override + String get agentChooseExistingConversations => '選擇現有對話目錄'; + + @override + String get agentMoveConversations => '搬移對話'; + + @override + String get agentLocationUnavailable => '對話儲存位置無法使用'; + + @override + String get agentLocationBusy => '請等待目前對話執行完畢再搬移'; + + @override + String get agentRelinkProvider => '重新關聯 Provider'; + + @override + String get settings => '設定'; + + @override + String get closeSettings => '關閉設定'; + + @override + String get general => '通用'; + + @override + String get appearance => '外觀'; + + @override + String get theme => '主題'; + + @override + String get system => '跟隨系統'; + + @override + String get light => '淺色'; + + @override + String get dark => '深色'; + + @override + String get saveAppearanceFailed => '無法儲存外觀設定,請重試'; + + @override + String get loadAppearanceFailed => '無法讀取外觀設定,請重新選擇主題'; + + @override + String get cancel => '取消'; + + @override + String get save => '儲存'; + + @override + String get create => '建立'; + + @override + String get close => '關閉'; + + @override + String get retry => '重試'; + + @override + String get select => '選擇'; + + @override + String get name => '名稱'; + + @override + String get enterName => '請輸入名稱'; + + @override + String get invalidName => '名稱不能包含路徑分隔符或控制字元'; + + @override + String get projects => '專案'; + + @override + String get projectName => '專案名稱'; + + @override + String get projectLocation => '專案儲存位置'; + + @override + String get projectLocationNotSet => '未設定'; + + @override + String get loadProjectLocationFailed => '無法讀取專案儲存位置。'; + + @override + String get saveProjectLocationFailed => '無法儲存專案儲存位置。'; + + @override + String get resourceLocation => '資源儲存位置'; + + @override + String get resourceLocationNotSet => '未設定'; + + @override + String get loadResourceLocationFailed => '無法讀取資源儲存位置。'; + + @override + String get saveResourceLocationFailed => '無法儲存資源儲存位置。'; + + @override + String get transcriptionResourceRequired => '產生字幕需要先下載語音辨識模型。'; + + @override + String get downloadAndContinue => '下載並繼續'; + + @override + String get downloadingResource => '正在下載…'; + + @override + String get downloadInBackground => '後臺下載'; + + @override + String get processingResourceDownloadFailed => '語音辨識資源下載失敗,請重試。'; + + @override + String get newProject => '新建專案'; + + @override + String get openProject => '開啟專案'; + + @override + String get openProjectMore => '開啟專案…'; + + @override + String get saveHere => '儲存到這裡'; + + @override + String get selectDirectoryFailed => '無法選擇目錄,請檢查系統許可權。'; + + @override + String get openingWorkspace => '正在開啟工作區…'; + + @override + String get loadProjectsFailed => '無法載入專案列表'; + + @override + String get projectsEmpty => '新建或開啟專案,開始剪輯。'; + + @override + String get backToProjects => '返回剪輯'; + + @override + String get timelines => '時間軸'; + + @override + String timelineLimitReached(int count) { + return '每個專案最多可建立 $count 條時間軸。'; + } + + @override + String get timelineName => '時間軸名稱'; + + @override + String defaultTimelineName(int index) { + return '時間軸 $index'; + } + + @override + String get newTimeline => '新建時間軸'; + + @override + String get noTimelines => '暫無時間軸'; + + @override + String get activeTimeline => '當前時間軸'; + + @override + String get timelineUnavailable => '時間軸不可用'; + + @override + String get projectNoTimelines => '專案中還沒有時間軸'; + + @override + String get createTimelineHint => '在左側“時間軸”分組中新建時間軸,開始剪輯。'; + + @override + String get createTimelineChat => '新建時間軸後即可開始對話'; + + @override + String get operationFailed => '操作失敗,請重試'; + + @override + String get collapseSidebar => '收起側邊欄'; + + @override + String get expandSidebar => '展開側邊欄'; + + @override + String get expandEditor => '展開剪輯區'; + + @override + String get collapseProperties => '收起屬性面板'; + + @override + String get expandProperties => '展開屬性面板'; + + @override + String get layout => '佈局'; + + @override + String get editingFirstLayout => '剪輯優先'; + + @override + String get agentEditingLayout => 'Agent + 剪輯'; + + @override + String get agentLayoutDescription => '規劃、協作和執行'; + + @override + String get editingLayoutDescription => '預覽、剪輯和調整'; + + @override + String get materials => '素材'; + + @override + String get all => '全部'; + + @override + String get video => '影片'; + + @override + String get audio => '音訊'; + + @override + String get image => '影象'; + + @override + String get picture => '圖片'; + + @override + String get captions => '字幕'; + + @override + String get text => '文字'; + + @override + String get noMedia => '暫無素材'; + + @override + String get mediaCategory => '素材分類'; + + @override + String get captionTasks => '字幕任務'; + + @override + String get listLayout => '列表佈局'; + + @override + String get gridLayout => '宮格佈局'; + + @override + String get addToTimeline => '新增到時間軸'; + + @override + String get rename => '重新命名'; + + @override + String get renameMedia => '重新命名素材'; + + @override + String get removeMedia => '移除素材'; + + @override + String get remove => '移除'; + + @override + String get revealFinder => '在訪達中顯示'; + + @override + String get revealFileManager => '在檔案管理器中顯示'; + + @override + String get dropToAdd => '放開即可新增'; + + @override + String get timelineDropToStart => '將媒體拖到此處以開始。'; + + @override + String get dragMediaHint => '將影片、音訊或影象拖到這裡\n原檔案保留在原位置'; + + @override + String get transcribe => '轉字幕'; + + @override + String get generateCaptions => '生成字幕'; + + @override + String get play => '播放'; + + @override + String get pause => '暫停播放'; + + @override + String get retryPreview => '重試預覽'; + + @override + String get canvasRatio => '畫布比例'; + + @override + String get noPreviewContent => '時間軸中暫無可預覽內容'; + + @override + String get nativePreviewUnsupported => '當前平臺尚未實現原生預覽'; + + @override + String get canvasTransformFailed => '無法完成畫布變換,請重試。'; + + @override + String get undo => '復原'; + + @override + String get redo => '重做'; + + @override + String get deleteSelectedClips => '刪除所選片段'; + + @override + String get splitAtPlayhead => '在播放頭處分割'; + + @override + String get trimLeft => '向左裁剪'; + + @override + String get trimRight => '向右裁剪'; + + @override + String get trimLeftTooltip => '裁掉播放頭左側,保留右側'; + + @override + String get trimRightTooltip => '裁掉播放頭右側,保留左側'; + + @override + String get currentSequence => '當前序列'; + + @override + String get projectProperties => '專案屬性'; + + @override + String get canvasSize => '畫布尺寸'; + + @override + String get frameRate => '幀率'; + + @override + String get duration => '時長'; + + @override + String get totalDuration => '總時長'; + + @override + String get clipDuration => '片段時長'; + + @override + String get seconds => '秒'; + + @override + String get clip => '片段'; + + @override + String get unnamedClip => '未命名片段'; + + @override + String get gap => '空隙'; + + @override + String get compoundClip => '複合片段'; + + @override + String get textClip => '文字片段'; + + @override + String get pictureProperties => '畫面'; + + @override + String get position => '位置'; + + @override + String get rotation => '旋轉'; + + @override + String get scale => '縮放'; + + @override + String get size => '尺寸'; + + @override + String get transform => '變換'; + + @override + String get resetPosition => '重置位置'; + + @override + String get keepAspectRatio => '等比縮放'; + + @override + String get alignment => '對齊'; + + @override + String get alignLeft => '左對齊'; + + @override + String get alignRight => '右對齊'; + + @override + String get alignTop => '頂部對齊'; + + @override + String get alignBottom => '底部對齊'; + + @override + String get alignHorizontalCenter => '水平置中'; + + @override + String get alignVerticalCenter => '垂直置中'; + + @override + String get volume => '音量'; + + @override + String get gain => '增益'; + + @override + String get mute => '靜音'; + + @override + String get unmute => '取消靜音'; + + @override + String get resetVolume => '重置音量'; + + @override + String get invalidGain => '請輸入 -90 到 +12 之間的數值'; + + @override + String get animation => '動畫'; + + @override + String get keyframes => '關鍵幀'; + + @override + String get removeAllKeyframes => '移除全部關鍵幀'; + + @override + String get linear => '線性'; + + @override + String get easeIn => '緩入'; + + @override + String get easeOut => '緩出'; + + @override + String get easeInOut => '緩入緩出'; + + @override + String get basic => '基本'; + + @override + String get mask => '遮罩'; + + @override + String get addMask => '新增遮罩'; + + @override + String get deleteMask => '刪除遮罩'; + + @override + String get resetMask => '重置遮罩'; + + @override + String get enableMask => '啟用遮罩'; + + @override + String get disableMask => '停用遮罩'; + + @override + String get moveMaskUp => '上移遮罩'; + + @override + String get moveMaskDown => '下移遮罩'; + + @override + String get rectangle => '矩形'; + + @override + String get ellipse => '橢圓'; + + @override + String get invert => '反轉'; + + @override + String get feather => '羽化'; + + @override + String get add => '相加'; + + @override + String get subtract => '相減'; + + @override + String get intersect => '相交'; + + @override + String get initialRegion => '初始區域'; + + @override + String get none => '無'; + + @override + String get color => '顏色'; + + @override + String get fontSize => '字級'; + + @override + String get outlineWidth => '描邊寬度'; + + @override + String get outlineColor => '描邊顏色'; + + @override + String get captionBaseline => '字幕基線'; + + @override + String get content => '文字'; + + @override + String get start => '開始'; + + @override + String get time => '時間'; + + @override + String get speed => '速度'; + + @override + String speedSegmentCount(int count) { + return '$count 個速度區間'; + } + + @override + String get splitSpeedAtPlayhead => '在播放磁頭分割速度區間'; + + @override + String get speedChange => '變速'; + + @override + String get speedMode => '變速模式'; + + @override + String get constantSpeed => '恆定速度'; + + @override + String get segmentedSpeed => '分段變速'; + + @override + String get speedNotAvailable => '變速調節控制元件尚未接入'; + + @override + String get custom => '自定義'; + + @override + String get invalidNumber => '無效數值'; + + @override + String get mediaUnavailable => '素材不可用'; + + @override + String get mediaMissing => '素材缺失'; + + @override + String get mediaColorSpace => '素材色彩空間'; + + @override + String get mediaColorInterpretation => '素材色彩解釋'; + + @override + String get colorInfoNotLoaded => '色彩資訊未讀取'; + + @override + String get unknownColorSpace => '色彩空間未知,暫按 Rec.709 顯示'; + + @override + String get colorBackendUnsupported => '當前後端不支援素材色彩解釋。'; + + @override + String get loadClipPropertiesFailed => '無法讀取片段屬性'; + + @override + String get updatePictureFailed => '無法更新畫面屬性'; + + @override + String get updateVolumeFailed => '無法更新音量'; + + @override + String get updateMaskFailed => '無法更新遮罩'; + + @override + String get updateKeyframesFailed => '無法更新關鍵幀'; + + @override + String get maskPreviewFailed => '無法準備遮罩預覽'; + + @override + String get alignClipFailed => '無法對齊片段,請等待預覽就緒後重試'; + + @override + String get invalidTransform => '縮放範圍為 1%–10000%,位置和角度必須為有效數值'; + + @override + String get editFailed => '無法修改,請檢查輸入和時間範圍。'; + + @override + String get addMediaFailed => '無法新增素材,請重試'; + + @override + String get deleteCaption => '刪除字幕'; + + @override + String get mergeCaptions => '合併字幕'; + + @override + String get captionDeleted => '字幕已刪除'; + + @override + String get captionChanged => '字幕已變化,請重試。'; + + @override + String get captionEditChanged => '字幕已變化,請重新編輯。'; + + @override + String get assistantHint => '描述你的剪輯想法'; + + @override + String get configureAgentHint => '配置 Agent 服務後開始對話'; + + @override + String get agentRestartHint => '請配置 Agent 服務後重新啟動應用。'; + + @override + String get replyInterrupted => '回覆已中斷'; + + @override + String get replying => '正在回覆…'; + + @override + String get stopReply => '停止回覆'; + + @override + String get sendMessage => '傳送訊息'; + + @override + String get addAttachment => '新增附件(暫未接入)'; + + @override + String get replyFailed => '回覆失敗,請檢查服務連線或稍後重試。'; + + @override + String get mcpService => 'MCP 服務'; + + @override + String get listenPort => '監聽埠'; + + @override + String get accessToken => '訪問令牌'; + + @override + String get copyAccessToken => '複製訪問令牌'; + + @override + String get accessTokenCopied => '訪問令牌已複製'; + + @override + String get loadMcpFailed => '無法讀取 MCP 設定,重試'; + + @override + String get saveMcpFailed => '無法儲存 MCP 設定,請重試'; + + @override + String get retryStart => '重試啟動'; + + @override + String get invalidPort => '埠必須為 1–65535'; + + @override + String get loadingSettings => '正在讀取設定…'; + + @override + String get starting => '正在啟動…'; + + @override + String get stopping => '正在停止…'; + + @override + String get disabled => '已停用'; + + @override + String get running => '執行中'; + + @override + String get startFailed => '啟動失敗'; + + @override + String get saved => '已儲存'; + + @override + String get unsaved => '未儲存'; + + @override + String get saving => '儲存中…'; + + @override + String get pendingSave => '待儲存'; + + @override + String get notApplied => '未應用'; + + @override + String get enable => '啟用'; + + @override + String get disable => '停用'; + + @override + String get type => '型別'; + + @override + String get status => '狀態'; + + @override + String get file => '檔案'; + + @override + String get unboundMedia => '未繫結素材'; + + @override + String get unboundAudio => '未繫結音軌'; + + @override + String get vertical => '垂直'; + + @override + String get language => '語言'; + + @override + String get saveLanguageFailed => '無法儲存語言設定,請重試'; + + @override + String get loadLanguageFailed => '無法讀取語言設定,請重新選擇'; + + @override + String get propertiesFirstLayout => '屬性優先佈局'; + + @override + String get defaultLayout => '預設佈局'; + + @override + String get separateVocals => '分離人聲'; + + @override + String get detachAudio => '分離音訊'; + + @override + String get restoreAudio => '恢復音訊'; + + @override + String get audioDetached => '音訊已分離'; + + @override + String get addAll => '全部新增'; + + @override + String get preparingMedia => '準備素材…'; + + @override + String get cancelling => '正在取消…'; + + @override + String get cancelled => '已取消'; + + @override + String get interruptedTask => '任務已中斷,可重新啟動並繼續'; + + @override + String get auto => '自動'; + + @override + String get autoDetect => '自動識別'; + + @override + String get noTranslation => '不翻譯'; + + @override + String get sourceLanguage => '源語言'; + + @override + String get translationLanguage => '翻譯語言'; + + @override + String get transcriptionNotConfigured => '轉字幕尚未配置,請安裝識別元件和 Whisper Turbo 模型。'; + + @override + String get translationNotConfigured => '字幕翻譯尚未配置,目前可生成源語言字幕。'; + + @override + String get sourceLanguageUnknown => '無法確定可翻譯的源語言。'; + + @override + String get startTranscriptionFailed => '無法啟動識別,請檢查素材,或等待當前任務完成。'; + + @override + String get placeMediaFirst => '請先將這份素材放到時間軸,再應用字幕。'; + + @override + String get placeTranslationMediaFirst => '請先將對應素材放到時間軸,再應用翻譯字幕。'; + + @override + String get selectTargetClip => '選擇目標片段'; + + @override + String get timelineChanged => '時間軸已變化,請重新選擇目標片段。'; + + @override + String get transcriptionAccessFailed => '識別失敗:無法訪問識別元件、模型或源素材(notConfigured)'; + + @override + String get transcriptionNoAudio => '識別失敗:所選素材或音軌沒有可識別的音訊(noAudio)'; + + @override + String get transcriptionInvalidResult => '識別失敗:元件返回的字幕檔案無效(invalidResult)'; + + @override + String get transcriptionWorkerExited => '識別失敗:識別元件意外退出(workerExited)'; + + @override + String get transcriptionProcessingFailed => '識別失敗:原生識別處理失敗(processingFailed)'; + + @override + String get transcriptionFailed => '識別失敗,請檢查元件、模型、音軌和時長'; + + @override + String get transcribing => '正在識別…'; + + @override + String get captionsGenerated => '字幕已生成'; + + @override + String get cancelTranscription => '取消識別'; + + @override + String get applyCaptions => '應用為字幕'; + + @override + String get preparingTranslation => '準備翻譯…'; + + @override + String get translatingCaptions => '正在翻譯字幕…'; + + @override + String get cancellingTranslation => '正在取消翻譯…'; + + @override + String get translatedCaptionsGenerated => '翻譯字幕已生成'; + + @override + String get translationCancelled => '翻譯已取消'; + + @override + String get translationInterrupted => '翻譯任務已中斷'; + + @override + String get cancelTranslation => '取消翻譯'; + + @override + String get editorServiceUnavailable => '編輯工具服務不可用,請重新開啟專案。'; + + @override + String get mcpUnavailable => 'MCP 連線不可用,請檢查本地埠和令牌配置。'; + + @override + String get openTimelineFailed => '無法開啟時間軸'; + + @override + String get noTimelineSequence => '時間軸中沒有序列'; + + @override + String get waitingForProject => '等待開啟工程'; + + @override + String get hold => '保持'; + + @override + String get noImportableFiles => '未收到可匯入的檔案'; + + @override + String get virtualFilesUnsupported => '請從檔案管理器拖入原檔案,暫不支援虛擬檔案'; + + @override + String get editorSessionStartFailed => '無法開啟時間軸編輯器'; + + @override + String get previewStartFailed => '無法啟動原生預覽'; + + @override + String get previewInvalidTrack => '素材中不存在所選音影片軌道。'; + + @override + String get previewMissingBinding => '缺少素材繫結,無法預覽當前時間軸。'; + + @override + String get previewUnsupportedEdits => '當前時間軸包含尚不支援預覽的編輯。'; + + @override + String get previewUnsupportedConfiguration => '當前平臺或系統版本尚不支援此預覽配置。'; + + @override + String get previewHdrUnsupported => 'HDR 素材需要色調對映才能在 SDR 預覽中顯示,當前系統或預覽配置不支援。'; + + @override + String get previewAudioOutOfRange => '音訊片段超出了素材音軌的有效範圍,無法預覽。'; + + @override + String get previewResourceMissing => '預覽素材已不存在,請重新定位原檔案。'; + + @override + String get previewInvalidComposition => '影片合成配置無效,無法建立預覽。'; + + @override + String get previewInvalidData => '預覽資料無效,請重試。'; + + @override + String get previewFailed => '預覽失敗,請檢查素材是否可訪問後重試。'; + + @override + String get chatFailed => '無法完成對話,請檢查服務配置或稍後重試。'; + + @override + String get delete => '刪除'; + + @override + String get pinTimeline => '置頂時間軸'; + + @override + String get unpinTimeline => '取消置頂'; + + @override + String deleteTimelineConfirmation(String name) { + return '刪除「$name」及其編輯歷史?此操作無法復原。'; + } + + @override + String get processingFailed => '處理失敗'; + + @override + String get noMatchingOptions => '沒有匹配的選項'; + + @override + String removeMediaConfirmation(String name) { + return '從專案移除“$name”?已有片段、歷史版本和原檔案會保留。'; + } + + @override + String mediaAdded(int count) { + return '已新增 $count 個素材引用'; + } + + @override + String duplicatesSkipped(int count) { + return '跳過 $count 個重複檔案'; + } + + @override + String mediaCount(int count) { + return '$count 個素材'; + } + + @override + String get importMedia => '匯入'; + + @override + String noMediaOfType(String type) { + return '暫無$type素材'; + } + + @override + String captionsImported(String count) { + return '已匯入 $count 條字幕'; + } + + @override + String editCaptionError(String message) { + return '無法修改字幕:$message'; + } + + @override + String mcpStartError(String message) { + return '無法啟動 MCP:$message'; + } + + @override + String manualColorSpace(String name) { + return '手動指定:$name'; + } + + @override + String detectedColorSpace(String name) { + return '已識別:$name'; + } + + @override + String keyframeLabel(String channel) { + return '$channel關鍵幀'; + } + + @override + String maskMode(String mode) { + return '組合方式:$mode'; + } + + @override + String keyframeCount(int count) { + return '$count 個關鍵幀'; + } + + @override + String toggleKeyframe(String action, String channel) { + return '$action$channel關鍵幀'; + } + + @override + String previousKeyframe(String channel) { + return '上一個$channel關鍵幀'; + } + + @override + String nextKeyframe(String channel) { + return '下一個$channel關鍵幀'; + } + + @override + String keyframeSettings(String channel) { + return '$channel關鍵幀設定'; + } + + @override + String selectedClipsHint(int count) { + return '已選擇 $count 個片段\n請選擇單個片段檢視屬性'; + } + + @override + String transcriptionError(String code) { + return '識別失敗,請檢查元件、模型、音軌和時長($code)'; + } + + @override + String captionsAdded(String count) { + return '已新增 $count 條字幕,可在屬性面板編輯。'; + } + + @override + String translatedCaptionsAdded(String count) { + return '已新增 $count 條翻譯字幕,可在屬性面板編輯。'; + } + + @override + String applyCaptionsError(String message) { + return '無法應用字幕:$message'; + } + + @override + String applyTranslatedCaptionsError(String message) { + return '無法應用翻譯字幕:$message'; + } + + @override + String recognizedCaptions(int count) { + return '已識別 $count 條'; + } + + @override + String captionCount(int count) { + return '$count 條字幕'; + } + + @override + String translationFailed(String message) { + return '翻譯失敗:$message'; + } + + @override + String translatedCaptionCount(int count, String language) { + return '$count 條$language字幕'; + } + + @override + String previewParameterError(String message) { + return '預覽引數無效:$message'; + } + + @override + String mediaOffline(String names) { + return '素材離線或不可用:$names'; + } + + @override + String searchOptions(String label) { + return '搜尋$label…'; + } + + @override + String get loadRecentProjectsFailed => '無法讀取最近專案記錄,仍可手動開啟專案。'; + + @override + String get projectAccessFailed => '專案無法使用'; + + @override + String get projectMissingDirectory => '專案不存在'; + + @override + String get recentProjectSaveFailed => '專案已開啟,但最近使用記錄未能儲存。'; + + @override + String get lastProjectSaveFailed => '專案已開啟,但上次專案記錄未能儲存。'; + + @override + String get enterProjectName => '請輸入專案名稱'; + + @override + String get projectSwitched => '專案已切換,請重新拖入素材'; + + @override + String get notLocalMedia => '該素材不是本地檔案'; + + @override + String get revealMediaFailed => '無法在檔案管理器中顯示素材'; + + @override + String get openMatchingProject => '請先開啟對應專案'; + + @override + String get projectMismatch => '此位置的專案與記錄不一致,請使用“開啟專案”重新選擇。'; + + @override + String get openProjectFirst => '請先開啟專案'; + + @override + String get localFilesOnly => '請從檔案管理器拖入本地檔案'; + + @override + String get foldersUnsupported => '請選擇檔案,暫不支援拖入資料夾'; + + @override + String get mediaImportCancelled => '素材匯入已取消'; + + @override + String get fileAccessFailed => '檔案不存在或無法讀取,請檢查位置與許可權'; + + @override + String get registerMediaFailed => '無法登記素材,請重試'; + + @override + String get mediaNoLongerExists => '素材已不存在'; + + @override + String get mediaNoTracks => '素材沒有可用的影片或音訊軌道'; + + @override + String get invalidMediaDuration => '素材時長無效'; + + @override + String get mediaInfoUnsupported => '當前平臺尚未支援素材資訊讀取'; + + @override + String get mediaInfoFailed => '無法讀取素材資訊,請檢查檔案與訪問許可權'; + + @override + String get saveTimelineFailed => '時間軸儲存失敗,請重試。未儲存的編輯仍保留在當前會話。'; + + @override + String get addKeyframeAction => '新增'; + + @override + String get backgroundTasks => '後臺任務'; + + @override + String get noBackgroundTasks => '暫無後臺任務'; + + @override + String get retryTask => '重試'; + + @override + String get applyOriginalCaptions => '應用原文字幕'; + + @override + String get applyTranslatedCaptions => '應用翻譯字幕'; + + @override + String get subtitleTaskStarted => '字幕任務已開始'; + + @override + String get fitTimeline => '符合整個時間軸'; + + @override + String get modify => '修改'; + + @override + String get projectSettings => '项目设置'; + + @override + String get projectSettingsDescription => '修改项目输出规格,保留片段的实际时长和速度。'; + + @override + String get projectColorSpace => '色彩空间'; + + @override + String get projectWidth => '宽度(px)'; + + @override + String get projectHeight => '高度(px)'; + + @override + String get projectResolutionInvalid => '请输入 1–16384 的整数'; + + @override + String get previewFullscreen => '全螢幕預覽'; + + @override + String get exitPreviewFullscreen => '退出全螢幕'; + + @override + String get previewGoToStart => '回到開頭'; + + @override + String get previewPreviousFrame => '上一影格'; + + @override + String get previewNextFrame => '下一影格'; + + @override + String get softwareUpdates => '軟體更新'; + + @override + String get checkForUpdates => '檢查更新'; + + @override + String get automaticallyCheckUpdates => '自動檢查更新'; + + @override + String get updatesUnavailable => '此版本暫不提供更新。'; + + @override + String get updateCheckFailed => '無法檢查更新,請重試。'; + + @override + String get removeBackground => '去背'; + + @override + String get startBackgroundRemoval => '開始去背'; + + @override + String get backgroundRemovalResourceRequired => '去背需要下載本機模型。下載完成後會自動開始去背。'; + + @override + String get backgroundRemovalDownloadTask => '下載去背資源'; + + @override + String get backgroundRemovalResourceName => '去背模型'; + + @override + String get backgroundRemovalDestructiveHint => + '產生的透明素材會直接替換目前片段;仍可透過復原還原原片段。'; + + @override + String get backgroundRemovalTaskStarted => '去背工作已開始'; + + @override + String get startBackgroundRemovalFailed => '無法啟動去背,請檢查素材,或等待目前的處理工作完成。'; + + @override + String get backgroundRemovalComplete => '去背完成'; + + @override + String get backgroundRemovalApplying => '正在替換片段素材'; + + @override + String get backgroundRemovalFailed => '去背失敗'; + + @override + String get agentSettings => 'Agent'; + + @override + String get agentSaveSettingsFailed => '無法儲存 Agent 設定。'; + + @override + String get agentDeleteProviderTitle => '刪除 Provider?'; + + @override + String agentDeleteProviderDescription(String providerName) { + return '將從此裝置移除「$providerName」及其儲存的 API Key。'; + } + + @override + String get agentProviderRequired => '請先新增 Provider,再啟用助手。'; + + @override + String get agentUseSelectedModel => '新的 Agent 請求將使用所選模型。'; + + @override + String get agentEnable => '啟用 Agent'; + + @override + String get agentDefaultModel => '預設模型'; + + @override + String get agentConfigureModel => '設定模型'; + + @override + String get agentSelectModel => '選擇模型'; + + @override + String get agentModelUnavailable => '此對話的模型已無法使用,請選擇其他模型開始新對話。'; + + @override + String get agentModelChangeSession => '切換模型後會開始新的 Agent 工作階段。'; + + @override + String get agentCustomProviders => '自訂 Provider'; + + @override + String get agentProviderStorageDescription => + 'Provider 中繼資料儲存在本機,API Key 儲存在系統憑證儲存區中。'; + + @override + String get agentAddProvider => '新增 Provider'; + + @override + String get agentBackToProviders => '返回 Provider 列表'; + + @override + String get agentLoadSettingsFailed => '無法讀取 Agent 設定,重試'; + + @override + String get agentEnableProvider => '啟用 Provider'; + + @override + String get agentEditProvider => '編輯 Provider'; + + @override + String get agentDeleteProvider => '刪除 Provider'; + + @override + String get agentModelIdsUnique => 'Model ID 不可重複。'; + + @override + String get agentEditProviderTitle => '編輯 Provider'; + + @override + String get agentProviderEndpointDescription => + '設定 OpenAI-compatible Chat Completions 服務。'; + + @override + String get agentSaveProvider => '儲存 Provider'; + + @override + String get agentProviderConfiguration => 'Provider 設定'; + + @override + String get agentAuthenticationAndModels => '驗證與模型'; + + @override + String get agentApiType => 'API 類型'; + + @override + String get agentOpenAiChatCompletions => 'OpenAI Completions'; + + @override + String get agentBaseUrl => 'Base URL'; + + @override + String get agentApiKey => 'API Key'; + + @override + String get agentProviderNameHint => '我的 Provider'; + + @override + String get agentApiKeyOptional => '不需要驗證的服務可以留空。'; + + @override + String get agentApiKeyKeep => '留空將保留已儲存的 Key。'; + + @override + String get agentOptional => '選填'; + + @override + String get agentApiKeyOneLine => 'API Key 必須為單行文字。'; + + @override + String get agentRemoveSavedApiKey => '移除已儲存的 API Key'; + + @override + String get agentModels => '模型'; + + @override + String get agentAddModel => '新增模型'; + + @override + String get agentRequiredField => '此欄位為必填。'; + + @override + String get agentInvalidBaseUrl => '請輸入不含憑證、查詢參數或片段的 HTTP(S) Base URL。'; + + @override + String get agentModelId => 'Model ID'; + + @override + String get agentContextWindow => '上下文視窗'; + + @override + String get agentMaxOutputTokens => '最大輸出'; + + @override + String get agentMaxOutputBelowContext => '必須小於上下文視窗。'; + + @override + String get agentDeleteModel => '刪除模型'; + + @override + String get agentPositiveInteger => '請輸入正整數。'; + + @override + String get agentConfigurationReadFailed => '無法讀取 Agent 設定,請檢查設定後重試。'; + + @override + String get agentConfigurationRequired => '請先在設定中配置並啟用 Agent。'; + + @override + String get agentSessionRestoreFailed => '無法恢復 Agent 工作階段,請稍後重試。'; + + @override + String get agentContextBudgetExceeded => + '輸入預算不足,無法容納系統指令、工具和訊息。請增大上下文視窗或降低最大輸出 tokens。'; + + @override + String get agentAuthenticationFailed => '驗證失敗,請檢查 Provider 的 API Key 和存取權限。'; + + @override + String get agentConnectionFailed => '模型服務連線失敗或請求逾時,請檢查 Base URL 和網路。'; + + @override + String get agentProtocolFailed => '服務回傳內容不符合所選 API 類型,或回應串流不完整。'; + + @override + String get agentContextBudgetTooSmall => + '需要為系統指令保留更多輸入空間,請增大上下文視窗或降低最大輸出 tokens。'; + + @override + String get agentCompacting => '整理上下文…'; + + @override + String get agentEditing => '編輯中…'; + + @override + String get agentVerifying => '核對結果…'; + + @override + String get agentTurnLimitReached => '本輪任務已達到執行上限,已完成的編輯已儲存。傳送「繼續」可接著執行。'; + + @override + String get agentRecoveryRequired => '上次操作的結果尚未確認。可繼續任務核對已儲存回執;未確認的編輯不會重複執行。'; + + @override + String get agentExportReplyFailed => '影片已成功匯出,摘要回覆失敗。可重試摘要,不會重複剪輯或匯出。'; + + @override + String get agentRetrySummary => '重試摘要'; + + @override + String get agentResumeTask => '繼續任務'; + + @override + String get agentTaskInterrupted => '任務已中斷,可從已儲存的進度繼續。'; + + @override + String get downloadSubtitleModel => '下載字幕模型'; + + @override + String get downloadModelAction => '下載'; + + @override + String get subtitleEngineUnavailable => '模型已安裝,但字幕處理引擎未能啟動。請修復處理引擎,無需重新下載模型。'; + + @override + String get backgroundTaskDetails => '任務詳情'; + + @override + String get backgroundTaskFailed => '失敗'; + + @override + String get backgroundTaskCompleted => '已完成'; + + @override + String get captionWrapLines => '換行顯示字幕'; + + @override + String get captionSingleLine => '單行顯示字幕'; + + @override + String get noMatchingCaptions => '沒有符合的字幕'; + + @override + String get subtitleResourcesRequired => '產生字幕需要這些資源。下載完成後會自動開始處理。'; + + @override + String subtitleResourcesDownloadSize(String size) { + return '需下載 $size'; + } + + @override + String get pauseDownload => '暫停'; + + @override + String get resumeDownload => '繼續'; + + @override + String get downloadPaused => '已暫停'; + + @override + String get cancelResourceDownloadTitle => '取消下載?'; + + @override + String get cancelResourceDownloadMessage => '下載任務將停止,目前資源的下載進度可能遺失。'; + + @override + String get continueDownload => '繼續下載'; + + @override + String get cancelDownload => '取消下載'; + + @override + String get speechResourceStage => '語音辨識資源'; + + @override + String get translationResourceStage => '翻譯資源'; + + @override + String get subtitleResourceDownloadTask => '下載語音與翻譯資源'; + + @override + String get downloadingSpeechModel => '正在下載語音模型'; + + @override + String get downloadingTranslationModel => '正在下載翻譯模型'; + + @override + String get checkingForUpdates => '正在檢查更新…'; + + @override + String get appIsUpToDate => '目前已是最新版本。'; + + @override + String downloadingUpdate(int progress) { + return '正在下載更新:$progress%'; + } + + @override + String updateAvailable(String version) { + return '發現新版本 $version。'; + } + + @override + String get downloadUpdate => '下載更新'; + + @override + String get restartToUpdate => '重新啟動並更新'; + + @override + String get updateOperationFailed => '無法更新,請完成正在執行的工作後重試。'; + + @override + String get windowMinimize => '最小化'; + + @override + String get windowMaximize => '最大化'; + + @override + String get windowRestore => '還原'; + + @override + String get workspaceAgent => '助手'; + + @override + String get workspaceCut => '剪輯'; + + @override + String get noAvailableOptions => '暫無可用選項'; + + @override + String get composerReferenceInvalid => '引用已失效,請切回原專案或移除引用'; + + @override + String durationSeconds(int seconds) { + return '$seconds秒'; + } + + @override + String durationMinutesSeconds(int minutes, int seconds) { + return '$minutes分鐘 $seconds秒'; + } + + @override + String get projectNameInvalid => '專案名稱無效。'; + + @override + String get projectLocationDefaultUnavailable => '無法存取預設專案位置,請在設定中重新選擇。'; + + @override + String get chooseProjectLocation => '請先在設定中選擇專案儲存位置。'; + + @override + String get untitledTimeline => '未命名時間軸'; + + @override + String get primarySequence => '主序列'; + + @override + String get primaryStoryline => '主線'; + + @override + String get projectSessionClosed => '專案工作階段已關閉,請重新開啟專案。'; + + @override + String get timelineSessionClosed => '時間軸工作階段已關閉,請重新開啟時間軸。'; + + @override + String get timelineMissing => '時間軸不存在或已被刪除'; + + @override + String get timelineInUse => '時間軸正在使用中,暫時無法刪除'; + + @override + String get timelineHasBackgroundTasks => '時間軸有正在進行的背景工作,暫時無法刪除'; + + @override + String get timelineRequired => '專案至少需要保留一條時間軸'; + + @override + String get mediaReadFailed => '無法讀取素材'; + + @override + String get mediaImportFailed => '無法匯入素材'; + + @override + String get unsupportedMediaType => '僅支援匯入影片、音訊和影像檔案'; + + @override + String get mediaNoVideoTracks => '素材沒有可用的影片軌道'; + + @override + String get mediaDurationOutOfRange => '素材時長超出時間軸範圍'; + + @override + String resourceDownloadHttpFailed(String statusCode) { + return '下載失敗(HTTP $statusCode)'; + } + + @override + String get resourceChecksumFailed => '模型檔案驗證失敗,請重新下載資源。'; + + @override + String get subtitleLanguageAf => '南非荷蘭文'; + + @override + String get subtitleLanguageAm => '阿姆哈拉文'; + + @override + String get subtitleLanguageAr => '阿拉伯文'; + + @override + String get subtitleLanguageAst => '阿斯圖里亞文'; + + @override + String get subtitleLanguageAz => '亞塞拜然文'; + + @override + String get subtitleLanguageBa => '巴什喀爾文'; + + @override + String get subtitleLanguageBe => '白俄羅斯文'; + + @override + String get subtitleLanguageBg => '保加利亞文'; + + @override + String get subtitleLanguageBn => '孟加拉文'; + + @override + String get subtitleLanguageBr => '布列塔尼文'; + + @override + String get subtitleLanguageBs => '波士尼亞文'; + + @override + String get subtitleLanguageCa => '加泰蘭文'; + + @override + String get subtitleLanguageCeb => '宿霧文'; + + @override + String get subtitleLanguageCs => '捷克文'; + + @override + String get subtitleLanguageCy => '威爾斯文'; + + @override + String get subtitleLanguageDa => '丹麥文'; + + @override + String get subtitleLanguageDe => '德文'; + + @override + String get subtitleLanguageEl => '希臘文'; + + @override + String get subtitleLanguageEn => '英文'; + + @override + String get subtitleLanguageEs => '西班牙文'; + + @override + String get subtitleLanguageEt => '愛沙尼亞文'; + + @override + String get subtitleLanguageFa => '波斯文'; + + @override + String get subtitleLanguageFf => '富拉文'; + + @override + String get subtitleLanguageFi => '芬蘭文'; + + @override + String get subtitleLanguageFr => '法文'; + + @override + String get subtitleLanguageFy => '西弗里西亞文'; + + @override + String get subtitleLanguageGa => '愛爾蘭文'; + + @override + String get subtitleLanguageGd => '蘇格蘭蓋爾文'; + + @override + String get subtitleLanguageGl => '加利西亞文'; + + @override + String get subtitleLanguageGu => '古吉拉特文'; + + @override + String get subtitleLanguageHa => '豪薩文'; + + @override + String get subtitleLanguageHe => '希伯來文'; + + @override + String get subtitleLanguageHi => '印地文'; + + @override + String get subtitleLanguageHr => '克羅埃西亞文'; + + @override + String get subtitleLanguageHt => '海地文'; + + @override + String get subtitleLanguageHu => '匈牙利文'; + + @override + String get subtitleLanguageHy => '亞美尼亞文'; + + @override + String get subtitleLanguageId => '印尼文'; + + @override + String get subtitleLanguageIg => '伊布文'; + + @override + String get subtitleLanguageIlo => '伊洛闊文'; + + @override + String get subtitleLanguageIs => '冰島文'; + + @override + String get subtitleLanguageIt => '義大利文'; + + @override + String get subtitleLanguageJa => '日文'; + + @override + String get subtitleLanguageJv => '爪哇文'; + + @override + String get subtitleLanguageKa => '喬治亞文'; + + @override + String get subtitleLanguageKk => '哈薩克文'; + + @override + String get subtitleLanguageKm => '高棉文'; + + @override + String get subtitleLanguageKn => '坎那達文'; + + @override + String get subtitleLanguageKo => '韓文'; + + @override + String get subtitleLanguageLb => '盧森堡文'; + + @override + String get subtitleLanguageLg => '干達文'; + + @override + String get subtitleLanguageLn => '林加拉文'; + + @override + String get subtitleLanguageLo => '寮文'; + + @override + String get subtitleLanguageLt => '立陶宛文'; + + @override + String get subtitleLanguageLv => '拉脫維亞文'; + + @override + String get subtitleLanguageMg => '馬達加斯加文'; + + @override + String get subtitleLanguageMk => '馬其頓文'; + + @override + String get subtitleLanguageMl => '馬來亞拉姆文'; + + @override + String get subtitleLanguageMn => '蒙古文'; + + @override + String get subtitleLanguageMr => '馬拉地文'; + + @override + String get subtitleLanguageMs => '馬來文'; + + @override + String get subtitleLanguageMy => '緬甸文'; + + @override + String get subtitleLanguageNe => '尼泊爾文'; + + @override + String get subtitleLanguageNl => '荷蘭文'; + + @override + String get subtitleLanguageNo => '挪威文'; + + @override + String get subtitleLanguageNs => '北索托文'; + + @override + String get subtitleLanguageOc => '奧克西坦文'; + + @override + String get subtitleLanguageOr => '歐迪亞文'; + + @override + String get subtitleLanguagePa => '旁遮普文'; + + @override + String get subtitleLanguagePl => '波蘭文'; + + @override + String get subtitleLanguagePs => '普什圖文'; + + @override + String get subtitleLanguagePt => '葡萄牙文'; + + @override + String get subtitleLanguageRo => '羅馬尼亞文'; + + @override + String get subtitleLanguageRu => '俄文'; + + @override + String get subtitleLanguageSd => '信德文'; + + @override + String get subtitleLanguageSi => '僧伽羅文'; + + @override + String get subtitleLanguageSk => '斯洛伐克文'; + + @override + String get subtitleLanguageSl => '斯洛維尼亞文'; + + @override + String get subtitleLanguageSo => '索馬利文'; + + @override + String get subtitleLanguageSq => '阿爾巴尼亞文'; + + @override + String get subtitleLanguageSr => '塞爾維亞文'; + + @override + String get subtitleLanguageSs => '斯瓦特文'; + + @override + String get subtitleLanguageSu => '巽他文'; + + @override + String get subtitleLanguageSv => '瑞典文'; + + @override + String get subtitleLanguageSw => '史瓦希里文'; + + @override + String get subtitleLanguageTa => '坦米爾文'; + + @override + String get subtitleLanguageTh => '泰文'; + + @override + String get subtitleLanguageTl => '他加祿文'; + + @override + String get subtitleLanguageTn => '塞茲瓦納文'; + + @override + String get subtitleLanguageTr => '土耳其文'; + + @override + String get subtitleLanguageUk => '烏克蘭文'; + + @override + String get subtitleLanguageUr => '烏都文'; + + @override + String get subtitleLanguageUz => '烏茲別克文'; + + @override + String get subtitleLanguageVi => '越南文'; + + @override + String get subtitleLanguageWo => '沃洛夫文'; + + @override + String get subtitleLanguageXh => '科薩文'; + + @override + String get subtitleLanguageYi => '意第緒文'; + + @override + String get subtitleLanguageYo => '約魯巴文'; + + @override + String get subtitleLanguageYue => '粵語'; + + @override + String get subtitleLanguageZh => '中文'; + + @override + String get subtitleLanguageZu => '祖魯文'; + + @override + String get linearRec2020 => '線性 Rec.2020'; + + @override + String get diagnostics => '診斷'; + + @override + String get exportDiagnostics => '匯出診斷套件'; + + @override + String get exportDiagnosticsFailed => '無法匯出診斷套件,請重試。'; + + @override + String get exportDiagnosticsSucceeded => '診斷套件已儲存。'; +} diff --git a/lib/l10n/app_messages.dart b/lib/l10n/app_messages.dart new file mode 100644 index 0000000..4be8f66 --- /dev/null +++ b/lib/l10n/app_messages.dart @@ -0,0 +1,69 @@ +import '../errors/app_failure.dart'; +import '../integrations/app_failure_adapter.dart'; + +import 'app_localizations.dart'; + +/// Presentation is the only layer that translates application failures. +extension LocalizedAppMessages on AppLocalizations { + String errorMessage(Object error) => + failureMessage(appFailureFromError(error)); + + String failureMessage(AppFailure failure) => switch (failure.code) { + AppErrorCode.operationFailed => operationFailed, + AppErrorCode.agentRestartHint => agentRestartHint, + AppErrorCode.loadRecentProjectsFailed => loadRecentProjectsFailed, + AppErrorCode.loadProjectsFailed => loadProjectsFailed, + AppErrorCode.projectAccessFailed => projectAccessFailed, + AppErrorCode.projectLocationNotWritable => projectLocationNotWritable, + AppErrorCode.projectLocationUnavailable => projectLocationUnavailable, + AppErrorCode.projectLocationCreateFailed => projectLocationCreateFailed, + AppErrorCode.projectMissingDirectory => projectMissingDirectory, + AppErrorCode.recentProjectSaveFailed => recentProjectSaveFailed, + AppErrorCode.lastProjectSaveFailed => lastProjectSaveFailed, + AppErrorCode.enterProjectName => enterProjectName, + AppErrorCode.projectSwitched => projectSwitched, + AppErrorCode.notLocalMedia => notLocalMedia, + AppErrorCode.revealMediaFailed => revealMediaFailed, + AppErrorCode.openMatchingProject => openMatchingProject, + AppErrorCode.openTimelineFailed => openTimelineFailed, + AppErrorCode.projectMismatch => projectMismatch, + AppErrorCode.openProjectFirst => openProjectFirst, + AppErrorCode.localFilesOnly => localFilesOnly, + AppErrorCode.foldersUnsupported => foldersUnsupported, + AppErrorCode.mediaImportCancelled => mediaImportCancelled, + AppErrorCode.fileAccessFailed => fileAccessFailed, + AppErrorCode.registerMediaFailed => registerMediaFailed, + AppErrorCode.mediaNoLongerExists => mediaNoLongerExists, + AppErrorCode.mediaNoTracks => mediaNoTracks, + AppErrorCode.invalidMediaDuration => invalidMediaDuration, + AppErrorCode.mediaInfoUnsupported => mediaInfoUnsupported, + AppErrorCode.mediaInfoFailed => mediaInfoFailed, + AppErrorCode.saveTimelineFailed => saveTimelineFailed, + AppErrorCode.projectNameInvalid => projectNameInvalid, + AppErrorCode.projectLocationDefaultUnavailable => + projectLocationDefaultUnavailable, + AppErrorCode.chooseProjectLocation => chooseProjectLocation, + AppErrorCode.timelineMissing => timelineMissing, + AppErrorCode.timelineInUse => timelineInUse, + AppErrorCode.timelineHasBackgroundTasks => timelineHasBackgroundTasks, + AppErrorCode.timelineRequired => timelineRequired, + AppErrorCode.projectSessionClosed => projectSessionClosed, + AppErrorCode.timelineSessionClosed => timelineSessionClosed, + AppErrorCode.mediaReadFailed => mediaReadFailed, + AppErrorCode.mediaImportFailed => mediaImportFailed, + AppErrorCode.unsupportedMediaType => unsupportedMediaType, + AppErrorCode.mediaNoVideoTracks => mediaNoVideoTracks, + AppErrorCode.mediaDurationOutOfRange => mediaDurationOutOfRange, + AppErrorCode.resourceChecksumFailed => resourceChecksumFailed, + AppErrorCode.enterName => enterName, + AppErrorCode.agentLocationUnavailable => agentLocationUnavailable, + AppErrorCode.agentLocationBusy => agentLocationBusy, + AppErrorCode.startBackgroundRemovalFailed => startBackgroundRemovalFailed, + AppErrorCode.subtitleEngineUnavailable => subtitleEngineUnavailable, + AppErrorCode.timelineChanged => timelineChanged, + AppErrorCode.resourceDownloadHttpFailed => resourceDownloadHttpFailed( + failure.httpStatusCode?.toString() ?? '—', + ), + AppErrorCode.diagnostic => failure.diagnostic ?? operationFailed, + }; +} diff --git a/lib/l10n/app_pt.arb b/lib/l10n/app_pt.arb new file mode 100644 index 0000000..427400c --- /dev/null +++ b/lib/l10n/app_pt.arb @@ -0,0 +1,889 @@ +{ + "projectsNone": "Nenhum projeto", + "agentConversations": "Conversas", + "renameConversationTitle": "Renomear conversa", + "renameConversationDescription": "Use um nome curto e fácil de reconhecer.", + "showMoreConversations": "Mostrar mais", + "showFewerConversations": "Mostrar menos", + "agentNewConversation": "Nova conversa", + "agentElapsedTime": "Duração {duration}", + "agentConversationActions": "Ações da conversa", + "agentMoveToTrash": "Mover para a lixeira", + "agentTrash": "Lixeira", + "agentRestore": "Restaurar", + "agentEmptyTrash": "Esvaziar lixeira", + "agentDeleteForever": "Excluir permanentemente", + "agentConversationLocation": "Local das conversas", + "agentChooseExistingConversations": "Escolher conversas existentes", + "agentMoveConversations": "Mover conversas", + "agentLocationUnavailable": "O local das conversas está indisponível", + "agentLocationBusy": "Aguarde as conversas em andamento terminarem", + "agentRelinkProvider": "Vincular provedor novamente", + "@@locale": "pt", + "settings": "Configurações", + "closeSettings": "Fechar configurações", + "general": "Geral", + "appearance": "Aparência", + "theme": "Tema", + "system": "Seguir o sistema", + "light": "Claro", + "dark": "Escuro", + "saveAppearanceFailed": "Não foi possível salvar a aparência. Por favor, tente novamente.", + "loadAppearanceFailed": "Não foi possível carregar a aparência. Selecione um tema novamente.", + "cancel": "Cancelar", + "save": "Salvar", + "create": "Criar", + "close": "Fechar", + "retry": "Tentar novamente", + "name": "Nome", + "enterName": "Digite um nome", + "invalidName": "Os nomes não podem conter separadores de caminho ou caracteres de controle", + "projectName": "Nome do projeto", + "newProject": "Novo projeto", + "openProject": "Abrir projeto", + "openProjectMore": "Abrir outro projeto", + "projects": "Projetos", + "projectsEmpty": "Nenhum projeto", + "openingWorkspace": "Abrindo o espaço de trabalho…", + "loadProjectsFailed": "Não foi possível carregar os projetos", + "backToProjects": "Voltar à edição", + "timelines": "Linhas do tempo", + "timelineLimitReached": "Cada projeto pode conter até {count} linhas do tempo.", + "timelineName": "Nome da linha do tempo", + "defaultTimelineName": "Linha do tempo {index}", + "newTimeline": "Nova linha do tempo", + "noTimelines": "Nenhuma linha do tempo", + "activeTimeline": "Linha do tempo atual", + "timelineUnavailable": "Linha do tempo indisponível", + "projectNoTimelines": "Este projeto ainda não tem linhas do tempo", + "createTimelineHint": "Crie uma linha do tempo na seção “Linhas do tempo” à esquerda para começar a editar.", + "createTimelineChat": "Crie uma linha do tempo para iniciar a conversa", + "editingFirstLayout": "Edição em primeiro lugar", + "agentEditingLayout": "Agente e edição", + "agentLayoutDescription": "Planejar, colaborar e executar", + "editingLayoutDescription": "Pré-visualizar, editar e refinar", + "saveHere": "Salvar aqui", + "selectDirectoryFailed": "Não foi possível selecionar um diretório. Verifique as permissões do sistema.", + "operationFailed": "A operação falhou. Por favor, tente novamente.", + "collapseSidebar": "Recolher barra lateral", + "expandSidebar": "Expandir barra lateral", + "expandEditor": "Expandir área de edição", + "collapseProperties": "Recolher propriedades", + "expandProperties": "Expandir propriedades", + "layout": "Layout", + "materials": "Mídia", + "all": "Todos", + "video": "Vídeo", + "audio": "Áudio", + "image": "Imagem", + "picture": "Imagem", + "captions": "Legendas", + "text": "Texto", + "noMedia": "Sem mídia", + "mediaCategory": "Categoria de mídia", + "captionTasks": "Tarefas de legendas", + "listLayout": "Visualização de lista", + "gridLayout": "Visualização em grade", + "addToTimeline": "Adicionar à linha do tempo", + "rename": "Renomear", + "renameMedia": "Renomear mídia", + "removeMedia": "Remover mídia", + "remove": "Remover", + "revealFinder": "Mostrar no Finder", + "revealFileManager": "Mostrar no gerenciador de arquivos", + "dropToAdd": "Solte para adicionar", + "timelineDropToStart": "Arraste a mídia aqui para começar.", + "dragMediaHint": "Arraste vídeo, áudio ou imagens aqui\nOs arquivos originais permanecem em seu local atual", + "transcribe": "Transcrever", + "generateCaptions": "Gerar legendas", + "play": "Reproduzir", + "pause": "Pausar", + "retryPreview": "Tentar visualizar novamente", + "canvasRatio": "Proporção da tela", + "noPreviewContent": "Nenhum conteúdo para visualizar na linha do tempo", + "nativePreviewUnsupported": "A visualização nativa não está disponível nesta plataforma", + "canvasTransformFailed": "Não foi possível transformar a tela. Por favor, tente novamente.", + "undo": "Desfazer", + "redo": "Refazer", + "deleteSelectedClips": "Excluir clipes selecionados", + "splitAtPlayhead": "Dividir no playhead", + "trimLeft": "Aparar à esquerda", + "trimRight": "Aparar à direita", + "trimLeftTooltip": "Remover à esquerda do cursor e manter a direita", + "trimRightTooltip": "Remover à direita do cursor e manter a esquerda", + "currentSequence": "Sequência atual", + "projectProperties": "Propriedades do projeto", + "canvasSize": "Tamanho da tela", + "frameRate": "Taxa de quadros", + "duration": "Duração", + "totalDuration": "Duração total", + "clipDuration": "Duração do clipe", + "seconds": "segundos", + "clip": "Clipe", + "unnamedClip": "Clipe sem nome", + "gap": "Espaço vazio", + "compoundClip": "Clipe composto", + "textClip": "Clipe de texto", + "pictureProperties": "Imagem", + "position": "Posição", + "rotation": "Rotação", + "scale": "Escala", + "size": "Tamanho", + "transform": "Transformação", + "resetPosition": "Redefinir posição", + "keepAspectRatio": "Bloquear proporção de aspecto", + "alignment": "Alinhamento", + "alignLeft": "Alinhar à esquerda", + "alignRight": "Alinhar à direita", + "alignTop": "Alinhar topo", + "alignBottom": "Alinhar parte inferior", + "alignHorizontalCenter": "Centralizar horizontalmente", + "alignVerticalCenter": "Centralizar verticalmente", + "volume": "Volume", + "gain": "Ganho", + "mute": "Silenciar", + "unmute": "Ativar som", + "resetVolume": "Redefinir volume", + "invalidGain": "Insira um valor entre -90 e +12", + "animation": "Animação", + "keyframes": "Quadros-chave", + "removeAllKeyframes": "Remover todos os quadros-chave", + "linear": "Linear", + "easeIn": "Entrada suave", + "easeOut": "Saída suave", + "easeInOut": "Entrada e saída suaves", + "basic": "Básico", + "mask": "Máscara", + "addMask": "Adicionar máscara", + "deleteMask": "Excluir máscara", + "resetMask": "Redefinir máscara", + "enableMask": "Habilitar máscara", + "disableMask": "Desativar máscara", + "moveMaskUp": "Mova a máscara para cima", + "moveMaskDown": "Mover máscara para baixo", + "rectangle": "Retângulo", + "ellipse": "Elipse", + "invert": "Inverter", + "feather": "Suavização", + "add": "Adicionar", + "subtract": "Subtrair", + "intersect": "Interseção", + "initialRegion": "Região inicial", + "none": "Nenhum", + "color": "Cor", + "fontSize": "Tamanho da fonte", + "outlineWidth": "Largura do contorno", + "outlineColor": "Cor do contorno", + "captionBaseline": "Linha de base das legendas", + "content": "Texto", + "start": "Início", + "time": "Tempo", + "speed": "Velocidade", + "speedSegmentCount": "{count} segmentos de velocidade", + "splitSpeedAtPlayhead": "Dividir velocidade no cursor", + "speedChange": "Velocidade", + "speedMode": "Modo de velocidade", + "constantSpeed": "Velocidade constante", + "segmentedSpeed": "Velocidade segmentada", + "speedNotAvailable": "Os controles de velocidade ainda não estão disponíveis", + "custom": "Personalizado", + "invalidNumber": "Valor inválido", + "mediaUnavailable": "Mídia indisponível", + "mediaMissing": "Mídia ausente", + "mediaColorSpace": "Espaço de cores da mídia", + "mediaColorInterpretation": "Interpretação de cores da mídia", + "colorInfoNotLoaded": "Informações de cor não carregadas", + "unknownColorSpace": "Espaço de cores desconhecido. Exibindo como Rec.709.", + "colorBackendUnsupported": "O back-end atual não oferece suporte à interpretação de cores de mídia.", + "loadClipPropertiesFailed": "Não foi possível ler as propriedades do clipe", + "updatePictureFailed": "Não foi possível atualizar as propriedades da imagem", + "updateVolumeFailed": "Não foi possível atualizar o volume", + "updateMaskFailed": "Não foi possível atualizar a máscara", + "updateKeyframesFailed": "Não foi possível atualizar os quadros-chave", + "maskPreviewFailed": "Não foi possível preparar a visualização da máscara", + "alignClipFailed": "Não foi possível alinhar o clipe. Aguarde a visualização e tente novamente.", + "invalidTransform": "A escala deve ser de 1% a 10.000%. A posição e o ângulo devem ser números válidos.", + "editFailed": "Não foi possível editar. Verifique a entrada e o intervalo de tempo.", + "addMediaFailed": "Não foi possível adicionar mídia. Por favor, tente novamente.", + "deleteCaption": "Excluir legenda", + "mergeCaptions": "Mesclar legendas", + "captionDeleted": "Legenda excluída", + "captionChanged": "As legendas mudaram. Por favor, tente novamente.", + "captionEditChanged": "As legendas mudaram. Edite novamente.", + "assistantHint": "Descreva sua ideia de edição", + "configureAgentHint": "Configure o serviço do agente para iniciar o bate-papo", + "agentRestartHint": "Configure o serviço do agente e reinicie o aplicativo.", + "replyInterrupted": "Resposta interrompida", + "replying": "Respondendo…", + "stopReply": "Parar resposta", + "sendMessage": "Enviar mensagem", + "addAttachment": "Adicionar anexo (ainda não disponível)", + "replyFailed": "A resposta falhou. Verifique a conexão ou tente novamente mais tarde.", + "mcpService": "Serviço MCP", + "listenPort": "Porta", + "accessToken": "Token de acesso", + "copyAccessToken": "Copiar token de acesso", + "accessTokenCopied": "Token de acesso copiado", + "loadMcpFailed": "Não foi possível carregar as configurações do MCP. Tentar novamente", + "saveMcpFailed": "Não foi possível salvar as configurações do MCP. Por favor, tente novamente.", + "retryStart": "Tentar iniciar novamente", + "invalidPort": "A porta deve estar entre 1 e 65535", + "loadingSettings": "Carregando configurações…", + "starting": "Iniciando…", + "stopping": "Parando…", + "disabled": "Desativado", + "running": "Em execução", + "startFailed": "Falha ao iniciar", + "saved": "Salvo", + "unsaved": "Não salvo", + "saving": "Salvando…", + "pendingSave": "Salvamento pendente", + "notApplied": "Não aplicado", + "enable": "Ativar", + "disable": "Desativar", + "type": "Tipo", + "status": "Status", + "file": "Arquivo", + "unboundMedia": "Nenhuma mídia vinculada", + "unboundAudio": "Nenhuma faixa de áudio vinculada", + "vertical": "Vertical", + "language": "Idioma", + "saveLanguageFailed": "Não foi possível salvar o idioma. Por favor, tente novamente.", + "loadLanguageFailed": "Não foi possível carregar o idioma. Selecione novamente.", + "propertiesFirstLayout": "Propriedades primeiro", + "defaultLayout": "Layout padrão", + "separateVocals": "Separar vocais", + "detachAudio": "Separar áudio", + "restoreAudio": "Restaurar áudio", + "audioDetached": "Áudio separado", + "addAll": "Adicionar tudo", + "preparingMedia": "Preparando mídia…", + "cancelling": "Cancelando…", + "cancelled": "Cancelado", + "interruptedTask": "Tarefa interrompida. Reinicie para continuar", + "auto": "Automático", + "autoDetect": "Detecção automática", + "noTranslation": "Não traduzir", + "sourceLanguage": "Idioma de origem", + "translationLanguage": "Idioma de destino", + "transcriptionNotConfigured": "A transcrição não está configurada. Instale o componente de reconhecimento e o modelo Whisper Turbo.", + "translationNotConfigured": "A tradução de legendas não está configurada. Você pode gerar legendas no idioma de origem.", + "sourceLanguageUnknown": "Não foi possível determinar um idioma de origem para tradução.", + "startTranscriptionFailed": "Não foi possível iniciar a transcrição. Verifique a mídia ou aguarde a conclusão da tarefa atual.", + "placeMediaFirst": "Coloque esta mídia na linha do tempo antes de aplicar as legendas.", + "placeTranslationMediaFirst": "Coloque a mídia correspondente na linha do tempo antes de aplicar as legendas traduzidas.", + "selectTargetClip": "Selecione o clipe alvo", + "timelineChanged": "A linha do tempo mudou. Selecione o clipe de destino novamente.", + "transcriptionAccessFailed": "Falha na transcrição: componente, modelo ou mídia de origem inacessível (notConfigured)", + "transcriptionNoAudio": "Falha na transcrição: nenhum áudio reconhecível na mídia ou faixa selecionada (noAudio)", + "transcriptionInvalidResult": "Falha na transcrição: arquivo de legenda inválido retornado (invalidResult)", + "transcriptionWorkerExited": "Falha na transcrição: o componente de reconhecimento foi encerrado inesperadamente (workerExited)", + "transcriptionProcessingFailed": "Falha na transcrição: falha no processamento nativo (processingFailed)", + "transcriptionFailed": "Falha na transcrição. Verifique o componente, modelo, trilha de áudio e duração", + "transcribing": "Transcrevendo…", + "captionsGenerated": "Legendas geradas", + "cancelTranscription": "Cancelar transcrição", + "applyCaptions": "Aplicar legendas", + "preparingTranslation": "Preparando tradução…", + "translatingCaptions": "Traduzindo legendas…", + "cancellingTranslation": "Cancelando tradução…", + "translatedCaptionsGenerated": "Legendas traduzidas geradas", + "translationCancelled": "Tradução cancelada", + "translationInterrupted": "Tradução interrompida", + "cancelTranslation": "Cancelar tradução", + "editorServiceUnavailable": "Serviço de edição indisponível. Reabra o projeto.", + "mcpUnavailable": "Conexão MCP indisponível. Verifique a porta local e o token.", + "openTimelineFailed": "Não foi possível abrir a linha do tempo", + "noTimelineSequence": "Esta linha do tempo não tem sequência.", + "waitingForProject": "Aguardando a abertura de um projeto", + "hold": "Manter", + "noImportableFiles": "Nenhum arquivo importável recebido", + "virtualFilesUnsupported": "Arraste os arquivos originais do gerenciador de arquivos. Arquivos virtuais ainda não são suportados.", + "editorSessionStartFailed": "Não foi possível abrir o editor da linha do tempo", + "previewStartFailed": "Não foi possível iniciar a visualização nativa", + "previewInvalidTrack": "A trilha de áudio ou vídeo selecionada não existe na mídia.", + "previewMissingBinding": "As vinculações de mídia estão faltando. Não foi possível visualizar esta linha do tempo.", + "previewUnsupportedEdits": "Esta linha do tempo contém edições que ainda não são suportadas pela visualização.", + "previewUnsupportedConfiguration": "Esta configuração de visualização não é compatível com a plataforma ou versão do sistema atual.", + "previewHdrUnsupported": "A mídia HDR requer mapeamento de tons para visualização SDR. O sistema atual ou a configuração de visualização não oferece suporte para isso.", + "previewAudioOutOfRange": "O clipe de áudio excede o intervalo da trilha de origem e não pode ser visualizado.", + "previewResourceMissing": "A mídia de visualização não existe mais. Localize o arquivo original novamente.", + "previewInvalidComposition": "Configuração de composição de vídeo inválida. Não foi possível criar a visualização.", + "previewInvalidData": "Dados de visualização inválidos. Por favor, tente novamente.", + "previewFailed": "Falha na visualização. Verifique o acesso à mídia e tente novamente.", + "chatFailed": "Não foi possível concluir a conversa. Verifique a configuração do serviço ou tente novamente mais tarde.", + "delete": "Excluir", + "pinTimeline": "Fixar linha do tempo", + "unpinTimeline": "Desafixar linha do tempo", + "deleteTimelineConfirmation": "Excluir “{name}” e seu histórico de edição? Esta ação não pode ser desfeita.", + "@deleteTimelineConfirmation": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "processingFailed": "Falha no processamento", + "noMatchingOptions": "Nenhuma opção correspondente", + "removeMediaConfirmation": "Remover “{name}” da biblioteca? Os clipes existentes, o histórico e o arquivo original serão mantidos.", + "@removeMediaConfirmation": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "mediaAdded": "{count} referências de mídia adicionadas", + "@mediaAdded": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "duplicatesSkipped": "Arquivos duplicados {count} ignorados", + "@duplicatesSkipped": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mediaCount": "{count} itens de mídia", + "importMedia": "Importar", + "@mediaCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "noMediaOfType": "Nenhuma mídia {type}", + "@noMediaOfType": { + "placeholders": { + "type": { + "type": "String" + } + } + }, + "captionsImported": "Legendas {count} importadas", + "@captionsImported": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "editCaptionError": "Não foi possível editar as legendas: {message}", + "@editCaptionError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "mcpStartError": "Não foi possível iniciar o MCP: {message}", + "@mcpStartError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "manualColorSpace": "Selecionado manualmente: {name}", + "@manualColorSpace": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "detectedColorSpace": "Detectado: {name}", + "@detectedColorSpace": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "keyframeLabel": "Quadro-chave de {channel}", + "@keyframeLabel": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "maskMode": "Modo de combinação: {mode}", + "@maskMode": { + "placeholders": { + "mode": { + "type": "String" + } + } + }, + "keyframeCount": "{count} quadros-chave", + "@keyframeCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "toggleKeyframe": "{action} quadro-chave de {channel}", + "@toggleKeyframe": { + "placeholders": { + "action": { + "type": "String" + }, + "channel": { + "type": "String" + } + } + }, + "previousKeyframe": "Quadro-chave anterior de {channel}", + "@previousKeyframe": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "nextKeyframe": "Próximo quadro-chave de {channel}", + "@nextKeyframe": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "keyframeSettings": "Configurações de quadros-chave de {channel}", + "@keyframeSettings": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "selectedClipsHint": "Clipes {count} selecionados\nSelecione um clipe para ver suas propriedades", + "@selectedClipsHint": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "transcriptionError": "Falha na transcrição. Verifique o componente, modelo, trilha de áudio e duração ({code})", + "@transcriptionError": { + "placeholders": { + "code": { + "type": "String" + } + } + }, + "captionsAdded": "Adicionadas legendas {count}. Edite-os no painel de propriedades.", + "@captionsAdded": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "translatedCaptionsAdded": "Adicionadas legendas traduzidas {count}. Edite-os no painel de propriedades.", + "@translatedCaptionsAdded": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "applyCaptionsError": "Não foi possível aplicar legendas: {message}", + "@applyCaptionsError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "applyTranslatedCaptionsError": "Não foi possível aplicar legendas traduzidas: {message}", + "@applyTranslatedCaptionsError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "recognizedCaptions": "{count} legendas reconhecidas", + "@recognizedCaptions": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "captionCount": "{count} legendas", + "@captionCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "translationFailed": "Falha na tradução: {message}", + "@translationFailed": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "translatedCaptionCount": "{count} legendas em {language}", + "@translatedCaptionCount": { + "placeholders": { + "count": { + "type": "int" + }, + "language": { + "type": "String" + } + } + }, + "previewParameterError": "Parâmetros de visualização inválidos: {message}", + "@previewParameterError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "mediaOffline": "Mídia offline ou indisponível: {names}", + "@mediaOffline": { + "placeholders": { + "names": { + "type": "String" + } + } + }, + "searchOptions": "Procurar {label}…", + "@searchOptions": { + "placeholders": { + "label": { + "type": "String" + } + } + }, + "loadRecentProjectsFailed": "Não foi possível carregar bibliotecas recentes. Você ainda pode abrir uma biblioteca manualmente.", + "projectAccessFailed": "Projeto indisponível", + "projectMissingDirectory": "Projeto não encontrado", + "recentProjectSaveFailed": "Biblioteca aberta, mas não foi possível salvar o registro recente da biblioteca.", + "lastProjectSaveFailed": "Projeto aberto, mas não foi possível salvar o último registro do projeto.", + "enterProjectName": "Insira um nome de projeto", + "projectSwitched": "O projeto mudou. Arraste a mídia novamente.", + "notLocalMedia": "Esta mídia não é um arquivo local", + "revealMediaFailed": "Não foi possível mostrar a mídia no gerenciador de arquivos", + "openMatchingProject": "Abra o projeto correspondente primeiro", + "projectMismatch": "A biblioteca neste local não corresponde ao registro. Selecione-o novamente com Abrir biblioteca.", + "openProjectFirst": "Abra uma biblioteca primeiro", + "localFilesOnly": "Arraste arquivos locais do gerenciador de arquivos", + "foldersUnsupported": "Selecione os arquivos. Arrastar pastas ainda não é compatível.", + "mediaImportCancelled": "Importação de mídia cancelada", + "fileAccessFailed": "O arquivo está ausente ou ilegível. Verifique sua localização e permissões", + "registerMediaFailed": "Não foi possível registrar a mídia. Por favor, tente novamente", + "mediaNoLongerExists": "A mídia não existe mais", + "mediaNoTracks": "A mídia não tem faixas de vídeo ou áudio utilizáveis", + "invalidMediaDuration": "Duração de mídia inválida", + "mediaInfoUnsupported": "A leitura de informações de mídia ainda não é compatível com esta plataforma", + "mediaInfoFailed": "Não foi possível ler as informações da mídia. Verifique o arquivo e as permissões de acesso", + "saveTimelineFailed": "Não foi possível salvar a linha do tempo. Tente novamente. As edições não salvas permanecem nesta sessão.", + "addKeyframeAction": "Adicionar", + "backgroundTasks": "Tarefas em segundo plano", + "noBackgroundTasks": "Nenhuma tarefa em segundo plano", + "retryTask": "Tentar novamente", + "applyOriginalCaptions": "Aplicar legendas originais", + "applyTranslatedCaptions": "Aplicar legendas traduzidas", + "subtitleTaskStarted": "Tarefa de legendas iniciada", + "fitTimeline": "Ajustar toda a linha do tempo", + "modify": "Modify", + "projectSettings": "Project settings", + "projectSettingsDescription": "Change project output settings while keeping clip timing and speed.", + "projectColorSpace": "Color space", + "projectWidth": "Width (px)", + "projectHeight": "Height (px)", + "projectResolutionInvalid": "Enter a whole number from 1 to 16384", + "previewFullscreen": "Prévia em tela cheia", + "exitPreviewFullscreen": "Sair da tela cheia", + "previewGoToStart": "Ir para o início", + "previewPreviousFrame": "Quadro anterior", + "previewNextFrame": "Próximo quadro", + "softwareUpdates": "Atualizações", + "checkForUpdates": "Verificar atualizações", + "automaticallyCheckUpdates": "Verificar atualizações automaticamente", + "updatesUnavailable": "Atualizações indisponíveis nesta compilação.", + "updateCheckFailed": "Não foi possível verificar atualizações. Tente novamente.", + "agentSettings": "Agente", + "agentSaveSettingsFailed": "Não foi possível salvar as configurações do agente.", + "agentDeleteProviderTitle": "Excluir provedor?", + "agentDeleteProviderDescription": "“{providerName}” e a chave de API salva serão removidos deste dispositivo.", + "agentProviderRequired": "Adicione um provedor antes de ativar o assistente.", + "agentUseSelectedModel": "As novas solicitações do agente usarão o modelo selecionado.", + "agentEnable": "Ativar agente", + "agentDefaultModel": "Modelo padrão", + "agentConfigureModel": "Configurar modelos", + "agentSelectModel": "Selecionar modelo", + "agentModelUnavailable": "O modelo desta conversa está indisponível. Selecione outro modelo para iniciar uma nova conversa.", + "agentModelChangeSession": "Alterar o modelo inicia uma nova sessão do agente.", + "agentCustomProviders": "Provedores personalizados", + "agentProviderStorageDescription": "Os metadados do provedor são armazenados localmente. As chaves de API ficam no armazenamento de credenciais do sistema.", + "agentAddProvider": "Adicionar provedor", + "agentBackToProviders": "Voltar aos provedores", + "agentLoadSettingsFailed": "Não foi possível carregar as configurações do agente. Tentar novamente", + "agentEnableProvider": "Ativar provedor", + "agentEditProvider": "Editar provedor", + "agentDeleteProvider": "Excluir provedor", + "agentModelIdsUnique": "Os IDs de modelo devem ser exclusivos.", + "agentEditProviderTitle": "Editar provedor", + "agentProviderEndpointDescription": "Configure um endpoint de Chat Completions compatível com OpenAI.", + "agentSaveProvider": "Salvar provedor", + "agentProviderConfiguration": "Configuração do provedor", + "agentAuthenticationAndModels": "Autenticação e modelos", + "agentApiType": "Tipo de API", + "agentOpenAiChatCompletions": "OpenAI Completions", + "agentBaseUrl": "URL base", + "agentApiKey": "Chave de API", + "agentProviderNameHint": "Meu provedor", + "agentApiKeyOptional": "Opcional para endpoints que não exigem autenticação.", + "agentApiKeyKeep": "Deixe em branco para manter a chave salva.", + "agentOptional": "Opcional", + "agentApiKeyOneLine": "A chave de API deve ter apenas uma linha.", + "agentRemoveSavedApiKey": "Remover chave de API salva", + "agentModels": "Modelos", + "agentAddModel": "Adicionar modelo", + "agentRequiredField": "Este campo é obrigatório.", + "agentInvalidBaseUrl": "Insira uma URL base HTTP(S) sem credenciais, consulta ou fragmento.", + "agentModelId": "ID do modelo", + "agentContextWindow": "Janela de contexto", + "agentMaxOutputTokens": "Saída máxima", + "agentMaxOutputBelowContext": "Deve ser menor que a janela de contexto.", + "agentDeleteModel": "Excluir modelo", + "agentPositiveInteger": "Insira um número inteiro positivo.", + "agentConfigurationReadFailed": "Não foi possível ler a configuração do agente. Verifique as configurações e tente novamente.", + "agentConfigurationRequired": "Primeiro configure e ative o agente em Configurações.", + "agentSessionRestoreFailed": "Não foi possível restaurar a sessão do agente. Tente novamente mais tarde.", + "select": "Selecionar", + "projectLocation": "Local de salvamento dos projetos", + "projectLocationNotSet": "Não definido", + "resourceLocation": "Local de armazenamento dos recursos", + "resourceLocationNotSet": "Não definido", + "loadProjectLocationFailed": "Não foi possível carregar o local de salvamento dos projetos.", + "saveProjectLocationFailed": "Não foi possível salvar o local dos projetos.", + "loadResourceLocationFailed": "Não foi possível carregar o local de armazenamento dos recursos.", + "saveResourceLocationFailed": "Não foi possível salvar o local dos recursos.", + "downloadAndContinue": "Baixar e continuar", + "downloadInBackground": "Baixar em segundo plano", + "downloadingResource": "Baixando…", + "processingResourceDownloadFailed": "Não foi possível baixar o recurso de reconhecimento de fala. Tente novamente.", + "transcriptionResourceRequired": "Para gerar legendas, primeiro é necessário baixar um modelo de reconhecimento de fala.", + "removeBackground": "Remover fundo", + "startBackgroundRemoval": "Remover fundo", + "backgroundRemovalResourceRequired": "A remoção de fundo precisa de um modelo local. Ela começa automaticamente após o download.", + "backgroundRemovalDownloadTask": "Baixar recurso de remoção de fundo", + "backgroundRemovalResourceName": "Modelo de remoção de fundo", + "backgroundRemovalTaskStarted": "Remoção de fundo iniciada", + "backgroundRemovalApplying": "Substituindo a mídia do clipe", + "backgroundRemovalComplete": "Remoção de fundo concluída", + "backgroundRemovalFailed": "Falha ao remover o fundo", + "backgroundRemovalDestructiveHint": "A mídia transparente gerada substituirá este clipe. Você ainda pode usar Desfazer para restaurar o clipe original.", + "startBackgroundRemovalFailed": "Não foi possível iniciar a remoção de fundo. Verifique a mídia ou aguarde a conclusão da tarefa de processamento atual.", + "agentContextBudgetExceeded": "O orçamento de entrada é insuficiente para instruções, ferramentas e mensagem. Aumente o contexto ou reduza a saída máxima.", + "agentAuthenticationFailed": "Falha na autenticação. Verifique a API Key e as permissões.", + "agentConnectionFailed": "Falha de conexão ou tempo esgotado. Verifique a Base URL e a rede.", + "agentProtocolFailed": "A resposta não corresponde ao tipo de API selecionado ou o fluxo está incompleto.", + "agentContextBudgetTooSmall": "Reserve mais espaço para instruções. Aumente o contexto ou reduza a saída máxima.", + "agentCompacting": "Organizando o contexto…", + "agentEditing": "Editando…", + "agentVerifying": "Verificando resultados…", + "agentTurnLimitReached": "A tarefa atingiu o limite de execução. As alterações foram salvas. Envie “Continuar” para retomar.", + "agentRecoveryRequired": "O resultado anterior não foi confirmado. Continue para verificar os registros salvos; edições não confirmadas não serão repetidas.", + "agentExportReplyFailed": "Vídeo exportado. A resposta de resumo falhou. Tente novamente sem repetir a edição ou exportação.", + "agentRetrySummary": "Tentar resumo novamente", + "agentResumeTask": "Continuar tarefa", + "agentTaskInterrupted": "A tarefa foi interrompida. Continue a partir do progresso salvo.", + "downloadSubtitleModel": "Baixar modelo de legendas", + "downloadModelAction": "Baixar", + "subtitleEngineUnavailable": "O modelo está instalado, mas o mecanismo de legendas não iniciou. Repare o mecanismo; não é necessário baixar o modelo novamente.", + "backgroundTaskDetails": "Detalhes da tarefa", + "backgroundTaskFailed": "Falhou", + "backgroundTaskCompleted": "Concluída", + "captionWrapLines": "Quebrar linhas das legendas", + "captionSingleLine": "Mostrar legendas numa linha", + "noMatchingCaptions": "Nenhuma legenda correspondente", + "subtitleResourcesRequired": "Estes recursos são necessários para as legendas. A geração começará automaticamente após o download.", + "subtitleResourcesDownloadSize": "Para baixar: {size}", + "pauseDownload": "Pausar", + "resumeDownload": "Retomar", + "downloadPaused": "Pausado", + "cancelResourceDownloadTitle": "Cancelar download?", + "cancelResourceDownloadMessage": "O download será interrompido. O progresso do recurso atual pode ser perdido.", + "continueDownload": "Continuar download", + "cancelDownload": "Cancelar download", + "speechResourceStage": "Recurso de reconhecimento de voz", + "translationResourceStage": "Recurso de tradução", + "subtitleResourceDownloadTask": "Baixar recursos de voz e tradução", + "downloadingSpeechModel": "A transferir o modelo de voz", + "downloadingTranslationModel": "A transferir o modelo de tradução", + "selectProject": "Selecionar projeto", + "searchProjects": "Pesquisar projetos", + "noMatchingProjects": "Nenhum projeto correspondente", + "projectLocationMissing": "A pasta não existe. Será criada ao criar um projeto.", + "projectLocationUnavailable": "O local de armazenamento está indisponível. Conecte o disco ou verifique a rede e tente novamente, ou altere o local.", + "projectLocationNotWritable": "Não é possível gravar no local de armazenamento. Verifique as permissões ou altere o local.", + "projectLocationCreateFailed": "Não foi possível criar a pasta do projeto ou gravar nela. Verifique as permissões ou altere o local.", + "removeProjectFromSidebar": "Remover da barra lateral", + "projectRemoved": "Projeto removido. Os arquivos locais e as conversas foram preservados.", + "agentNoConversations": "Ainda não há conversas", + "collapseProject": "Recolher projeto", + "expandProject": "Expandir projeto", + "agentDeleteConfirmation": "Excluir permanentemente “{title}” e todas as mensagens? Esta ação não pode ser desfeita. Os arquivos locais do projeto não serão afetados.", + "agentEmptyTrashConfirmation": "Excluir permanentemente todas as conversas da lixeira? Esta ação não pode ser desfeita. Os arquivos locais do projeto não serão afetados.", + "checkingForUpdates": "Verificando atualizações…", + "appIsUpToDate": "O aplicativo está atualizado.", + "downloadingUpdate": "Baixando atualização: {progress}%", + "updateAvailable": "A versão {version} está disponível.", + "downloadUpdate": "Baixar atualização", + "restartToUpdate": "Reiniciar para atualizar", + "updateOperationFailed": "Não foi possível atualizar. Conclua as tarefas ativas e tente novamente.", + "windowMinimize": "Minimizar", + "windowMaximize": "Maximizar", + "windowRestore": "Restaurar", + "workspaceAgent": "Assistente", + "workspaceCut": "Edição", + "noAvailableOptions": "Nenhuma opção disponível", + "composerReferenceInvalid": "Uma referência não é mais válida. Volte ao projeto dela ou remova-a.", + "durationSeconds": "{seconds} s", + "durationMinutesSeconds": "{minutes} min {seconds} s", + "projectNameInvalid": "Nome de projeto inválido", + "projectLocationDefaultUnavailable": "Não foi possível acessar o local padrão dos projetos. Selecione-o novamente nas configurações.", + "chooseProjectLocation": "Selecione primeiro um local para salvar projetos nas configurações.", + "untitledTimeline": "Linha do tempo sem título", + "primarySequence": "Sequência principal", + "primaryStoryline": "Linha principal", + "projectSessionClosed": "A sessão do projeto foi fechada. Reabra o projeto.", + "timelineSessionClosed": "A sessão da linha do tempo foi fechada. Reabra a linha do tempo.", + "timelineMissing": "A linha do tempo não existe ou foi excluída.", + "timelineInUse": "A linha do tempo está em uso e ainda não pode ser excluída.", + "timelineHasBackgroundTasks": "Conclua as tarefas em segundo plano da linha do tempo antes de excluí-la.", + "timelineRequired": "Um projeto deve manter pelo menos uma linha do tempo.", + "mediaReadFailed": "Não foi possível ler a mídia", + "mediaImportFailed": "Não foi possível importar a mídia", + "unsupportedMediaType": "Somente arquivos de vídeo, áudio e imagem podem ser importados.", + "mediaNoVideoTracks": "A mídia não tem uma faixa de vídeo utilizável", + "mediaDurationOutOfRange": "A duração da mídia excede o intervalo da linha do tempo", + "resourceDownloadHttpFailed": "Falha no download (HTTP {statusCode})", + "resourceChecksumFailed": "A verificação do arquivo do modelo falhou. Baixe o recurso novamente.", + "subtitleLanguageAf": "africâner", + "subtitleLanguageAm": "amárico", + "subtitleLanguageAr": "árabe", + "subtitleLanguageAst": "asturiano", + "subtitleLanguageAz": "azerbaijano", + "subtitleLanguageBa": "bashkir", + "subtitleLanguageBe": "bielorrusso", + "subtitleLanguageBg": "búlgaro", + "subtitleLanguageBn": "bengali", + "subtitleLanguageBr": "bretão", + "subtitleLanguageBs": "bósnio", + "subtitleLanguageCa": "catalão", + "subtitleLanguageCeb": "cebuano", + "subtitleLanguageCs": "tcheco", + "subtitleLanguageCy": "galês", + "subtitleLanguageDa": "dinamarquês", + "subtitleLanguageDe": "alemão", + "subtitleLanguageEl": "grego", + "subtitleLanguageEn": "inglês", + "subtitleLanguageEs": "espanhol", + "subtitleLanguageEt": "estoniano", + "subtitleLanguageFa": "persa", + "subtitleLanguageFf": "fula", + "subtitleLanguageFi": "finlandês", + "subtitleLanguageFr": "francês", + "subtitleLanguageFy": "frísio ocidental", + "subtitleLanguageGa": "irlandês", + "subtitleLanguageGd": "gaélico escocês", + "subtitleLanguageGl": "galego", + "subtitleLanguageGu": "guzerate", + "subtitleLanguageHa": "hauçá", + "subtitleLanguageHe": "hebraico", + "subtitleLanguageHi": "hindi", + "subtitleLanguageHr": "croata", + "subtitleLanguageHt": "haitiano", + "subtitleLanguageHu": "húngaro", + "subtitleLanguageHy": "armênio", + "subtitleLanguageId": "indonésio", + "subtitleLanguageIg": "igbo", + "subtitleLanguageIlo": "ilocano", + "subtitleLanguageIs": "islandês", + "subtitleLanguageIt": "italiano", + "subtitleLanguageJa": "japonês", + "subtitleLanguageJv": "javanês", + "subtitleLanguageKa": "georgiano", + "subtitleLanguageKk": "cazaque", + "subtitleLanguageKm": "khmer", + "subtitleLanguageKn": "canarim", + "subtitleLanguageKo": "coreano", + "subtitleLanguageLb": "luxemburguês", + "subtitleLanguageLg": "luganda", + "subtitleLanguageLn": "lingala", + "subtitleLanguageLo": "laosiano", + "subtitleLanguageLt": "lituano", + "subtitleLanguageLv": "letão", + "subtitleLanguageMg": "malgaxe", + "subtitleLanguageMk": "macedônio", + "subtitleLanguageMl": "malaiala", + "subtitleLanguageMn": "mongol", + "subtitleLanguageMr": "marati", + "subtitleLanguageMs": "malaio", + "subtitleLanguageMy": "birmanês", + "subtitleLanguageNe": "nepalês", + "subtitleLanguageNl": "holandês", + "subtitleLanguageNo": "norueguês", + "subtitleLanguageNs": "soto setentrional", + "subtitleLanguageOc": "occitânico", + "subtitleLanguageOr": "oriá", + "subtitleLanguagePa": "panjabi", + "subtitleLanguagePl": "polonês", + "subtitleLanguagePs": "pashto", + "subtitleLanguagePt": "português", + "subtitleLanguageRo": "romeno", + "subtitleLanguageRu": "russo", + "subtitleLanguageSd": "sindi", + "subtitleLanguageSi": "cingalês", + "subtitleLanguageSk": "eslovaco", + "subtitleLanguageSl": "esloveno", + "subtitleLanguageSo": "somali", + "subtitleLanguageSq": "albanês", + "subtitleLanguageSr": "sérvio", + "subtitleLanguageSs": "suázi", + "subtitleLanguageSu": "sundanês", + "subtitleLanguageSv": "sueco", + "subtitleLanguageSw": "suaíli", + "subtitleLanguageTa": "tâmil", + "subtitleLanguageTh": "tailandês", + "subtitleLanguageTl": "tagalo", + "subtitleLanguageTn": "tswana", + "subtitleLanguageTr": "turco", + "subtitleLanguageUk": "ucraniano", + "subtitleLanguageUr": "urdu", + "subtitleLanguageUz": "uzbeque", + "subtitleLanguageVi": "vietnamita", + "subtitleLanguageWo": "uolofe", + "subtitleLanguageXh": "xhosa", + "subtitleLanguageYi": "iídiche", + "subtitleLanguageYo": "iorubá", + "subtitleLanguageYue": "cantonês", + "subtitleLanguageZh": "chinês", + "subtitleLanguageZu": "zulu", + "linearRec2020": "Rec.2020 linear", + "diagnostics": "Diagnóstico", + "exportDiagnostics": "Exportar pacote de diagnóstico", + "exportDiagnosticsFailed": "Não foi possível exportar o diagnóstico. Tente novamente.", + "exportDiagnosticsSucceeded": "Pacote de diagnóstico salvo." +} diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb new file mode 100644 index 0000000..86c7a30 --- /dev/null +++ b/lib/l10n/app_ru.arb @@ -0,0 +1,889 @@ +{ + "projectsNone": "Нет проектов", + "agentConversations": "Диалоги", + "renameConversationTitle": "Переименовать чат", + "renameConversationDescription": "Выберите короткое и узнаваемое название.", + "showMoreConversations": "Показать ещё", + "showFewerConversations": "Показать меньше", + "agentNewConversation": "Новый диалог", + "agentElapsedTime": "Время {duration}", + "agentConversationActions": "Действия с диалогом", + "agentMoveToTrash": "Переместить в корзину", + "agentTrash": "Корзина", + "agentRestore": "Восстановить", + "agentEmptyTrash": "Очистить корзину", + "agentDeleteForever": "Удалить навсегда", + "agentConversationLocation": "Расположение диалогов", + "agentChooseExistingConversations": "Выбрать существующие диалоги", + "agentMoveConversations": "Переместить диалоги", + "agentLocationUnavailable": "Расположение диалогов недоступно", + "agentLocationBusy": "Дождитесь завершения активных диалогов", + "agentRelinkProvider": "Повторно связать провайдера", + "@@locale": "ru", + "settings": "Настройки", + "closeSettings": "Закрыть настройки", + "general": "Общие", + "appearance": "Оформление", + "theme": "Тема", + "system": "Как в системе", + "light": "Светлая", + "dark": "Тёмная", + "saveAppearanceFailed": "Не удалось сохранить внешний вид. Пожалуйста, попробуйте еще раз.", + "loadAppearanceFailed": "Не удалось загрузить внешний вид. Пожалуйста, выберите тему еще раз.", + "cancel": "Отмена", + "save": "Сохранить", + "create": "Создать", + "close": "Закрыть", + "retry": "Повторить", + "name": "Имя", + "enterName": "Введите имя", + "invalidName": "Имена не могут содержать разделители путей или управляющие символы.", + "projectName": "Название проекта", + "newProject": "Новый проект", + "openProject": "Открыть проект", + "openProjectMore": "Открыть другой проект", + "projects": "Проекты", + "projectsEmpty": "Нет проектов", + "openingWorkspace": "Открытие рабочего пространства…", + "loadProjectsFailed": "Не удалось загрузить проекты", + "backToProjects": "Вернуться к монтажу", + "timelines": "Таймлайны", + "timelineLimitReached": "В каждом проекте может быть не более {count} таймлайнов.", + "timelineName": "Название таймлайна", + "defaultTimelineName": "Таймлайн {index}", + "newTimeline": "Новый таймлайн", + "noTimelines": "Нет таймлайнов", + "activeTimeline": "Текущий таймлайн", + "timelineUnavailable": "Таймлайн недоступен", + "projectNoTimelines": "В этом проекте пока нет таймлайнов", + "createTimelineHint": "Создайте таймлайн в разделе «Таймлайны» слева, чтобы начать монтаж.", + "createTimelineChat": "Создайте таймлайн, чтобы начать чат", + "editingFirstLayout": "Монтаж в приоритете", + "agentEditingLayout": "Агент и монтаж", + "agentLayoutDescription": "Планирование, совместная работа и выполнение", + "editingLayoutDescription": "Просмотр, монтаж и доработка", + "saveHere": "Сохранить здесь", + "selectDirectoryFailed": "Не удалось выбрать каталог. Проверьте системные разрешения.", + "operationFailed": "Операция не удалась. Пожалуйста, попробуйте еще раз.", + "collapseSidebar": "Свернуть боковую панель", + "expandSidebar": "Развернуть боковую панель", + "expandEditor": "Развернуть область монтажа", + "collapseProperties": "Свернуть свойства", + "expandProperties": "Развернуть свойства", + "layout": "Компоновка", + "materials": "Медиа", + "all": "Все", + "video": "Видео", + "audio": "Аудио", + "image": "Изображение", + "picture": "Изображение", + "captions": "Субтитры", + "text": "Текст", + "noMedia": "Нет медиа", + "mediaCategory": "Категория медиа", + "captionTasks": "Задачи субтитров", + "listLayout": "Просмотр списка", + "gridLayout": "Представление в виде сетки", + "addToTimeline": "Добавить на таймлайн", + "rename": "Переименовать", + "renameMedia": "Переименовать медиа", + "removeMedia": "Удалить медиа", + "remove": "Удалить", + "revealFinder": "Показать в Finder", + "revealFileManager": "Показать в файловом менеджере", + "dropToAdd": "Отпустите, чтобы добавить", + "timelineDropToStart": "Перетащите медиафайлы сюда, чтобы начать.", + "dragMediaHint": "Перетащите сюда видео, аудио или изображения.\nИсходные файлы остаются в своем текущем местоположении.", + "transcribe": "Транскрибировать", + "generateCaptions": "Создать субтитры", + "play": "Воспроизвести", + "pause": "Пауза", + "retryPreview": "Повторить предварительный просмотр", + "canvasRatio": "Соотношение сторон", + "noPreviewContent": "На временной шкале нет контента для предварительного просмотра.", + "nativePreviewUnsupported": "Нативная предварительная версия недоступна на этой платформе.", + "canvasTransformFailed": "Не удалось трансформировать полотно. Пожалуйста, попробуйте еще раз.", + "undo": "Отменить", + "redo": "Повторить", + "deleteSelectedClips": "Удалить выбранные клипы", + "splitAtPlayhead": "Разделить по точке воспроизведения", + "trimLeft": "Обрезать слева", + "trimRight": "Обрезать справа", + "trimLeftTooltip": "Удалить слева от курсора, сохранив правую часть", + "trimRightTooltip": "Удалить справа от курсора, сохранив левую часть", + "currentSequence": "Текущая секвенция", + "projectProperties": "Свойства проекта", + "canvasSize": "Размер холста", + "frameRate": "Частота кадров", + "duration": "Продолжительность", + "totalDuration": "Общая продолжительность", + "clipDuration": "Продолжительность клипа", + "seconds": "сек.", + "clip": "Клип", + "unnamedClip": "Безымянный клип", + "gap": "Промежуток", + "compoundClip": "Составной клип", + "textClip": "Текстовый клип", + "pictureProperties": "Изображение", + "position": "Позиция", + "rotation": "Вращение", + "scale": "Масштаб", + "size": "Размер", + "transform": "Преобразование", + "resetPosition": "Сбросить позицию", + "keepAspectRatio": "Блокировка соотношения сторон", + "alignment": "Выравнивание", + "alignLeft": "Выровнять по левому краю", + "alignRight": "Выровнять справа", + "alignTop": "Выровнять по верху", + "alignBottom": "Выровнять низ", + "alignHorizontalCenter": "Центрировать по горизонтали", + "alignVerticalCenter": "Центрировать по вертикали", + "volume": "Громкость", + "gain": "Усиление", + "mute": "Отключить звук", + "unmute": "Включить звук", + "resetVolume": "Сбросить громкость", + "invalidGain": "Введите значение от -90 до +12.", + "animation": "Анимация", + "keyframes": "Ключевые кадры", + "removeAllKeyframes": "Удалить все ключевые кадры", + "linear": "Линейная", + "easeIn": "Плавное ускорение", + "easeOut": "Плавное замедление", + "easeInOut": "Плавное ускорение и замедление", + "basic": "Основные", + "mask": "Маска", + "addMask": "Добавить маску", + "deleteMask": "Удалить маску", + "resetMask": "Сбросить маску", + "enableMask": "Включить маску", + "disableMask": "Отключить маску", + "moveMaskUp": "Переместить маску вверх", + "moveMaskDown": "Переместить маску вниз", + "rectangle": "Прямоугольник", + "ellipse": "Эллипс", + "invert": "Инвертировать", + "feather": "Растушёвка", + "add": "Сложение", + "subtract": "Вычитание", + "intersect": "Пересечение", + "initialRegion": "Начальная область", + "none": "Нет", + "color": "Цвет", + "fontSize": "Размер шрифта", + "outlineWidth": "Толщина контура", + "outlineColor": "Цвет контура", + "captionBaseline": "Базовая линия субтитров", + "content": "Текст", + "start": "Начало", + "time": "Время", + "speed": "Скорость", + "speedSegmentCount": "Сегментов скорости: {count}", + "splitSpeedAtPlayhead": "Разделить скорость на позиции указателя", + "speedChange": "Скорость", + "speedMode": "Режим скорости", + "constantSpeed": "Постоянная скорость", + "segmentedSpeed": "Сегментированная скорость", + "speedNotAvailable": "Регулировка скорости пока недоступна.", + "custom": "Настраиваемый", + "invalidNumber": "Недопустимое значение", + "mediaUnavailable": "Медиа недоступно", + "mediaMissing": "Медиа отсутствует", + "mediaColorSpace": "Цветовое пространство мультимедиа", + "mediaColorInterpretation": "Интерпретация цвета медиа", + "colorInfoNotLoaded": "Информация о цвете не загружена", + "unknownColorSpace": "Неизвестное цветовое пространство. Отображается как Rec.709.", + "colorBackendUnsupported": "Текущая серверная часть не поддерживает интерпретацию цвета мультимедиа.", + "loadClipPropertiesFailed": "Не удалось прочитать свойства клипа.", + "updatePictureFailed": "Не удалось обновить свойства изображения.", + "updateVolumeFailed": "Не удалось изменить громкость", + "updateMaskFailed": "Не удалось обновить маску", + "updateKeyframesFailed": "Не удалось обновить ключевые кадры", + "maskPreviewFailed": "Не удалось подготовить предварительный просмотр маски.", + "alignClipFailed": "Не удалось выровнять клип. Подождите предварительного просмотра и повторите попытку.", + "invalidTransform": "Масштаб должен быть 1–10 000 %. Позиция и угол должны быть допустимыми числами.", + "editFailed": "Не удалось отредактировать. Проверьте ввод и временной диапазон.", + "addMediaFailed": "Не удалось добавить медиа. Пожалуйста, попробуйте еще раз.", + "deleteCaption": "Удалить субтитр", + "mergeCaptions": "Объединить субтитры", + "captionDeleted": "Субтитр удалён", + "captionChanged": "Субтитры изменились. Пожалуйста, попробуйте еще раз.", + "captionEditChanged": "Субтитры изменились. Пожалуйста, отредактируйте еще раз.", + "assistantHint": "Опишите свою идею редактирования", + "configureAgentHint": "Настройте службу агента, чтобы начать общение", + "agentRestartHint": "Настройте службу агента, затем перезапустите приложение.", + "replyInterrupted": "Ответ прерван", + "replying": "Подготовка ответа…", + "stopReply": "Остановить ответ", + "sendMessage": "Отправить сообщение", + "addAttachment": "Добавить вложение (пока недоступно)", + "replyFailed": "Ответ не удался. Проверьте соединение или повторите попытку позже.", + "mcpService": "MCP-сервис", + "listenPort": "Порт", + "accessToken": "Токен доступа", + "copyAccessToken": "Копировать токен доступа", + "accessTokenCopied": "Токен доступа скопирован.", + "loadMcpFailed": "Не удалось загрузить настройки MCP. Повторить попытку", + "saveMcpFailed": "Не удалось сохранить настройки MCP. Пожалуйста, попробуйте еще раз.", + "retryStart": "Повторить попытку запуска", + "invalidPort": "Порт должен быть в диапазоне от 1 до 65535.", + "loadingSettings": "Загрузка настроек…", + "starting": "Запуск…", + "stopping": "Остановка…", + "disabled": "Отключено", + "running": "Работает", + "startFailed": "Не удалось запустить", + "saved": "Сохранено", + "unsaved": "несохраненный", + "saving": "Сохранение…", + "pendingSave": "Ожидание сохранения", + "notApplied": "Не применено", + "enable": "Включить", + "disable": "Отключить", + "type": "Тип", + "status": "Статус", + "file": "Файл", + "unboundMedia": "Медиа не привязано", + "unboundAudio": "Аудиодорожка не привязана", + "vertical": "Вертикально", + "language": "Язык", + "saveLanguageFailed": "Не удалось сохранить язык. Пожалуйста, попробуйте еще раз.", + "loadLanguageFailed": "Не удалось загрузить язык. Пожалуйста, выберите еще раз.", + "propertiesFirstLayout": "Свойства в первую очередь", + "defaultLayout": "Макет по умолчанию", + "separateVocals": "Отделить вокал", + "detachAudio": "Отделить аудио", + "restoreAudio": "Восстановить аудио", + "audioDetached": "Аудио отделено", + "addAll": "Добавить всё", + "preparingMedia": "Подготовка медиа…", + "cancelling": "Отмена…", + "cancelled": "Отменено", + "interruptedTask": "Задача прервана. Перезапустите, чтобы продолжить", + "auto": "Автоматически", + "autoDetect": "Определить автоматически", + "noTranslation": "Не переводить", + "sourceLanguage": "Исходный язык", + "translationLanguage": "Язык перевода", + "transcriptionNotConfigured": "Транскрипция не настроена. Установите компонент распознавания и модель Whisper Turbo.", + "translationNotConfigured": "Перевод титров не настроен. Вы можете создавать субтитры на исходном языке.", + "sourceLanguageUnknown": "Не удалось определить исходный язык для перевода.", + "startTranscriptionFailed": "Не удалось начать транскрипцию. Проверьте носитель или дождитесь завершения текущей задачи.", + "placeMediaFirst": "Поместите этот медиафайл на временную шкалу перед применением субтитров.", + "placeTranslationMediaFirst": "Прежде чем применять переведенные субтитры, поместите соответствующие медиафайлы на временную шкалу.", + "selectTargetClip": "Выберите целевой клип", + "timelineChanged": "Временная шкала изменилась. Снова выберите целевой клип.", + "transcriptionAccessFailed": "Ошибка транскрипции: компонент, модель или исходный носитель недоступны (notConfigured)", + "transcriptionNoAudio": "Ошибка транскрипции: на выбранном носителе или дорожке нет распознаваемого звука (noAudio)", + "transcriptionInvalidResult": "Ошибка транскрипции: возвращен недопустимый файл субтитров (invalidResult)", + "transcriptionWorkerExited": "Транскрипция не удалась: компонент распознавания неожиданно завершил работу (workerExited)", + "transcriptionProcessingFailed": "Ошибка транскрипции: ошибка встроенной обработки (processingFailed)", + "transcriptionFailed": "Транскрипция не удалась. Проверьте компонент, модель, звуковую дорожку и продолжительность.", + "transcribing": "Транскрибирование…", + "captionsGenerated": "Субтитры созданы", + "cancelTranscription": "Отменить транскрибирование", + "applyCaptions": "Применить субтитры", + "preparingTranslation": "Подготовка перевода…", + "translatingCaptions": "Перевод субтитров…", + "cancellingTranslation": "Отмена перевода…", + "translatedCaptionsGenerated": "Переведённые субтитры созданы", + "translationCancelled": "Перевод отменён", + "translationInterrupted": "Перевод прерван", + "cancelTranslation": "Отменить перевод", + "editorServiceUnavailable": "Сервис редактирования недоступен. Снова откройте проект.", + "mcpUnavailable": "Соединение MCP недоступно. Проверьте локальный порт и токен.", + "openTimelineFailed": "Не удалось открыть хронологию", + "noTimelineSequence": "В этом таймлайне нет секвенции.", + "waitingForProject": "Ждем открытия проекта", + "hold": "Удержание", + "noImportableFiles": "Импортируемые файлы не получены", + "virtualFilesUnsupported": "Перетащите оригинальные файлы из файлового менеджера. Виртуальные файлы пока не поддерживаются.", + "editorSessionStartFailed": "Не удалось открыть редактор таймлайна", + "previewStartFailed": "Не удалось запустить встроенный предварительный просмотр.", + "previewInvalidTrack": "Выбранная аудио- или видеодорожка не существует на носителе.", + "previewMissingBinding": "Привязки мультимедиа отсутствуют. Не удалось просмотреть эту хронологию.", + "previewUnsupportedEdits": "Эта временная шкала содержит изменения, которые еще не поддерживаются предварительной версией.", + "previewUnsupportedConfiguration": "Эта предварительная конфигурация не поддерживается на текущей платформе или версии системы.", + "previewHdrUnsupported": "Для мультимедиа HDR требуется тональная компрессия для предварительного просмотра SDR. Текущая система или предварительная конфигурация не поддерживают его.", + "previewAudioOutOfRange": "Аудиоклип выходит за пределы диапазона исходной дорожки и не может быть просмотрен.", + "previewResourceMissing": "Предварительный просмотр носителя больше не существует. Снова найдите исходный файл.", + "previewInvalidComposition": "Неверная конфигурация композиции видео. Не удалось создать предварительный просмотр.", + "previewInvalidData": "Неверные данные предварительного просмотра. Пожалуйста, попробуйте еще раз.", + "previewFailed": "Предварительный просмотр не удался. Проверьте доступ к мультимедиа и повторите попытку.", + "chatFailed": "Не удалось завершить разговор. Проверьте конфигурацию службы или повторите попытку позже.", + "delete": "Удалить", + "pinTimeline": "Закрепить таймлайн", + "unpinTimeline": "Открепить таймлайн", + "deleteTimelineConfirmation": "Удалить «{name}» и историю изменений? Это действие нельзя отменить.", + "@deleteTimelineConfirmation": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "processingFailed": "Ошибка обработки", + "noMatchingOptions": "Нет подходящих вариантов", + "removeMediaConfirmation": "Удалить «{name}» из библиотеки? Существующие клипы, история и исходный файл будут сохранены.", + "@removeMediaConfirmation": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "mediaAdded": "Добавлено ссылок на медиа: {count}", + "@mediaAdded": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "duplicatesSkipped": "Пропущены дубликаты файлов {count}.", + "@duplicatesSkipped": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mediaCount": "Медиа: {count}", + "importMedia": "Импортировать", + "@mediaCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "noMediaOfType": "Нет носителя {type}", + "@noMediaOfType": { + "placeholders": { + "type": { + "type": "String" + } + } + }, + "captionsImported": "Импортированные субтитры {count}.", + "@captionsImported": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "editCaptionError": "Не удалось редактировать субтитры: {message}.", + "@editCaptionError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "mcpStartError": "Не удалось запустить MCP: {message}.", + "@mcpStartError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "manualColorSpace": "Выбрано вручную: {name}", + "@manualColorSpace": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "detectedColorSpace": "Обнаружено: {name}", + "@detectedColorSpace": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "keyframeLabel": "Ключевой кадр: {channel}", + "@keyframeLabel": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "maskMode": "Комбинированный режим: {mode}", + "@maskMode": { + "placeholders": { + "mode": { + "type": "String" + } + } + }, + "keyframeCount": "Ключевых кадров: {count}", + "@keyframeCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "toggleKeyframe": "{action} ключевой кадр: {channel}", + "@toggleKeyframe": { + "placeholders": { + "action": { + "type": "String" + }, + "channel": { + "type": "String" + } + } + }, + "previousKeyframe": "Предыдущий ключевой кадр: {channel}", + "@previousKeyframe": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "nextKeyframe": "Следующий ключевой кадр: {channel}", + "@nextKeyframe": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "keyframeSettings": "Настройки ключевых кадров: {channel}", + "@keyframeSettings": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "selectedClipsHint": "Выбраны клипы {count}.\nВыберите один клип, чтобы просмотреть его свойства.", + "@selectedClipsHint": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "transcriptionError": "Транскрипция не удалась. Проверьте компонент, модель, звуковую дорожку и продолжительность ({code})", + "@transcriptionError": { + "placeholders": { + "code": { + "type": "String" + } + } + }, + "captionsAdded": "Добавлены субтитры {count}. Отредактируйте их на панели свойств.", + "@captionsAdded": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "translatedCaptionsAdded": "Добавлены переведенные субтитры {count}. Отредактируйте их на панели свойств.", + "@translatedCaptionsAdded": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "applyCaptionsError": "Не удалось применить субтитры: {message}.", + "@applyCaptionsError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "applyTranslatedCaptionsError": "Не удалось применить переведенные субтитры: {message}.", + "@applyTranslatedCaptionsError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "recognizedCaptions": "Распознано субтитров: {count}", + "@recognizedCaptions": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "captionCount": "Субтитров: {count}", + "@captionCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "translationFailed": "Ошибка перевода: {message}", + "@translationFailed": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "translatedCaptionCount": "Субтитров: {count} ({language})", + "@translatedCaptionCount": { + "placeholders": { + "count": { + "type": "int" + }, + "language": { + "type": "String" + } + } + }, + "previewParameterError": "Неверные параметры предварительного просмотра: {message}.", + "@previewParameterError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "mediaOffline": "Мультимедиа не в сети или недоступно: {names}", + "@mediaOffline": { + "placeholders": { + "names": { + "type": "String" + } + } + }, + "searchOptions": "Поиск {label}…", + "@searchOptions": { + "placeholders": { + "label": { + "type": "String" + } + } + }, + "loadRecentProjectsFailed": "Не удалось загрузить последние библиотеки. Вы по-прежнему можете открыть библиотеку вручную.", + "projectAccessFailed": "Проект недоступен", + "projectMissingDirectory": "Проект не найден", + "recentProjectSaveFailed": "Библиотека открылась, но недавнюю запись библиотеки сохранить не удалось.", + "lastProjectSaveFailed": "Проект открыт, но последнюю запись проекта сохранить не удалось.", + "enterProjectName": "Введите название проекта", + "projectSwitched": "Проект изменился. Перетащите медиа снова.", + "notLocalMedia": "Этот носитель не является локальным файлом", + "revealMediaFailed": "Не удалось отобразить медиафайлы в файловом менеджере.", + "openMatchingProject": "Сначала откройте соответствующий проект", + "projectMismatch": "Библиотека по этому адресу не соответствует записи. Выберите его еще раз с помощью команды «Открыть библиотеку».", + "openProjectFirst": "Сначала откройте библиотеку", + "localFilesOnly": "Перетащите локальные файлы из файлового менеджера", + "foldersUnsupported": "Выберите файлы. Перетаскивание папок пока не поддерживается.", + "mediaImportCancelled": "Импорт мультимедиа отменен", + "fileAccessFailed": "Файл отсутствует или не читается. Проверьте его местоположение и разрешения", + "registerMediaFailed": "Не удалось зарегистрировать носитель. Пожалуйста, попробуйте еще раз", + "mediaNoLongerExists": "медиа больше не существует", + "mediaNoTracks": "В медиафайле нет пригодных для использования видео- или аудиодорожек.", + "invalidMediaDuration": "Неверная продолжительность медиа.", + "mediaInfoUnsupported": "Чтение медиаинформации пока не поддерживается на этой платформе.", + "mediaInfoFailed": "Не удалось прочитать медиа-информацию. Проверьте файл и права доступа", + "saveTimelineFailed": "Не удалось сохранить хронологию. Попробуйте еще раз. Несохраненные изменения остаются в этом сеансе.", + "addKeyframeAction": "Добавить", + "backgroundTasks": "Фоновые задачи", + "noBackgroundTasks": "Нет фоновых задач", + "retryTask": "Повторить", + "applyOriginalCaptions": "Применить исходные субтитры", + "applyTranslatedCaptions": "Применить переведённые субтитры", + "subtitleTaskStarted": "Создание субтитров начато", + "fitTimeline": "Показать всю временную шкалу", + "modify": "Modify", + "projectSettings": "Project settings", + "projectSettingsDescription": "Change project output settings while keeping clip timing and speed.", + "projectColorSpace": "Color space", + "projectWidth": "Width (px)", + "projectHeight": "Height (px)", + "projectResolutionInvalid": "Enter a whole number from 1 to 16384", + "previewFullscreen": "Полноэкранный просмотр", + "exitPreviewFullscreen": "Выйти из полноэкранного режима", + "previewGoToStart": "В начало", + "previewPreviousFrame": "Предыдущий кадр", + "previewNextFrame": "Следующий кадр", + "softwareUpdates": "Обновления", + "checkForUpdates": "Проверить обновления", + "automaticallyCheckUpdates": "Проверять обновления автоматически", + "updatesUnavailable": "В этой сборке обновления недоступны.", + "updateCheckFailed": "Не удалось проверить обновления. Повторите попытку.", + "agentSettings": "Агент", + "agentSaveSettingsFailed": "Не удалось сохранить настройки агента.", + "agentDeleteProviderTitle": "Удалить провайдера?", + "agentDeleteProviderDescription": "«{providerName}» и сохранённый ключ API будут удалены с этого устройства.", + "agentProviderRequired": "Добавьте провайдера, прежде чем включать помощника.", + "agentUseSelectedModel": "Новые запросы агента будут использовать выбранную модель.", + "agentEnable": "Включить агента", + "agentDefaultModel": "Модель по умолчанию", + "agentConfigureModel": "Настроить модели", + "agentSelectModel": "Выбрать модель", + "agentModelUnavailable": "Модель этого диалога недоступна. Выберите другую модель, чтобы начать новый диалог.", + "agentModelChangeSession": "При смене модели начинается новый сеанс агента.", + "agentCustomProviders": "Пользовательские провайдеры", + "agentProviderStorageDescription": "Метаданные провайдера хранятся локально. Ключи API сохраняются в системном хранилище учётных данных.", + "agentAddProvider": "Добавить провайдера", + "agentBackToProviders": "Назад к провайдерам", + "agentLoadSettingsFailed": "Не удалось загрузить настройки агента. Повторить", + "agentEnableProvider": "Включить провайдера", + "agentEditProvider": "Изменить провайдера", + "agentDeleteProvider": "Удалить провайдера", + "agentModelIdsUnique": "Идентификаторы моделей должны быть уникальными.", + "agentEditProviderTitle": "Изменить провайдера", + "agentProviderEndpointDescription": "Настройте конечную точку Chat Completions, совместимую с OpenAI.", + "agentSaveProvider": "Сохранить провайдера", + "agentProviderConfiguration": "Настройка провайдера", + "agentAuthenticationAndModels": "Аутентификация и модели", + "agentApiType": "Тип API", + "agentOpenAiChatCompletions": "OpenAI Completions", + "agentBaseUrl": "Базовый URL", + "agentApiKey": "Ключ API", + "agentProviderNameHint": "Мой провайдер", + "agentApiKeyOptional": "Необязательно для конечных точек без аутентификации.", + "agentApiKeyKeep": "Оставьте поле пустым, чтобы сохранить текущий ключ.", + "agentOptional": "Необязательно", + "agentApiKeyOneLine": "Ключ API должен занимать одну строку.", + "agentRemoveSavedApiKey": "Удалить сохранённый ключ API", + "agentModels": "Модели", + "agentAddModel": "Добавить модель", + "agentRequiredField": "Это поле обязательно.", + "agentInvalidBaseUrl": "Введите базовый URL HTTP(S) без учётных данных, строки запроса и фрагмента.", + "agentModelId": "Идентификатор модели", + "agentContextWindow": "Контекстное окно", + "agentMaxOutputTokens": "Максимальный вывод", + "agentMaxOutputBelowContext": "Значение должно быть меньше контекстного окна.", + "agentDeleteModel": "Удалить модель", + "agentPositiveInteger": "Введите положительное целое число.", + "agentConfigurationReadFailed": "Не удалось прочитать конфигурацию агента. Проверьте настройки и повторите попытку.", + "agentConfigurationRequired": "Сначала настройте и включите агента в настройках.", + "agentSessionRestoreFailed": "Не удалось восстановить сеанс агента. Повторите попытку позже.", + "select": "Выбрать", + "projectLocation": "Место сохранения проектов", + "projectLocationNotSet": "Не задано", + "resourceLocation": "Место хранения ресурсов", + "resourceLocationNotSet": "Не задано", + "loadProjectLocationFailed": "Не удалось загрузить место сохранения проектов.", + "saveProjectLocationFailed": "Не удалось сохранить место для проектов.", + "loadResourceLocationFailed": "Не удалось загрузить место хранения ресурсов.", + "saveResourceLocationFailed": "Не удалось сохранить место для ресурсов.", + "downloadAndContinue": "Скачать и продолжить", + "downloadInBackground": "Скачать в фоновом режиме", + "downloadingResource": "Скачивание…", + "processingResourceDownloadFailed": "Не удалось скачать ресурс распознавания речи. Повторите попытку.", + "transcriptionResourceRequired": "Для создания субтитров сначала необходимо скачать модель распознавания речи.", + "removeBackground": "Удалить фон", + "startBackgroundRemoval": "Удалить фон", + "backgroundRemovalResourceRequired": "Для удаления фона нужна локальная модель. После загрузки обработка начнётся автоматически.", + "backgroundRemovalDownloadTask": "Загрузить ресурс удаления фона", + "backgroundRemovalResourceName": "Модель удаления фона", + "backgroundRemovalTaskStarted": "Удаление фона запущено", + "backgroundRemovalApplying": "Замена медиафайла клипа", + "backgroundRemovalComplete": "Удаление фона завершено", + "backgroundRemovalFailed": "Не удалось удалить фон", + "backgroundRemovalDestructiveHint": "Созданный медиафайл с прозрачным фоном заменит этот клип. Исходный клип можно восстановить командой «Отменить».", + "startBackgroundRemovalFailed": "Не удалось начать удаление фона. Проверьте медиафайл или дождитесь завершения текущей задачи обработки.", + "agentContextBudgetExceeded": "Недостаточно места для системных инструкций, инструментов и сообщения. Увеличьте контекст или уменьшите максимальный вывод.", + "agentAuthenticationFailed": "Ошибка авторизации. Проверьте API Key и разрешения.", + "agentConnectionFailed": "Ошибка подключения или тайм-аут. Проверьте Base URL и сеть.", + "agentProtocolFailed": "Ответ не соответствует выбранному типу API или поток неполный.", + "agentContextBudgetTooSmall": "Оставьте больше места для инструкций. Увеличьте контекст или уменьшите максимальный вывод.", + "agentCompacting": "Упорядочивание контекста…", + "agentEditing": "Редактирование…", + "agentVerifying": "Проверка результатов…", + "agentTurnLimitReached": "Достигнут лимит выполнения задачи. Изменения сохранены. Отправьте «Продолжить», чтобы возобновить.", + "agentRecoveryRequired": "Результат предыдущей операции не подтверждён. Продолжите для проверки сохранённых записей; неподтверждённые изменения не будут повторены.", + "agentExportReplyFailed": "Видео экспортировано. Не удалось получить итоговый ответ. Повторите запрос итога без повторного монтажа или экспорта.", + "agentRetrySummary": "Повторить итог", + "agentResumeTask": "Продолжить задачу", + "agentTaskInterrupted": "Задача прервана. Продолжите с сохранённого состояния.", + "downloadSubtitleModel": "Скачать модель субтитров", + "downloadModelAction": "Скачать", + "subtitleEngineUnavailable": "Модель установлена, но движок субтитров не запустился. Исправьте движок; повторно скачивать модель не нужно.", + "backgroundTaskDetails": "Сведения о задаче", + "backgroundTaskFailed": "Ошибка", + "backgroundTaskCompleted": "Завершено", + "captionWrapLines": "Переносить текст субтитров", + "captionSingleLine": "Показывать субтитры в одну строку", + "noMatchingCaptions": "Нет подходящих субтитров", + "subtitleResourcesRequired": "Эти ресурсы нужны для субтитров. После загрузки создание начнётся автоматически.", + "subtitleResourcesDownloadSize": "Объём загрузки: {size}", + "pauseDownload": "Пауза", + "resumeDownload": "Продолжить", + "downloadPaused": "Приостановлено", + "cancelResourceDownloadTitle": "Отменить загрузку?", + "cancelResourceDownloadMessage": "Загрузка остановится. Прогресс загрузки текущего ресурса может быть потерян.", + "continueDownload": "Продолжить загрузку", + "cancelDownload": "Отменить загрузку", + "speechResourceStage": "Ресурс распознавания речи", + "translationResourceStage": "Ресурс перевода", + "subtitleResourceDownloadTask": "Загрузить ресурсы распознавания речи и перевода", + "downloadingSpeechModel": "Загрузка речевой модели", + "downloadingTranslationModel": "Загрузка модели перевода", + "selectProject": "Выбрать проект", + "searchProjects": "Поиск проектов", + "noMatchingProjects": "Подходящих проектов нет", + "projectLocationMissing": "Папка не существует. Она будет создана при создании проекта.", + "projectLocationUnavailable": "Место сохранения проекта недоступно. Подключите диск или проверьте сеть и повторите попытку либо выберите другое место.", + "projectLocationNotWritable": "Запись в место сохранения проекта невозможна. Проверьте разрешения или выберите другое место.", + "projectLocationCreateFailed": "Не удалось создать папку проекта или записать в неё данные. Проверьте разрешения или выберите другое место.", + "removeProjectFromSidebar": "Убрать с боковой панели", + "projectRemoved": "Проект убран. Локальные файлы и беседы сохранены.", + "agentNoConversations": "Бесед пока нет", + "collapseProject": "Свернуть проект", + "expandProject": "Развернуть проект", + "agentDeleteConfirmation": "Навсегда удалить «{title}» и все сообщения? Это действие нельзя отменить. Локальные файлы проекта не будут затронуты.", + "agentEmptyTrashConfirmation": "Навсегда удалить все беседы из корзины? Это действие нельзя отменить. Локальные файлы проекта не будут затронуты.", + "checkingForUpdates": "Проверка обновлений…", + "appIsUpToDate": "Установлена последняя версия.", + "downloadingUpdate": "Загрузка обновления: {progress}%", + "updateAvailable": "Доступна версия {version}.", + "downloadUpdate": "Скачать обновление", + "restartToUpdate": "Перезапустить и обновить", + "updateOperationFailed": "Не удалось обновить. Завершите активные задачи и повторите попытку.", + "windowMinimize": "Свернуть", + "windowMaximize": "Развернуть", + "windowRestore": "Восстановить", + "workspaceAgent": "Ассистент", + "workspaceCut": "Монтаж", + "noAvailableOptions": "Нет доступных вариантов", + "composerReferenceInvalid": "Ссылка больше недействительна. Вернитесь к её проекту или удалите её.", + "durationSeconds": "{seconds} с", + "durationMinutesSeconds": "{minutes} мин {seconds} с", + "projectNameInvalid": "Недопустимое имя проекта", + "projectLocationDefaultUnavailable": "Нет доступа к папке проектов по умолчанию. Выберите её заново в настройках.", + "chooseProjectLocation": "Сначала выберите папку для сохранения проектов в настройках.", + "untitledTimeline": "Таймлайн без названия", + "primarySequence": "Основная последовательность", + "primaryStoryline": "Основная линия", + "projectSessionClosed": "Сеанс проекта закрыт. Откройте проект заново.", + "timelineSessionClosed": "Сеанс таймлайна закрыт. Откройте таймлайн заново.", + "timelineMissing": "Таймлайн не существует или был удалён.", + "timelineInUse": "Таймлайн используется и пока не может быть удалён.", + "timelineHasBackgroundTasks": "Завершите фоновые задачи таймлайна перед удалением.", + "timelineRequired": "В проекте должен оставаться хотя бы один таймлайн.", + "mediaReadFailed": "Не удалось прочитать медиафайл", + "mediaImportFailed": "Не удалось импортировать медиафайл", + "unsupportedMediaType": "Можно импортировать только видео, аудио и изображения.", + "mediaNoVideoTracks": "В медиафайле нет доступной видеодорожки", + "mediaDurationOutOfRange": "Длительность медиафайла превышает диапазон таймлайна", + "resourceDownloadHttpFailed": "Ошибка загрузки (HTTP {statusCode})", + "resourceChecksumFailed": "Проверка файла модели не пройдена. Загрузите ресурс заново.", + "subtitleLanguageAf": "африкаанс", + "subtitleLanguageAm": "амхарский", + "subtitleLanguageAr": "арабский", + "subtitleLanguageAst": "астурийский", + "subtitleLanguageAz": "азербайджанский", + "subtitleLanguageBa": "башкирский", + "subtitleLanguageBe": "белорусский", + "subtitleLanguageBg": "болгарский", + "subtitleLanguageBn": "бенгальский", + "subtitleLanguageBr": "бретонский", + "subtitleLanguageBs": "боснийский", + "subtitleLanguageCa": "каталанский", + "subtitleLanguageCeb": "себуано", + "subtitleLanguageCs": "чешский", + "subtitleLanguageCy": "валлийский", + "subtitleLanguageDa": "датский", + "subtitleLanguageDe": "немецкий", + "subtitleLanguageEl": "греческий", + "subtitleLanguageEn": "английский", + "subtitleLanguageEs": "испанский", + "subtitleLanguageEt": "эстонский", + "subtitleLanguageFa": "персидский", + "subtitleLanguageFf": "фулах", + "subtitleLanguageFi": "финский", + "subtitleLanguageFr": "французский", + "subtitleLanguageFy": "западнофризский", + "subtitleLanguageGa": "ирландский", + "subtitleLanguageGd": "гэльский", + "subtitleLanguageGl": "галисийский", + "subtitleLanguageGu": "гуджарати", + "subtitleLanguageHa": "хауса", + "subtitleLanguageHe": "иврит", + "subtitleLanguageHi": "хинди", + "subtitleLanguageHr": "хорватский", + "subtitleLanguageHt": "гаитянский", + "subtitleLanguageHu": "венгерский", + "subtitleLanguageHy": "армянский", + "subtitleLanguageId": "индонезийский", + "subtitleLanguageIg": "игбо", + "subtitleLanguageIlo": "илоко", + "subtitleLanguageIs": "исландский", + "subtitleLanguageIt": "итальянский", + "subtitleLanguageJa": "японский", + "subtitleLanguageJv": "яванский", + "subtitleLanguageKa": "грузинский", + "subtitleLanguageKk": "казахский", + "subtitleLanguageKm": "кхмерский", + "subtitleLanguageKn": "каннада", + "subtitleLanguageKo": "корейский", + "subtitleLanguageLb": "люксембургский", + "subtitleLanguageLg": "ганда", + "subtitleLanguageLn": "лингала", + "subtitleLanguageLo": "лаосский", + "subtitleLanguageLt": "литовский", + "subtitleLanguageLv": "латышский", + "subtitleLanguageMg": "малагасийский", + "subtitleLanguageMk": "македонский", + "subtitleLanguageMl": "малаялам", + "subtitleLanguageMn": "монгольский", + "subtitleLanguageMr": "маратхи", + "subtitleLanguageMs": "малайский", + "subtitleLanguageMy": "бирманский", + "subtitleLanguageNe": "непальский", + "subtitleLanguageNl": "нидерландский", + "subtitleLanguageNo": "норвежский", + "subtitleLanguageNs": "северный сото", + "subtitleLanguageOc": "окситанский", + "subtitleLanguageOr": "ория", + "subtitleLanguagePa": "панджаби", + "subtitleLanguagePl": "польский", + "subtitleLanguagePs": "пушту", + "subtitleLanguagePt": "португальский", + "subtitleLanguageRo": "румынский", + "subtitleLanguageRu": "русский", + "subtitleLanguageSd": "синдхи", + "subtitleLanguageSi": "сингальский", + "subtitleLanguageSk": "словацкий", + "subtitleLanguageSl": "словенский", + "subtitleLanguageSo": "сомали", + "subtitleLanguageSq": "албанский", + "subtitleLanguageSr": "сербский", + "subtitleLanguageSs": "свази", + "subtitleLanguageSu": "сунданский", + "subtitleLanguageSv": "шведский", + "subtitleLanguageSw": "суахили", + "subtitleLanguageTa": "тамильский", + "subtitleLanguageTh": "тайский", + "subtitleLanguageTl": "тагалог", + "subtitleLanguageTn": "тсвана", + "subtitleLanguageTr": "турецкий", + "subtitleLanguageUk": "украинский", + "subtitleLanguageUr": "урду", + "subtitleLanguageUz": "узбекский", + "subtitleLanguageVi": "вьетнамский", + "subtitleLanguageWo": "волоф", + "subtitleLanguageXh": "коса", + "subtitleLanguageYi": "идиш", + "subtitleLanguageYo": "йоруба", + "subtitleLanguageYue": "кантонский", + "subtitleLanguageZh": "китайский", + "subtitleLanguageZu": "зулу", + "linearRec2020": "Линейный Rec.2020", + "diagnostics": "Диагностика", + "exportDiagnostics": "Экспортировать пакет диагностики", + "exportDiagnosticsFailed": "Не удалось экспортировать диагностику. Повторите попытку.", + "exportDiagnosticsSucceeded": "Пакет диагностики сохранён." +} diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb new file mode 100644 index 0000000..084adab --- /dev/null +++ b/lib/l10n/app_zh.arb @@ -0,0 +1,889 @@ +{ + "selectProject": "选择项目", + "searchProjects": "搜索项目", + "noMatchingProjects": "没有匹配的项目", + "projectsNone": "暂无项目", + "projectLocationMissing": "目录不存在,创建项目时将自动创建。", + "projectLocationUnavailable": "项目保存位置不可用,请连接磁盘或检查网络后重试,也可以更改位置。", + "projectLocationNotWritable": "项目保存位置没有写入权限,请检查权限或更改位置。", + "projectLocationCreateFailed": "无法创建或写入项目保存目录,请检查权限或更改位置。", + "removeProjectFromSidebar": "从侧边栏移除", + "projectRemoved": "已移除项目,本地文件和聊天记录已保留。", + "agentNoConversations": "暂无聊天", + "renameConversationTitle": "重命名聊天", + "renameConversationDescription": "保持简短且易于识别", + "collapseProject": "收起项目", + "expandProject": "展开项目", + "agentDeleteConfirmation": "聊天“{title}”及其消息记录将被永久删除,无法恢复。本地项目文件不受影响。", + "agentEmptyTrashConfirmation": "回收站中的所有聊天将被永久删除,无法恢复。本地项目文件不受影响。", + "agentConversations": "对话", + "showMoreConversations": "展开显示", + "showFewerConversations": "收起显示", + "agentNewConversation": "新建对话", + "agentElapsedTime": "用时 {duration}", + "agentConversationActions": "对话操作", + "agentMoveToTrash": "移至回收区", + "agentTrash": "回收区", + "agentRestore": "恢复", + "agentEmptyTrash": "清空回收区", + "agentDeleteForever": "永久删除", + "agentConversationLocation": "对话存储位置", + "agentChooseExistingConversations": "选择已有对话目录", + "agentMoveConversations": "移动对话", + "agentLocationUnavailable": "对话存储位置不可用", + "agentLocationBusy": "请等待当前对话运行结束后再移动", + "agentRelinkProvider": "重新关联 Provider", + "@@locale": "zh", + "settings": "设置", + "closeSettings": "关闭设置", + "general": "通用", + "appearance": "外观", + "theme": "主题", + "system": "跟随系统", + "light": "明亮", + "dark": "深色", + "saveAppearanceFailed": "无法保存外观设置,请重试", + "loadAppearanceFailed": "无法读取外观设置,请重新选择主题", + "cancel": "取消", + "save": "保存", + "create": "创建", + "close": "关闭", + "retry": "重试", + "select": "选择", + "name": "名称", + "enterName": "请输入名称", + "invalidName": "名称不能包含路径分隔符或控制字符", + "projects": "项目", + "projectName": "项目名称", + "projectLocation": "项目保存位置", + "projectLocationNotSet": "未设置", + "loadProjectLocationFailed": "无法读取项目保存位置。", + "saveProjectLocationFailed": "无法保存项目保存位置。", + "resourceLocation": "资源存储位置", + "resourceLocationNotSet": "未设置", + "loadResourceLocationFailed": "无法读取资源存储位置。", + "saveResourceLocationFailed": "无法保存资源存储位置。", + "transcriptionResourceRequired": "生成字幕需要先下载语音识别模型。", + "downloadAndContinue": "下载并继续", + "downloadingResource": "正在下载…", + "downloadInBackground": "后台下载", + "processingResourceDownloadFailed": "语音识别资源下载失败,请重试。", + "newProject": "新建项目", + "openProject": "打开项目", + "openProjectMore": "打开项目…", + "saveHere": "保存到这里", + "selectDirectoryFailed": "无法选择目录,请检查系统权限。", + "openingWorkspace": "正在打开工作区…", + "loadProjectsFailed": "无法加载项目列表", + "projectsEmpty": "新建或打开项目,开始剪辑。", + "backToProjects": "返回剪辑", + "timelines": "时间线", + "timelineLimitReached": "每个项目最多可创建 {count} 条时间线。", + "timelineName": "时间线名称", + "defaultTimelineName": "时间线 {index}", + "newTimeline": "新建时间线", + "noTimelines": "暂无时间线", + "activeTimeline": "当前时间线", + "timelineUnavailable": "时间线不可用", + "projectNoTimelines": "项目中还没有时间线", + "createTimelineHint": "在左侧“时间线”分组中新建时间线,开始剪辑。", + "createTimelineChat": "新建时间线后即可开始对话", + "operationFailed": "操作失败,请重试", + "collapseSidebar": "收起侧边栏", + "expandSidebar": "展开侧边栏", + "expandEditor": "展开剪辑区", + "collapseProperties": "收起属性面板", + "expandProperties": "展开属性面板", + "layout": "布局", + "editingFirstLayout": "剪辑优先", + "agentEditingLayout": "Agent + 剪辑", + "agentLayoutDescription": "规划、协作和执行", + "editingLayoutDescription": "预览、剪辑和调整", + "materials": "素材", + "all": "全部", + "video": "视频", + "audio": "音频", + "image": "图像", + "picture": "图片", + "captions": "字幕", + "text": "文字", + "noMedia": "暂无素材", + "mediaCategory": "素材分类", + "captionTasks": "字幕任务", + "listLayout": "列表布局", + "gridLayout": "宫格布局", + "addToTimeline": "添加到时间线", + "rename": "重命名", + "renameMedia": "重命名素材", + "removeMedia": "移除素材", + "remove": "移除", + "revealFinder": "在访达中显示", + "revealFileManager": "在文件管理器中显示", + "dropToAdd": "松手即可添加", + "timelineDropToStart": "将媒体拖到此处以开始。", + "dragMediaHint": "将视频、音频或图像拖到这里\n原文件保留在原位置", + "transcribe": "转字幕", + "generateCaptions": "生成字幕", + "play": "播放", + "pause": "暂停播放", + "retryPreview": "重试预览", + "canvasRatio": "画布比例", + "noPreviewContent": "时间线中暂无可预览内容", + "nativePreviewUnsupported": "当前平台尚未实现原生预览", + "canvasTransformFailed": "无法完成画布变换,请重试。", + "undo": "撤销", + "redo": "重做", + "deleteSelectedClips": "删除所选片段", + "splitAtPlayhead": "在播放头处分割", + "trimLeft": "向左裁剪", + "trimRight": "向右裁剪", + "trimLeftTooltip": "裁掉播放头左侧,保留右侧", + "trimRightTooltip": "裁掉播放头右侧,保留左侧", + "currentSequence": "当前序列", + "projectProperties": "项目属性", + "canvasSize": "画布尺寸", + "frameRate": "帧率", + "duration": "时长", + "totalDuration": "总时长", + "clipDuration": "片段时长", + "seconds": "秒", + "clip": "片段", + "unnamedClip": "未命名片段", + "gap": "空隙", + "compoundClip": "复合片段", + "textClip": "文字片段", + "pictureProperties": "画面", + "position": "位置", + "rotation": "旋转", + "scale": "缩放", + "size": "尺寸", + "transform": "变换", + "resetPosition": "重置位置", + "keepAspectRatio": "等比缩放", + "alignment": "对齐", + "alignLeft": "左对齐", + "alignRight": "右对齐", + "alignTop": "顶部对齐", + "alignBottom": "底部对齐", + "alignHorizontalCenter": "水平居中", + "alignVerticalCenter": "垂直居中", + "volume": "音量", + "gain": "增益", + "mute": "静音", + "unmute": "取消静音", + "resetVolume": "重置音量", + "invalidGain": "请输入 -90 到 +12 之间的数值", + "animation": "动画", + "keyframes": "关键帧", + "removeAllKeyframes": "移除全部关键帧", + "linear": "线性", + "easeIn": "缓入", + "easeOut": "缓出", + "easeInOut": "缓入缓出", + "basic": "基本", + "mask": "蒙版", + "addMask": "添加蒙版", + "deleteMask": "删除蒙版", + "resetMask": "重置蒙版", + "enableMask": "启用蒙版", + "disableMask": "停用蒙版", + "moveMaskUp": "上移蒙版", + "moveMaskDown": "下移蒙版", + "rectangle": "矩形", + "ellipse": "椭圆", + "invert": "反转", + "feather": "羽化", + "add": "相加", + "subtract": "相减", + "intersect": "相交", + "initialRegion": "初始区域", + "none": "无", + "color": "颜色", + "fontSize": "字号", + "outlineWidth": "描边宽度", + "outlineColor": "描边颜色", + "captionBaseline": "字幕基线", + "content": "文本", + "start": "开始", + "time": "时间", + "speed": "速度", + "speedSegmentCount": "{count} 个速度区间", + "splitSpeedAtPlayhead": "在播放头分割速度区间", + "speedChange": "变速", + "speedMode": "变速模式", + "constantSpeed": "恒定速度", + "segmentedSpeed": "分段变速", + "speedNotAvailable": "变速调节控件尚未接入", + "custom": "自定义", + "invalidNumber": "无效数值", + "mediaUnavailable": "素材不可用", + "mediaMissing": "素材缺失", + "mediaColorSpace": "素材色彩空间", + "mediaColorInterpretation": "素材色彩解释", + "colorInfoNotLoaded": "色彩信息未读取", + "unknownColorSpace": "色彩空间未知,暂按 Rec.709 显示", + "colorBackendUnsupported": "当前后端不支持素材色彩解释。", + "loadClipPropertiesFailed": "无法读取片段属性", + "updatePictureFailed": "无法更新画面属性", + "updateVolumeFailed": "无法更新音量", + "updateMaskFailed": "无法更新蒙版", + "updateKeyframesFailed": "无法更新关键帧", + "maskPreviewFailed": "无法准备蒙版预览", + "alignClipFailed": "无法对齐片段,请等待预览就绪后重试", + "invalidTransform": "缩放范围为 1%–10000%,位置和角度必须为有效数值", + "editFailed": "无法修改,请检查输入和时间范围。", + "addMediaFailed": "无法添加素材,请重试", + "deleteCaption": "删除字幕", + "mergeCaptions": "合并字幕", + "captionDeleted": "字幕已删除", + "captionChanged": "字幕已变化,请重试。", + "captionEditChanged": "字幕已变化,请重新编辑。", + "assistantHint": "描述你的剪辑想法", + "configureAgentHint": "配置 Agent 服务后开始对话", + "agentRestartHint": "请配置 Agent 服务后重新启动应用。", + "replyInterrupted": "回复已中断", + "replying": "正在回复…", + "stopReply": "停止回复", + "sendMessage": "发送消息", + "addAttachment": "添加附件(暂未接入)", + "replyFailed": "回复失败,请检查服务连接或稍后重试。", + "mcpService": "MCP 服务", + "listenPort": "监听端口", + "accessToken": "访问令牌", + "copyAccessToken": "复制访问令牌", + "accessTokenCopied": "访问令牌已复制", + "loadMcpFailed": "无法读取 MCP 设置,重试", + "saveMcpFailed": "无法保存 MCP 设置,请重试", + "retryStart": "重试启动", + "invalidPort": "端口必须为 1–65535", + "loadingSettings": "正在读取设置…", + "starting": "正在启动…", + "stopping": "正在停止…", + "disabled": "已停用", + "running": "运行中", + "startFailed": "启动失败", + "saved": "已保存", + "unsaved": "未保存", + "saving": "保存中…", + "pendingSave": "待保存", + "notApplied": "未应用", + "enable": "启用", + "disable": "停用", + "type": "类型", + "status": "状态", + "file": "文件", + "unboundMedia": "未绑定素材", + "unboundAudio": "未绑定音轨", + "vertical": "垂直", + "language": "语言", + "saveLanguageFailed": "无法保存语言设置,请重试", + "loadLanguageFailed": "无法读取语言设置,请重新选择", + "propertiesFirstLayout": "属性优先布局", + "defaultLayout": "默认布局", + "separateVocals": "分离人声", + "detachAudio": "分离音频", + "restoreAudio": "恢复音频", + "audioDetached": "音频已分离", + "addAll": "全部添加", + "preparingMedia": "准备素材…", + "cancelling": "正在取消…", + "cancelled": "已取消", + "interruptedTask": "任务已中断,可重新启动并继续", + "auto": "自动", + "autoDetect": "自动识别", + "noTranslation": "不翻译", + "sourceLanguage": "源语言", + "translationLanguage": "翻译语言", + "transcriptionNotConfigured": "转字幕尚未配置,请安装识别组件和 Whisper Turbo 模型。", + "translationNotConfigured": "字幕翻译尚未配置,目前可生成源语言字幕。", + "sourceLanguageUnknown": "无法确定可翻译的源语言。", + "startTranscriptionFailed": "无法启动识别,请检查素材,或等待当前任务完成。", + "placeMediaFirst": "请先将这份素材放到时间线,再应用字幕。", + "placeTranslationMediaFirst": "请先将对应素材放到时间线,再应用翻译字幕。", + "selectTargetClip": "选择目标片段", + "timelineChanged": "时间线已变化,请重新选择目标片段。", + "transcriptionAccessFailed": "识别失败:无法访问识别组件、模型或源素材(notConfigured)", + "transcriptionNoAudio": "识别失败:所选素材或音轨没有可识别的音频(noAudio)", + "transcriptionInvalidResult": "识别失败:组件返回的字幕文件无效(invalidResult)", + "transcriptionWorkerExited": "识别失败:识别组件意外退出(workerExited)", + "transcriptionProcessingFailed": "识别失败:原生识别处理失败(processingFailed)", + "transcriptionFailed": "识别失败,请检查组件、模型、音轨和时长", + "transcribing": "正在识别…", + "captionsGenerated": "字幕已生成", + "cancelTranscription": "取消识别", + "applyCaptions": "应用为字幕", + "preparingTranslation": "准备翻译…", + "translatingCaptions": "正在翻译字幕…", + "cancellingTranslation": "正在取消翻译…", + "translatedCaptionsGenerated": "翻译字幕已生成", + "translationCancelled": "翻译已取消", + "translationInterrupted": "翻译任务已中断", + "cancelTranslation": "取消翻译", + "editorServiceUnavailable": "编辑工具服务不可用,请重新打开项目。", + "mcpUnavailable": "MCP 连接不可用,请检查本地端口和令牌配置。", + "openTimelineFailed": "无法打开时间线", + "noTimelineSequence": "时间线中没有序列", + "waitingForProject": "等待打开工程", + "hold": "保持", + "noImportableFiles": "未收到可导入的文件", + "virtualFilesUnsupported": "请从文件管理器拖入原文件,暂不支持虚拟文件", + "editorSessionStartFailed": "无法打开时间线编辑器", + "previewStartFailed": "无法启动原生预览", + "previewInvalidTrack": "素材中不存在所选音视频轨道。", + "previewMissingBinding": "缺少素材绑定,无法预览当前时间线。", + "previewUnsupportedEdits": "当前时间线包含尚不支持预览的编辑。", + "previewUnsupportedConfiguration": "当前平台或系统版本尚不支持此预览配置。", + "previewHdrUnsupported": "HDR 素材需要色调映射才能在 SDR 预览中显示,当前系统或预览配置不支持。", + "previewAudioOutOfRange": "音频片段超出了素材音轨的有效范围,无法预览。", + "previewResourceMissing": "预览素材已不存在,请重新定位原文件。", + "previewInvalidComposition": "视频合成配置无效,无法创建预览。", + "previewInvalidData": "预览数据无效,请重试。", + "previewFailed": "预览失败,请检查素材是否可访问后重试。", + "chatFailed": "无法完成对话,请检查服务配置或稍后重试。", + "delete": "删除", + "pinTimeline": "置顶时间线", + "unpinTimeline": "取消置顶", + "deleteTimelineConfirmation": "删除“{name}”及其编辑历史?此操作无法撤销。", + "@deleteTimelineConfirmation": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "processingFailed": "处理失败", + "noMatchingOptions": "没有匹配的选项", + "removeMediaConfirmation": "从项目移除“{name}”?已有片段、历史版本和原文件会保留。", + "@removeMediaConfirmation": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "mediaAdded": "已添加 {count} 个素材引用", + "@mediaAdded": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "duplicatesSkipped": "跳过 {count} 个重复文件", + "@duplicatesSkipped": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mediaCount": "{count} 个素材", + "@mediaCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "importMedia": "导入", + "noMediaOfType": "暂无{type}素材", + "@noMediaOfType": { + "placeholders": { + "type": { + "type": "String" + } + } + }, + "captionsImported": "已导入 {count} 条字幕", + "@captionsImported": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "editCaptionError": "无法修改字幕:{message}", + "@editCaptionError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "mcpStartError": "无法启动 MCP:{message}", + "@mcpStartError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "manualColorSpace": "手动指定:{name}", + "@manualColorSpace": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "detectedColorSpace": "已识别:{name}", + "@detectedColorSpace": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "keyframeLabel": "{channel}关键帧", + "@keyframeLabel": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "maskMode": "组合方式:{mode}", + "@maskMode": { + "placeholders": { + "mode": { + "type": "String" + } + } + }, + "keyframeCount": "{count} 个关键帧", + "@keyframeCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "toggleKeyframe": "{action}{channel}关键帧", + "@toggleKeyframe": { + "placeholders": { + "action": { + "type": "String" + }, + "channel": { + "type": "String" + } + } + }, + "previousKeyframe": "上一个{channel}关键帧", + "@previousKeyframe": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "nextKeyframe": "下一个{channel}关键帧", + "@nextKeyframe": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "keyframeSettings": "{channel}关键帧设置", + "@keyframeSettings": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "selectedClipsHint": "已选择 {count} 个片段\n请选择单个片段查看属性", + "@selectedClipsHint": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "transcriptionError": "识别失败,请检查组件、模型、音轨和时长({code})", + "@transcriptionError": { + "placeholders": { + "code": { + "type": "String" + } + } + }, + "captionsAdded": "已添加 {count} 条字幕,可在属性面板编辑。", + "@captionsAdded": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "translatedCaptionsAdded": "已添加 {count} 条翻译字幕,可在属性面板编辑。", + "@translatedCaptionsAdded": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "applyCaptionsError": "无法应用字幕:{message}", + "@applyCaptionsError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "applyTranslatedCaptionsError": "无法应用翻译字幕:{message}", + "@applyTranslatedCaptionsError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "recognizedCaptions": "已识别 {count} 条", + "@recognizedCaptions": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "captionCount": "{count} 条字幕", + "@captionCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "translationFailed": "翻译失败:{message}", + "@translationFailed": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "translatedCaptionCount": "{count} 条{language}字幕", + "@translatedCaptionCount": { + "placeholders": { + "count": { + "type": "int" + }, + "language": { + "type": "String" + } + } + }, + "previewParameterError": "预览参数无效:{message}", + "@previewParameterError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "mediaOffline": "素材离线或不可用:{names}", + "@mediaOffline": { + "placeholders": { + "names": { + "type": "String" + } + } + }, + "searchOptions": "搜索{label}…", + "@searchOptions": { + "placeholders": { + "label": { + "type": "String" + } + } + }, + "loadRecentProjectsFailed": "无法读取最近项目记录,仍可手动打开项目。", + "projectAccessFailed": "项目不可用", + "projectMissingDirectory": "项目不存在", + "recentProjectSaveFailed": "项目已打开,但最近使用记录未能保存。", + "lastProjectSaveFailed": "项目已打开,但上次项目记录未能保存。", + "enterProjectName": "请输入项目名称", + "projectSwitched": "项目已切换,请重新拖入素材", + "notLocalMedia": "该素材不是本地文件", + "revealMediaFailed": "无法在文件管理器中显示素材", + "openMatchingProject": "请先打开对应项目", + "projectMismatch": "此位置的项目与记录不一致,请使用“打开项目”重新选择。", + "openProjectFirst": "请先打开项目", + "localFilesOnly": "请从文件管理器拖入本地文件", + "foldersUnsupported": "请选择文件,暂不支持拖入文件夹", + "mediaImportCancelled": "素材导入已取消", + "fileAccessFailed": "文件不存在或无法读取,请检查位置与权限", + "registerMediaFailed": "无法登记素材,请重试", + "mediaNoLongerExists": "素材已不存在", + "mediaNoTracks": "素材没有可用的视频或音频轨道", + "invalidMediaDuration": "素材时长无效", + "mediaInfoUnsupported": "当前平台尚未支持素材信息读取", + "mediaInfoFailed": "无法读取素材信息,请检查文件与访问权限", + "saveTimelineFailed": "时间线保存失败,请重试。未保存的编辑仍保留在当前会话。", + "addKeyframeAction": "添加", + "backgroundTasks": "后台任务", + "noBackgroundTasks": "暂无后台任务", + "retryTask": "重试", + "applyOriginalCaptions": "应用原文字幕", + "applyTranslatedCaptions": "应用翻译字幕", + "subtitleTaskStarted": "字幕任务已开始", + "fitTimeline": "适合整个时间线", + "modify": "修改", + "projectSettings": "项目设置", + "projectSettingsDescription": "修改项目输出规格,保留片段的实际时长和速度。", + "projectColorSpace": "色彩空间", + "projectWidth": "宽度(px)", + "projectHeight": "高度(px)", + "projectResolutionInvalid": "请输入 1–16384 的整数", + "previewFullscreen": "全屏预览", + "exitPreviewFullscreen": "退出全屏", + "previewGoToStart": "回到开头", + "previewPreviousFrame": "上一帧", + "previewNextFrame": "下一帧", + "softwareUpdates": "软件更新", + "checkForUpdates": "检查更新", + "automaticallyCheckUpdates": "自动检查更新", + "updatesUnavailable": "此构建暂不提供更新。", + "updateCheckFailed": "无法检查更新,请重试。", + "removeBackground": "抠像", + "startBackgroundRemoval": "开始抠像", + "backgroundRemovalResourceRequired": "抠像需要下载本地模型。下载完成后会自动开始抠像。", + "backgroundRemovalDownloadTask": "下载抠像资源", + "backgroundRemovalResourceName": "抠像模型", + "backgroundRemovalDestructiveHint": "生成的透明素材会直接替换当前片段;仍可通过撤销恢复原片段。", + "backgroundRemovalTaskStarted": "抠像任务已开始", + "startBackgroundRemovalFailed": "无法启动抠像,请检查素材,或等待当前处理任务完成。", + "backgroundRemovalComplete": "抠像完成", + "backgroundRemovalApplying": "正在替换片段素材", + "backgroundRemovalFailed": "抠像失败", + "agentSettings": "Agent", + "agentSaveSettingsFailed": "无法保存 Agent 设置。", + "agentDeleteProviderTitle": "删除 Provider?", + "agentDeleteProviderDescription": "将从此设备移除“{providerName}”及其保存的 API Key。", + "agentProviderRequired": "请先添加 Provider,再启用助手。", + "agentUseSelectedModel": "新的 Agent 请求将使用所选模型。", + "agentEnable": "启用 Agent", + "agentDefaultModel": "默认模型", + "agentConfigureModel": "配置模型", + "agentSelectModel": "选择模型", + "agentModelUnavailable": "此对话的模型已不可用,请选择其他模型开始新对话。", + "agentModelChangeSession": "切换模型后会开始新的 Agent 会话。", + "agentCustomProviders": "自定义 Provider", + "agentProviderStorageDescription": "Provider 元数据保存在本机,API Key 保存在系统凭据存储中。", + "agentAddProvider": "添加 Provider", + "agentBackToProviders": "返回 Provider 列表", + "agentLoadSettingsFailed": "无法读取 Agent 设置,重试", + "agentEnableProvider": "启用 Provider", + "agentEditProvider": "编辑 Provider", + "agentDeleteProvider": "删除 Provider", + "agentModelIdsUnique": "Model ID 不能重复。", + "agentEditProviderTitle": "编辑 Provider", + "agentProviderEndpointDescription": "配置 OpenAI-compatible Chat Completions 服务。", + "agentSaveProvider": "保存 Provider", + "agentProviderConfiguration": "Provider 配置", + "agentAuthenticationAndModels": "认证与模型", + "agentApiType": "API 类型", + "agentOpenAiChatCompletions": "OpenAI Completions", + "agentBaseUrl": "Base URL", + "agentApiKey": "API Key", + "agentProviderNameHint": "我的 Provider", + "agentApiKeyOptional": "不需要鉴权的服务可以留空。", + "agentApiKeyKeep": "留空将保留已保存的 Key。", + "agentOptional": "可选", + "agentApiKeyOneLine": "API Key 必须为单行文本。", + "agentRemoveSavedApiKey": "移除已保存的 API Key", + "agentModels": "模型", + "agentAddModel": "添加模型", + "agentRequiredField": "此项为必填项。", + "agentInvalidBaseUrl": "请输入不含凭据、查询参数或片段的 HTTP(S) Base URL。", + "agentModelId": "Model ID", + "agentContextWindow": "上下文窗口", + "agentMaxOutputTokens": "最大输出", + "agentMaxOutputBelowContext": "必须小于上下文窗口。", + "agentDeleteModel": "删除模型", + "agentPositiveInteger": "请输入正整数。", + "agentConfigurationReadFailed": "无法读取 Agent 配置,请检查设置后重试。", + "agentConfigurationRequired": "请先在设置中配置并启用 Agent。", + "agentSessionRestoreFailed": "无法恢复 Agent 会话,请稍后重试。", + "agentContextBudgetExceeded": "输入预算不足,无法容纳系统指令、工具和消息。请增大上下文窗口或降低最大输出 tokens。", + "agentAuthenticationFailed": "鉴权失败,请检查 Provider 的 API Key 和访问权限。", + "agentConnectionFailed": "模型服务连接失败或请求超时,请检查 Base URL 和网络。", + "agentProtocolFailed": "服务返回内容不符合所选 API 类型,或响应流不完整。", + "agentContextBudgetTooSmall": "需要为系统指令保留更多输入空间,请增大上下文窗口或降低最大输出 tokens。", + "agentCompacting": "整理上下文…", + "agentEditing": "编辑中…", + "agentVerifying": "核对结果…", + "agentTurnLimitReached": "本轮任务已达到执行上限,已完成的编辑已保存。发送“继续”可接着执行。", + "agentRecoveryRequired": "上次操作的结果尚未确认。可继续任务核对已保存回执;未确认的编辑不会重复执行。", + "agentExportReplyFailed": "视频已成功导出,总结回复失败。可重试总结,不会重复剪辑或导出。", + "agentRetrySummary": "重试总结", + "agentResumeTask": "继续任务", + "agentTaskInterrupted": "任务已中断,可从已保存的进度继续。", + "downloadSubtitleModel": "下载字幕模型", + "downloadModelAction": "下载", + "subtitleEngineUnavailable": "模型已安装,但字幕处理引擎未能启动。请修复处理引擎,无需重新下载模型。", + "backgroundTaskDetails": "任务详情", + "backgroundTaskFailed": "失败", + "backgroundTaskCompleted": "已完成", + "captionWrapLines": "换行显示字幕", + "captionSingleLine": "单行显示字幕", + "noMatchingCaptions": "没有匹配的字幕", + "subtitleResourcesRequired": "生成字幕需要这些资源。下载完成后会自动开始处理。", + "subtitleResourcesDownloadSize": "需下载 {size}", + "pauseDownload": "暂停", + "resumeDownload": "继续", + "downloadPaused": "已暂停", + "cancelResourceDownloadTitle": "取消下载?", + "cancelResourceDownloadMessage": "下载任务将停止,当前资源的下载进度可能丢失。", + "continueDownload": "继续下载", + "cancelDownload": "取消下载", + "speechResourceStage": "语音识别资源", + "translationResourceStage": "翻译资源", + "subtitleResourceDownloadTask": "下载语音与翻译资源", + "downloadingSpeechModel": "正在下载语音模型", + "downloadingTranslationModel": "正在下载翻译模型", + "checkingForUpdates": "正在检查更新…", + "appIsUpToDate": "当前已是最新版本。", + "downloadingUpdate": "正在下载更新:{progress}%", + "updateAvailable": "发现新版本 {version}。", + "downloadUpdate": "下载更新", + "restartToUpdate": "重启并更新", + "updateOperationFailed": "无法更新,请完成正在运行的任务后重试。", + "windowMinimize": "最小化", + "windowMaximize": "最大化", + "windowRestore": "还原", + "workspaceAgent": "助手", + "workspaceCut": "剪辑", + "noAvailableOptions": "暂无可用选项", + "composerReferenceInvalid": "引用已失效,请切回原项目或移除引用", + "durationSeconds": "{seconds}秒", + "durationMinutesSeconds": "{minutes}分钟 {seconds}秒", + "projectNameInvalid": "项目名称无效。", + "projectLocationDefaultUnavailable": "无法访问默认项目位置,请在设置中重新选择。", + "chooseProjectLocation": "请先在设置中选择项目保存位置。", + "untitledTimeline": "未命名时间线", + "primarySequence": "主序列", + "primaryStoryline": "主线", + "projectSessionClosed": "项目会话已关闭,请重新打开项目。", + "timelineSessionClosed": "时间线会话已关闭,请重新打开时间线。", + "timelineMissing": "时间线不存在或已被删除", + "timelineInUse": "时间线正在使用中,暂时无法删除", + "timelineHasBackgroundTasks": "时间线有正在进行的后台任务,暂时无法删除", + "timelineRequired": "项目至少需要保留一条时间线", + "mediaReadFailed": "无法读取素材", + "mediaImportFailed": "无法导入素材", + "unsupportedMediaType": "仅支持导入视频、音频和图像文件", + "mediaNoVideoTracks": "素材没有可用的视频轨道", + "mediaDurationOutOfRange": "素材时长超出时间线范围", + "resourceDownloadHttpFailed": "下载失败(HTTP {statusCode})", + "resourceChecksumFailed": "模型文件校验失败,请重新下载资源。", + "subtitleLanguageAf": "南非荷兰语", + "subtitleLanguageAm": "阿姆哈拉语", + "subtitleLanguageAr": "阿拉伯语", + "subtitleLanguageAst": "阿斯图里亚斯语", + "subtitleLanguageAz": "阿塞拜疆语", + "subtitleLanguageBa": "巴什基尔语", + "subtitleLanguageBe": "白俄罗斯语", + "subtitleLanguageBg": "保加利亚语", + "subtitleLanguageBn": "孟加拉语", + "subtitleLanguageBr": "布列塔尼语", + "subtitleLanguageBs": "波斯尼亚语", + "subtitleLanguageCa": "加泰罗尼亚语", + "subtitleLanguageCeb": "宿务语", + "subtitleLanguageCs": "捷克语", + "subtitleLanguageCy": "威尔士语", + "subtitleLanguageDa": "丹麦语", + "subtitleLanguageDe": "德语", + "subtitleLanguageEl": "希腊语", + "subtitleLanguageEn": "英语", + "subtitleLanguageEs": "西班牙语", + "subtitleLanguageEt": "爱沙尼亚语", + "subtitleLanguageFa": "波斯语", + "subtitleLanguageFf": "富拉语", + "subtitleLanguageFi": "芬兰语", + "subtitleLanguageFr": "法语", + "subtitleLanguageFy": "西弗里斯语", + "subtitleLanguageGa": "爱尔兰语", + "subtitleLanguageGd": "苏格兰盖尔语", + "subtitleLanguageGl": "加利西亚语", + "subtitleLanguageGu": "古吉拉特语", + "subtitleLanguageHa": "豪萨语", + "subtitleLanguageHe": "希伯来语", + "subtitleLanguageHi": "印地语", + "subtitleLanguageHr": "克罗地亚语", + "subtitleLanguageHt": "海地克里奥尔语", + "subtitleLanguageHu": "匈牙利语", + "subtitleLanguageHy": "亚美尼亚语", + "subtitleLanguageId": "印度尼西亚语", + "subtitleLanguageIg": "伊博语", + "subtitleLanguageIlo": "伊洛卡诺语", + "subtitleLanguageIs": "冰岛语", + "subtitleLanguageIt": "意大利语", + "subtitleLanguageJa": "日语", + "subtitleLanguageJv": "爪哇语", + "subtitleLanguageKa": "格鲁吉亚语", + "subtitleLanguageKk": "哈萨克语", + "subtitleLanguageKm": "高棉语", + "subtitleLanguageKn": "卡纳达语", + "subtitleLanguageKo": "韩语", + "subtitleLanguageLb": "卢森堡语", + "subtitleLanguageLg": "卢干达语", + "subtitleLanguageLn": "林加拉语", + "subtitleLanguageLo": "老挝语", + "subtitleLanguageLt": "立陶宛语", + "subtitleLanguageLv": "拉脱维亚语", + "subtitleLanguageMg": "马拉加斯语", + "subtitleLanguageMk": "马其顿语", + "subtitleLanguageMl": "马拉雅拉姆语", + "subtitleLanguageMn": "蒙古语", + "subtitleLanguageMr": "马拉地语", + "subtitleLanguageMs": "马来语", + "subtitleLanguageMy": "缅甸语", + "subtitleLanguageNe": "尼泊尔语", + "subtitleLanguageNl": "荷兰语", + "subtitleLanguageNo": "挪威语", + "subtitleLanguageNs": "北索托语", + "subtitleLanguageOc": "奥克语", + "subtitleLanguageOr": "奥里亚语", + "subtitleLanguagePa": "旁遮普语", + "subtitleLanguagePl": "波兰语", + "subtitleLanguagePs": "普什图语", + "subtitleLanguagePt": "葡萄牙语", + "subtitleLanguageRo": "罗马尼亚语", + "subtitleLanguageRu": "俄语", + "subtitleLanguageSd": "信德语", + "subtitleLanguageSi": "僧伽罗语", + "subtitleLanguageSk": "斯洛伐克语", + "subtitleLanguageSl": "斯洛文尼亚语", + "subtitleLanguageSo": "索马里语", + "subtitleLanguageSq": "阿尔巴尼亚语", + "subtitleLanguageSr": "塞尔维亚语", + "subtitleLanguageSs": "斯瓦蒂语", + "subtitleLanguageSu": "巽他语", + "subtitleLanguageSv": "瑞典语", + "subtitleLanguageSw": "斯瓦希里语", + "subtitleLanguageTa": "泰米尔语", + "subtitleLanguageTh": "泰语", + "subtitleLanguageTl": "他加禄语", + "subtitleLanguageTn": "茨瓦纳语", + "subtitleLanguageTr": "土耳其语", + "subtitleLanguageUk": "乌克兰语", + "subtitleLanguageUr": "乌尔都语", + "subtitleLanguageUz": "乌兹别克语", + "subtitleLanguageVi": "越南语", + "subtitleLanguageWo": "沃洛夫语", + "subtitleLanguageXh": "科萨语", + "subtitleLanguageYi": "意第绪语", + "subtitleLanguageYo": "约鲁巴语", + "subtitleLanguageYue": "粤语", + "subtitleLanguageZh": "中文", + "subtitleLanguageZu": "祖鲁语", + "linearRec2020": "线性 Rec.2020", + "diagnostics": "诊断", + "exportDiagnostics": "导出诊断包", + "exportDiagnosticsFailed": "无法导出诊断包,请重试。", + "exportDiagnosticsSucceeded": "诊断包已保存。" +} diff --git a/lib/l10n/app_zh_Hans.arb b/lib/l10n/app_zh_Hans.arb new file mode 100644 index 0000000..38825f9 --- /dev/null +++ b/lib/l10n/app_zh_Hans.arb @@ -0,0 +1,889 @@ +{ + "selectProject": "选择项目", + "searchProjects": "搜索项目", + "noMatchingProjects": "没有匹配的项目", + "projectsNone": "暂无项目", + "projectLocationMissing": "目录不存在,创建项目时将自动创建。", + "projectLocationUnavailable": "项目保存位置不可用,请连接磁盘或检查网络后重试,也可以更改位置。", + "projectLocationNotWritable": "项目保存位置没有写入权限,请检查权限或更改位置。", + "projectLocationCreateFailed": "无法创建或写入项目保存目录,请检查权限或更改位置。", + "removeProjectFromSidebar": "从侧边栏移除", + "projectRemoved": "已移除项目,本地文件和聊天记录已保留。", + "agentNoConversations": "暂无聊天", + "renameConversationTitle": "重命名聊天", + "renameConversationDescription": "保持简短且易于识别", + "collapseProject": "收起项目", + "expandProject": "展开项目", + "agentDeleteConfirmation": "聊天“{title}”及其消息记录将被永久删除,无法恢复。本地项目文件不受影响。", + "agentEmptyTrashConfirmation": "回收站中的所有聊天将被永久删除,无法恢复。本地项目文件不受影响。", + "agentConversations": "对话", + "showMoreConversations": "展开显示", + "showFewerConversations": "收起显示", + "agentNewConversation": "新建对话", + "agentElapsedTime": "用时 {duration}", + "agentConversationActions": "对话操作", + "agentMoveToTrash": "移至回收区", + "agentTrash": "回收区", + "agentRestore": "恢复", + "agentEmptyTrash": "清空回收区", + "agentDeleteForever": "永久删除", + "agentConversationLocation": "对话存储位置", + "agentChooseExistingConversations": "选择已有对话目录", + "agentMoveConversations": "移动对话", + "agentLocationUnavailable": "对话存储位置不可用", + "agentLocationBusy": "请等待当前对话运行结束后再移动", + "agentRelinkProvider": "重新关联 Provider", + "@@locale": "zh_Hans", + "settings": "设置", + "closeSettings": "关闭设置", + "general": "通用", + "appearance": "外观", + "theme": "主题", + "system": "跟随系统", + "light": "明亮", + "dark": "深色", + "saveAppearanceFailed": "无法保存外观设置,请重试", + "loadAppearanceFailed": "无法读取外观设置,请重新选择主题", + "cancel": "取消", + "save": "保存", + "create": "创建", + "close": "关闭", + "retry": "重试", + "select": "选择", + "name": "名称", + "enterName": "请输入名称", + "invalidName": "名称不能包含路径分隔符或控制字符", + "projects": "项目", + "projectName": "项目名称", + "projectLocation": "项目保存位置", + "projectLocationNotSet": "未设置", + "loadProjectLocationFailed": "无法读取项目保存位置。", + "saveProjectLocationFailed": "无法保存项目保存位置。", + "resourceLocation": "资源存储位置", + "resourceLocationNotSet": "未设置", + "loadResourceLocationFailed": "无法读取资源存储位置。", + "saveResourceLocationFailed": "无法保存资源存储位置。", + "transcriptionResourceRequired": "生成字幕需要先下载语音识别模型。", + "downloadAndContinue": "下载并继续", + "downloadingResource": "正在下载…", + "downloadInBackground": "后台下载", + "processingResourceDownloadFailed": "语音识别资源下载失败,请重试。", + "newProject": "新建项目", + "openProject": "打开项目", + "openProjectMore": "打开项目…", + "saveHere": "保存到这里", + "selectDirectoryFailed": "无法选择目录,请检查系统权限。", + "openingWorkspace": "正在打开工作区…", + "loadProjectsFailed": "无法加载项目列表", + "projectsEmpty": "新建或打开项目,开始剪辑。", + "backToProjects": "返回剪辑", + "timelines": "时间线", + "timelineLimitReached": "每个项目最多可创建 {count} 条时间线。", + "timelineName": "时间线名称", + "defaultTimelineName": "时间线 {index}", + "newTimeline": "新建时间线", + "noTimelines": "暂无时间线", + "activeTimeline": "当前时间线", + "timelineUnavailable": "时间线不可用", + "projectNoTimelines": "项目中还没有时间线", + "createTimelineHint": "在左侧“时间线”分组中新建时间线,开始剪辑。", + "createTimelineChat": "新建时间线后即可开始对话", + "operationFailed": "操作失败,请重试", + "collapseSidebar": "收起侧边栏", + "expandSidebar": "展开侧边栏", + "expandEditor": "展开剪辑区", + "collapseProperties": "收起属性面板", + "expandProperties": "展开属性面板", + "layout": "布局", + "editingFirstLayout": "剪辑优先", + "agentEditingLayout": "Agent + 剪辑", + "agentLayoutDescription": "规划、协作和执行", + "editingLayoutDescription": "预览、剪辑和调整", + "materials": "素材", + "all": "全部", + "video": "视频", + "audio": "音频", + "image": "图像", + "picture": "图片", + "captions": "字幕", + "text": "文字", + "noMedia": "暂无素材", + "mediaCategory": "素材分类", + "captionTasks": "字幕任务", + "listLayout": "列表布局", + "gridLayout": "宫格布局", + "addToTimeline": "添加到时间线", + "rename": "重命名", + "renameMedia": "重命名素材", + "removeMedia": "移除素材", + "remove": "移除", + "revealFinder": "在访达中显示", + "revealFileManager": "在文件管理器中显示", + "dropToAdd": "松手即可添加", + "timelineDropToStart": "将媒体拖到此处以开始。", + "dragMediaHint": "将视频、音频或图像拖到这里\n原文件保留在原位置", + "transcribe": "转字幕", + "generateCaptions": "生成字幕", + "play": "播放", + "pause": "暂停播放", + "retryPreview": "重试预览", + "canvasRatio": "画布比例", + "noPreviewContent": "时间线中暂无可预览内容", + "nativePreviewUnsupported": "当前平台尚未实现原生预览", + "canvasTransformFailed": "无法完成画布变换,请重试。", + "undo": "撤销", + "redo": "重做", + "deleteSelectedClips": "删除所选片段", + "splitAtPlayhead": "在播放头处分割", + "trimLeft": "向左裁剪", + "trimRight": "向右裁剪", + "trimLeftTooltip": "裁掉播放头左侧,保留右侧", + "trimRightTooltip": "裁掉播放头右侧,保留左侧", + "currentSequence": "当前序列", + "projectProperties": "项目属性", + "canvasSize": "画布尺寸", + "frameRate": "帧率", + "duration": "时长", + "totalDuration": "总时长", + "clipDuration": "片段时长", + "seconds": "秒", + "clip": "片段", + "unnamedClip": "未命名片段", + "gap": "空隙", + "compoundClip": "复合片段", + "textClip": "文字片段", + "pictureProperties": "画面", + "position": "位置", + "rotation": "旋转", + "scale": "缩放", + "size": "尺寸", + "transform": "变换", + "resetPosition": "重置位置", + "keepAspectRatio": "等比缩放", + "alignment": "对齐", + "alignLeft": "左对齐", + "alignRight": "右对齐", + "alignTop": "顶部对齐", + "alignBottom": "底部对齐", + "alignHorizontalCenter": "水平居中", + "alignVerticalCenter": "垂直居中", + "volume": "音量", + "gain": "增益", + "mute": "静音", + "unmute": "取消静音", + "resetVolume": "重置音量", + "invalidGain": "请输入 -90 到 +12 之间的数值", + "animation": "动画", + "keyframes": "关键帧", + "removeAllKeyframes": "移除全部关键帧", + "linear": "线性", + "easeIn": "缓入", + "easeOut": "缓出", + "easeInOut": "缓入缓出", + "basic": "基本", + "mask": "蒙版", + "addMask": "添加蒙版", + "deleteMask": "删除蒙版", + "resetMask": "重置蒙版", + "enableMask": "启用蒙版", + "disableMask": "停用蒙版", + "moveMaskUp": "上移蒙版", + "moveMaskDown": "下移蒙版", + "rectangle": "矩形", + "ellipse": "椭圆", + "invert": "反转", + "feather": "羽化", + "add": "相加", + "subtract": "相减", + "intersect": "相交", + "initialRegion": "初始区域", + "none": "无", + "color": "颜色", + "fontSize": "字号", + "outlineWidth": "描边宽度", + "outlineColor": "描边颜色", + "captionBaseline": "字幕基线", + "content": "文本", + "start": "开始", + "time": "时间", + "speed": "速度", + "speedSegmentCount": "{count} 个速度区间", + "splitSpeedAtPlayhead": "在播放头分割速度区间", + "speedChange": "变速", + "speedMode": "变速模式", + "constantSpeed": "恒定速度", + "segmentedSpeed": "分段变速", + "speedNotAvailable": "变速调节控件尚未接入", + "custom": "自定义", + "invalidNumber": "无效数值", + "mediaUnavailable": "素材不可用", + "mediaMissing": "素材缺失", + "mediaColorSpace": "素材色彩空间", + "mediaColorInterpretation": "素材色彩解释", + "colorInfoNotLoaded": "色彩信息未读取", + "unknownColorSpace": "色彩空间未知,暂按 Rec.709 显示", + "colorBackendUnsupported": "当前后端不支持素材色彩解释。", + "loadClipPropertiesFailed": "无法读取片段属性", + "updatePictureFailed": "无法更新画面属性", + "updateVolumeFailed": "无法更新音量", + "updateMaskFailed": "无法更新蒙版", + "updateKeyframesFailed": "无法更新关键帧", + "maskPreviewFailed": "无法准备蒙版预览", + "alignClipFailed": "无法对齐片段,请等待预览就绪后重试", + "invalidTransform": "缩放范围为 1%–10000%,位置和角度必须为有效数值", + "editFailed": "无法修改,请检查输入和时间范围。", + "addMediaFailed": "无法添加素材,请重试", + "deleteCaption": "删除字幕", + "mergeCaptions": "合并字幕", + "captionDeleted": "字幕已删除", + "captionChanged": "字幕已变化,请重试。", + "captionEditChanged": "字幕已变化,请重新编辑。", + "assistantHint": "描述你的剪辑想法", + "configureAgentHint": "配置 Agent 服务后开始对话", + "agentRestartHint": "请配置 Agent 服务后重新启动应用。", + "replyInterrupted": "回复已中断", + "replying": "正在回复…", + "stopReply": "停止回复", + "sendMessage": "发送消息", + "addAttachment": "添加附件(暂未接入)", + "replyFailed": "回复失败,请检查服务连接或稍后重试。", + "mcpService": "MCP 服务", + "listenPort": "监听端口", + "accessToken": "访问令牌", + "copyAccessToken": "复制访问令牌", + "accessTokenCopied": "访问令牌已复制", + "loadMcpFailed": "无法读取 MCP 设置,重试", + "saveMcpFailed": "无法保存 MCP 设置,请重试", + "retryStart": "重试启动", + "invalidPort": "端口必须为 1–65535", + "loadingSettings": "正在读取设置…", + "starting": "正在启动…", + "stopping": "正在停止…", + "disabled": "已停用", + "running": "运行中", + "startFailed": "启动失败", + "saved": "已保存", + "unsaved": "未保存", + "saving": "保存中…", + "pendingSave": "待保存", + "notApplied": "未应用", + "enable": "启用", + "disable": "停用", + "type": "类型", + "status": "状态", + "file": "文件", + "unboundMedia": "未绑定素材", + "unboundAudio": "未绑定音轨", + "vertical": "垂直", + "language": "语言", + "saveLanguageFailed": "无法保存语言设置,请重试", + "loadLanguageFailed": "无法读取语言设置,请重新选择", + "propertiesFirstLayout": "属性优先布局", + "defaultLayout": "默认布局", + "separateVocals": "分离人声", + "detachAudio": "分离音频", + "restoreAudio": "恢复音频", + "audioDetached": "音频已分离", + "addAll": "全部添加", + "preparingMedia": "准备素材…", + "cancelling": "正在取消…", + "cancelled": "已取消", + "interruptedTask": "任务已中断,可重新启动并继续", + "auto": "自动", + "autoDetect": "自动识别", + "noTranslation": "不翻译", + "sourceLanguage": "源语言", + "translationLanguage": "翻译语言", + "transcriptionNotConfigured": "转字幕尚未配置,请安装识别组件和 Whisper Turbo 模型。", + "translationNotConfigured": "字幕翻译尚未配置,目前可生成源语言字幕。", + "sourceLanguageUnknown": "无法确定可翻译的源语言。", + "startTranscriptionFailed": "无法启动识别,请检查素材,或等待当前任务完成。", + "placeMediaFirst": "请先将这份素材放到时间线,再应用字幕。", + "placeTranslationMediaFirst": "请先将对应素材放到时间线,再应用翻译字幕。", + "selectTargetClip": "选择目标片段", + "timelineChanged": "时间线已变化,请重新选择目标片段。", + "transcriptionAccessFailed": "识别失败:无法访问识别组件、模型或源素材(notConfigured)", + "transcriptionNoAudio": "识别失败:所选素材或音轨没有可识别的音频(noAudio)", + "transcriptionInvalidResult": "识别失败:组件返回的字幕文件无效(invalidResult)", + "transcriptionWorkerExited": "识别失败:识别组件意外退出(workerExited)", + "transcriptionProcessingFailed": "识别失败:原生识别处理失败(processingFailed)", + "transcriptionFailed": "识别失败,请检查组件、模型、音轨和时长", + "transcribing": "正在识别…", + "captionsGenerated": "字幕已生成", + "cancelTranscription": "取消识别", + "applyCaptions": "应用为字幕", + "preparingTranslation": "准备翻译…", + "translatingCaptions": "正在翻译字幕…", + "cancellingTranslation": "正在取消翻译…", + "translatedCaptionsGenerated": "翻译字幕已生成", + "translationCancelled": "翻译已取消", + "translationInterrupted": "翻译任务已中断", + "cancelTranslation": "取消翻译", + "editorServiceUnavailable": "编辑工具服务不可用,请重新打开项目。", + "mcpUnavailable": "MCP 连接不可用,请检查本地端口和令牌配置。", + "openTimelineFailed": "无法打开时间线", + "noTimelineSequence": "时间线中没有序列", + "waitingForProject": "等待打开工程", + "hold": "保持", + "noImportableFiles": "未收到可导入的文件", + "virtualFilesUnsupported": "请从文件管理器拖入原文件,暂不支持虚拟文件", + "editorSessionStartFailed": "无法打开时间线编辑器", + "previewStartFailed": "无法启动原生预览", + "previewInvalidTrack": "素材中不存在所选音视频轨道。", + "previewMissingBinding": "缺少素材绑定,无法预览当前时间线。", + "previewUnsupportedEdits": "当前时间线包含尚不支持预览的编辑。", + "previewUnsupportedConfiguration": "当前平台或系统版本尚不支持此预览配置。", + "previewHdrUnsupported": "HDR 素材需要色调映射才能在 SDR 预览中显示,当前系统或预览配置不支持。", + "previewAudioOutOfRange": "音频片段超出了素材音轨的有效范围,无法预览。", + "previewResourceMissing": "预览素材已不存在,请重新定位原文件。", + "previewInvalidComposition": "视频合成配置无效,无法创建预览。", + "previewInvalidData": "预览数据无效,请重试。", + "previewFailed": "预览失败,请检查素材是否可访问后重试。", + "chatFailed": "无法完成对话,请检查服务配置或稍后重试。", + "delete": "删除", + "pinTimeline": "置顶时间线", + "unpinTimeline": "取消置顶", + "deleteTimelineConfirmation": "删除“{name}”及其编辑历史?此操作无法撤销。", + "@deleteTimelineConfirmation": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "processingFailed": "处理失败", + "noMatchingOptions": "没有匹配的选项", + "removeMediaConfirmation": "从项目移除“{name}”?已有片段、历史版本和原文件会保留。", + "@removeMediaConfirmation": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "mediaAdded": "已添加 {count} 个素材引用", + "@mediaAdded": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "duplicatesSkipped": "跳过 {count} 个重复文件", + "@duplicatesSkipped": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mediaCount": "{count} 个素材", + "importMedia": "导入", + "@mediaCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "noMediaOfType": "暂无{type}素材", + "@noMediaOfType": { + "placeholders": { + "type": { + "type": "String" + } + } + }, + "captionsImported": "已导入 {count} 条字幕", + "@captionsImported": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "editCaptionError": "无法修改字幕:{message}", + "@editCaptionError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "mcpStartError": "无法启动 MCP:{message}", + "@mcpStartError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "manualColorSpace": "手动指定:{name}", + "@manualColorSpace": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "detectedColorSpace": "已识别:{name}", + "@detectedColorSpace": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "keyframeLabel": "{channel}关键帧", + "@keyframeLabel": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "maskMode": "组合方式:{mode}", + "@maskMode": { + "placeholders": { + "mode": { + "type": "String" + } + } + }, + "keyframeCount": "{count} 个关键帧", + "@keyframeCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "toggleKeyframe": "{action}{channel}关键帧", + "@toggleKeyframe": { + "placeholders": { + "action": { + "type": "String" + }, + "channel": { + "type": "String" + } + } + }, + "previousKeyframe": "上一个{channel}关键帧", + "@previousKeyframe": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "nextKeyframe": "下一个{channel}关键帧", + "@nextKeyframe": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "keyframeSettings": "{channel}关键帧设置", + "@keyframeSettings": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "selectedClipsHint": "已选择 {count} 个片段\n请选择单个片段查看属性", + "@selectedClipsHint": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "transcriptionError": "识别失败,请检查组件、模型、音轨和时长({code})", + "@transcriptionError": { + "placeholders": { + "code": { + "type": "String" + } + } + }, + "captionsAdded": "已添加 {count} 条字幕,可在属性面板编辑。", + "@captionsAdded": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "translatedCaptionsAdded": "已添加 {count} 条翻译字幕,可在属性面板编辑。", + "@translatedCaptionsAdded": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "applyCaptionsError": "无法应用字幕:{message}", + "@applyCaptionsError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "applyTranslatedCaptionsError": "无法应用翻译字幕:{message}", + "@applyTranslatedCaptionsError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "recognizedCaptions": "已识别 {count} 条", + "@recognizedCaptions": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "captionCount": "{count} 条字幕", + "@captionCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "translationFailed": "翻译失败:{message}", + "@translationFailed": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "translatedCaptionCount": "{count} 条{language}字幕", + "@translatedCaptionCount": { + "placeholders": { + "count": { + "type": "int" + }, + "language": { + "type": "String" + } + } + }, + "previewParameterError": "预览参数无效:{message}", + "@previewParameterError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "mediaOffline": "素材离线或不可用:{names}", + "@mediaOffline": { + "placeholders": { + "names": { + "type": "String" + } + } + }, + "searchOptions": "搜索{label}…", + "@searchOptions": { + "placeholders": { + "label": { + "type": "String" + } + } + }, + "loadRecentProjectsFailed": "无法读取最近项目记录,仍可手动打开项目。", + "projectAccessFailed": "项目不可用", + "projectMissingDirectory": "项目不存在", + "recentProjectSaveFailed": "项目已打开,但最近使用记录未能保存。", + "lastProjectSaveFailed": "项目已打开,但上次项目记录未能保存。", + "enterProjectName": "请输入项目名称", + "projectSwitched": "项目已切换,请重新拖入素材", + "notLocalMedia": "该素材不是本地文件", + "revealMediaFailed": "无法在文件管理器中显示素材", + "openMatchingProject": "请先打开对应项目", + "projectMismatch": "此位置的项目与记录不一致,请使用“打开项目”重新选择。", + "openProjectFirst": "请先打开项目", + "localFilesOnly": "请从文件管理器拖入本地文件", + "foldersUnsupported": "请选择文件,暂不支持拖入文件夹", + "mediaImportCancelled": "素材导入已取消", + "fileAccessFailed": "文件不存在或无法读取,请检查位置与权限", + "registerMediaFailed": "无法登记素材,请重试", + "mediaNoLongerExists": "素材已不存在", + "mediaNoTracks": "素材没有可用的视频或音频轨道", + "invalidMediaDuration": "素材时长无效", + "mediaInfoUnsupported": "当前平台尚未支持素材信息读取", + "mediaInfoFailed": "无法读取素材信息,请检查文件与访问权限", + "saveTimelineFailed": "时间线保存失败,请重试。未保存的编辑仍保留在当前会话。", + "addKeyframeAction": "添加", + "backgroundTasks": "后台任务", + "noBackgroundTasks": "暂无后台任务", + "retryTask": "重试", + "applyOriginalCaptions": "应用原文字幕", + "applyTranslatedCaptions": "应用翻译字幕", + "subtitleTaskStarted": "字幕任务已开始", + "fitTimeline": "适合整个时间线", + "modify": "修改", + "projectSettings": "项目设置", + "projectSettingsDescription": "修改项目输出规格,保留片段的实际时长和速度。", + "projectColorSpace": "色彩空间", + "projectWidth": "宽度(px)", + "projectHeight": "高度(px)", + "projectResolutionInvalid": "请输入 1–16384 的整数", + "previewFullscreen": "全屏预览", + "exitPreviewFullscreen": "退出全屏", + "previewGoToStart": "回到开头", + "previewPreviousFrame": "上一帧", + "previewNextFrame": "下一帧", + "softwareUpdates": "软件更新", + "checkForUpdates": "检查更新", + "automaticallyCheckUpdates": "自动检查更新", + "updatesUnavailable": "此构建暂不提供更新。", + "updateCheckFailed": "无法检查更新,请重试。", + "agentSettings": "Agent", + "agentSaveSettingsFailed": "无法保存 Agent 设置。", + "agentDeleteProviderTitle": "删除 Provider?", + "agentDeleteProviderDescription": "将从此设备移除“{providerName}”及其保存的 API Key。", + "agentProviderRequired": "请先添加 Provider,再启用助手。", + "agentUseSelectedModel": "新的 Agent 请求将使用所选模型。", + "agentEnable": "启用 Agent", + "agentDefaultModel": "默认模型", + "agentConfigureModel": "配置模型", + "agentSelectModel": "选择模型", + "agentModelUnavailable": "此对话的模型已不可用,请选择其他模型开始新对话。", + "agentModelChangeSession": "切换模型后会开始新的 Agent 会话。", + "agentCustomProviders": "自定义 Provider", + "agentProviderStorageDescription": "Provider 元数据保存在本机,API Key 保存在系统凭据存储中。", + "agentAddProvider": "添加 Provider", + "agentBackToProviders": "返回 Provider 列表", + "agentLoadSettingsFailed": "无法读取 Agent 设置,重试", + "agentEnableProvider": "启用 Provider", + "agentEditProvider": "编辑 Provider", + "agentDeleteProvider": "删除 Provider", + "agentModelIdsUnique": "Model ID 不能重复。", + "agentEditProviderTitle": "编辑 Provider", + "agentProviderEndpointDescription": "配置 OpenAI-compatible Chat Completions 服务。", + "agentSaveProvider": "保存 Provider", + "agentProviderConfiguration": "Provider 配置", + "agentAuthenticationAndModels": "认证与模型", + "agentApiType": "API 类型", + "agentOpenAiChatCompletions": "OpenAI Completions", + "agentBaseUrl": "Base URL", + "agentApiKey": "API Key", + "agentProviderNameHint": "我的 Provider", + "agentApiKeyOptional": "不需要鉴权的服务可以留空。", + "agentApiKeyKeep": "留空将保留已保存的 Key。", + "agentOptional": "可选", + "agentApiKeyOneLine": "API Key 必须为单行文本。", + "agentRemoveSavedApiKey": "移除已保存的 API Key", + "agentModels": "模型", + "agentAddModel": "添加模型", + "agentRequiredField": "此项为必填项。", + "agentInvalidBaseUrl": "请输入不含凭据、查询参数或片段的 HTTP(S) Base URL。", + "agentModelId": "Model ID", + "agentContextWindow": "上下文窗口", + "agentMaxOutputTokens": "最大输出", + "agentMaxOutputBelowContext": "必须小于上下文窗口。", + "agentDeleteModel": "删除模型", + "agentPositiveInteger": "请输入正整数。", + "agentConfigurationReadFailed": "无法读取 Agent 配置,请检查设置后重试。", + "agentConfigurationRequired": "请先在设置中配置并启用 Agent。", + "agentSessionRestoreFailed": "无法恢复 Agent 会话,请稍后重试。", + "removeBackground": "抠像", + "startBackgroundRemoval": "开始抠像", + "backgroundRemovalResourceRequired": "抠像需要下载本地模型。下载完成后会自动开始抠像。", + "backgroundRemovalDownloadTask": "下载抠像资源", + "backgroundRemovalResourceName": "抠像模型", + "backgroundRemovalTaskStarted": "抠像任务已开始", + "backgroundRemovalApplying": "正在替换片段素材", + "backgroundRemovalComplete": "抠像完成", + "backgroundRemovalFailed": "抠像失败", + "backgroundRemovalDestructiveHint": "生成的透明素材会直接替换当前片段;仍可通过撤销恢复原片段。", + "startBackgroundRemovalFailed": "无法启动抠像,请检查素材,或等待当前处理任务完成。", + "agentContextBudgetExceeded": "输入预算不足,无法容纳系统指令、工具和消息。请增大上下文窗口或降低最大输出 tokens。", + "agentAuthenticationFailed": "鉴权失败,请检查 Provider 的 API Key 和访问权限。", + "agentConnectionFailed": "模型服务连接失败或请求超时,请检查 Base URL 和网络。", + "agentProtocolFailed": "服务返回内容不符合所选 API 类型,或响应流不完整。", + "agentContextBudgetTooSmall": "需要为系统指令保留更多输入空间,请增大上下文窗口或降低最大输出 tokens。", + "agentCompacting": "整理上下文…", + "agentEditing": "编辑中…", + "agentVerifying": "核对结果…", + "agentRecoveryRequired": "上次操作的结果尚未确认。可继续任务核对已保存回执;未确认的编辑不会重复执行。", + "agentExportReplyFailed": "视频已成功导出,总结回复失败。可重试总结,不会重复剪辑或导出。", + "agentRetrySummary": "重试总结", + "agentResumeTask": "继续任务", + "agentTaskInterrupted": "任务已中断,可从已保存的进度继续。", + "downloadSubtitleModel": "下载字幕模型", + "downloadModelAction": "下载", + "subtitleEngineUnavailable": "模型已安装,但字幕处理引擎未能启动。请修复处理引擎,无需重新下载模型。", + "backgroundTaskDetails": "任务详情", + "backgroundTaskFailed": "失败", + "backgroundTaskCompleted": "已完成", + "captionWrapLines": "换行显示字幕", + "captionSingleLine": "单行显示字幕", + "noMatchingCaptions": "没有匹配的字幕", + "subtitleResourcesRequired": "生成字幕需要这些资源。下载完成后会自动开始处理。", + "subtitleResourcesDownloadSize": "需下载 {size}", + "pauseDownload": "暂停", + "resumeDownload": "继续", + "downloadPaused": "已暂停", + "cancelResourceDownloadTitle": "取消下载?", + "cancelResourceDownloadMessage": "下载任务将停止,当前资源的下载进度可能丢失。", + "continueDownload": "继续下载", + "cancelDownload": "取消下载", + "speechResourceStage": "语音识别资源", + "translationResourceStage": "翻译资源", + "subtitleResourceDownloadTask": "下载语音与翻译资源", + "downloadingSpeechModel": "正在下载语音模型", + "downloadingTranslationModel": "正在下载翻译模型", + "agentTurnLimitReached": "本轮任务已达到执行上限,已完成的编辑已保存。发送“继续”可接着执行。", + "checkingForUpdates": "正在检查更新…", + "appIsUpToDate": "当前已是最新版本。", + "downloadingUpdate": "正在下载更新:{progress}%", + "updateAvailable": "发现新版本 {version}。", + "downloadUpdate": "下载更新", + "restartToUpdate": "重启并更新", + "updateOperationFailed": "无法更新,请完成正在运行的任务后重试。", + "windowMinimize": "最小化", + "windowMaximize": "最大化", + "windowRestore": "还原", + "workspaceAgent": "助手", + "workspaceCut": "剪辑", + "noAvailableOptions": "暂无可用选项", + "composerReferenceInvalid": "引用已失效,请切回原项目或移除引用", + "durationSeconds": "{seconds}秒", + "durationMinutesSeconds": "{minutes}分钟 {seconds}秒", + "projectNameInvalid": "项目名称无效。", + "projectLocationDefaultUnavailable": "无法访问默认项目位置,请在设置中重新选择。", + "chooseProjectLocation": "请先在设置中选择项目保存位置。", + "untitledTimeline": "未命名时间线", + "primarySequence": "主序列", + "primaryStoryline": "主线", + "projectSessionClosed": "项目会话已关闭,请重新打开项目。", + "timelineSessionClosed": "时间线会话已关闭,请重新打开时间线。", + "timelineMissing": "时间线不存在或已被删除", + "timelineInUse": "时间线正在使用中,暂时无法删除", + "timelineHasBackgroundTasks": "时间线有正在进行的后台任务,暂时无法删除", + "timelineRequired": "项目至少需要保留一条时间线", + "mediaReadFailed": "无法读取素材", + "mediaImportFailed": "无法导入素材", + "unsupportedMediaType": "仅支持导入视频、音频和图像文件", + "mediaNoVideoTracks": "素材没有可用的视频轨道", + "mediaDurationOutOfRange": "素材时长超出时间线范围", + "resourceDownloadHttpFailed": "下载失败(HTTP {statusCode})", + "resourceChecksumFailed": "模型文件校验失败,请重新下载资源。", + "subtitleLanguageAf": "南非荷兰语", + "subtitleLanguageAm": "阿姆哈拉语", + "subtitleLanguageAr": "阿拉伯语", + "subtitleLanguageAst": "阿斯图里亚斯语", + "subtitleLanguageAz": "阿塞拜疆语", + "subtitleLanguageBa": "巴什基尔语", + "subtitleLanguageBe": "白俄罗斯语", + "subtitleLanguageBg": "保加利亚语", + "subtitleLanguageBn": "孟加拉语", + "subtitleLanguageBr": "布列塔尼语", + "subtitleLanguageBs": "波斯尼亚语", + "subtitleLanguageCa": "加泰罗尼亚语", + "subtitleLanguageCeb": "宿务语", + "subtitleLanguageCs": "捷克语", + "subtitleLanguageCy": "威尔士语", + "subtitleLanguageDa": "丹麦语", + "subtitleLanguageDe": "德语", + "subtitleLanguageEl": "希腊语", + "subtitleLanguageEn": "英语", + "subtitleLanguageEs": "西班牙语", + "subtitleLanguageEt": "爱沙尼亚语", + "subtitleLanguageFa": "波斯语", + "subtitleLanguageFf": "富拉语", + "subtitleLanguageFi": "芬兰语", + "subtitleLanguageFr": "法语", + "subtitleLanguageFy": "西弗里斯语", + "subtitleLanguageGa": "爱尔兰语", + "subtitleLanguageGd": "苏格兰盖尔语", + "subtitleLanguageGl": "加利西亚语", + "subtitleLanguageGu": "古吉拉特语", + "subtitleLanguageHa": "豪萨语", + "subtitleLanguageHe": "希伯来语", + "subtitleLanguageHi": "印地语", + "subtitleLanguageHr": "克罗地亚语", + "subtitleLanguageHt": "海地克里奥尔语", + "subtitleLanguageHu": "匈牙利语", + "subtitleLanguageHy": "亚美尼亚语", + "subtitleLanguageId": "印度尼西亚语", + "subtitleLanguageIg": "伊博语", + "subtitleLanguageIlo": "伊洛卡诺语", + "subtitleLanguageIs": "冰岛语", + "subtitleLanguageIt": "意大利语", + "subtitleLanguageJa": "日语", + "subtitleLanguageJv": "爪哇语", + "subtitleLanguageKa": "格鲁吉亚语", + "subtitleLanguageKk": "哈萨克语", + "subtitleLanguageKm": "高棉语", + "subtitleLanguageKn": "卡纳达语", + "subtitleLanguageKo": "韩语", + "subtitleLanguageLb": "卢森堡语", + "subtitleLanguageLg": "卢干达语", + "subtitleLanguageLn": "林加拉语", + "subtitleLanguageLo": "老挝语", + "subtitleLanguageLt": "立陶宛语", + "subtitleLanguageLv": "拉脱维亚语", + "subtitleLanguageMg": "马拉加斯语", + "subtitleLanguageMk": "马其顿语", + "subtitleLanguageMl": "马拉雅拉姆语", + "subtitleLanguageMn": "蒙古语", + "subtitleLanguageMr": "马拉地语", + "subtitleLanguageMs": "马来语", + "subtitleLanguageMy": "缅甸语", + "subtitleLanguageNe": "尼泊尔语", + "subtitleLanguageNl": "荷兰语", + "subtitleLanguageNo": "挪威语", + "subtitleLanguageNs": "北索托语", + "subtitleLanguageOc": "奥克语", + "subtitleLanguageOr": "奥里亚语", + "subtitleLanguagePa": "旁遮普语", + "subtitleLanguagePl": "波兰语", + "subtitleLanguagePs": "普什图语", + "subtitleLanguagePt": "葡萄牙语", + "subtitleLanguageRo": "罗马尼亚语", + "subtitleLanguageRu": "俄语", + "subtitleLanguageSd": "信德语", + "subtitleLanguageSi": "僧伽罗语", + "subtitleLanguageSk": "斯洛伐克语", + "subtitleLanguageSl": "斯洛文尼亚语", + "subtitleLanguageSo": "索马里语", + "subtitleLanguageSq": "阿尔巴尼亚语", + "subtitleLanguageSr": "塞尔维亚语", + "subtitleLanguageSs": "斯瓦蒂语", + "subtitleLanguageSu": "巽他语", + "subtitleLanguageSv": "瑞典语", + "subtitleLanguageSw": "斯瓦希里语", + "subtitleLanguageTa": "泰米尔语", + "subtitleLanguageTh": "泰语", + "subtitleLanguageTl": "他加禄语", + "subtitleLanguageTn": "茨瓦纳语", + "subtitleLanguageTr": "土耳其语", + "subtitleLanguageUk": "乌克兰语", + "subtitleLanguageUr": "乌尔都语", + "subtitleLanguageUz": "乌兹别克语", + "subtitleLanguageVi": "越南语", + "subtitleLanguageWo": "沃洛夫语", + "subtitleLanguageXh": "科萨语", + "subtitleLanguageYi": "意第绪语", + "subtitleLanguageYo": "约鲁巴语", + "subtitleLanguageYue": "粤语", + "subtitleLanguageZh": "中文", + "subtitleLanguageZu": "祖鲁语", + "linearRec2020": "线性 Rec.2020", + "diagnostics": "诊断", + "exportDiagnostics": "导出诊断包", + "exportDiagnosticsFailed": "无法导出诊断包,请重试。", + "exportDiagnosticsSucceeded": "诊断包已保存。" +} diff --git a/lib/l10n/app_zh_Hant.arb b/lib/l10n/app_zh_Hant.arb new file mode 100644 index 0000000..51164aa --- /dev/null +++ b/lib/l10n/app_zh_Hant.arb @@ -0,0 +1,889 @@ +{ + "selectProject": "選擇專案", + "searchProjects": "搜尋專案", + "noMatchingProjects": "沒有符合的專案", + "projectsNone": "暫無專案", + "projectLocationMissing": "目錄不存在,建立專案時將自動建立。", + "projectLocationUnavailable": "專案儲存位置無法使用,請連接磁碟或檢查網路後重試,也可以變更位置。", + "projectLocationNotWritable": "專案儲存位置沒有寫入權限,請檢查權限或變更位置。", + "projectLocationCreateFailed": "無法建立或寫入專案儲存目錄,請檢查權限或變更位置。", + "removeProjectFromSidebar": "從側邊欄移除", + "projectRemoved": "已移除專案,本機檔案和聊天記錄已保留。", + "agentNoConversations": "暫無聊天", + "renameConversationTitle": "重新命名聊天", + "renameConversationDescription": "保持簡短且易於辨識", + "collapseProject": "收合專案", + "expandProject": "展開專案", + "agentDeleteConfirmation": "聊天「{title}」及其訊息記錄將被永久刪除,無法復原。本機專案檔案不受影響。", + "agentEmptyTrashConfirmation": "垃圾桶中的所有聊天將被永久刪除,無法復原。本機專案檔案不受影響。", + "agentConversations": "對話", + "showMoreConversations": "展開顯示", + "showFewerConversations": "收起顯示", + "agentNewConversation": "新增對話", + "agentElapsedTime": "耗時 {duration}", + "agentConversationActions": "對話操作", + "agentMoveToTrash": "移至資源回收桶", + "agentTrash": "資源回收桶", + "agentRestore": "還原", + "agentEmptyTrash": "清空資源回收桶", + "agentDeleteForever": "永久刪除", + "agentConversationLocation": "對話儲存位置", + "agentChooseExistingConversations": "選擇現有對話目錄", + "agentMoveConversations": "搬移對話", + "agentLocationUnavailable": "對話儲存位置無法使用", + "agentLocationBusy": "請等待目前對話執行完畢再搬移", + "agentRelinkProvider": "重新關聯 Provider", + "@@locale": "zh_Hant", + "settings": "設定", + "closeSettings": "關閉設定", + "general": "通用", + "appearance": "外觀", + "theme": "主題", + "system": "跟隨系統", + "light": "淺色", + "dark": "深色", + "saveAppearanceFailed": "無法儲存外觀設定,請重試", + "loadAppearanceFailed": "無法讀取外觀設定,請重新選擇主題", + "cancel": "取消", + "save": "儲存", + "create": "建立", + "close": "關閉", + "retry": "重試", + "select": "選擇", + "name": "名稱", + "enterName": "請輸入名稱", + "invalidName": "名稱不能包含路徑分隔符或控制字元", + "projects": "專案", + "projectName": "專案名稱", + "projectLocation": "專案儲存位置", + "projectLocationNotSet": "未設定", + "loadProjectLocationFailed": "無法讀取專案儲存位置。", + "saveProjectLocationFailed": "無法儲存專案儲存位置。", + "resourceLocation": "資源儲存位置", + "resourceLocationNotSet": "未設定", + "loadResourceLocationFailed": "無法讀取資源儲存位置。", + "saveResourceLocationFailed": "無法儲存資源儲存位置。", + "transcriptionResourceRequired": "產生字幕需要先下載語音辨識模型。", + "downloadAndContinue": "下載並繼續", + "downloadingResource": "正在下載…", + "downloadInBackground": "後臺下載", + "processingResourceDownloadFailed": "語音辨識資源下載失敗,請重試。", + "newProject": "新建專案", + "openProject": "開啟專案", + "openProjectMore": "開啟專案…", + "saveHere": "儲存到這裡", + "selectDirectoryFailed": "無法選擇目錄,請檢查系統許可權。", + "openingWorkspace": "正在開啟工作區…", + "loadProjectsFailed": "無法載入專案列表", + "projectsEmpty": "新建或開啟專案,開始剪輯。", + "backToProjects": "返回剪輯", + "timelines": "時間軸", + "timelineLimitReached": "每個專案最多可建立 {count} 條時間軸。", + "timelineName": "時間軸名稱", + "defaultTimelineName": "時間軸 {index}", + "newTimeline": "新建時間軸", + "noTimelines": "暫無時間軸", + "activeTimeline": "當前時間軸", + "timelineUnavailable": "時間軸不可用", + "projectNoTimelines": "專案中還沒有時間軸", + "createTimelineHint": "在左側“時間軸”分組中新建時間軸,開始剪輯。", + "createTimelineChat": "新建時間軸後即可開始對話", + "operationFailed": "操作失敗,請重試", + "collapseSidebar": "收起側邊欄", + "expandSidebar": "展開側邊欄", + "expandEditor": "展開剪輯區", + "collapseProperties": "收起屬性面板", + "expandProperties": "展開屬性面板", + "layout": "佈局", + "editingFirstLayout": "剪輯優先", + "agentEditingLayout": "Agent + 剪輯", + "agentLayoutDescription": "規劃、協作和執行", + "editingLayoutDescription": "預覽、剪輯和調整", + "materials": "素材", + "all": "全部", + "video": "影片", + "audio": "音訊", + "image": "影象", + "picture": "圖片", + "captions": "字幕", + "text": "文字", + "noMedia": "暫無素材", + "mediaCategory": "素材分類", + "captionTasks": "字幕任務", + "listLayout": "列表佈局", + "gridLayout": "宮格佈局", + "addToTimeline": "新增到時間軸", + "rename": "重新命名", + "renameMedia": "重新命名素材", + "removeMedia": "移除素材", + "remove": "移除", + "revealFinder": "在訪達中顯示", + "revealFileManager": "在檔案管理器中顯示", + "dropToAdd": "放開即可新增", + "timelineDropToStart": "將媒體拖到此處以開始。", + "dragMediaHint": "將影片、音訊或影象拖到這裡\n原檔案保留在原位置", + "transcribe": "轉字幕", + "generateCaptions": "生成字幕", + "play": "播放", + "pause": "暫停播放", + "retryPreview": "重試預覽", + "canvasRatio": "畫布比例", + "noPreviewContent": "時間軸中暫無可預覽內容", + "nativePreviewUnsupported": "當前平臺尚未實現原生預覽", + "canvasTransformFailed": "無法完成畫布變換,請重試。", + "undo": "復原", + "redo": "重做", + "deleteSelectedClips": "刪除所選片段", + "splitAtPlayhead": "在播放頭處分割", + "trimLeft": "向左裁剪", + "trimRight": "向右裁剪", + "trimLeftTooltip": "裁掉播放頭左側,保留右側", + "trimRightTooltip": "裁掉播放頭右側,保留左側", + "currentSequence": "當前序列", + "projectProperties": "專案屬性", + "canvasSize": "畫布尺寸", + "frameRate": "幀率", + "duration": "時長", + "totalDuration": "總時長", + "clipDuration": "片段時長", + "seconds": "秒", + "clip": "片段", + "unnamedClip": "未命名片段", + "gap": "空隙", + "compoundClip": "複合片段", + "textClip": "文字片段", + "pictureProperties": "畫面", + "position": "位置", + "rotation": "旋轉", + "scale": "縮放", + "size": "尺寸", + "transform": "變換", + "resetPosition": "重置位置", + "keepAspectRatio": "等比縮放", + "alignment": "對齊", + "alignLeft": "左對齊", + "alignRight": "右對齊", + "alignTop": "頂部對齊", + "alignBottom": "底部對齊", + "alignHorizontalCenter": "水平置中", + "alignVerticalCenter": "垂直置中", + "volume": "音量", + "gain": "增益", + "mute": "靜音", + "unmute": "取消靜音", + "resetVolume": "重置音量", + "invalidGain": "請輸入 -90 到 +12 之間的數值", + "animation": "動畫", + "keyframes": "關鍵幀", + "removeAllKeyframes": "移除全部關鍵幀", + "linear": "線性", + "easeIn": "緩入", + "easeOut": "緩出", + "easeInOut": "緩入緩出", + "basic": "基本", + "mask": "遮罩", + "addMask": "新增遮罩", + "deleteMask": "刪除遮罩", + "resetMask": "重置遮罩", + "enableMask": "啟用遮罩", + "disableMask": "停用遮罩", + "moveMaskUp": "上移遮罩", + "moveMaskDown": "下移遮罩", + "rectangle": "矩形", + "ellipse": "橢圓", + "invert": "反轉", + "feather": "羽化", + "add": "相加", + "subtract": "相減", + "intersect": "相交", + "initialRegion": "初始區域", + "none": "無", + "color": "顏色", + "fontSize": "字級", + "outlineWidth": "描邊寬度", + "outlineColor": "描邊顏色", + "captionBaseline": "字幕基線", + "content": "文字", + "start": "開始", + "time": "時間", + "speed": "速度", + "speedSegmentCount": "{count} 個速度區間", + "splitSpeedAtPlayhead": "在播放磁頭分割速度區間", + "speedChange": "變速", + "speedMode": "變速模式", + "constantSpeed": "恆定速度", + "segmentedSpeed": "分段變速", + "speedNotAvailable": "變速調節控制元件尚未接入", + "custom": "自定義", + "invalidNumber": "無效數值", + "mediaUnavailable": "素材不可用", + "mediaMissing": "素材缺失", + "mediaColorSpace": "素材色彩空間", + "mediaColorInterpretation": "素材色彩解釋", + "colorInfoNotLoaded": "色彩資訊未讀取", + "unknownColorSpace": "色彩空間未知,暫按 Rec.709 顯示", + "colorBackendUnsupported": "當前後端不支援素材色彩解釋。", + "loadClipPropertiesFailed": "無法讀取片段屬性", + "updatePictureFailed": "無法更新畫面屬性", + "updateVolumeFailed": "無法更新音量", + "updateMaskFailed": "無法更新遮罩", + "updateKeyframesFailed": "無法更新關鍵幀", + "maskPreviewFailed": "無法準備遮罩預覽", + "alignClipFailed": "無法對齊片段,請等待預覽就緒後重試", + "invalidTransform": "縮放範圍為 1%–10000%,位置和角度必須為有效數值", + "editFailed": "無法修改,請檢查輸入和時間範圍。", + "addMediaFailed": "無法新增素材,請重試", + "deleteCaption": "刪除字幕", + "mergeCaptions": "合併字幕", + "captionDeleted": "字幕已刪除", + "captionChanged": "字幕已變化,請重試。", + "captionEditChanged": "字幕已變化,請重新編輯。", + "assistantHint": "描述你的剪輯想法", + "configureAgentHint": "配置 Agent 服務後開始對話", + "agentRestartHint": "請配置 Agent 服務後重新啟動應用。", + "replyInterrupted": "回覆已中斷", + "replying": "正在回覆…", + "stopReply": "停止回覆", + "sendMessage": "傳送訊息", + "addAttachment": "新增附件(暫未接入)", + "replyFailed": "回覆失敗,請檢查服務連線或稍後重試。", + "mcpService": "MCP 服務", + "listenPort": "監聽埠", + "accessToken": "訪問令牌", + "copyAccessToken": "複製訪問令牌", + "accessTokenCopied": "訪問令牌已複製", + "loadMcpFailed": "無法讀取 MCP 設定,重試", + "saveMcpFailed": "無法儲存 MCP 設定,請重試", + "retryStart": "重試啟動", + "invalidPort": "埠必須為 1–65535", + "loadingSettings": "正在讀取設定…", + "starting": "正在啟動…", + "stopping": "正在停止…", + "disabled": "已停用", + "running": "執行中", + "startFailed": "啟動失敗", + "saved": "已儲存", + "unsaved": "未儲存", + "saving": "儲存中…", + "pendingSave": "待儲存", + "notApplied": "未應用", + "enable": "啟用", + "disable": "停用", + "type": "型別", + "status": "狀態", + "file": "檔案", + "unboundMedia": "未繫結素材", + "unboundAudio": "未繫結音軌", + "vertical": "垂直", + "language": "語言", + "saveLanguageFailed": "無法儲存語言設定,請重試", + "loadLanguageFailed": "無法讀取語言設定,請重新選擇", + "propertiesFirstLayout": "屬性優先佈局", + "defaultLayout": "預設佈局", + "separateVocals": "分離人聲", + "detachAudio": "分離音訊", + "restoreAudio": "恢復音訊", + "audioDetached": "音訊已分離", + "addAll": "全部新增", + "preparingMedia": "準備素材…", + "cancelling": "正在取消…", + "cancelled": "已取消", + "interruptedTask": "任務已中斷,可重新啟動並繼續", + "auto": "自動", + "autoDetect": "自動識別", + "noTranslation": "不翻譯", + "sourceLanguage": "源語言", + "translationLanguage": "翻譯語言", + "transcriptionNotConfigured": "轉字幕尚未配置,請安裝識別元件和 Whisper Turbo 模型。", + "translationNotConfigured": "字幕翻譯尚未配置,目前可生成源語言字幕。", + "sourceLanguageUnknown": "無法確定可翻譯的源語言。", + "startTranscriptionFailed": "無法啟動識別,請檢查素材,或等待當前任務完成。", + "placeMediaFirst": "請先將這份素材放到時間軸,再應用字幕。", + "placeTranslationMediaFirst": "請先將對應素材放到時間軸,再應用翻譯字幕。", + "selectTargetClip": "選擇目標片段", + "timelineChanged": "時間軸已變化,請重新選擇目標片段。", + "transcriptionAccessFailed": "識別失敗:無法訪問識別元件、模型或源素材(notConfigured)", + "transcriptionNoAudio": "識別失敗:所選素材或音軌沒有可識別的音訊(noAudio)", + "transcriptionInvalidResult": "識別失敗:元件返回的字幕檔案無效(invalidResult)", + "transcriptionWorkerExited": "識別失敗:識別元件意外退出(workerExited)", + "transcriptionProcessingFailed": "識別失敗:原生識別處理失敗(processingFailed)", + "transcriptionFailed": "識別失敗,請檢查元件、模型、音軌和時長", + "transcribing": "正在識別…", + "captionsGenerated": "字幕已生成", + "cancelTranscription": "取消識別", + "applyCaptions": "應用為字幕", + "preparingTranslation": "準備翻譯…", + "translatingCaptions": "正在翻譯字幕…", + "cancellingTranslation": "正在取消翻譯…", + "translatedCaptionsGenerated": "翻譯字幕已生成", + "translationCancelled": "翻譯已取消", + "translationInterrupted": "翻譯任務已中斷", + "cancelTranslation": "取消翻譯", + "editorServiceUnavailable": "編輯工具服務不可用,請重新開啟專案。", + "mcpUnavailable": "MCP 連線不可用,請檢查本地埠和令牌配置。", + "openTimelineFailed": "無法開啟時間軸", + "noTimelineSequence": "時間軸中沒有序列", + "waitingForProject": "等待開啟工程", + "hold": "保持", + "noImportableFiles": "未收到可匯入的檔案", + "virtualFilesUnsupported": "請從檔案管理器拖入原檔案,暫不支援虛擬檔案", + "editorSessionStartFailed": "無法開啟時間軸編輯器", + "previewStartFailed": "無法啟動原生預覽", + "previewInvalidTrack": "素材中不存在所選音影片軌道。", + "previewMissingBinding": "缺少素材繫結,無法預覽當前時間軸。", + "previewUnsupportedEdits": "當前時間軸包含尚不支援預覽的編輯。", + "previewUnsupportedConfiguration": "當前平臺或系統版本尚不支援此預覽配置。", + "previewHdrUnsupported": "HDR 素材需要色調對映才能在 SDR 預覽中顯示,當前系統或預覽配置不支援。", + "previewAudioOutOfRange": "音訊片段超出了素材音軌的有效範圍,無法預覽。", + "previewResourceMissing": "預覽素材已不存在,請重新定位原檔案。", + "previewInvalidComposition": "影片合成配置無效,無法建立預覽。", + "previewInvalidData": "預覽資料無效,請重試。", + "previewFailed": "預覽失敗,請檢查素材是否可訪問後重試。", + "chatFailed": "無法完成對話,請檢查服務配置或稍後重試。", + "delete": "刪除", + "pinTimeline": "置頂時間軸", + "unpinTimeline": "取消置頂", + "deleteTimelineConfirmation": "刪除「{name}」及其編輯歷史?此操作無法復原。", + "@deleteTimelineConfirmation": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "processingFailed": "處理失敗", + "noMatchingOptions": "沒有匹配的選項", + "removeMediaConfirmation": "從專案移除“{name}”?已有片段、歷史版本和原檔案會保留。", + "@removeMediaConfirmation": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "mediaAdded": "已新增 {count} 個素材引用", + "@mediaAdded": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "duplicatesSkipped": "跳過 {count} 個重複檔案", + "@duplicatesSkipped": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "mediaCount": "{count} 個素材", + "importMedia": "匯入", + "@mediaCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "noMediaOfType": "暫無{type}素材", + "@noMediaOfType": { + "placeholders": { + "type": { + "type": "String" + } + } + }, + "captionsImported": "已匯入 {count} 條字幕", + "@captionsImported": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "editCaptionError": "無法修改字幕:{message}", + "@editCaptionError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "mcpStartError": "無法啟動 MCP:{message}", + "@mcpStartError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "manualColorSpace": "手動指定:{name}", + "@manualColorSpace": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "detectedColorSpace": "已識別:{name}", + "@detectedColorSpace": { + "placeholders": { + "name": { + "type": "String" + } + } + }, + "keyframeLabel": "{channel}關鍵幀", + "@keyframeLabel": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "maskMode": "組合方式:{mode}", + "@maskMode": { + "placeholders": { + "mode": { + "type": "String" + } + } + }, + "keyframeCount": "{count} 個關鍵幀", + "@keyframeCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "toggleKeyframe": "{action}{channel}關鍵幀", + "@toggleKeyframe": { + "placeholders": { + "action": { + "type": "String" + }, + "channel": { + "type": "String" + } + } + }, + "previousKeyframe": "上一個{channel}關鍵幀", + "@previousKeyframe": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "nextKeyframe": "下一個{channel}關鍵幀", + "@nextKeyframe": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "keyframeSettings": "{channel}關鍵幀設定", + "@keyframeSettings": { + "placeholders": { + "channel": { + "type": "String" + } + } + }, + "selectedClipsHint": "已選擇 {count} 個片段\n請選擇單個片段檢視屬性", + "@selectedClipsHint": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "transcriptionError": "識別失敗,請檢查元件、模型、音軌和時長({code})", + "@transcriptionError": { + "placeholders": { + "code": { + "type": "String" + } + } + }, + "captionsAdded": "已新增 {count} 條字幕,可在屬性面板編輯。", + "@captionsAdded": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "translatedCaptionsAdded": "已新增 {count} 條翻譯字幕,可在屬性面板編輯。", + "@translatedCaptionsAdded": { + "placeholders": { + "count": { + "type": "String" + } + } + }, + "applyCaptionsError": "無法應用字幕:{message}", + "@applyCaptionsError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "applyTranslatedCaptionsError": "無法應用翻譯字幕:{message}", + "@applyTranslatedCaptionsError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "recognizedCaptions": "已識別 {count} 條", + "@recognizedCaptions": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "captionCount": "{count} 條字幕", + "@captionCount": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "translationFailed": "翻譯失敗:{message}", + "@translationFailed": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "translatedCaptionCount": "{count} 條{language}字幕", + "@translatedCaptionCount": { + "placeholders": { + "count": { + "type": "int" + }, + "language": { + "type": "String" + } + } + }, + "previewParameterError": "預覽引數無效:{message}", + "@previewParameterError": { + "placeholders": { + "message": { + "type": "String" + } + } + }, + "mediaOffline": "素材離線或不可用:{names}", + "@mediaOffline": { + "placeholders": { + "names": { + "type": "String" + } + } + }, + "searchOptions": "搜尋{label}…", + "@searchOptions": { + "placeholders": { + "label": { + "type": "String" + } + } + }, + "loadRecentProjectsFailed": "無法讀取最近專案記錄,仍可手動開啟專案。", + "projectAccessFailed": "專案無法使用", + "projectMissingDirectory": "專案不存在", + "recentProjectSaveFailed": "專案已開啟,但最近使用記錄未能儲存。", + "lastProjectSaveFailed": "專案已開啟,但上次專案記錄未能儲存。", + "enterProjectName": "請輸入專案名稱", + "projectSwitched": "專案已切換,請重新拖入素材", + "notLocalMedia": "該素材不是本地檔案", + "revealMediaFailed": "無法在檔案管理器中顯示素材", + "openMatchingProject": "請先開啟對應專案", + "projectMismatch": "此位置的專案與記錄不一致,請使用“開啟專案”重新選擇。", + "openProjectFirst": "請先開啟專案", + "localFilesOnly": "請從檔案管理器拖入本地檔案", + "foldersUnsupported": "請選擇檔案,暫不支援拖入資料夾", + "mediaImportCancelled": "素材匯入已取消", + "fileAccessFailed": "檔案不存在或無法讀取,請檢查位置與許可權", + "registerMediaFailed": "無法登記素材,請重試", + "mediaNoLongerExists": "素材已不存在", + "mediaNoTracks": "素材沒有可用的影片或音訊軌道", + "invalidMediaDuration": "素材時長無效", + "mediaInfoUnsupported": "當前平臺尚未支援素材資訊讀取", + "mediaInfoFailed": "無法讀取素材資訊,請檢查檔案與訪問許可權", + "saveTimelineFailed": "時間軸儲存失敗,請重試。未儲存的編輯仍保留在當前會話。", + "addKeyframeAction": "新增", + "backgroundTasks": "後臺任務", + "noBackgroundTasks": "暫無後臺任務", + "retryTask": "重試", + "applyOriginalCaptions": "應用原文字幕", + "applyTranslatedCaptions": "應用翻譯字幕", + "subtitleTaskStarted": "字幕任務已開始", + "fitTimeline": "符合整個時間軸", + "modify": "修改", + "projectSettings": "项目设置", + "projectSettingsDescription": "修改项目输出规格,保留片段的实际时长和速度。", + "projectColorSpace": "色彩空间", + "projectWidth": "宽度(px)", + "projectHeight": "高度(px)", + "projectResolutionInvalid": "请输入 1–16384 的整数", + "previewFullscreen": "全螢幕預覽", + "exitPreviewFullscreen": "退出全螢幕", + "previewGoToStart": "回到開頭", + "previewPreviousFrame": "上一影格", + "previewNextFrame": "下一影格", + "softwareUpdates": "軟體更新", + "checkForUpdates": "檢查更新", + "automaticallyCheckUpdates": "自動檢查更新", + "updatesUnavailable": "此版本暫不提供更新。", + "updateCheckFailed": "無法檢查更新,請重試。", + "agentSettings": "Agent", + "agentSaveSettingsFailed": "無法儲存 Agent 設定。", + "agentDeleteProviderTitle": "刪除 Provider?", + "agentDeleteProviderDescription": "將從此裝置移除「{providerName}」及其儲存的 API Key。", + "agentProviderRequired": "請先新增 Provider,再啟用助手。", + "agentUseSelectedModel": "新的 Agent 請求將使用所選模型。", + "agentEnable": "啟用 Agent", + "agentDefaultModel": "預設模型", + "agentConfigureModel": "設定模型", + "agentSelectModel": "選擇模型", + "agentModelUnavailable": "此對話的模型已無法使用,請選擇其他模型開始新對話。", + "agentModelChangeSession": "切換模型後會開始新的 Agent 工作階段。", + "agentCustomProviders": "自訂 Provider", + "agentProviderStorageDescription": "Provider 中繼資料儲存在本機,API Key 儲存在系統憑證儲存區中。", + "agentAddProvider": "新增 Provider", + "agentBackToProviders": "返回 Provider 列表", + "agentLoadSettingsFailed": "無法讀取 Agent 設定,重試", + "agentEnableProvider": "啟用 Provider", + "agentEditProvider": "編輯 Provider", + "agentDeleteProvider": "刪除 Provider", + "agentModelIdsUnique": "Model ID 不可重複。", + "agentEditProviderTitle": "編輯 Provider", + "agentProviderEndpointDescription": "設定 OpenAI-compatible Chat Completions 服務。", + "agentSaveProvider": "儲存 Provider", + "agentProviderConfiguration": "Provider 設定", + "agentAuthenticationAndModels": "驗證與模型", + "agentApiType": "API 類型", + "agentOpenAiChatCompletions": "OpenAI Completions", + "agentBaseUrl": "Base URL", + "agentApiKey": "API Key", + "agentProviderNameHint": "我的 Provider", + "agentApiKeyOptional": "不需要驗證的服務可以留空。", + "agentApiKeyKeep": "留空將保留已儲存的 Key。", + "agentOptional": "選填", + "agentApiKeyOneLine": "API Key 必須為單行文字。", + "agentRemoveSavedApiKey": "移除已儲存的 API Key", + "agentModels": "模型", + "agentAddModel": "新增模型", + "agentRequiredField": "此欄位為必填。", + "agentInvalidBaseUrl": "請輸入不含憑證、查詢參數或片段的 HTTP(S) Base URL。", + "agentModelId": "Model ID", + "agentContextWindow": "上下文視窗", + "agentMaxOutputTokens": "最大輸出", + "agentMaxOutputBelowContext": "必須小於上下文視窗。", + "agentDeleteModel": "刪除模型", + "agentPositiveInteger": "請輸入正整數。", + "agentConfigurationReadFailed": "無法讀取 Agent 設定,請檢查設定後重試。", + "agentConfigurationRequired": "請先在設定中配置並啟用 Agent。", + "agentSessionRestoreFailed": "無法恢復 Agent 工作階段,請稍後重試。", + "removeBackground": "去背", + "startBackgroundRemoval": "開始去背", + "backgroundRemovalResourceRequired": "去背需要下載本機模型。下載完成後會自動開始去背。", + "backgroundRemovalDownloadTask": "下載去背資源", + "backgroundRemovalResourceName": "去背模型", + "backgroundRemovalTaskStarted": "去背工作已開始", + "backgroundRemovalApplying": "正在替換片段素材", + "backgroundRemovalComplete": "去背完成", + "backgroundRemovalFailed": "去背失敗", + "backgroundRemovalDestructiveHint": "產生的透明素材會直接替換目前片段;仍可透過復原還原原片段。", + "startBackgroundRemovalFailed": "無法啟動去背,請檢查素材,或等待目前的處理工作完成。", + "agentContextBudgetExceeded": "輸入預算不足,無法容納系統指令、工具和訊息。請增大上下文視窗或降低最大輸出 tokens。", + "agentAuthenticationFailed": "驗證失敗,請檢查 Provider 的 API Key 和存取權限。", + "agentConnectionFailed": "模型服務連線失敗或請求逾時,請檢查 Base URL 和網路。", + "agentProtocolFailed": "服務回傳內容不符合所選 API 類型,或回應串流不完整。", + "agentContextBudgetTooSmall": "需要為系統指令保留更多輸入空間,請增大上下文視窗或降低最大輸出 tokens。", + "agentRecoveryRequired": "上次操作的結果尚未確認。可繼續任務核對已儲存回執;未確認的編輯不會重複執行。", + "agentExportReplyFailed": "影片已成功匯出,摘要回覆失敗。可重試摘要,不會重複剪輯或匯出。", + "agentRetrySummary": "重試摘要", + "agentResumeTask": "繼續任務", + "agentTaskInterrupted": "任務已中斷,可從已儲存的進度繼續。", + "downloadSubtitleModel": "下載字幕模型", + "downloadModelAction": "下載", + "subtitleEngineUnavailable": "模型已安裝,但字幕處理引擎未能啟動。請修復處理引擎,無需重新下載模型。", + "backgroundTaskDetails": "任務詳情", + "backgroundTaskFailed": "失敗", + "backgroundTaskCompleted": "已完成", + "captionWrapLines": "換行顯示字幕", + "captionSingleLine": "單行顯示字幕", + "noMatchingCaptions": "沒有符合的字幕", + "subtitleResourcesRequired": "產生字幕需要這些資源。下載完成後會自動開始處理。", + "subtitleResourcesDownloadSize": "需下載 {size}", + "pauseDownload": "暫停", + "resumeDownload": "繼續", + "downloadPaused": "已暫停", + "cancelResourceDownloadTitle": "取消下載?", + "cancelResourceDownloadMessage": "下載任務將停止,目前資源的下載進度可能遺失。", + "continueDownload": "繼續下載", + "cancelDownload": "取消下載", + "speechResourceStage": "語音辨識資源", + "translationResourceStage": "翻譯資源", + "subtitleResourceDownloadTask": "下載語音與翻譯資源", + "downloadingSpeechModel": "正在下載語音模型", + "downloadingTranslationModel": "正在下載翻譯模型", + "agentCompacting": "整理上下文…", + "agentEditing": "編輯中…", + "agentVerifying": "核對結果…", + "agentTurnLimitReached": "本輪任務已達到執行上限,已完成的編輯已儲存。傳送「繼續」可接著執行。", + "checkingForUpdates": "正在檢查更新…", + "appIsUpToDate": "目前已是最新版本。", + "downloadingUpdate": "正在下載更新:{progress}%", + "updateAvailable": "發現新版本 {version}。", + "downloadUpdate": "下載更新", + "restartToUpdate": "重新啟動並更新", + "updateOperationFailed": "無法更新,請完成正在執行的工作後重試。", + "windowMinimize": "最小化", + "windowMaximize": "最大化", + "windowRestore": "還原", + "workspaceAgent": "助手", + "workspaceCut": "剪輯", + "noAvailableOptions": "暫無可用選項", + "composerReferenceInvalid": "引用已失效,請切回原專案或移除引用", + "durationSeconds": "{seconds}秒", + "durationMinutesSeconds": "{minutes}分鐘 {seconds}秒", + "projectNameInvalid": "專案名稱無效。", + "projectLocationDefaultUnavailable": "無法存取預設專案位置,請在設定中重新選擇。", + "chooseProjectLocation": "請先在設定中選擇專案儲存位置。", + "untitledTimeline": "未命名時間軸", + "primarySequence": "主序列", + "primaryStoryline": "主線", + "projectSessionClosed": "專案工作階段已關閉,請重新開啟專案。", + "timelineSessionClosed": "時間軸工作階段已關閉,請重新開啟時間軸。", + "timelineMissing": "時間軸不存在或已被刪除", + "timelineInUse": "時間軸正在使用中,暫時無法刪除", + "timelineHasBackgroundTasks": "時間軸有正在進行的背景工作,暫時無法刪除", + "timelineRequired": "專案至少需要保留一條時間軸", + "mediaReadFailed": "無法讀取素材", + "mediaImportFailed": "無法匯入素材", + "unsupportedMediaType": "僅支援匯入影片、音訊和影像檔案", + "mediaNoVideoTracks": "素材沒有可用的影片軌道", + "mediaDurationOutOfRange": "素材時長超出時間軸範圍", + "resourceDownloadHttpFailed": "下載失敗(HTTP {statusCode})", + "resourceChecksumFailed": "模型檔案驗證失敗,請重新下載資源。", + "subtitleLanguageAf": "南非荷蘭文", + "subtitleLanguageAm": "阿姆哈拉文", + "subtitleLanguageAr": "阿拉伯文", + "subtitleLanguageAst": "阿斯圖里亞文", + "subtitleLanguageAz": "亞塞拜然文", + "subtitleLanguageBa": "巴什喀爾文", + "subtitleLanguageBe": "白俄羅斯文", + "subtitleLanguageBg": "保加利亞文", + "subtitleLanguageBn": "孟加拉文", + "subtitleLanguageBr": "布列塔尼文", + "subtitleLanguageBs": "波士尼亞文", + "subtitleLanguageCa": "加泰蘭文", + "subtitleLanguageCeb": "宿霧文", + "subtitleLanguageCs": "捷克文", + "subtitleLanguageCy": "威爾斯文", + "subtitleLanguageDa": "丹麥文", + "subtitleLanguageDe": "德文", + "subtitleLanguageEl": "希臘文", + "subtitleLanguageEn": "英文", + "subtitleLanguageEs": "西班牙文", + "subtitleLanguageEt": "愛沙尼亞文", + "subtitleLanguageFa": "波斯文", + "subtitleLanguageFf": "富拉文", + "subtitleLanguageFi": "芬蘭文", + "subtitleLanguageFr": "法文", + "subtitleLanguageFy": "西弗里西亞文", + "subtitleLanguageGa": "愛爾蘭文", + "subtitleLanguageGd": "蘇格蘭蓋爾文", + "subtitleLanguageGl": "加利西亞文", + "subtitleLanguageGu": "古吉拉特文", + "subtitleLanguageHa": "豪薩文", + "subtitleLanguageHe": "希伯來文", + "subtitleLanguageHi": "印地文", + "subtitleLanguageHr": "克羅埃西亞文", + "subtitleLanguageHt": "海地文", + "subtitleLanguageHu": "匈牙利文", + "subtitleLanguageHy": "亞美尼亞文", + "subtitleLanguageId": "印尼文", + "subtitleLanguageIg": "伊布文", + "subtitleLanguageIlo": "伊洛闊文", + "subtitleLanguageIs": "冰島文", + "subtitleLanguageIt": "義大利文", + "subtitleLanguageJa": "日文", + "subtitleLanguageJv": "爪哇文", + "subtitleLanguageKa": "喬治亞文", + "subtitleLanguageKk": "哈薩克文", + "subtitleLanguageKm": "高棉文", + "subtitleLanguageKn": "坎那達文", + "subtitleLanguageKo": "韓文", + "subtitleLanguageLb": "盧森堡文", + "subtitleLanguageLg": "干達文", + "subtitleLanguageLn": "林加拉文", + "subtitleLanguageLo": "寮文", + "subtitleLanguageLt": "立陶宛文", + "subtitleLanguageLv": "拉脫維亞文", + "subtitleLanguageMg": "馬達加斯加文", + "subtitleLanguageMk": "馬其頓文", + "subtitleLanguageMl": "馬來亞拉姆文", + "subtitleLanguageMn": "蒙古文", + "subtitleLanguageMr": "馬拉地文", + "subtitleLanguageMs": "馬來文", + "subtitleLanguageMy": "緬甸文", + "subtitleLanguageNe": "尼泊爾文", + "subtitleLanguageNl": "荷蘭文", + "subtitleLanguageNo": "挪威文", + "subtitleLanguageNs": "北索托文", + "subtitleLanguageOc": "奧克西坦文", + "subtitleLanguageOr": "歐迪亞文", + "subtitleLanguagePa": "旁遮普文", + "subtitleLanguagePl": "波蘭文", + "subtitleLanguagePs": "普什圖文", + "subtitleLanguagePt": "葡萄牙文", + "subtitleLanguageRo": "羅馬尼亞文", + "subtitleLanguageRu": "俄文", + "subtitleLanguageSd": "信德文", + "subtitleLanguageSi": "僧伽羅文", + "subtitleLanguageSk": "斯洛伐克文", + "subtitleLanguageSl": "斯洛維尼亞文", + "subtitleLanguageSo": "索馬利文", + "subtitleLanguageSq": "阿爾巴尼亞文", + "subtitleLanguageSr": "塞爾維亞文", + "subtitleLanguageSs": "斯瓦特文", + "subtitleLanguageSu": "巽他文", + "subtitleLanguageSv": "瑞典文", + "subtitleLanguageSw": "史瓦希里文", + "subtitleLanguageTa": "坦米爾文", + "subtitleLanguageTh": "泰文", + "subtitleLanguageTl": "他加祿文", + "subtitleLanguageTn": "塞茲瓦納文", + "subtitleLanguageTr": "土耳其文", + "subtitleLanguageUk": "烏克蘭文", + "subtitleLanguageUr": "烏都文", + "subtitleLanguageUz": "烏茲別克文", + "subtitleLanguageVi": "越南文", + "subtitleLanguageWo": "沃洛夫文", + "subtitleLanguageXh": "科薩文", + "subtitleLanguageYi": "意第緒文", + "subtitleLanguageYo": "約魯巴文", + "subtitleLanguageYue": "粵語", + "subtitleLanguageZh": "中文", + "subtitleLanguageZu": "祖魯文", + "linearRec2020": "線性 Rec.2020", + "diagnostics": "診斷", + "exportDiagnostics": "匯出診斷套件", + "exportDiagnosticsFailed": "無法匯出診斷套件,請重試。", + "exportDiagnosticsSucceeded": "診斷套件已儲存。" +} diff --git a/lib/l10n/l10n.dart b/lib/l10n/l10n.dart new file mode 100644 index 0000000..1d877a7 --- /dev/null +++ b/lib/l10n/l10n.dart @@ -0,0 +1,11 @@ +import 'package:flutter/widgets.dart'; + +import 'app_localizations.dart'; + +export 'app_localizations.dart'; +export 'app_messages.dart'; +export 'subtitle_languages.dart'; + +extension LocalizedContext on BuildContext { + AppLocalizations get l10n => AppLocalizations.of(this)!; +} diff --git a/lib/l10n/subtitle_languages.dart b/lib/l10n/subtitle_languages.dart new file mode 100644 index 0000000..acdb854 --- /dev/null +++ b/lib/l10n/subtitle_languages.dart @@ -0,0 +1,216 @@ +import 'app_localizations.dart'; + +/// Subtitle language codes remain unchanged in requests and saved projects. +extension LocalizedSubtitleLanguages on AppLocalizations { + String subtitleLanguageName(String code) => switch (code) { + 'auto' => autoDetect, + 'none' => noTranslation, + 'af' => subtitleLanguageAf, + 'am' => subtitleLanguageAm, + 'ar' => subtitleLanguageAr, + 'ast' => subtitleLanguageAst, + 'az' => subtitleLanguageAz, + 'ba' => subtitleLanguageBa, + 'be' => subtitleLanguageBe, + 'bg' => subtitleLanguageBg, + 'bn' => subtitleLanguageBn, + 'br' => subtitleLanguageBr, + 'bs' => subtitleLanguageBs, + 'ca' => subtitleLanguageCa, + 'ceb' => subtitleLanguageCeb, + 'cs' => subtitleLanguageCs, + 'cy' => subtitleLanguageCy, + 'da' => subtitleLanguageDa, + 'de' => subtitleLanguageDe, + 'el' => subtitleLanguageEl, + 'en' => subtitleLanguageEn, + 'es' => subtitleLanguageEs, + 'et' => subtitleLanguageEt, + 'fa' => subtitleLanguageFa, + 'ff' => subtitleLanguageFf, + 'fi' => subtitleLanguageFi, + 'fr' => subtitleLanguageFr, + 'fy' => subtitleLanguageFy, + 'ga' => subtitleLanguageGa, + 'gd' => subtitleLanguageGd, + 'gl' => subtitleLanguageGl, + 'gu' => subtitleLanguageGu, + 'ha' => subtitleLanguageHa, + 'he' => subtitleLanguageHe, + 'hi' => subtitleLanguageHi, + 'hr' => subtitleLanguageHr, + 'ht' => subtitleLanguageHt, + 'hu' => subtitleLanguageHu, + 'hy' => subtitleLanguageHy, + 'id' => subtitleLanguageId, + 'ig' => subtitleLanguageIg, + 'ilo' => subtitleLanguageIlo, + 'is' => subtitleLanguageIs, + 'it' => subtitleLanguageIt, + 'ja' => subtitleLanguageJa, + 'jv' => subtitleLanguageJv, + 'ka' => subtitleLanguageKa, + 'kk' => subtitleLanguageKk, + 'km' => subtitleLanguageKm, + 'kn' => subtitleLanguageKn, + 'ko' => subtitleLanguageKo, + 'lb' => subtitleLanguageLb, + 'lg' => subtitleLanguageLg, + 'ln' => subtitleLanguageLn, + 'lo' => subtitleLanguageLo, + 'lt' => subtitleLanguageLt, + 'lv' => subtitleLanguageLv, + 'mg' => subtitleLanguageMg, + 'mk' => subtitleLanguageMk, + 'ml' => subtitleLanguageMl, + 'mn' => subtitleLanguageMn, + 'mr' => subtitleLanguageMr, + 'ms' => subtitleLanguageMs, + 'my' => subtitleLanguageMy, + 'ne' => subtitleLanguageNe, + 'nl' => subtitleLanguageNl, + 'no' => subtitleLanguageNo, + 'ns' => subtitleLanguageNs, + 'oc' => subtitleLanguageOc, + 'or' => subtitleLanguageOr, + 'pa' => subtitleLanguagePa, + 'pl' => subtitleLanguagePl, + 'ps' => subtitleLanguagePs, + 'pt' => subtitleLanguagePt, + 'ro' => subtitleLanguageRo, + 'ru' => subtitleLanguageRu, + 'sd' => subtitleLanguageSd, + 'si' => subtitleLanguageSi, + 'sk' => subtitleLanguageSk, + 'sl' => subtitleLanguageSl, + 'so' => subtitleLanguageSo, + 'sq' => subtitleLanguageSq, + 'sr' => subtitleLanguageSr, + 'ss' => subtitleLanguageSs, + 'su' => subtitleLanguageSu, + 'sv' => subtitleLanguageSv, + 'sw' => subtitleLanguageSw, + 'ta' => subtitleLanguageTa, + 'th' => subtitleLanguageTh, + 'tl' => subtitleLanguageTl, + 'tn' => subtitleLanguageTn, + 'tr' => subtitleLanguageTr, + 'uk' => subtitleLanguageUk, + 'ur' => subtitleLanguageUr, + 'uz' => subtitleLanguageUz, + 'vi' => subtitleLanguageVi, + 'wo' => subtitleLanguageWo, + 'xh' => subtitleLanguageXh, + 'yi' => subtitleLanguageYi, + 'yo' => subtitleLanguageYo, + 'zh' => subtitleLanguageZh, + 'zu' => subtitleLanguageZu, + 'yue' => subtitleLanguageYue, + _ => code, + }; +} + +/// Native names are search aliases, so users can find a language in its own script. +const subtitleNativeLanguageNames = { + 'af': 'Afrikaans', + 'am': 'አማርኛ', + 'ar': 'العربية', + 'ast': 'Asturianu', + 'az': 'Azərbaycanca', + 'ba': 'Башҡортса', + 'be': 'Беларуская', + 'bg': 'Български', + 'bn': 'বাংলা', + 'br': 'Brezhoneg', + 'bs': 'Bosanski', + 'ca': 'Català', + 'ceb': 'Cebuano', + 'cs': 'Čeština', + 'cy': 'Cymraeg', + 'da': 'Dansk', + 'de': 'Deutsch', + 'el': 'Ελληνικά', + 'en': 'English', + 'es': 'Español', + 'et': 'Eesti', + 'fa': 'فارسی', + 'ff': 'Fulfulde', + 'fi': 'Suomi', + 'fr': 'Français', + 'fy': 'Frysk', + 'ga': 'Gaeilge', + 'gd': 'Gàidhlig', + 'gl': 'Galego', + 'gu': 'ગુજરાતી', + 'ha': 'Hausa', + 'he': 'עברית', + 'hi': 'हिन्दी', + 'hr': 'Hrvatski', + 'ht': 'Kreyòl ayisyen', + 'hu': 'Magyar', + 'hy': 'Հայերեն', + 'id': 'Bahasa Indonesia', + 'ig': 'Igbo', + 'ilo': 'Ilokano', + 'is': 'Íslenska', + 'it': 'Italiano', + 'ja': '日本語', + 'jv': 'Basa Jawa', + 'ka': 'ქართული', + 'kk': 'Қазақша', + 'km': 'ភាសាខ្មែរ', + 'kn': 'ಕನ್ನಡ', + 'ko': '한국어', + 'lb': 'Lëtzebuergesch', + 'lg': 'Luganda', + 'ln': 'Lingála', + 'lo': 'ລາວ', + 'lt': 'Lietuvių', + 'lv': 'Latviešu', + 'mg': 'Malagasy', + 'mk': 'Македонски', + 'ml': 'മലയാളം', + 'mn': 'Монгол', + 'mr': 'मराठी', + 'ms': 'Bahasa Melayu', + 'my': 'မြန်မာဘာသာ', + 'ne': 'नेपाली', + 'nl': 'Nederlands', + 'no': 'Norsk', + 'ns': 'Sepedi', + 'oc': 'Occitan', + 'or': 'ଓଡ଼ିଆ', + 'pa': 'ਪੰਜਾਬੀ', + 'pl': 'Polski', + 'ps': 'پښتو', + 'pt': 'Português', + 'ro': 'Română', + 'ru': 'Русский', + 'sd': 'سنڌي', + 'si': 'සිංහල', + 'sk': 'Slovenčina', + 'sl': 'Slovenščina', + 'so': 'Soomaali', + 'sq': 'Shqip', + 'sr': 'Српски', + 'ss': 'SiSwati', + 'su': 'Basa Sunda', + 'sv': 'Svenska', + 'sw': 'Kiswahili', + 'ta': 'தமிழ்', + 'th': 'ไทย', + 'tl': 'Tagalog', + 'tn': 'Setswana', + 'tr': 'Türkçe', + 'uk': 'Українська', + 'ur': 'اردو', + 'uz': 'Oʻzbekcha', + 'vi': 'Tiếng Việt', + 'wo': 'Wolof', + 'xh': 'isiXhosa', + 'yi': 'ייִדיש', + 'yo': 'Yorùbá', + 'zh': '中文', + 'zu': 'isiZulu', + 'yue': '粵語', +}; diff --git a/lib/main.dart b/lib/main.dart new file mode 100644 index 0000000..1eebd31 --- /dev/null +++ b/lib/main.dart @@ -0,0 +1,32 @@ +import 'dart:ui' as ui; + +import 'package:flutter/foundation.dart'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import 'app/app.dart'; +import 'diagnostics/frame_timings.dart'; +import 'diagnostics/app_diagnostics.dart'; +import 'integrations/platform/device_experience.dart'; + +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + final diagnostics = await AppDiagnostics.initialize(); + diagnostics.installErrorHandlers(); + await diagnostics.readApplicationInfo(); + recordFrameTimingsFromEnvironment(); + final display = ui.PlatformDispatcher.instance.views.firstOrNull?.display; + final experience = await DeviceExperienceDetector.detect( + platform: defaultTargetPlatform, + displaySize: display?.size ?? ui.Size.zero, + pixelRatio: display?.devicePixelRatio ?? 1, + web: kIsWeb, + ); + runApp( + ProviderScope( + overrides: [deviceExperienceProvider.overrideWithValue(experience)], + child: const CutdexApp(), + ), + ); +} diff --git a/lib/persistence/app_database.dart b/lib/persistence/app_database.dart new file mode 100644 index 0000000..a4f79ec --- /dev/null +++ b/lib/persistence/app_database.dart @@ -0,0 +1,203 @@ +import 'dart:io'; + +import 'package:drift/drift.dart'; +import 'package:drift/native.dart'; +import 'package:path/path.dart' as p; +import 'package:path_provider/path_provider.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +part 'app_database.g.dart'; + +class RecentProjectRecords extends Table { + TextColumn get id => text()(); + TextColumn get name => text()(); + TextColumn get path => text()(); + IntColumn get position => integer()(); + + @override + Set> get primaryKey => {id}; +} + +class LastOpenedTimelines extends Table { + TextColumn get projectId => text()(); + TextColumn get timelineId => text()(); + + @override + Set> get primaryKey => {projectId}; +} + +class McpConfigurations extends Table { + IntColumn get id => integer()(); + BoolColumn get enabled => boolean()(); + IntColumn get port => integer()(); + TextColumn get token => text()(); + + @override + Set> get primaryKey => {id}; +} + +class AppearanceConfigurations extends Table { + IntColumn get id => integer()(); + TextColumn get themeMode => text()(); + + @override + Set> get primaryKey => {id}; +} + +class LanguageConfigurations extends Table { + IntColumn get id => integer()(); + TextColumn get language => text()(); + + @override + Set> get primaryKey => {id}; +} + +class ConversationLocationConfigurations extends Table { + IntColumn get id => integer()(); + TextColumn get directory => text()(); + + @override + Set> get primaryKey => {id}; +} + +class ProjectLocationConfigurations extends Table { + IntColumn get id => integer()(); + TextColumn get directory => text()(); + + @override + Set> get primaryKey => {id}; +} + +class ResourceLocationConfigurations extends Table { + IntColumn get id => integer()(); + TextColumn get directory => text()(); + + @override + Set> get primaryKey => {id}; +} + +class AgentConfigurations extends Table { + IntColumn get id => integer()(); + BoolColumn get enabled => boolean()(); + TextColumn get selectedProviderId => text().nullable()(); + TextColumn get selectedModelId => text().nullable()(); + IntColumn get revision => integer()(); + + @override + Set> get primaryKey => {id}; +} + +class AgentProviders extends Table { + BoolColumn get enabled => boolean().withDefault(const Constant(true))(); + TextColumn get id => text()(); + TextColumn get name => text()(); + TextColumn get apiType => text()(); + TextColumn get baseUrl => text()(); + TextColumn get credentialId => text().nullable()(); + + @override + Set> get primaryKey => {id}; +} + +class AgentModels extends Table { + TextColumn get providerId => text()(); + TextColumn get modelId => text()(); + IntColumn get contextWindow => integer().nullable()(); + IntColumn get maxOutputTokens => integer().nullable()(); + + @override + Set> get primaryKey => {providerId, modelId}; +} + +class WorkspaceViewConfigurations extends Table { + TextColumn get mode => text().withDefault(const Constant('agent'))(); + IntColumn get id => integer()(); + TextColumn get activeProjectId => text().nullable()(); + BoolColumn get sidebarCollapsed => boolean()(); + RealColumn get sidebarWidth => real().nullable()(); + + @override + Set> get primaryKey => {id}; +} + +class ProjectViewConfigurations extends Table { + TextColumn get projectId => text()(); + BoolColumn get propertiesOpen => boolean()(); + RealColumn get timelineHeight => real().nullable()(); + + @override + Set> get primaryKey => {projectId}; +} + +class TimelineViewConfigurations extends Table { + TextColumn get projectId => text()(); + TextColumn get timelineId => text()(); + TextColumn get sequenceId => text()(); + BoolColumn get active => boolean()(); + IntColumn get playheadTick => integer()(); + IntColumn get baseTick => integer()(); + RealColumn get fractionalTick => real()(); + RealColumn get pixelsPerTick => real()(); + RealColumn get verticalOffset => real()(); + + @override + Set> get primaryKey => {projectId, timelineId, sequenceId}; +} + +@DriftDatabase( + tables: [ + RecentProjectRecords, + LastOpenedTimelines, + McpConfigurations, + AppearanceConfigurations, + LanguageConfigurations, + ConversationLocationConfigurations, + ProjectLocationConfigurations, + ResourceLocationConfigurations, + AgentConfigurations, + AgentProviders, + AgentModels, + WorkspaceViewConfigurations, + ProjectViewConfigurations, + TimelineViewConfigurations, + ], +) +class AppDatabase extends _$AppDatabase { + AppDatabase(super.executor); + + @override + int get schemaVersion => 2; + + @override + MigrationStrategy get migration => MigrationStrategy( + onCreate: (migrator) => migrator.createAll(), + onUpgrade: (_, from, _) async { + throw StateError('Unsupported app database schema version: $from'); + }, + beforeOpen: (_) async { + await customStatement('PRAGMA journal_mode = WAL'); + await customStatement('PRAGMA synchronous = FULL'); + await customStatement('PRAGMA busy_timeout = 5000'); + }, + ); +} + +@Riverpod(keepAlive: true) +AppDatabase appDatabase(Ref ref) { + final database = AppDatabase(LazyDatabase(_openAppDatabase)); + ref.onDispose(database.close); + return database; +} + +Future _openAppDatabase() async { + if (Platform.environment.containsKey('FLUTTER_TEST')) { + return NativeDatabase.memory(); + } + final support = Directory( + p.join((await getApplicationSupportDirectory()).path, 'Cutdex'), + ); + await support.create(recursive: true); + return NativeDatabase.createInBackground( + File(p.join(support.path, 'app.sqlite')), + ); +} diff --git a/lib/persistence/app_database.g.dart b/lib/persistence/app_database.g.dart new file mode 100644 index 0000000..381059c --- /dev/null +++ b/lib/persistence/app_database.g.dart @@ -0,0 +1,7253 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'app_database.dart'; + +// ignore_for_file: type=lint +class $RecentProjectRecordsTable extends RecentProjectRecords + with TableInfo<$RecentProjectRecordsTable, RecentProjectRecord> { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + $RecentProjectRecordsTable(this.attachedDatabase, [this._alias]); + static const VerificationMeta _idMeta = const VerificationMeta('id'); + @override + late final GeneratedColumn id = GeneratedColumn( + 'id', + aliasedName, + false, + type: DriftSqlType.string, + requiredDuringInsert: true, + ); + static const VerificationMeta _nameMeta = const VerificationMeta('name'); + @override + late final GeneratedColumn name = GeneratedColumn( + 'name', + aliasedName, + false, + type: DriftSqlType.string, + requiredDuringInsert: true, + ); + static const VerificationMeta _pathMeta = const VerificationMeta('path'); + @override + late final GeneratedColumn path = GeneratedColumn( + 'path', + aliasedName, + false, + type: DriftSqlType.string, + requiredDuringInsert: true, + ); + static const VerificationMeta _positionMeta = const VerificationMeta( + 'position', + ); + @override + late final GeneratedColumn position = GeneratedColumn( + 'position', + aliasedName, + false, + type: DriftSqlType.int, + requiredDuringInsert: true, + ); + @override + List get $columns => [id, name, path, position]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'recent_project_records'; + @override + VerificationContext validateIntegrity( + Insertable instance, { + bool isInserting = false, + }) { + final context = VerificationContext(); + final data = instance.toColumns(true); + if (data.containsKey('id')) { + context.handle(_idMeta, id.isAcceptableOrUnknown(data['id']!, _idMeta)); + } else if (isInserting) { + context.missing(_idMeta); + } + if (data.containsKey('name')) { + context.handle( + _nameMeta, + name.isAcceptableOrUnknown(data['name']!, _nameMeta), + ); + } else if (isInserting) { + context.missing(_nameMeta); + } + if (data.containsKey('path')) { + context.handle( + _pathMeta, + path.isAcceptableOrUnknown(data['path']!, _pathMeta), + ); + } else if (isInserting) { + context.missing(_pathMeta); + } + if (data.containsKey('position')) { + context.handle( + _positionMeta, + position.isAcceptableOrUnknown(data['position']!, _positionMeta), + ); + } else if (isInserting) { + context.missing(_positionMeta); + } + return context; + } + + @override + Set get $primaryKey => {id}; + @override + RecentProjectRecord map(Map data, {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return RecentProjectRecord( + id: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}id'], + )!, + name: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}name'], + )!, + path: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}path'], + )!, + position: attachedDatabase.typeMapping.read( + DriftSqlType.int, + data['${effectivePrefix}position'], + )!, + ); + } + + @override + $RecentProjectRecordsTable createAlias(String alias) { + return $RecentProjectRecordsTable(attachedDatabase, alias); + } +} + +class RecentProjectRecord extends DataClass + implements Insertable { + final String id; + final String name; + final String path; + final int position; + const RecentProjectRecord({ + required this.id, + required this.name, + required this.path, + required this.position, + }); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['id'] = Variable(id); + map['name'] = Variable(name); + map['path'] = Variable(path); + map['position'] = Variable(position); + return map; + } + + RecentProjectRecordsCompanion toCompanion(bool nullToAbsent) { + return RecentProjectRecordsCompanion( + id: Value(id), + name: Value(name), + path: Value(path), + position: Value(position), + ); + } + + factory RecentProjectRecord.fromJson( + Map json, { + ValueSerializer? serializer, + }) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return RecentProjectRecord( + id: serializer.fromJson(json['id']), + name: serializer.fromJson(json['name']), + path: serializer.fromJson(json['path']), + position: serializer.fromJson(json['position']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'id': serializer.toJson(id), + 'name': serializer.toJson(name), + 'path': serializer.toJson(path), + 'position': serializer.toJson(position), + }; + } + + RecentProjectRecord copyWith({ + String? id, + String? name, + String? path, + int? position, + }) => RecentProjectRecord( + id: id ?? this.id, + name: name ?? this.name, + path: path ?? this.path, + position: position ?? this.position, + ); + RecentProjectRecord copyWithCompanion(RecentProjectRecordsCompanion data) { + return RecentProjectRecord( + id: data.id.present ? data.id.value : this.id, + name: data.name.present ? data.name.value : this.name, + path: data.path.present ? data.path.value : this.path, + position: data.position.present ? data.position.value : this.position, + ); + } + + @override + String toString() { + return (StringBuffer('RecentProjectRecord(') + ..write('id: $id, ') + ..write('name: $name, ') + ..write('path: $path, ') + ..write('position: $position') + ..write(')')) + .toString(); + } + + @override + int get hashCode => Object.hash(id, name, path, position); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is RecentProjectRecord && + other.id == this.id && + other.name == this.name && + other.path == this.path && + other.position == this.position); +} + +class RecentProjectRecordsCompanion + extends UpdateCompanion { + final Value id; + final Value name; + final Value path; + final Value position; + final Value rowid; + const RecentProjectRecordsCompanion({ + this.id = const Value.absent(), + this.name = const Value.absent(), + this.path = const Value.absent(), + this.position = const Value.absent(), + this.rowid = const Value.absent(), + }); + RecentProjectRecordsCompanion.insert({ + required String id, + required String name, + required String path, + required int position, + this.rowid = const Value.absent(), + }) : id = Value(id), + name = Value(name), + path = Value(path), + position = Value(position); + static Insertable custom({ + Expression? id, + Expression? name, + Expression? path, + Expression? position, + Expression? rowid, + }) { + return RawValuesInsertable({ + if (id != null) 'id': id, + if (name != null) 'name': name, + if (path != null) 'path': path, + if (position != null) 'position': position, + if (rowid != null) 'rowid': rowid, + }); + } + + RecentProjectRecordsCompanion copyWith({ + Value? id, + Value? name, + Value? path, + Value? position, + Value? rowid, + }) { + return RecentProjectRecordsCompanion( + id: id ?? this.id, + name: name ?? this.name, + path: path ?? this.path, + position: position ?? this.position, + rowid: rowid ?? this.rowid, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (id.present) { + map['id'] = Variable(id.value); + } + if (name.present) { + map['name'] = Variable(name.value); + } + if (path.present) { + map['path'] = Variable(path.value); + } + if (position.present) { + map['position'] = Variable(position.value); + } + if (rowid.present) { + map['rowid'] = Variable(rowid.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('RecentProjectRecordsCompanion(') + ..write('id: $id, ') + ..write('name: $name, ') + ..write('path: $path, ') + ..write('position: $position, ') + ..write('rowid: $rowid') + ..write(')')) + .toString(); + } +} + +class $LastOpenedTimelinesTable extends LastOpenedTimelines + with TableInfo<$LastOpenedTimelinesTable, LastOpenedTimeline> { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + $LastOpenedTimelinesTable(this.attachedDatabase, [this._alias]); + static const VerificationMeta _projectIdMeta = const VerificationMeta( + 'projectId', + ); + @override + late final GeneratedColumn projectId = GeneratedColumn( + 'project_id', + aliasedName, + false, + type: DriftSqlType.string, + requiredDuringInsert: true, + ); + static const VerificationMeta _timelineIdMeta = const VerificationMeta( + 'timelineId', + ); + @override + late final GeneratedColumn timelineId = GeneratedColumn( + 'timeline_id', + aliasedName, + false, + type: DriftSqlType.string, + requiredDuringInsert: true, + ); + @override + List get $columns => [projectId, timelineId]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'last_opened_timelines'; + @override + VerificationContext validateIntegrity( + Insertable instance, { + bool isInserting = false, + }) { + final context = VerificationContext(); + final data = instance.toColumns(true); + if (data.containsKey('project_id')) { + context.handle( + _projectIdMeta, + projectId.isAcceptableOrUnknown(data['project_id']!, _projectIdMeta), + ); + } else if (isInserting) { + context.missing(_projectIdMeta); + } + if (data.containsKey('timeline_id')) { + context.handle( + _timelineIdMeta, + timelineId.isAcceptableOrUnknown(data['timeline_id']!, _timelineIdMeta), + ); + } else if (isInserting) { + context.missing(_timelineIdMeta); + } + return context; + } + + @override + Set get $primaryKey => {projectId}; + @override + LastOpenedTimeline map(Map data, {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return LastOpenedTimeline( + projectId: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}project_id'], + )!, + timelineId: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}timeline_id'], + )!, + ); + } + + @override + $LastOpenedTimelinesTable createAlias(String alias) { + return $LastOpenedTimelinesTable(attachedDatabase, alias); + } +} + +class LastOpenedTimeline extends DataClass + implements Insertable { + final String projectId; + final String timelineId; + const LastOpenedTimeline({required this.projectId, required this.timelineId}); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['project_id'] = Variable(projectId); + map['timeline_id'] = Variable(timelineId); + return map; + } + + LastOpenedTimelinesCompanion toCompanion(bool nullToAbsent) { + return LastOpenedTimelinesCompanion( + projectId: Value(projectId), + timelineId: Value(timelineId), + ); + } + + factory LastOpenedTimeline.fromJson( + Map json, { + ValueSerializer? serializer, + }) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return LastOpenedTimeline( + projectId: serializer.fromJson(json['projectId']), + timelineId: serializer.fromJson(json['timelineId']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'projectId': serializer.toJson(projectId), + 'timelineId': serializer.toJson(timelineId), + }; + } + + LastOpenedTimeline copyWith({String? projectId, String? timelineId}) => + LastOpenedTimeline( + projectId: projectId ?? this.projectId, + timelineId: timelineId ?? this.timelineId, + ); + LastOpenedTimeline copyWithCompanion(LastOpenedTimelinesCompanion data) { + return LastOpenedTimeline( + projectId: data.projectId.present ? data.projectId.value : this.projectId, + timelineId: data.timelineId.present + ? data.timelineId.value + : this.timelineId, + ); + } + + @override + String toString() { + return (StringBuffer('LastOpenedTimeline(') + ..write('projectId: $projectId, ') + ..write('timelineId: $timelineId') + ..write(')')) + .toString(); + } + + @override + int get hashCode => Object.hash(projectId, timelineId); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is LastOpenedTimeline && + other.projectId == this.projectId && + other.timelineId == this.timelineId); +} + +class LastOpenedTimelinesCompanion extends UpdateCompanion { + final Value projectId; + final Value timelineId; + final Value rowid; + const LastOpenedTimelinesCompanion({ + this.projectId = const Value.absent(), + this.timelineId = const Value.absent(), + this.rowid = const Value.absent(), + }); + LastOpenedTimelinesCompanion.insert({ + required String projectId, + required String timelineId, + this.rowid = const Value.absent(), + }) : projectId = Value(projectId), + timelineId = Value(timelineId); + static Insertable custom({ + Expression? projectId, + Expression? timelineId, + Expression? rowid, + }) { + return RawValuesInsertable({ + if (projectId != null) 'project_id': projectId, + if (timelineId != null) 'timeline_id': timelineId, + if (rowid != null) 'rowid': rowid, + }); + } + + LastOpenedTimelinesCompanion copyWith({ + Value? projectId, + Value? timelineId, + Value? rowid, + }) { + return LastOpenedTimelinesCompanion( + projectId: projectId ?? this.projectId, + timelineId: timelineId ?? this.timelineId, + rowid: rowid ?? this.rowid, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (projectId.present) { + map['project_id'] = Variable(projectId.value); + } + if (timelineId.present) { + map['timeline_id'] = Variable(timelineId.value); + } + if (rowid.present) { + map['rowid'] = Variable(rowid.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('LastOpenedTimelinesCompanion(') + ..write('projectId: $projectId, ') + ..write('timelineId: $timelineId, ') + ..write('rowid: $rowid') + ..write(')')) + .toString(); + } +} + +class $McpConfigurationsTable extends McpConfigurations + with TableInfo<$McpConfigurationsTable, McpConfiguration> { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + $McpConfigurationsTable(this.attachedDatabase, [this._alias]); + static const VerificationMeta _idMeta = const VerificationMeta('id'); + @override + late final GeneratedColumn id = GeneratedColumn( + 'id', + aliasedName, + false, + type: DriftSqlType.int, + requiredDuringInsert: false, + ); + static const VerificationMeta _enabledMeta = const VerificationMeta( + 'enabled', + ); + @override + late final GeneratedColumn enabled = GeneratedColumn( + 'enabled', + aliasedName, + false, + type: DriftSqlType.bool, + requiredDuringInsert: true, + defaultConstraints: GeneratedColumn.constraintIsAlways( + 'CHECK ("enabled" IN (0, 1))', + ), + ); + static const VerificationMeta _portMeta = const VerificationMeta('port'); + @override + late final GeneratedColumn port = GeneratedColumn( + 'port', + aliasedName, + false, + type: DriftSqlType.int, + requiredDuringInsert: true, + ); + static const VerificationMeta _tokenMeta = const VerificationMeta('token'); + @override + late final GeneratedColumn token = GeneratedColumn( + 'token', + aliasedName, + false, + type: DriftSqlType.string, + requiredDuringInsert: true, + ); + @override + List get $columns => [id, enabled, port, token]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'mcp_configurations'; + @override + VerificationContext validateIntegrity( + Insertable instance, { + bool isInserting = false, + }) { + final context = VerificationContext(); + final data = instance.toColumns(true); + if (data.containsKey('id')) { + context.handle(_idMeta, id.isAcceptableOrUnknown(data['id']!, _idMeta)); + } + if (data.containsKey('enabled')) { + context.handle( + _enabledMeta, + enabled.isAcceptableOrUnknown(data['enabled']!, _enabledMeta), + ); + } else if (isInserting) { + context.missing(_enabledMeta); + } + if (data.containsKey('port')) { + context.handle( + _portMeta, + port.isAcceptableOrUnknown(data['port']!, _portMeta), + ); + } else if (isInserting) { + context.missing(_portMeta); + } + if (data.containsKey('token')) { + context.handle( + _tokenMeta, + token.isAcceptableOrUnknown(data['token']!, _tokenMeta), + ); + } else if (isInserting) { + context.missing(_tokenMeta); + } + return context; + } + + @override + Set get $primaryKey => {id}; + @override + McpConfiguration map(Map data, {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return McpConfiguration( + id: attachedDatabase.typeMapping.read( + DriftSqlType.int, + data['${effectivePrefix}id'], + )!, + enabled: attachedDatabase.typeMapping.read( + DriftSqlType.bool, + data['${effectivePrefix}enabled'], + )!, + port: attachedDatabase.typeMapping.read( + DriftSqlType.int, + data['${effectivePrefix}port'], + )!, + token: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}token'], + )!, + ); + } + + @override + $McpConfigurationsTable createAlias(String alias) { + return $McpConfigurationsTable(attachedDatabase, alias); + } +} + +class McpConfiguration extends DataClass + implements Insertable { + final int id; + final bool enabled; + final int port; + final String token; + const McpConfiguration({ + required this.id, + required this.enabled, + required this.port, + required this.token, + }); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['id'] = Variable(id); + map['enabled'] = Variable(enabled); + map['port'] = Variable(port); + map['token'] = Variable(token); + return map; + } + + McpConfigurationsCompanion toCompanion(bool nullToAbsent) { + return McpConfigurationsCompanion( + id: Value(id), + enabled: Value(enabled), + port: Value(port), + token: Value(token), + ); + } + + factory McpConfiguration.fromJson( + Map json, { + ValueSerializer? serializer, + }) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return McpConfiguration( + id: serializer.fromJson(json['id']), + enabled: serializer.fromJson(json['enabled']), + port: serializer.fromJson(json['port']), + token: serializer.fromJson(json['token']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'id': serializer.toJson(id), + 'enabled': serializer.toJson(enabled), + 'port': serializer.toJson(port), + 'token': serializer.toJson(token), + }; + } + + McpConfiguration copyWith({ + int? id, + bool? enabled, + int? port, + String? token, + }) => McpConfiguration( + id: id ?? this.id, + enabled: enabled ?? this.enabled, + port: port ?? this.port, + token: token ?? this.token, + ); + McpConfiguration copyWithCompanion(McpConfigurationsCompanion data) { + return McpConfiguration( + id: data.id.present ? data.id.value : this.id, + enabled: data.enabled.present ? data.enabled.value : this.enabled, + port: data.port.present ? data.port.value : this.port, + token: data.token.present ? data.token.value : this.token, + ); + } + + @override + String toString() { + return (StringBuffer('McpConfiguration(') + ..write('id: $id, ') + ..write('enabled: $enabled, ') + ..write('port: $port, ') + ..write('token: $token') + ..write(')')) + .toString(); + } + + @override + int get hashCode => Object.hash(id, enabled, port, token); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is McpConfiguration && + other.id == this.id && + other.enabled == this.enabled && + other.port == this.port && + other.token == this.token); +} + +class McpConfigurationsCompanion extends UpdateCompanion { + final Value id; + final Value enabled; + final Value port; + final Value token; + const McpConfigurationsCompanion({ + this.id = const Value.absent(), + this.enabled = const Value.absent(), + this.port = const Value.absent(), + this.token = const Value.absent(), + }); + McpConfigurationsCompanion.insert({ + this.id = const Value.absent(), + required bool enabled, + required int port, + required String token, + }) : enabled = Value(enabled), + port = Value(port), + token = Value(token); + static Insertable custom({ + Expression? id, + Expression? enabled, + Expression? port, + Expression? token, + }) { + return RawValuesInsertable({ + if (id != null) 'id': id, + if (enabled != null) 'enabled': enabled, + if (port != null) 'port': port, + if (token != null) 'token': token, + }); + } + + McpConfigurationsCompanion copyWith({ + Value? id, + Value? enabled, + Value? port, + Value? token, + }) { + return McpConfigurationsCompanion( + id: id ?? this.id, + enabled: enabled ?? this.enabled, + port: port ?? this.port, + token: token ?? this.token, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (id.present) { + map['id'] = Variable(id.value); + } + if (enabled.present) { + map['enabled'] = Variable(enabled.value); + } + if (port.present) { + map['port'] = Variable(port.value); + } + if (token.present) { + map['token'] = Variable(token.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('McpConfigurationsCompanion(') + ..write('id: $id, ') + ..write('enabled: $enabled, ') + ..write('port: $port, ') + ..write('token: $token') + ..write(')')) + .toString(); + } +} + +class $AppearanceConfigurationsTable extends AppearanceConfigurations + with TableInfo<$AppearanceConfigurationsTable, AppearanceConfiguration> { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + $AppearanceConfigurationsTable(this.attachedDatabase, [this._alias]); + static const VerificationMeta _idMeta = const VerificationMeta('id'); + @override + late final GeneratedColumn id = GeneratedColumn( + 'id', + aliasedName, + false, + type: DriftSqlType.int, + requiredDuringInsert: false, + ); + static const VerificationMeta _themeModeMeta = const VerificationMeta( + 'themeMode', + ); + @override + late final GeneratedColumn themeMode = GeneratedColumn( + 'theme_mode', + aliasedName, + false, + type: DriftSqlType.string, + requiredDuringInsert: true, + ); + @override + List get $columns => [id, themeMode]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'appearance_configurations'; + @override + VerificationContext validateIntegrity( + Insertable instance, { + bool isInserting = false, + }) { + final context = VerificationContext(); + final data = instance.toColumns(true); + if (data.containsKey('id')) { + context.handle(_idMeta, id.isAcceptableOrUnknown(data['id']!, _idMeta)); + } + if (data.containsKey('theme_mode')) { + context.handle( + _themeModeMeta, + themeMode.isAcceptableOrUnknown(data['theme_mode']!, _themeModeMeta), + ); + } else if (isInserting) { + context.missing(_themeModeMeta); + } + return context; + } + + @override + Set get $primaryKey => {id}; + @override + AppearanceConfiguration map( + Map data, { + String? tablePrefix, + }) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return AppearanceConfiguration( + id: attachedDatabase.typeMapping.read( + DriftSqlType.int, + data['${effectivePrefix}id'], + )!, + themeMode: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}theme_mode'], + )!, + ); + } + + @override + $AppearanceConfigurationsTable createAlias(String alias) { + return $AppearanceConfigurationsTable(attachedDatabase, alias); + } +} + +class AppearanceConfiguration extends DataClass + implements Insertable { + final int id; + final String themeMode; + const AppearanceConfiguration({required this.id, required this.themeMode}); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['id'] = Variable(id); + map['theme_mode'] = Variable(themeMode); + return map; + } + + AppearanceConfigurationsCompanion toCompanion(bool nullToAbsent) { + return AppearanceConfigurationsCompanion( + id: Value(id), + themeMode: Value(themeMode), + ); + } + + factory AppearanceConfiguration.fromJson( + Map json, { + ValueSerializer? serializer, + }) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return AppearanceConfiguration( + id: serializer.fromJson(json['id']), + themeMode: serializer.fromJson(json['themeMode']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'id': serializer.toJson(id), + 'themeMode': serializer.toJson(themeMode), + }; + } + + AppearanceConfiguration copyWith({int? id, String? themeMode}) => + AppearanceConfiguration( + id: id ?? this.id, + themeMode: themeMode ?? this.themeMode, + ); + AppearanceConfiguration copyWithCompanion( + AppearanceConfigurationsCompanion data, + ) { + return AppearanceConfiguration( + id: data.id.present ? data.id.value : this.id, + themeMode: data.themeMode.present ? data.themeMode.value : this.themeMode, + ); + } + + @override + String toString() { + return (StringBuffer('AppearanceConfiguration(') + ..write('id: $id, ') + ..write('themeMode: $themeMode') + ..write(')')) + .toString(); + } + + @override + int get hashCode => Object.hash(id, themeMode); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is AppearanceConfiguration && + other.id == this.id && + other.themeMode == this.themeMode); +} + +class AppearanceConfigurationsCompanion + extends UpdateCompanion { + final Value id; + final Value themeMode; + const AppearanceConfigurationsCompanion({ + this.id = const Value.absent(), + this.themeMode = const Value.absent(), + }); + AppearanceConfigurationsCompanion.insert({ + this.id = const Value.absent(), + required String themeMode, + }) : themeMode = Value(themeMode); + static Insertable custom({ + Expression? id, + Expression? themeMode, + }) { + return RawValuesInsertable({ + if (id != null) 'id': id, + if (themeMode != null) 'theme_mode': themeMode, + }); + } + + AppearanceConfigurationsCompanion copyWith({ + Value? id, + Value? themeMode, + }) { + return AppearanceConfigurationsCompanion( + id: id ?? this.id, + themeMode: themeMode ?? this.themeMode, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (id.present) { + map['id'] = Variable(id.value); + } + if (themeMode.present) { + map['theme_mode'] = Variable(themeMode.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('AppearanceConfigurationsCompanion(') + ..write('id: $id, ') + ..write('themeMode: $themeMode') + ..write(')')) + .toString(); + } +} + +class $LanguageConfigurationsTable extends LanguageConfigurations + with TableInfo<$LanguageConfigurationsTable, LanguageConfiguration> { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + $LanguageConfigurationsTable(this.attachedDatabase, [this._alias]); + static const VerificationMeta _idMeta = const VerificationMeta('id'); + @override + late final GeneratedColumn id = GeneratedColumn( + 'id', + aliasedName, + false, + type: DriftSqlType.int, + requiredDuringInsert: false, + ); + static const VerificationMeta _languageMeta = const VerificationMeta( + 'language', + ); + @override + late final GeneratedColumn language = GeneratedColumn( + 'language', + aliasedName, + false, + type: DriftSqlType.string, + requiredDuringInsert: true, + ); + @override + List get $columns => [id, language]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'language_configurations'; + @override + VerificationContext validateIntegrity( + Insertable instance, { + bool isInserting = false, + }) { + final context = VerificationContext(); + final data = instance.toColumns(true); + if (data.containsKey('id')) { + context.handle(_idMeta, id.isAcceptableOrUnknown(data['id']!, _idMeta)); + } + if (data.containsKey('language')) { + context.handle( + _languageMeta, + language.isAcceptableOrUnknown(data['language']!, _languageMeta), + ); + } else if (isInserting) { + context.missing(_languageMeta); + } + return context; + } + + @override + Set get $primaryKey => {id}; + @override + LanguageConfiguration map(Map data, {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return LanguageConfiguration( + id: attachedDatabase.typeMapping.read( + DriftSqlType.int, + data['${effectivePrefix}id'], + )!, + language: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}language'], + )!, + ); + } + + @override + $LanguageConfigurationsTable createAlias(String alias) { + return $LanguageConfigurationsTable(attachedDatabase, alias); + } +} + +class LanguageConfiguration extends DataClass + implements Insertable { + final int id; + final String language; + const LanguageConfiguration({required this.id, required this.language}); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['id'] = Variable(id); + map['language'] = Variable(language); + return map; + } + + LanguageConfigurationsCompanion toCompanion(bool nullToAbsent) { + return LanguageConfigurationsCompanion( + id: Value(id), + language: Value(language), + ); + } + + factory LanguageConfiguration.fromJson( + Map json, { + ValueSerializer? serializer, + }) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return LanguageConfiguration( + id: serializer.fromJson(json['id']), + language: serializer.fromJson(json['language']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'id': serializer.toJson(id), + 'language': serializer.toJson(language), + }; + } + + LanguageConfiguration copyWith({int? id, String? language}) => + LanguageConfiguration( + id: id ?? this.id, + language: language ?? this.language, + ); + LanguageConfiguration copyWithCompanion( + LanguageConfigurationsCompanion data, + ) { + return LanguageConfiguration( + id: data.id.present ? data.id.value : this.id, + language: data.language.present ? data.language.value : this.language, + ); + } + + @override + String toString() { + return (StringBuffer('LanguageConfiguration(') + ..write('id: $id, ') + ..write('language: $language') + ..write(')')) + .toString(); + } + + @override + int get hashCode => Object.hash(id, language); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is LanguageConfiguration && + other.id == this.id && + other.language == this.language); +} + +class LanguageConfigurationsCompanion + extends UpdateCompanion { + final Value id; + final Value language; + const LanguageConfigurationsCompanion({ + this.id = const Value.absent(), + this.language = const Value.absent(), + }); + LanguageConfigurationsCompanion.insert({ + this.id = const Value.absent(), + required String language, + }) : language = Value(language); + static Insertable custom({ + Expression? id, + Expression? language, + }) { + return RawValuesInsertable({ + if (id != null) 'id': id, + if (language != null) 'language': language, + }); + } + + LanguageConfigurationsCompanion copyWith({ + Value? id, + Value? language, + }) { + return LanguageConfigurationsCompanion( + id: id ?? this.id, + language: language ?? this.language, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (id.present) { + map['id'] = Variable(id.value); + } + if (language.present) { + map['language'] = Variable(language.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('LanguageConfigurationsCompanion(') + ..write('id: $id, ') + ..write('language: $language') + ..write(')')) + .toString(); + } +} + +class $ConversationLocationConfigurationsTable + extends ConversationLocationConfigurations + with + TableInfo< + $ConversationLocationConfigurationsTable, + ConversationLocationConfiguration + > { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + $ConversationLocationConfigurationsTable( + this.attachedDatabase, [ + this._alias, + ]); + static const VerificationMeta _idMeta = const VerificationMeta('id'); + @override + late final GeneratedColumn id = GeneratedColumn( + 'id', + aliasedName, + false, + type: DriftSqlType.int, + requiredDuringInsert: false, + ); + static const VerificationMeta _directoryMeta = const VerificationMeta( + 'directory', + ); + @override + late final GeneratedColumn directory = GeneratedColumn( + 'directory', + aliasedName, + false, + type: DriftSqlType.string, + requiredDuringInsert: true, + ); + @override + List get $columns => [id, directory]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'conversation_location_configurations'; + @override + VerificationContext validateIntegrity( + Insertable instance, { + bool isInserting = false, + }) { + final context = VerificationContext(); + final data = instance.toColumns(true); + if (data.containsKey('id')) { + context.handle(_idMeta, id.isAcceptableOrUnknown(data['id']!, _idMeta)); + } + if (data.containsKey('directory')) { + context.handle( + _directoryMeta, + directory.isAcceptableOrUnknown(data['directory']!, _directoryMeta), + ); + } else if (isInserting) { + context.missing(_directoryMeta); + } + return context; + } + + @override + Set get $primaryKey => {id}; + @override + ConversationLocationConfiguration map( + Map data, { + String? tablePrefix, + }) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return ConversationLocationConfiguration( + id: attachedDatabase.typeMapping.read( + DriftSqlType.int, + data['${effectivePrefix}id'], + )!, + directory: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}directory'], + )!, + ); + } + + @override + $ConversationLocationConfigurationsTable createAlias(String alias) { + return $ConversationLocationConfigurationsTable(attachedDatabase, alias); + } +} + +class ConversationLocationConfiguration extends DataClass + implements Insertable { + final int id; + final String directory; + const ConversationLocationConfiguration({ + required this.id, + required this.directory, + }); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['id'] = Variable(id); + map['directory'] = Variable(directory); + return map; + } + + ConversationLocationConfigurationsCompanion toCompanion(bool nullToAbsent) { + return ConversationLocationConfigurationsCompanion( + id: Value(id), + directory: Value(directory), + ); + } + + factory ConversationLocationConfiguration.fromJson( + Map json, { + ValueSerializer? serializer, + }) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return ConversationLocationConfiguration( + id: serializer.fromJson(json['id']), + directory: serializer.fromJson(json['directory']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'id': serializer.toJson(id), + 'directory': serializer.toJson(directory), + }; + } + + ConversationLocationConfiguration copyWith({int? id, String? directory}) => + ConversationLocationConfiguration( + id: id ?? this.id, + directory: directory ?? this.directory, + ); + ConversationLocationConfiguration copyWithCompanion( + ConversationLocationConfigurationsCompanion data, + ) { + return ConversationLocationConfiguration( + id: data.id.present ? data.id.value : this.id, + directory: data.directory.present ? data.directory.value : this.directory, + ); + } + + @override + String toString() { + return (StringBuffer('ConversationLocationConfiguration(') + ..write('id: $id, ') + ..write('directory: $directory') + ..write(')')) + .toString(); + } + + @override + int get hashCode => Object.hash(id, directory); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is ConversationLocationConfiguration && + other.id == this.id && + other.directory == this.directory); +} + +class ConversationLocationConfigurationsCompanion + extends UpdateCompanion { + final Value id; + final Value directory; + const ConversationLocationConfigurationsCompanion({ + this.id = const Value.absent(), + this.directory = const Value.absent(), + }); + ConversationLocationConfigurationsCompanion.insert({ + this.id = const Value.absent(), + required String directory, + }) : directory = Value(directory); + static Insertable custom({ + Expression? id, + Expression? directory, + }) { + return RawValuesInsertable({ + if (id != null) 'id': id, + if (directory != null) 'directory': directory, + }); + } + + ConversationLocationConfigurationsCompanion copyWith({ + Value? id, + Value? directory, + }) { + return ConversationLocationConfigurationsCompanion( + id: id ?? this.id, + directory: directory ?? this.directory, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (id.present) { + map['id'] = Variable(id.value); + } + if (directory.present) { + map['directory'] = Variable(directory.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('ConversationLocationConfigurationsCompanion(') + ..write('id: $id, ') + ..write('directory: $directory') + ..write(')')) + .toString(); + } +} + +class $ProjectLocationConfigurationsTable extends ProjectLocationConfigurations + with + TableInfo< + $ProjectLocationConfigurationsTable, + ProjectLocationConfiguration + > { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + $ProjectLocationConfigurationsTable(this.attachedDatabase, [this._alias]); + static const VerificationMeta _idMeta = const VerificationMeta('id'); + @override + late final GeneratedColumn id = GeneratedColumn( + 'id', + aliasedName, + false, + type: DriftSqlType.int, + requiredDuringInsert: false, + ); + static const VerificationMeta _directoryMeta = const VerificationMeta( + 'directory', + ); + @override + late final GeneratedColumn directory = GeneratedColumn( + 'directory', + aliasedName, + false, + type: DriftSqlType.string, + requiredDuringInsert: true, + ); + @override + List get $columns => [id, directory]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'project_location_configurations'; + @override + VerificationContext validateIntegrity( + Insertable instance, { + bool isInserting = false, + }) { + final context = VerificationContext(); + final data = instance.toColumns(true); + if (data.containsKey('id')) { + context.handle(_idMeta, id.isAcceptableOrUnknown(data['id']!, _idMeta)); + } + if (data.containsKey('directory')) { + context.handle( + _directoryMeta, + directory.isAcceptableOrUnknown(data['directory']!, _directoryMeta), + ); + } else if (isInserting) { + context.missing(_directoryMeta); + } + return context; + } + + @override + Set get $primaryKey => {id}; + @override + ProjectLocationConfiguration map( + Map data, { + String? tablePrefix, + }) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return ProjectLocationConfiguration( + id: attachedDatabase.typeMapping.read( + DriftSqlType.int, + data['${effectivePrefix}id'], + )!, + directory: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}directory'], + )!, + ); + } + + @override + $ProjectLocationConfigurationsTable createAlias(String alias) { + return $ProjectLocationConfigurationsTable(attachedDatabase, alias); + } +} + +class ProjectLocationConfiguration extends DataClass + implements Insertable { + final int id; + final String directory; + const ProjectLocationConfiguration({ + required this.id, + required this.directory, + }); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['id'] = Variable(id); + map['directory'] = Variable(directory); + return map; + } + + ProjectLocationConfigurationsCompanion toCompanion(bool nullToAbsent) { + return ProjectLocationConfigurationsCompanion( + id: Value(id), + directory: Value(directory), + ); + } + + factory ProjectLocationConfiguration.fromJson( + Map json, { + ValueSerializer? serializer, + }) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return ProjectLocationConfiguration( + id: serializer.fromJson(json['id']), + directory: serializer.fromJson(json['directory']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'id': serializer.toJson(id), + 'directory': serializer.toJson(directory), + }; + } + + ProjectLocationConfiguration copyWith({int? id, String? directory}) => + ProjectLocationConfiguration( + id: id ?? this.id, + directory: directory ?? this.directory, + ); + ProjectLocationConfiguration copyWithCompanion( + ProjectLocationConfigurationsCompanion data, + ) { + return ProjectLocationConfiguration( + id: data.id.present ? data.id.value : this.id, + directory: data.directory.present ? data.directory.value : this.directory, + ); + } + + @override + String toString() { + return (StringBuffer('ProjectLocationConfiguration(') + ..write('id: $id, ') + ..write('directory: $directory') + ..write(')')) + .toString(); + } + + @override + int get hashCode => Object.hash(id, directory); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is ProjectLocationConfiguration && + other.id == this.id && + other.directory == this.directory); +} + +class ProjectLocationConfigurationsCompanion + extends UpdateCompanion { + final Value id; + final Value directory; + const ProjectLocationConfigurationsCompanion({ + this.id = const Value.absent(), + this.directory = const Value.absent(), + }); + ProjectLocationConfigurationsCompanion.insert({ + this.id = const Value.absent(), + required String directory, + }) : directory = Value(directory); + static Insertable custom({ + Expression? id, + Expression? directory, + }) { + return RawValuesInsertable({ + if (id != null) 'id': id, + if (directory != null) 'directory': directory, + }); + } + + ProjectLocationConfigurationsCompanion copyWith({ + Value? id, + Value? directory, + }) { + return ProjectLocationConfigurationsCompanion( + id: id ?? this.id, + directory: directory ?? this.directory, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (id.present) { + map['id'] = Variable(id.value); + } + if (directory.present) { + map['directory'] = Variable(directory.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('ProjectLocationConfigurationsCompanion(') + ..write('id: $id, ') + ..write('directory: $directory') + ..write(')')) + .toString(); + } +} + +class $ResourceLocationConfigurationsTable + extends ResourceLocationConfigurations + with + TableInfo< + $ResourceLocationConfigurationsTable, + ResourceLocationConfiguration + > { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + $ResourceLocationConfigurationsTable(this.attachedDatabase, [this._alias]); + static const VerificationMeta _idMeta = const VerificationMeta('id'); + @override + late final GeneratedColumn id = GeneratedColumn( + 'id', + aliasedName, + false, + type: DriftSqlType.int, + requiredDuringInsert: false, + ); + static const VerificationMeta _directoryMeta = const VerificationMeta( + 'directory', + ); + @override + late final GeneratedColumn directory = GeneratedColumn( + 'directory', + aliasedName, + false, + type: DriftSqlType.string, + requiredDuringInsert: true, + ); + @override + List get $columns => [id, directory]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'resource_location_configurations'; + @override + VerificationContext validateIntegrity( + Insertable instance, { + bool isInserting = false, + }) { + final context = VerificationContext(); + final data = instance.toColumns(true); + if (data.containsKey('id')) { + context.handle(_idMeta, id.isAcceptableOrUnknown(data['id']!, _idMeta)); + } + if (data.containsKey('directory')) { + context.handle( + _directoryMeta, + directory.isAcceptableOrUnknown(data['directory']!, _directoryMeta), + ); + } else if (isInserting) { + context.missing(_directoryMeta); + } + return context; + } + + @override + Set get $primaryKey => {id}; + @override + ResourceLocationConfiguration map( + Map data, { + String? tablePrefix, + }) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return ResourceLocationConfiguration( + id: attachedDatabase.typeMapping.read( + DriftSqlType.int, + data['${effectivePrefix}id'], + )!, + directory: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}directory'], + )!, + ); + } + + @override + $ResourceLocationConfigurationsTable createAlias(String alias) { + return $ResourceLocationConfigurationsTable(attachedDatabase, alias); + } +} + +class ResourceLocationConfiguration extends DataClass + implements Insertable { + final int id; + final String directory; + const ResourceLocationConfiguration({ + required this.id, + required this.directory, + }); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['id'] = Variable(id); + map['directory'] = Variable(directory); + return map; + } + + ResourceLocationConfigurationsCompanion toCompanion(bool nullToAbsent) { + return ResourceLocationConfigurationsCompanion( + id: Value(id), + directory: Value(directory), + ); + } + + factory ResourceLocationConfiguration.fromJson( + Map json, { + ValueSerializer? serializer, + }) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return ResourceLocationConfiguration( + id: serializer.fromJson(json['id']), + directory: serializer.fromJson(json['directory']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'id': serializer.toJson(id), + 'directory': serializer.toJson(directory), + }; + } + + ResourceLocationConfiguration copyWith({int? id, String? directory}) => + ResourceLocationConfiguration( + id: id ?? this.id, + directory: directory ?? this.directory, + ); + ResourceLocationConfiguration copyWithCompanion( + ResourceLocationConfigurationsCompanion data, + ) { + return ResourceLocationConfiguration( + id: data.id.present ? data.id.value : this.id, + directory: data.directory.present ? data.directory.value : this.directory, + ); + } + + @override + String toString() { + return (StringBuffer('ResourceLocationConfiguration(') + ..write('id: $id, ') + ..write('directory: $directory') + ..write(')')) + .toString(); + } + + @override + int get hashCode => Object.hash(id, directory); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is ResourceLocationConfiguration && + other.id == this.id && + other.directory == this.directory); +} + +class ResourceLocationConfigurationsCompanion + extends UpdateCompanion { + final Value id; + final Value directory; + const ResourceLocationConfigurationsCompanion({ + this.id = const Value.absent(), + this.directory = const Value.absent(), + }); + ResourceLocationConfigurationsCompanion.insert({ + this.id = const Value.absent(), + required String directory, + }) : directory = Value(directory); + static Insertable custom({ + Expression? id, + Expression? directory, + }) { + return RawValuesInsertable({ + if (id != null) 'id': id, + if (directory != null) 'directory': directory, + }); + } + + ResourceLocationConfigurationsCompanion copyWith({ + Value? id, + Value? directory, + }) { + return ResourceLocationConfigurationsCompanion( + id: id ?? this.id, + directory: directory ?? this.directory, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (id.present) { + map['id'] = Variable(id.value); + } + if (directory.present) { + map['directory'] = Variable(directory.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('ResourceLocationConfigurationsCompanion(') + ..write('id: $id, ') + ..write('directory: $directory') + ..write(')')) + .toString(); + } +} + +class $AgentConfigurationsTable extends AgentConfigurations + with TableInfo<$AgentConfigurationsTable, AgentConfiguration> { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + $AgentConfigurationsTable(this.attachedDatabase, [this._alias]); + static const VerificationMeta _idMeta = const VerificationMeta('id'); + @override + late final GeneratedColumn id = GeneratedColumn( + 'id', + aliasedName, + false, + type: DriftSqlType.int, + requiredDuringInsert: false, + ); + static const VerificationMeta _enabledMeta = const VerificationMeta( + 'enabled', + ); + @override + late final GeneratedColumn enabled = GeneratedColumn( + 'enabled', + aliasedName, + false, + type: DriftSqlType.bool, + requiredDuringInsert: true, + defaultConstraints: GeneratedColumn.constraintIsAlways( + 'CHECK ("enabled" IN (0, 1))', + ), + ); + static const VerificationMeta _selectedProviderIdMeta = + const VerificationMeta('selectedProviderId'); + @override + late final GeneratedColumn selectedProviderId = + GeneratedColumn( + 'selected_provider_id', + aliasedName, + true, + type: DriftSqlType.string, + requiredDuringInsert: false, + ); + static const VerificationMeta _selectedModelIdMeta = const VerificationMeta( + 'selectedModelId', + ); + @override + late final GeneratedColumn selectedModelId = GeneratedColumn( + 'selected_model_id', + aliasedName, + true, + type: DriftSqlType.string, + requiredDuringInsert: false, + ); + static const VerificationMeta _revisionMeta = const VerificationMeta( + 'revision', + ); + @override + late final GeneratedColumn revision = GeneratedColumn( + 'revision', + aliasedName, + false, + type: DriftSqlType.int, + requiredDuringInsert: true, + ); + @override + List get $columns => [ + id, + enabled, + selectedProviderId, + selectedModelId, + revision, + ]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'agent_configurations'; + @override + VerificationContext validateIntegrity( + Insertable instance, { + bool isInserting = false, + }) { + final context = VerificationContext(); + final data = instance.toColumns(true); + if (data.containsKey('id')) { + context.handle(_idMeta, id.isAcceptableOrUnknown(data['id']!, _idMeta)); + } + if (data.containsKey('enabled')) { + context.handle( + _enabledMeta, + enabled.isAcceptableOrUnknown(data['enabled']!, _enabledMeta), + ); + } else if (isInserting) { + context.missing(_enabledMeta); + } + if (data.containsKey('selected_provider_id')) { + context.handle( + _selectedProviderIdMeta, + selectedProviderId.isAcceptableOrUnknown( + data['selected_provider_id']!, + _selectedProviderIdMeta, + ), + ); + } + if (data.containsKey('selected_model_id')) { + context.handle( + _selectedModelIdMeta, + selectedModelId.isAcceptableOrUnknown( + data['selected_model_id']!, + _selectedModelIdMeta, + ), + ); + } + if (data.containsKey('revision')) { + context.handle( + _revisionMeta, + revision.isAcceptableOrUnknown(data['revision']!, _revisionMeta), + ); + } else if (isInserting) { + context.missing(_revisionMeta); + } + return context; + } + + @override + Set get $primaryKey => {id}; + @override + AgentConfiguration map(Map data, {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return AgentConfiguration( + id: attachedDatabase.typeMapping.read( + DriftSqlType.int, + data['${effectivePrefix}id'], + )!, + enabled: attachedDatabase.typeMapping.read( + DriftSqlType.bool, + data['${effectivePrefix}enabled'], + )!, + selectedProviderId: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}selected_provider_id'], + ), + selectedModelId: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}selected_model_id'], + ), + revision: attachedDatabase.typeMapping.read( + DriftSqlType.int, + data['${effectivePrefix}revision'], + )!, + ); + } + + @override + $AgentConfigurationsTable createAlias(String alias) { + return $AgentConfigurationsTable(attachedDatabase, alias); + } +} + +class AgentConfiguration extends DataClass + implements Insertable { + final int id; + final bool enabled; + final String? selectedProviderId; + final String? selectedModelId; + final int revision; + const AgentConfiguration({ + required this.id, + required this.enabled, + this.selectedProviderId, + this.selectedModelId, + required this.revision, + }); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['id'] = Variable(id); + map['enabled'] = Variable(enabled); + if (!nullToAbsent || selectedProviderId != null) { + map['selected_provider_id'] = Variable(selectedProviderId); + } + if (!nullToAbsent || selectedModelId != null) { + map['selected_model_id'] = Variable(selectedModelId); + } + map['revision'] = Variable(revision); + return map; + } + + AgentConfigurationsCompanion toCompanion(bool nullToAbsent) { + return AgentConfigurationsCompanion( + id: Value(id), + enabled: Value(enabled), + selectedProviderId: selectedProviderId == null && nullToAbsent + ? const Value.absent() + : Value(selectedProviderId), + selectedModelId: selectedModelId == null && nullToAbsent + ? const Value.absent() + : Value(selectedModelId), + revision: Value(revision), + ); + } + + factory AgentConfiguration.fromJson( + Map json, { + ValueSerializer? serializer, + }) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return AgentConfiguration( + id: serializer.fromJson(json['id']), + enabled: serializer.fromJson(json['enabled']), + selectedProviderId: serializer.fromJson( + json['selectedProviderId'], + ), + selectedModelId: serializer.fromJson(json['selectedModelId']), + revision: serializer.fromJson(json['revision']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'id': serializer.toJson(id), + 'enabled': serializer.toJson(enabled), + 'selectedProviderId': serializer.toJson(selectedProviderId), + 'selectedModelId': serializer.toJson(selectedModelId), + 'revision': serializer.toJson(revision), + }; + } + + AgentConfiguration copyWith({ + int? id, + bool? enabled, + Value selectedProviderId = const Value.absent(), + Value selectedModelId = const Value.absent(), + int? revision, + }) => AgentConfiguration( + id: id ?? this.id, + enabled: enabled ?? this.enabled, + selectedProviderId: selectedProviderId.present + ? selectedProviderId.value + : this.selectedProviderId, + selectedModelId: selectedModelId.present + ? selectedModelId.value + : this.selectedModelId, + revision: revision ?? this.revision, + ); + AgentConfiguration copyWithCompanion(AgentConfigurationsCompanion data) { + return AgentConfiguration( + id: data.id.present ? data.id.value : this.id, + enabled: data.enabled.present ? data.enabled.value : this.enabled, + selectedProviderId: data.selectedProviderId.present + ? data.selectedProviderId.value + : this.selectedProviderId, + selectedModelId: data.selectedModelId.present + ? data.selectedModelId.value + : this.selectedModelId, + revision: data.revision.present ? data.revision.value : this.revision, + ); + } + + @override + String toString() { + return (StringBuffer('AgentConfiguration(') + ..write('id: $id, ') + ..write('enabled: $enabled, ') + ..write('selectedProviderId: $selectedProviderId, ') + ..write('selectedModelId: $selectedModelId, ') + ..write('revision: $revision') + ..write(')')) + .toString(); + } + + @override + int get hashCode => + Object.hash(id, enabled, selectedProviderId, selectedModelId, revision); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is AgentConfiguration && + other.id == this.id && + other.enabled == this.enabled && + other.selectedProviderId == this.selectedProviderId && + other.selectedModelId == this.selectedModelId && + other.revision == this.revision); +} + +class AgentConfigurationsCompanion extends UpdateCompanion { + final Value id; + final Value enabled; + final Value selectedProviderId; + final Value selectedModelId; + final Value revision; + const AgentConfigurationsCompanion({ + this.id = const Value.absent(), + this.enabled = const Value.absent(), + this.selectedProviderId = const Value.absent(), + this.selectedModelId = const Value.absent(), + this.revision = const Value.absent(), + }); + AgentConfigurationsCompanion.insert({ + this.id = const Value.absent(), + required bool enabled, + this.selectedProviderId = const Value.absent(), + this.selectedModelId = const Value.absent(), + required int revision, + }) : enabled = Value(enabled), + revision = Value(revision); + static Insertable custom({ + Expression? id, + Expression? enabled, + Expression? selectedProviderId, + Expression? selectedModelId, + Expression? revision, + }) { + return RawValuesInsertable({ + if (id != null) 'id': id, + if (enabled != null) 'enabled': enabled, + if (selectedProviderId != null) + 'selected_provider_id': selectedProviderId, + if (selectedModelId != null) 'selected_model_id': selectedModelId, + if (revision != null) 'revision': revision, + }); + } + + AgentConfigurationsCompanion copyWith({ + Value? id, + Value? enabled, + Value? selectedProviderId, + Value? selectedModelId, + Value? revision, + }) { + return AgentConfigurationsCompanion( + id: id ?? this.id, + enabled: enabled ?? this.enabled, + selectedProviderId: selectedProviderId ?? this.selectedProviderId, + selectedModelId: selectedModelId ?? this.selectedModelId, + revision: revision ?? this.revision, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (id.present) { + map['id'] = Variable(id.value); + } + if (enabled.present) { + map['enabled'] = Variable(enabled.value); + } + if (selectedProviderId.present) { + map['selected_provider_id'] = Variable(selectedProviderId.value); + } + if (selectedModelId.present) { + map['selected_model_id'] = Variable(selectedModelId.value); + } + if (revision.present) { + map['revision'] = Variable(revision.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('AgentConfigurationsCompanion(') + ..write('id: $id, ') + ..write('enabled: $enabled, ') + ..write('selectedProviderId: $selectedProviderId, ') + ..write('selectedModelId: $selectedModelId, ') + ..write('revision: $revision') + ..write(')')) + .toString(); + } +} + +class $AgentProvidersTable extends AgentProviders + with TableInfo<$AgentProvidersTable, AgentProvider> { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + $AgentProvidersTable(this.attachedDatabase, [this._alias]); + static const VerificationMeta _enabledMeta = const VerificationMeta( + 'enabled', + ); + @override + late final GeneratedColumn enabled = GeneratedColumn( + 'enabled', + aliasedName, + false, + type: DriftSqlType.bool, + requiredDuringInsert: false, + defaultConstraints: GeneratedColumn.constraintIsAlways( + 'CHECK ("enabled" IN (0, 1))', + ), + defaultValue: const Constant(true), + ); + static const VerificationMeta _idMeta = const VerificationMeta('id'); + @override + late final GeneratedColumn id = GeneratedColumn( + 'id', + aliasedName, + false, + type: DriftSqlType.string, + requiredDuringInsert: true, + ); + static const VerificationMeta _nameMeta = const VerificationMeta('name'); + @override + late final GeneratedColumn name = GeneratedColumn( + 'name', + aliasedName, + false, + type: DriftSqlType.string, + requiredDuringInsert: true, + ); + static const VerificationMeta _apiTypeMeta = const VerificationMeta( + 'apiType', + ); + @override + late final GeneratedColumn apiType = GeneratedColumn( + 'api_type', + aliasedName, + false, + type: DriftSqlType.string, + requiredDuringInsert: true, + ); + static const VerificationMeta _baseUrlMeta = const VerificationMeta( + 'baseUrl', + ); + @override + late final GeneratedColumn baseUrl = GeneratedColumn( + 'base_url', + aliasedName, + false, + type: DriftSqlType.string, + requiredDuringInsert: true, + ); + static const VerificationMeta _credentialIdMeta = const VerificationMeta( + 'credentialId', + ); + @override + late final GeneratedColumn credentialId = GeneratedColumn( + 'credential_id', + aliasedName, + true, + type: DriftSqlType.string, + requiredDuringInsert: false, + ); + @override + List get $columns => [ + enabled, + id, + name, + apiType, + baseUrl, + credentialId, + ]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'agent_providers'; + @override + VerificationContext validateIntegrity( + Insertable instance, { + bool isInserting = false, + }) { + final context = VerificationContext(); + final data = instance.toColumns(true); + if (data.containsKey('enabled')) { + context.handle( + _enabledMeta, + enabled.isAcceptableOrUnknown(data['enabled']!, _enabledMeta), + ); + } + if (data.containsKey('id')) { + context.handle(_idMeta, id.isAcceptableOrUnknown(data['id']!, _idMeta)); + } else if (isInserting) { + context.missing(_idMeta); + } + if (data.containsKey('name')) { + context.handle( + _nameMeta, + name.isAcceptableOrUnknown(data['name']!, _nameMeta), + ); + } else if (isInserting) { + context.missing(_nameMeta); + } + if (data.containsKey('api_type')) { + context.handle( + _apiTypeMeta, + apiType.isAcceptableOrUnknown(data['api_type']!, _apiTypeMeta), + ); + } else if (isInserting) { + context.missing(_apiTypeMeta); + } + if (data.containsKey('base_url')) { + context.handle( + _baseUrlMeta, + baseUrl.isAcceptableOrUnknown(data['base_url']!, _baseUrlMeta), + ); + } else if (isInserting) { + context.missing(_baseUrlMeta); + } + if (data.containsKey('credential_id')) { + context.handle( + _credentialIdMeta, + credentialId.isAcceptableOrUnknown( + data['credential_id']!, + _credentialIdMeta, + ), + ); + } + return context; + } + + @override + Set get $primaryKey => {id}; + @override + AgentProvider map(Map data, {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return AgentProvider( + enabled: attachedDatabase.typeMapping.read( + DriftSqlType.bool, + data['${effectivePrefix}enabled'], + )!, + id: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}id'], + )!, + name: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}name'], + )!, + apiType: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}api_type'], + )!, + baseUrl: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}base_url'], + )!, + credentialId: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}credential_id'], + ), + ); + } + + @override + $AgentProvidersTable createAlias(String alias) { + return $AgentProvidersTable(attachedDatabase, alias); + } +} + +class AgentProvider extends DataClass implements Insertable { + final bool enabled; + final String id; + final String name; + final String apiType; + final String baseUrl; + final String? credentialId; + const AgentProvider({ + required this.enabled, + required this.id, + required this.name, + required this.apiType, + required this.baseUrl, + this.credentialId, + }); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['enabled'] = Variable(enabled); + map['id'] = Variable(id); + map['name'] = Variable(name); + map['api_type'] = Variable(apiType); + map['base_url'] = Variable(baseUrl); + if (!nullToAbsent || credentialId != null) { + map['credential_id'] = Variable(credentialId); + } + return map; + } + + AgentProvidersCompanion toCompanion(bool nullToAbsent) { + return AgentProvidersCompanion( + enabled: Value(enabled), + id: Value(id), + name: Value(name), + apiType: Value(apiType), + baseUrl: Value(baseUrl), + credentialId: credentialId == null && nullToAbsent + ? const Value.absent() + : Value(credentialId), + ); + } + + factory AgentProvider.fromJson( + Map json, { + ValueSerializer? serializer, + }) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return AgentProvider( + enabled: serializer.fromJson(json['enabled']), + id: serializer.fromJson(json['id']), + name: serializer.fromJson(json['name']), + apiType: serializer.fromJson(json['apiType']), + baseUrl: serializer.fromJson(json['baseUrl']), + credentialId: serializer.fromJson(json['credentialId']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'enabled': serializer.toJson(enabled), + 'id': serializer.toJson(id), + 'name': serializer.toJson(name), + 'apiType': serializer.toJson(apiType), + 'baseUrl': serializer.toJson(baseUrl), + 'credentialId': serializer.toJson(credentialId), + }; + } + + AgentProvider copyWith({ + bool? enabled, + String? id, + String? name, + String? apiType, + String? baseUrl, + Value credentialId = const Value.absent(), + }) => AgentProvider( + enabled: enabled ?? this.enabled, + id: id ?? this.id, + name: name ?? this.name, + apiType: apiType ?? this.apiType, + baseUrl: baseUrl ?? this.baseUrl, + credentialId: credentialId.present ? credentialId.value : this.credentialId, + ); + AgentProvider copyWithCompanion(AgentProvidersCompanion data) { + return AgentProvider( + enabled: data.enabled.present ? data.enabled.value : this.enabled, + id: data.id.present ? data.id.value : this.id, + name: data.name.present ? data.name.value : this.name, + apiType: data.apiType.present ? data.apiType.value : this.apiType, + baseUrl: data.baseUrl.present ? data.baseUrl.value : this.baseUrl, + credentialId: data.credentialId.present + ? data.credentialId.value + : this.credentialId, + ); + } + + @override + String toString() { + return (StringBuffer('AgentProvider(') + ..write('enabled: $enabled, ') + ..write('id: $id, ') + ..write('name: $name, ') + ..write('apiType: $apiType, ') + ..write('baseUrl: $baseUrl, ') + ..write('credentialId: $credentialId') + ..write(')')) + .toString(); + } + + @override + int get hashCode => + Object.hash(enabled, id, name, apiType, baseUrl, credentialId); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is AgentProvider && + other.enabled == this.enabled && + other.id == this.id && + other.name == this.name && + other.apiType == this.apiType && + other.baseUrl == this.baseUrl && + other.credentialId == this.credentialId); +} + +class AgentProvidersCompanion extends UpdateCompanion { + final Value enabled; + final Value id; + final Value name; + final Value apiType; + final Value baseUrl; + final Value credentialId; + final Value rowid; + const AgentProvidersCompanion({ + this.enabled = const Value.absent(), + this.id = const Value.absent(), + this.name = const Value.absent(), + this.apiType = const Value.absent(), + this.baseUrl = const Value.absent(), + this.credentialId = const Value.absent(), + this.rowid = const Value.absent(), + }); + AgentProvidersCompanion.insert({ + this.enabled = const Value.absent(), + required String id, + required String name, + required String apiType, + required String baseUrl, + this.credentialId = const Value.absent(), + this.rowid = const Value.absent(), + }) : id = Value(id), + name = Value(name), + apiType = Value(apiType), + baseUrl = Value(baseUrl); + static Insertable custom({ + Expression? enabled, + Expression? id, + Expression? name, + Expression? apiType, + Expression? baseUrl, + Expression? credentialId, + Expression? rowid, + }) { + return RawValuesInsertable({ + if (enabled != null) 'enabled': enabled, + if (id != null) 'id': id, + if (name != null) 'name': name, + if (apiType != null) 'api_type': apiType, + if (baseUrl != null) 'base_url': baseUrl, + if (credentialId != null) 'credential_id': credentialId, + if (rowid != null) 'rowid': rowid, + }); + } + + AgentProvidersCompanion copyWith({ + Value? enabled, + Value? id, + Value? name, + Value? apiType, + Value? baseUrl, + Value? credentialId, + Value? rowid, + }) { + return AgentProvidersCompanion( + enabled: enabled ?? this.enabled, + id: id ?? this.id, + name: name ?? this.name, + apiType: apiType ?? this.apiType, + baseUrl: baseUrl ?? this.baseUrl, + credentialId: credentialId ?? this.credentialId, + rowid: rowid ?? this.rowid, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (enabled.present) { + map['enabled'] = Variable(enabled.value); + } + if (id.present) { + map['id'] = Variable(id.value); + } + if (name.present) { + map['name'] = Variable(name.value); + } + if (apiType.present) { + map['api_type'] = Variable(apiType.value); + } + if (baseUrl.present) { + map['base_url'] = Variable(baseUrl.value); + } + if (credentialId.present) { + map['credential_id'] = Variable(credentialId.value); + } + if (rowid.present) { + map['rowid'] = Variable(rowid.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('AgentProvidersCompanion(') + ..write('enabled: $enabled, ') + ..write('id: $id, ') + ..write('name: $name, ') + ..write('apiType: $apiType, ') + ..write('baseUrl: $baseUrl, ') + ..write('credentialId: $credentialId, ') + ..write('rowid: $rowid') + ..write(')')) + .toString(); + } +} + +class $AgentModelsTable extends AgentModels + with TableInfo<$AgentModelsTable, AgentModel> { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + $AgentModelsTable(this.attachedDatabase, [this._alias]); + static const VerificationMeta _providerIdMeta = const VerificationMeta( + 'providerId', + ); + @override + late final GeneratedColumn providerId = GeneratedColumn( + 'provider_id', + aliasedName, + false, + type: DriftSqlType.string, + requiredDuringInsert: true, + ); + static const VerificationMeta _modelIdMeta = const VerificationMeta( + 'modelId', + ); + @override + late final GeneratedColumn modelId = GeneratedColumn( + 'model_id', + aliasedName, + false, + type: DriftSqlType.string, + requiredDuringInsert: true, + ); + static const VerificationMeta _contextWindowMeta = const VerificationMeta( + 'contextWindow', + ); + @override + late final GeneratedColumn contextWindow = GeneratedColumn( + 'context_window', + aliasedName, + true, + type: DriftSqlType.int, + requiredDuringInsert: false, + ); + static const VerificationMeta _maxOutputTokensMeta = const VerificationMeta( + 'maxOutputTokens', + ); + @override + late final GeneratedColumn maxOutputTokens = GeneratedColumn( + 'max_output_tokens', + aliasedName, + true, + type: DriftSqlType.int, + requiredDuringInsert: false, + ); + @override + List get $columns => [ + providerId, + modelId, + contextWindow, + maxOutputTokens, + ]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'agent_models'; + @override + VerificationContext validateIntegrity( + Insertable instance, { + bool isInserting = false, + }) { + final context = VerificationContext(); + final data = instance.toColumns(true); + if (data.containsKey('provider_id')) { + context.handle( + _providerIdMeta, + providerId.isAcceptableOrUnknown(data['provider_id']!, _providerIdMeta), + ); + } else if (isInserting) { + context.missing(_providerIdMeta); + } + if (data.containsKey('model_id')) { + context.handle( + _modelIdMeta, + modelId.isAcceptableOrUnknown(data['model_id']!, _modelIdMeta), + ); + } else if (isInserting) { + context.missing(_modelIdMeta); + } + if (data.containsKey('context_window')) { + context.handle( + _contextWindowMeta, + contextWindow.isAcceptableOrUnknown( + data['context_window']!, + _contextWindowMeta, + ), + ); + } + if (data.containsKey('max_output_tokens')) { + context.handle( + _maxOutputTokensMeta, + maxOutputTokens.isAcceptableOrUnknown( + data['max_output_tokens']!, + _maxOutputTokensMeta, + ), + ); + } + return context; + } + + @override + Set get $primaryKey => {providerId, modelId}; + @override + AgentModel map(Map data, {String? tablePrefix}) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return AgentModel( + providerId: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}provider_id'], + )!, + modelId: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}model_id'], + )!, + contextWindow: attachedDatabase.typeMapping.read( + DriftSqlType.int, + data['${effectivePrefix}context_window'], + ), + maxOutputTokens: attachedDatabase.typeMapping.read( + DriftSqlType.int, + data['${effectivePrefix}max_output_tokens'], + ), + ); + } + + @override + $AgentModelsTable createAlias(String alias) { + return $AgentModelsTable(attachedDatabase, alias); + } +} + +class AgentModel extends DataClass implements Insertable { + final String providerId; + final String modelId; + final int? contextWindow; + final int? maxOutputTokens; + const AgentModel({ + required this.providerId, + required this.modelId, + this.contextWindow, + this.maxOutputTokens, + }); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['provider_id'] = Variable(providerId); + map['model_id'] = Variable(modelId); + if (!nullToAbsent || contextWindow != null) { + map['context_window'] = Variable(contextWindow); + } + if (!nullToAbsent || maxOutputTokens != null) { + map['max_output_tokens'] = Variable(maxOutputTokens); + } + return map; + } + + AgentModelsCompanion toCompanion(bool nullToAbsent) { + return AgentModelsCompanion( + providerId: Value(providerId), + modelId: Value(modelId), + contextWindow: contextWindow == null && nullToAbsent + ? const Value.absent() + : Value(contextWindow), + maxOutputTokens: maxOutputTokens == null && nullToAbsent + ? const Value.absent() + : Value(maxOutputTokens), + ); + } + + factory AgentModel.fromJson( + Map json, { + ValueSerializer? serializer, + }) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return AgentModel( + providerId: serializer.fromJson(json['providerId']), + modelId: serializer.fromJson(json['modelId']), + contextWindow: serializer.fromJson(json['contextWindow']), + maxOutputTokens: serializer.fromJson(json['maxOutputTokens']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'providerId': serializer.toJson(providerId), + 'modelId': serializer.toJson(modelId), + 'contextWindow': serializer.toJson(contextWindow), + 'maxOutputTokens': serializer.toJson(maxOutputTokens), + }; + } + + AgentModel copyWith({ + String? providerId, + String? modelId, + Value contextWindow = const Value.absent(), + Value maxOutputTokens = const Value.absent(), + }) => AgentModel( + providerId: providerId ?? this.providerId, + modelId: modelId ?? this.modelId, + contextWindow: contextWindow.present + ? contextWindow.value + : this.contextWindow, + maxOutputTokens: maxOutputTokens.present + ? maxOutputTokens.value + : this.maxOutputTokens, + ); + AgentModel copyWithCompanion(AgentModelsCompanion data) { + return AgentModel( + providerId: data.providerId.present + ? data.providerId.value + : this.providerId, + modelId: data.modelId.present ? data.modelId.value : this.modelId, + contextWindow: data.contextWindow.present + ? data.contextWindow.value + : this.contextWindow, + maxOutputTokens: data.maxOutputTokens.present + ? data.maxOutputTokens.value + : this.maxOutputTokens, + ); + } + + @override + String toString() { + return (StringBuffer('AgentModel(') + ..write('providerId: $providerId, ') + ..write('modelId: $modelId, ') + ..write('contextWindow: $contextWindow, ') + ..write('maxOutputTokens: $maxOutputTokens') + ..write(')')) + .toString(); + } + + @override + int get hashCode => + Object.hash(providerId, modelId, contextWindow, maxOutputTokens); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is AgentModel && + other.providerId == this.providerId && + other.modelId == this.modelId && + other.contextWindow == this.contextWindow && + other.maxOutputTokens == this.maxOutputTokens); +} + +class AgentModelsCompanion extends UpdateCompanion { + final Value providerId; + final Value modelId; + final Value contextWindow; + final Value maxOutputTokens; + final Value rowid; + const AgentModelsCompanion({ + this.providerId = const Value.absent(), + this.modelId = const Value.absent(), + this.contextWindow = const Value.absent(), + this.maxOutputTokens = const Value.absent(), + this.rowid = const Value.absent(), + }); + AgentModelsCompanion.insert({ + required String providerId, + required String modelId, + this.contextWindow = const Value.absent(), + this.maxOutputTokens = const Value.absent(), + this.rowid = const Value.absent(), + }) : providerId = Value(providerId), + modelId = Value(modelId); + static Insertable custom({ + Expression? providerId, + Expression? modelId, + Expression? contextWindow, + Expression? maxOutputTokens, + Expression? rowid, + }) { + return RawValuesInsertable({ + if (providerId != null) 'provider_id': providerId, + if (modelId != null) 'model_id': modelId, + if (contextWindow != null) 'context_window': contextWindow, + if (maxOutputTokens != null) 'max_output_tokens': maxOutputTokens, + if (rowid != null) 'rowid': rowid, + }); + } + + AgentModelsCompanion copyWith({ + Value? providerId, + Value? modelId, + Value? contextWindow, + Value? maxOutputTokens, + Value? rowid, + }) { + return AgentModelsCompanion( + providerId: providerId ?? this.providerId, + modelId: modelId ?? this.modelId, + contextWindow: contextWindow ?? this.contextWindow, + maxOutputTokens: maxOutputTokens ?? this.maxOutputTokens, + rowid: rowid ?? this.rowid, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (providerId.present) { + map['provider_id'] = Variable(providerId.value); + } + if (modelId.present) { + map['model_id'] = Variable(modelId.value); + } + if (contextWindow.present) { + map['context_window'] = Variable(contextWindow.value); + } + if (maxOutputTokens.present) { + map['max_output_tokens'] = Variable(maxOutputTokens.value); + } + if (rowid.present) { + map['rowid'] = Variable(rowid.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('AgentModelsCompanion(') + ..write('providerId: $providerId, ') + ..write('modelId: $modelId, ') + ..write('contextWindow: $contextWindow, ') + ..write('maxOutputTokens: $maxOutputTokens, ') + ..write('rowid: $rowid') + ..write(')')) + .toString(); + } +} + +class $WorkspaceViewConfigurationsTable extends WorkspaceViewConfigurations + with + TableInfo< + $WorkspaceViewConfigurationsTable, + WorkspaceViewConfiguration + > { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + $WorkspaceViewConfigurationsTable(this.attachedDatabase, [this._alias]); + static const VerificationMeta _modeMeta = const VerificationMeta('mode'); + @override + late final GeneratedColumn mode = GeneratedColumn( + 'mode', + aliasedName, + false, + type: DriftSqlType.string, + requiredDuringInsert: false, + defaultValue: const Constant('agent'), + ); + static const VerificationMeta _idMeta = const VerificationMeta('id'); + @override + late final GeneratedColumn id = GeneratedColumn( + 'id', + aliasedName, + false, + type: DriftSqlType.int, + requiredDuringInsert: false, + ); + static const VerificationMeta _activeProjectIdMeta = const VerificationMeta( + 'activeProjectId', + ); + @override + late final GeneratedColumn activeProjectId = GeneratedColumn( + 'active_project_id', + aliasedName, + true, + type: DriftSqlType.string, + requiredDuringInsert: false, + ); + static const VerificationMeta _sidebarCollapsedMeta = const VerificationMeta( + 'sidebarCollapsed', + ); + @override + late final GeneratedColumn sidebarCollapsed = GeneratedColumn( + 'sidebar_collapsed', + aliasedName, + false, + type: DriftSqlType.bool, + requiredDuringInsert: true, + defaultConstraints: GeneratedColumn.constraintIsAlways( + 'CHECK ("sidebar_collapsed" IN (0, 1))', + ), + ); + static const VerificationMeta _sidebarWidthMeta = const VerificationMeta( + 'sidebarWidth', + ); + @override + late final GeneratedColumn sidebarWidth = GeneratedColumn( + 'sidebar_width', + aliasedName, + true, + type: DriftSqlType.double, + requiredDuringInsert: false, + ); + @override + List get $columns => [ + mode, + id, + activeProjectId, + sidebarCollapsed, + sidebarWidth, + ]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'workspace_view_configurations'; + @override + VerificationContext validateIntegrity( + Insertable instance, { + bool isInserting = false, + }) { + final context = VerificationContext(); + final data = instance.toColumns(true); + if (data.containsKey('mode')) { + context.handle( + _modeMeta, + mode.isAcceptableOrUnknown(data['mode']!, _modeMeta), + ); + } + if (data.containsKey('id')) { + context.handle(_idMeta, id.isAcceptableOrUnknown(data['id']!, _idMeta)); + } + if (data.containsKey('active_project_id')) { + context.handle( + _activeProjectIdMeta, + activeProjectId.isAcceptableOrUnknown( + data['active_project_id']!, + _activeProjectIdMeta, + ), + ); + } + if (data.containsKey('sidebar_collapsed')) { + context.handle( + _sidebarCollapsedMeta, + sidebarCollapsed.isAcceptableOrUnknown( + data['sidebar_collapsed']!, + _sidebarCollapsedMeta, + ), + ); + } else if (isInserting) { + context.missing(_sidebarCollapsedMeta); + } + if (data.containsKey('sidebar_width')) { + context.handle( + _sidebarWidthMeta, + sidebarWidth.isAcceptableOrUnknown( + data['sidebar_width']!, + _sidebarWidthMeta, + ), + ); + } + return context; + } + + @override + Set get $primaryKey => {id}; + @override + WorkspaceViewConfiguration map( + Map data, { + String? tablePrefix, + }) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return WorkspaceViewConfiguration( + mode: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}mode'], + )!, + id: attachedDatabase.typeMapping.read( + DriftSqlType.int, + data['${effectivePrefix}id'], + )!, + activeProjectId: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}active_project_id'], + ), + sidebarCollapsed: attachedDatabase.typeMapping.read( + DriftSqlType.bool, + data['${effectivePrefix}sidebar_collapsed'], + )!, + sidebarWidth: attachedDatabase.typeMapping.read( + DriftSqlType.double, + data['${effectivePrefix}sidebar_width'], + ), + ); + } + + @override + $WorkspaceViewConfigurationsTable createAlias(String alias) { + return $WorkspaceViewConfigurationsTable(attachedDatabase, alias); + } +} + +class WorkspaceViewConfiguration extends DataClass + implements Insertable { + final String mode; + final int id; + final String? activeProjectId; + final bool sidebarCollapsed; + final double? sidebarWidth; + const WorkspaceViewConfiguration({ + required this.mode, + required this.id, + this.activeProjectId, + required this.sidebarCollapsed, + this.sidebarWidth, + }); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['mode'] = Variable(mode); + map['id'] = Variable(id); + if (!nullToAbsent || activeProjectId != null) { + map['active_project_id'] = Variable(activeProjectId); + } + map['sidebar_collapsed'] = Variable(sidebarCollapsed); + if (!nullToAbsent || sidebarWidth != null) { + map['sidebar_width'] = Variable(sidebarWidth); + } + return map; + } + + WorkspaceViewConfigurationsCompanion toCompanion(bool nullToAbsent) { + return WorkspaceViewConfigurationsCompanion( + mode: Value(mode), + id: Value(id), + activeProjectId: activeProjectId == null && nullToAbsent + ? const Value.absent() + : Value(activeProjectId), + sidebarCollapsed: Value(sidebarCollapsed), + sidebarWidth: sidebarWidth == null && nullToAbsent + ? const Value.absent() + : Value(sidebarWidth), + ); + } + + factory WorkspaceViewConfiguration.fromJson( + Map json, { + ValueSerializer? serializer, + }) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return WorkspaceViewConfiguration( + mode: serializer.fromJson(json['mode']), + id: serializer.fromJson(json['id']), + activeProjectId: serializer.fromJson(json['activeProjectId']), + sidebarCollapsed: serializer.fromJson(json['sidebarCollapsed']), + sidebarWidth: serializer.fromJson(json['sidebarWidth']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'mode': serializer.toJson(mode), + 'id': serializer.toJson(id), + 'activeProjectId': serializer.toJson(activeProjectId), + 'sidebarCollapsed': serializer.toJson(sidebarCollapsed), + 'sidebarWidth': serializer.toJson(sidebarWidth), + }; + } + + WorkspaceViewConfiguration copyWith({ + String? mode, + int? id, + Value activeProjectId = const Value.absent(), + bool? sidebarCollapsed, + Value sidebarWidth = const Value.absent(), + }) => WorkspaceViewConfiguration( + mode: mode ?? this.mode, + id: id ?? this.id, + activeProjectId: activeProjectId.present + ? activeProjectId.value + : this.activeProjectId, + sidebarCollapsed: sidebarCollapsed ?? this.sidebarCollapsed, + sidebarWidth: sidebarWidth.present ? sidebarWidth.value : this.sidebarWidth, + ); + WorkspaceViewConfiguration copyWithCompanion( + WorkspaceViewConfigurationsCompanion data, + ) { + return WorkspaceViewConfiguration( + mode: data.mode.present ? data.mode.value : this.mode, + id: data.id.present ? data.id.value : this.id, + activeProjectId: data.activeProjectId.present + ? data.activeProjectId.value + : this.activeProjectId, + sidebarCollapsed: data.sidebarCollapsed.present + ? data.sidebarCollapsed.value + : this.sidebarCollapsed, + sidebarWidth: data.sidebarWidth.present + ? data.sidebarWidth.value + : this.sidebarWidth, + ); + } + + @override + String toString() { + return (StringBuffer('WorkspaceViewConfiguration(') + ..write('mode: $mode, ') + ..write('id: $id, ') + ..write('activeProjectId: $activeProjectId, ') + ..write('sidebarCollapsed: $sidebarCollapsed, ') + ..write('sidebarWidth: $sidebarWidth') + ..write(')')) + .toString(); + } + + @override + int get hashCode => + Object.hash(mode, id, activeProjectId, sidebarCollapsed, sidebarWidth); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is WorkspaceViewConfiguration && + other.mode == this.mode && + other.id == this.id && + other.activeProjectId == this.activeProjectId && + other.sidebarCollapsed == this.sidebarCollapsed && + other.sidebarWidth == this.sidebarWidth); +} + +class WorkspaceViewConfigurationsCompanion + extends UpdateCompanion { + final Value mode; + final Value id; + final Value activeProjectId; + final Value sidebarCollapsed; + final Value sidebarWidth; + const WorkspaceViewConfigurationsCompanion({ + this.mode = const Value.absent(), + this.id = const Value.absent(), + this.activeProjectId = const Value.absent(), + this.sidebarCollapsed = const Value.absent(), + this.sidebarWidth = const Value.absent(), + }); + WorkspaceViewConfigurationsCompanion.insert({ + this.mode = const Value.absent(), + this.id = const Value.absent(), + this.activeProjectId = const Value.absent(), + required bool sidebarCollapsed, + this.sidebarWidth = const Value.absent(), + }) : sidebarCollapsed = Value(sidebarCollapsed); + static Insertable custom({ + Expression? mode, + Expression? id, + Expression? activeProjectId, + Expression? sidebarCollapsed, + Expression? sidebarWidth, + }) { + return RawValuesInsertable({ + if (mode != null) 'mode': mode, + if (id != null) 'id': id, + if (activeProjectId != null) 'active_project_id': activeProjectId, + if (sidebarCollapsed != null) 'sidebar_collapsed': sidebarCollapsed, + if (sidebarWidth != null) 'sidebar_width': sidebarWidth, + }); + } + + WorkspaceViewConfigurationsCompanion copyWith({ + Value? mode, + Value? id, + Value? activeProjectId, + Value? sidebarCollapsed, + Value? sidebarWidth, + }) { + return WorkspaceViewConfigurationsCompanion( + mode: mode ?? this.mode, + id: id ?? this.id, + activeProjectId: activeProjectId ?? this.activeProjectId, + sidebarCollapsed: sidebarCollapsed ?? this.sidebarCollapsed, + sidebarWidth: sidebarWidth ?? this.sidebarWidth, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (mode.present) { + map['mode'] = Variable(mode.value); + } + if (id.present) { + map['id'] = Variable(id.value); + } + if (activeProjectId.present) { + map['active_project_id'] = Variable(activeProjectId.value); + } + if (sidebarCollapsed.present) { + map['sidebar_collapsed'] = Variable(sidebarCollapsed.value); + } + if (sidebarWidth.present) { + map['sidebar_width'] = Variable(sidebarWidth.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('WorkspaceViewConfigurationsCompanion(') + ..write('mode: $mode, ') + ..write('id: $id, ') + ..write('activeProjectId: $activeProjectId, ') + ..write('sidebarCollapsed: $sidebarCollapsed, ') + ..write('sidebarWidth: $sidebarWidth') + ..write(')')) + .toString(); + } +} + +class $ProjectViewConfigurationsTable extends ProjectViewConfigurations + with TableInfo<$ProjectViewConfigurationsTable, ProjectViewConfiguration> { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + $ProjectViewConfigurationsTable(this.attachedDatabase, [this._alias]); + static const VerificationMeta _projectIdMeta = const VerificationMeta( + 'projectId', + ); + @override + late final GeneratedColumn projectId = GeneratedColumn( + 'project_id', + aliasedName, + false, + type: DriftSqlType.string, + requiredDuringInsert: true, + ); + static const VerificationMeta _propertiesOpenMeta = const VerificationMeta( + 'propertiesOpen', + ); + @override + late final GeneratedColumn propertiesOpen = GeneratedColumn( + 'properties_open', + aliasedName, + false, + type: DriftSqlType.bool, + requiredDuringInsert: true, + defaultConstraints: GeneratedColumn.constraintIsAlways( + 'CHECK ("properties_open" IN (0, 1))', + ), + ); + static const VerificationMeta _timelineHeightMeta = const VerificationMeta( + 'timelineHeight', + ); + @override + late final GeneratedColumn timelineHeight = GeneratedColumn( + 'timeline_height', + aliasedName, + true, + type: DriftSqlType.double, + requiredDuringInsert: false, + ); + @override + List get $columns => [ + projectId, + propertiesOpen, + timelineHeight, + ]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'project_view_configurations'; + @override + VerificationContext validateIntegrity( + Insertable instance, { + bool isInserting = false, + }) { + final context = VerificationContext(); + final data = instance.toColumns(true); + if (data.containsKey('project_id')) { + context.handle( + _projectIdMeta, + projectId.isAcceptableOrUnknown(data['project_id']!, _projectIdMeta), + ); + } else if (isInserting) { + context.missing(_projectIdMeta); + } + if (data.containsKey('properties_open')) { + context.handle( + _propertiesOpenMeta, + propertiesOpen.isAcceptableOrUnknown( + data['properties_open']!, + _propertiesOpenMeta, + ), + ); + } else if (isInserting) { + context.missing(_propertiesOpenMeta); + } + if (data.containsKey('timeline_height')) { + context.handle( + _timelineHeightMeta, + timelineHeight.isAcceptableOrUnknown( + data['timeline_height']!, + _timelineHeightMeta, + ), + ); + } + return context; + } + + @override + Set get $primaryKey => {projectId}; + @override + ProjectViewConfiguration map( + Map data, { + String? tablePrefix, + }) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return ProjectViewConfiguration( + projectId: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}project_id'], + )!, + propertiesOpen: attachedDatabase.typeMapping.read( + DriftSqlType.bool, + data['${effectivePrefix}properties_open'], + )!, + timelineHeight: attachedDatabase.typeMapping.read( + DriftSqlType.double, + data['${effectivePrefix}timeline_height'], + ), + ); + } + + @override + $ProjectViewConfigurationsTable createAlias(String alias) { + return $ProjectViewConfigurationsTable(attachedDatabase, alias); + } +} + +class ProjectViewConfiguration extends DataClass + implements Insertable { + final String projectId; + final bool propertiesOpen; + final double? timelineHeight; + const ProjectViewConfiguration({ + required this.projectId, + required this.propertiesOpen, + this.timelineHeight, + }); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['project_id'] = Variable(projectId); + map['properties_open'] = Variable(propertiesOpen); + if (!nullToAbsent || timelineHeight != null) { + map['timeline_height'] = Variable(timelineHeight); + } + return map; + } + + ProjectViewConfigurationsCompanion toCompanion(bool nullToAbsent) { + return ProjectViewConfigurationsCompanion( + projectId: Value(projectId), + propertiesOpen: Value(propertiesOpen), + timelineHeight: timelineHeight == null && nullToAbsent + ? const Value.absent() + : Value(timelineHeight), + ); + } + + factory ProjectViewConfiguration.fromJson( + Map json, { + ValueSerializer? serializer, + }) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return ProjectViewConfiguration( + projectId: serializer.fromJson(json['projectId']), + propertiesOpen: serializer.fromJson(json['propertiesOpen']), + timelineHeight: serializer.fromJson(json['timelineHeight']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'projectId': serializer.toJson(projectId), + 'propertiesOpen': serializer.toJson(propertiesOpen), + 'timelineHeight': serializer.toJson(timelineHeight), + }; + } + + ProjectViewConfiguration copyWith({ + String? projectId, + bool? propertiesOpen, + Value timelineHeight = const Value.absent(), + }) => ProjectViewConfiguration( + projectId: projectId ?? this.projectId, + propertiesOpen: propertiesOpen ?? this.propertiesOpen, + timelineHeight: timelineHeight.present + ? timelineHeight.value + : this.timelineHeight, + ); + ProjectViewConfiguration copyWithCompanion( + ProjectViewConfigurationsCompanion data, + ) { + return ProjectViewConfiguration( + projectId: data.projectId.present ? data.projectId.value : this.projectId, + propertiesOpen: data.propertiesOpen.present + ? data.propertiesOpen.value + : this.propertiesOpen, + timelineHeight: data.timelineHeight.present + ? data.timelineHeight.value + : this.timelineHeight, + ); + } + + @override + String toString() { + return (StringBuffer('ProjectViewConfiguration(') + ..write('projectId: $projectId, ') + ..write('propertiesOpen: $propertiesOpen, ') + ..write('timelineHeight: $timelineHeight') + ..write(')')) + .toString(); + } + + @override + int get hashCode => Object.hash(projectId, propertiesOpen, timelineHeight); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is ProjectViewConfiguration && + other.projectId == this.projectId && + other.propertiesOpen == this.propertiesOpen && + other.timelineHeight == this.timelineHeight); +} + +class ProjectViewConfigurationsCompanion + extends UpdateCompanion { + final Value projectId; + final Value propertiesOpen; + final Value timelineHeight; + final Value rowid; + const ProjectViewConfigurationsCompanion({ + this.projectId = const Value.absent(), + this.propertiesOpen = const Value.absent(), + this.timelineHeight = const Value.absent(), + this.rowid = const Value.absent(), + }); + ProjectViewConfigurationsCompanion.insert({ + required String projectId, + required bool propertiesOpen, + this.timelineHeight = const Value.absent(), + this.rowid = const Value.absent(), + }) : projectId = Value(projectId), + propertiesOpen = Value(propertiesOpen); + static Insertable custom({ + Expression? projectId, + Expression? propertiesOpen, + Expression? timelineHeight, + Expression? rowid, + }) { + return RawValuesInsertable({ + if (projectId != null) 'project_id': projectId, + if (propertiesOpen != null) 'properties_open': propertiesOpen, + if (timelineHeight != null) 'timeline_height': timelineHeight, + if (rowid != null) 'rowid': rowid, + }); + } + + ProjectViewConfigurationsCompanion copyWith({ + Value? projectId, + Value? propertiesOpen, + Value? timelineHeight, + Value? rowid, + }) { + return ProjectViewConfigurationsCompanion( + projectId: projectId ?? this.projectId, + propertiesOpen: propertiesOpen ?? this.propertiesOpen, + timelineHeight: timelineHeight ?? this.timelineHeight, + rowid: rowid ?? this.rowid, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (projectId.present) { + map['project_id'] = Variable(projectId.value); + } + if (propertiesOpen.present) { + map['properties_open'] = Variable(propertiesOpen.value); + } + if (timelineHeight.present) { + map['timeline_height'] = Variable(timelineHeight.value); + } + if (rowid.present) { + map['rowid'] = Variable(rowid.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('ProjectViewConfigurationsCompanion(') + ..write('projectId: $projectId, ') + ..write('propertiesOpen: $propertiesOpen, ') + ..write('timelineHeight: $timelineHeight, ') + ..write('rowid: $rowid') + ..write(')')) + .toString(); + } +} + +class $TimelineViewConfigurationsTable extends TimelineViewConfigurations + with + TableInfo<$TimelineViewConfigurationsTable, TimelineViewConfiguration> { + @override + final GeneratedDatabase attachedDatabase; + final String? _alias; + $TimelineViewConfigurationsTable(this.attachedDatabase, [this._alias]); + static const VerificationMeta _projectIdMeta = const VerificationMeta( + 'projectId', + ); + @override + late final GeneratedColumn projectId = GeneratedColumn( + 'project_id', + aliasedName, + false, + type: DriftSqlType.string, + requiredDuringInsert: true, + ); + static const VerificationMeta _timelineIdMeta = const VerificationMeta( + 'timelineId', + ); + @override + late final GeneratedColumn timelineId = GeneratedColumn( + 'timeline_id', + aliasedName, + false, + type: DriftSqlType.string, + requiredDuringInsert: true, + ); + static const VerificationMeta _sequenceIdMeta = const VerificationMeta( + 'sequenceId', + ); + @override + late final GeneratedColumn sequenceId = GeneratedColumn( + 'sequence_id', + aliasedName, + false, + type: DriftSqlType.string, + requiredDuringInsert: true, + ); + static const VerificationMeta _activeMeta = const VerificationMeta('active'); + @override + late final GeneratedColumn active = GeneratedColumn( + 'active', + aliasedName, + false, + type: DriftSqlType.bool, + requiredDuringInsert: true, + defaultConstraints: GeneratedColumn.constraintIsAlways( + 'CHECK ("active" IN (0, 1))', + ), + ); + static const VerificationMeta _playheadTickMeta = const VerificationMeta( + 'playheadTick', + ); + @override + late final GeneratedColumn playheadTick = GeneratedColumn( + 'playhead_tick', + aliasedName, + false, + type: DriftSqlType.int, + requiredDuringInsert: true, + ); + static const VerificationMeta _baseTickMeta = const VerificationMeta( + 'baseTick', + ); + @override + late final GeneratedColumn baseTick = GeneratedColumn( + 'base_tick', + aliasedName, + false, + type: DriftSqlType.int, + requiredDuringInsert: true, + ); + static const VerificationMeta _fractionalTickMeta = const VerificationMeta( + 'fractionalTick', + ); + @override + late final GeneratedColumn fractionalTick = GeneratedColumn( + 'fractional_tick', + aliasedName, + false, + type: DriftSqlType.double, + requiredDuringInsert: true, + ); + static const VerificationMeta _pixelsPerTickMeta = const VerificationMeta( + 'pixelsPerTick', + ); + @override + late final GeneratedColumn pixelsPerTick = GeneratedColumn( + 'pixels_per_tick', + aliasedName, + false, + type: DriftSqlType.double, + requiredDuringInsert: true, + ); + static const VerificationMeta _verticalOffsetMeta = const VerificationMeta( + 'verticalOffset', + ); + @override + late final GeneratedColumn verticalOffset = GeneratedColumn( + 'vertical_offset', + aliasedName, + false, + type: DriftSqlType.double, + requiredDuringInsert: true, + ); + @override + List get $columns => [ + projectId, + timelineId, + sequenceId, + active, + playheadTick, + baseTick, + fractionalTick, + pixelsPerTick, + verticalOffset, + ]; + @override + String get aliasedName => _alias ?? actualTableName; + @override + String get actualTableName => $name; + static const String $name = 'timeline_view_configurations'; + @override + VerificationContext validateIntegrity( + Insertable instance, { + bool isInserting = false, + }) { + final context = VerificationContext(); + final data = instance.toColumns(true); + if (data.containsKey('project_id')) { + context.handle( + _projectIdMeta, + projectId.isAcceptableOrUnknown(data['project_id']!, _projectIdMeta), + ); + } else if (isInserting) { + context.missing(_projectIdMeta); + } + if (data.containsKey('timeline_id')) { + context.handle( + _timelineIdMeta, + timelineId.isAcceptableOrUnknown(data['timeline_id']!, _timelineIdMeta), + ); + } else if (isInserting) { + context.missing(_timelineIdMeta); + } + if (data.containsKey('sequence_id')) { + context.handle( + _sequenceIdMeta, + sequenceId.isAcceptableOrUnknown(data['sequence_id']!, _sequenceIdMeta), + ); + } else if (isInserting) { + context.missing(_sequenceIdMeta); + } + if (data.containsKey('active')) { + context.handle( + _activeMeta, + active.isAcceptableOrUnknown(data['active']!, _activeMeta), + ); + } else if (isInserting) { + context.missing(_activeMeta); + } + if (data.containsKey('playhead_tick')) { + context.handle( + _playheadTickMeta, + playheadTick.isAcceptableOrUnknown( + data['playhead_tick']!, + _playheadTickMeta, + ), + ); + } else if (isInserting) { + context.missing(_playheadTickMeta); + } + if (data.containsKey('base_tick')) { + context.handle( + _baseTickMeta, + baseTick.isAcceptableOrUnknown(data['base_tick']!, _baseTickMeta), + ); + } else if (isInserting) { + context.missing(_baseTickMeta); + } + if (data.containsKey('fractional_tick')) { + context.handle( + _fractionalTickMeta, + fractionalTick.isAcceptableOrUnknown( + data['fractional_tick']!, + _fractionalTickMeta, + ), + ); + } else if (isInserting) { + context.missing(_fractionalTickMeta); + } + if (data.containsKey('pixels_per_tick')) { + context.handle( + _pixelsPerTickMeta, + pixelsPerTick.isAcceptableOrUnknown( + data['pixels_per_tick']!, + _pixelsPerTickMeta, + ), + ); + } else if (isInserting) { + context.missing(_pixelsPerTickMeta); + } + if (data.containsKey('vertical_offset')) { + context.handle( + _verticalOffsetMeta, + verticalOffset.isAcceptableOrUnknown( + data['vertical_offset']!, + _verticalOffsetMeta, + ), + ); + } else if (isInserting) { + context.missing(_verticalOffsetMeta); + } + return context; + } + + @override + Set get $primaryKey => {projectId, timelineId, sequenceId}; + @override + TimelineViewConfiguration map( + Map data, { + String? tablePrefix, + }) { + final effectivePrefix = tablePrefix != null ? '$tablePrefix.' : ''; + return TimelineViewConfiguration( + projectId: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}project_id'], + )!, + timelineId: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}timeline_id'], + )!, + sequenceId: attachedDatabase.typeMapping.read( + DriftSqlType.string, + data['${effectivePrefix}sequence_id'], + )!, + active: attachedDatabase.typeMapping.read( + DriftSqlType.bool, + data['${effectivePrefix}active'], + )!, + playheadTick: attachedDatabase.typeMapping.read( + DriftSqlType.int, + data['${effectivePrefix}playhead_tick'], + )!, + baseTick: attachedDatabase.typeMapping.read( + DriftSqlType.int, + data['${effectivePrefix}base_tick'], + )!, + fractionalTick: attachedDatabase.typeMapping.read( + DriftSqlType.double, + data['${effectivePrefix}fractional_tick'], + )!, + pixelsPerTick: attachedDatabase.typeMapping.read( + DriftSqlType.double, + data['${effectivePrefix}pixels_per_tick'], + )!, + verticalOffset: attachedDatabase.typeMapping.read( + DriftSqlType.double, + data['${effectivePrefix}vertical_offset'], + )!, + ); + } + + @override + $TimelineViewConfigurationsTable createAlias(String alias) { + return $TimelineViewConfigurationsTable(attachedDatabase, alias); + } +} + +class TimelineViewConfiguration extends DataClass + implements Insertable { + final String projectId; + final String timelineId; + final String sequenceId; + final bool active; + final int playheadTick; + final int baseTick; + final double fractionalTick; + final double pixelsPerTick; + final double verticalOffset; + const TimelineViewConfiguration({ + required this.projectId, + required this.timelineId, + required this.sequenceId, + required this.active, + required this.playheadTick, + required this.baseTick, + required this.fractionalTick, + required this.pixelsPerTick, + required this.verticalOffset, + }); + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + map['project_id'] = Variable(projectId); + map['timeline_id'] = Variable(timelineId); + map['sequence_id'] = Variable(sequenceId); + map['active'] = Variable(active); + map['playhead_tick'] = Variable(playheadTick); + map['base_tick'] = Variable(baseTick); + map['fractional_tick'] = Variable(fractionalTick); + map['pixels_per_tick'] = Variable(pixelsPerTick); + map['vertical_offset'] = Variable(verticalOffset); + return map; + } + + TimelineViewConfigurationsCompanion toCompanion(bool nullToAbsent) { + return TimelineViewConfigurationsCompanion( + projectId: Value(projectId), + timelineId: Value(timelineId), + sequenceId: Value(sequenceId), + active: Value(active), + playheadTick: Value(playheadTick), + baseTick: Value(baseTick), + fractionalTick: Value(fractionalTick), + pixelsPerTick: Value(pixelsPerTick), + verticalOffset: Value(verticalOffset), + ); + } + + factory TimelineViewConfiguration.fromJson( + Map json, { + ValueSerializer? serializer, + }) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return TimelineViewConfiguration( + projectId: serializer.fromJson(json['projectId']), + timelineId: serializer.fromJson(json['timelineId']), + sequenceId: serializer.fromJson(json['sequenceId']), + active: serializer.fromJson(json['active']), + playheadTick: serializer.fromJson(json['playheadTick']), + baseTick: serializer.fromJson(json['baseTick']), + fractionalTick: serializer.fromJson(json['fractionalTick']), + pixelsPerTick: serializer.fromJson(json['pixelsPerTick']), + verticalOffset: serializer.fromJson(json['verticalOffset']), + ); + } + @override + Map toJson({ValueSerializer? serializer}) { + serializer ??= driftRuntimeOptions.defaultSerializer; + return { + 'projectId': serializer.toJson(projectId), + 'timelineId': serializer.toJson(timelineId), + 'sequenceId': serializer.toJson(sequenceId), + 'active': serializer.toJson(active), + 'playheadTick': serializer.toJson(playheadTick), + 'baseTick': serializer.toJson(baseTick), + 'fractionalTick': serializer.toJson(fractionalTick), + 'pixelsPerTick': serializer.toJson(pixelsPerTick), + 'verticalOffset': serializer.toJson(verticalOffset), + }; + } + + TimelineViewConfiguration copyWith({ + String? projectId, + String? timelineId, + String? sequenceId, + bool? active, + int? playheadTick, + int? baseTick, + double? fractionalTick, + double? pixelsPerTick, + double? verticalOffset, + }) => TimelineViewConfiguration( + projectId: projectId ?? this.projectId, + timelineId: timelineId ?? this.timelineId, + sequenceId: sequenceId ?? this.sequenceId, + active: active ?? this.active, + playheadTick: playheadTick ?? this.playheadTick, + baseTick: baseTick ?? this.baseTick, + fractionalTick: fractionalTick ?? this.fractionalTick, + pixelsPerTick: pixelsPerTick ?? this.pixelsPerTick, + verticalOffset: verticalOffset ?? this.verticalOffset, + ); + TimelineViewConfiguration copyWithCompanion( + TimelineViewConfigurationsCompanion data, + ) { + return TimelineViewConfiguration( + projectId: data.projectId.present ? data.projectId.value : this.projectId, + timelineId: data.timelineId.present + ? data.timelineId.value + : this.timelineId, + sequenceId: data.sequenceId.present + ? data.sequenceId.value + : this.sequenceId, + active: data.active.present ? data.active.value : this.active, + playheadTick: data.playheadTick.present + ? data.playheadTick.value + : this.playheadTick, + baseTick: data.baseTick.present ? data.baseTick.value : this.baseTick, + fractionalTick: data.fractionalTick.present + ? data.fractionalTick.value + : this.fractionalTick, + pixelsPerTick: data.pixelsPerTick.present + ? data.pixelsPerTick.value + : this.pixelsPerTick, + verticalOffset: data.verticalOffset.present + ? data.verticalOffset.value + : this.verticalOffset, + ); + } + + @override + String toString() { + return (StringBuffer('TimelineViewConfiguration(') + ..write('projectId: $projectId, ') + ..write('timelineId: $timelineId, ') + ..write('sequenceId: $sequenceId, ') + ..write('active: $active, ') + ..write('playheadTick: $playheadTick, ') + ..write('baseTick: $baseTick, ') + ..write('fractionalTick: $fractionalTick, ') + ..write('pixelsPerTick: $pixelsPerTick, ') + ..write('verticalOffset: $verticalOffset') + ..write(')')) + .toString(); + } + + @override + int get hashCode => Object.hash( + projectId, + timelineId, + sequenceId, + active, + playheadTick, + baseTick, + fractionalTick, + pixelsPerTick, + verticalOffset, + ); + @override + bool operator ==(Object other) => + identical(this, other) || + (other is TimelineViewConfiguration && + other.projectId == this.projectId && + other.timelineId == this.timelineId && + other.sequenceId == this.sequenceId && + other.active == this.active && + other.playheadTick == this.playheadTick && + other.baseTick == this.baseTick && + other.fractionalTick == this.fractionalTick && + other.pixelsPerTick == this.pixelsPerTick && + other.verticalOffset == this.verticalOffset); +} + +class TimelineViewConfigurationsCompanion + extends UpdateCompanion { + final Value projectId; + final Value timelineId; + final Value sequenceId; + final Value active; + final Value playheadTick; + final Value baseTick; + final Value fractionalTick; + final Value pixelsPerTick; + final Value verticalOffset; + final Value rowid; + const TimelineViewConfigurationsCompanion({ + this.projectId = const Value.absent(), + this.timelineId = const Value.absent(), + this.sequenceId = const Value.absent(), + this.active = const Value.absent(), + this.playheadTick = const Value.absent(), + this.baseTick = const Value.absent(), + this.fractionalTick = const Value.absent(), + this.pixelsPerTick = const Value.absent(), + this.verticalOffset = const Value.absent(), + this.rowid = const Value.absent(), + }); + TimelineViewConfigurationsCompanion.insert({ + required String projectId, + required String timelineId, + required String sequenceId, + required bool active, + required int playheadTick, + required int baseTick, + required double fractionalTick, + required double pixelsPerTick, + required double verticalOffset, + this.rowid = const Value.absent(), + }) : projectId = Value(projectId), + timelineId = Value(timelineId), + sequenceId = Value(sequenceId), + active = Value(active), + playheadTick = Value(playheadTick), + baseTick = Value(baseTick), + fractionalTick = Value(fractionalTick), + pixelsPerTick = Value(pixelsPerTick), + verticalOffset = Value(verticalOffset); + static Insertable custom({ + Expression? projectId, + Expression? timelineId, + Expression? sequenceId, + Expression? active, + Expression? playheadTick, + Expression? baseTick, + Expression? fractionalTick, + Expression? pixelsPerTick, + Expression? verticalOffset, + Expression? rowid, + }) { + return RawValuesInsertable({ + if (projectId != null) 'project_id': projectId, + if (timelineId != null) 'timeline_id': timelineId, + if (sequenceId != null) 'sequence_id': sequenceId, + if (active != null) 'active': active, + if (playheadTick != null) 'playhead_tick': playheadTick, + if (baseTick != null) 'base_tick': baseTick, + if (fractionalTick != null) 'fractional_tick': fractionalTick, + if (pixelsPerTick != null) 'pixels_per_tick': pixelsPerTick, + if (verticalOffset != null) 'vertical_offset': verticalOffset, + if (rowid != null) 'rowid': rowid, + }); + } + + TimelineViewConfigurationsCompanion copyWith({ + Value? projectId, + Value? timelineId, + Value? sequenceId, + Value? active, + Value? playheadTick, + Value? baseTick, + Value? fractionalTick, + Value? pixelsPerTick, + Value? verticalOffset, + Value? rowid, + }) { + return TimelineViewConfigurationsCompanion( + projectId: projectId ?? this.projectId, + timelineId: timelineId ?? this.timelineId, + sequenceId: sequenceId ?? this.sequenceId, + active: active ?? this.active, + playheadTick: playheadTick ?? this.playheadTick, + baseTick: baseTick ?? this.baseTick, + fractionalTick: fractionalTick ?? this.fractionalTick, + pixelsPerTick: pixelsPerTick ?? this.pixelsPerTick, + verticalOffset: verticalOffset ?? this.verticalOffset, + rowid: rowid ?? this.rowid, + ); + } + + @override + Map toColumns(bool nullToAbsent) { + final map = {}; + if (projectId.present) { + map['project_id'] = Variable(projectId.value); + } + if (timelineId.present) { + map['timeline_id'] = Variable(timelineId.value); + } + if (sequenceId.present) { + map['sequence_id'] = Variable(sequenceId.value); + } + if (active.present) { + map['active'] = Variable(active.value); + } + if (playheadTick.present) { + map['playhead_tick'] = Variable(playheadTick.value); + } + if (baseTick.present) { + map['base_tick'] = Variable(baseTick.value); + } + if (fractionalTick.present) { + map['fractional_tick'] = Variable(fractionalTick.value); + } + if (pixelsPerTick.present) { + map['pixels_per_tick'] = Variable(pixelsPerTick.value); + } + if (verticalOffset.present) { + map['vertical_offset'] = Variable(verticalOffset.value); + } + if (rowid.present) { + map['rowid'] = Variable(rowid.value); + } + return map; + } + + @override + String toString() { + return (StringBuffer('TimelineViewConfigurationsCompanion(') + ..write('projectId: $projectId, ') + ..write('timelineId: $timelineId, ') + ..write('sequenceId: $sequenceId, ') + ..write('active: $active, ') + ..write('playheadTick: $playheadTick, ') + ..write('baseTick: $baseTick, ') + ..write('fractionalTick: $fractionalTick, ') + ..write('pixelsPerTick: $pixelsPerTick, ') + ..write('verticalOffset: $verticalOffset, ') + ..write('rowid: $rowid') + ..write(')')) + .toString(); + } +} + +abstract class _$AppDatabase extends GeneratedDatabase { + _$AppDatabase(QueryExecutor e) : super(e); + $AppDatabaseManager get managers => $AppDatabaseManager(this); + late final $RecentProjectRecordsTable recentProjectRecords = + $RecentProjectRecordsTable(this); + late final $LastOpenedTimelinesTable lastOpenedTimelines = + $LastOpenedTimelinesTable(this); + late final $McpConfigurationsTable mcpConfigurations = + $McpConfigurationsTable(this); + late final $AppearanceConfigurationsTable appearanceConfigurations = + $AppearanceConfigurationsTable(this); + late final $LanguageConfigurationsTable languageConfigurations = + $LanguageConfigurationsTable(this); + late final $ConversationLocationConfigurationsTable + conversationLocationConfigurations = $ConversationLocationConfigurationsTable( + this, + ); + late final $ProjectLocationConfigurationsTable projectLocationConfigurations = + $ProjectLocationConfigurationsTable(this); + late final $ResourceLocationConfigurationsTable + resourceLocationConfigurations = $ResourceLocationConfigurationsTable(this); + late final $AgentConfigurationsTable agentConfigurations = + $AgentConfigurationsTable(this); + late final $AgentProvidersTable agentProviders = $AgentProvidersTable(this); + late final $AgentModelsTable agentModels = $AgentModelsTable(this); + late final $WorkspaceViewConfigurationsTable workspaceViewConfigurations = + $WorkspaceViewConfigurationsTable(this); + late final $ProjectViewConfigurationsTable projectViewConfigurations = + $ProjectViewConfigurationsTable(this); + late final $TimelineViewConfigurationsTable timelineViewConfigurations = + $TimelineViewConfigurationsTable(this); + @override + Iterable> get allTables => + allSchemaEntities.whereType>(); + @override + List get allSchemaEntities => [ + recentProjectRecords, + lastOpenedTimelines, + mcpConfigurations, + appearanceConfigurations, + languageConfigurations, + conversationLocationConfigurations, + projectLocationConfigurations, + resourceLocationConfigurations, + agentConfigurations, + agentProviders, + agentModels, + workspaceViewConfigurations, + projectViewConfigurations, + timelineViewConfigurations, + ]; +} + +typedef $$RecentProjectRecordsTableCreateCompanionBuilder = + RecentProjectRecordsCompanion Function({ + required String id, + required String name, + required String path, + required int position, + Value rowid, + }); +typedef $$RecentProjectRecordsTableUpdateCompanionBuilder = + RecentProjectRecordsCompanion Function({ + Value id, + Value name, + Value path, + Value position, + Value rowid, + }); + +class $$RecentProjectRecordsTableFilterComposer + extends Composer<_$AppDatabase, $RecentProjectRecordsTable> { + $$RecentProjectRecordsTableFilterComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + ColumnFilters get id => $composableBuilder( + column: $table.id, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get name => $composableBuilder( + column: $table.name, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get path => $composableBuilder( + column: $table.path, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get position => $composableBuilder( + column: $table.position, + builder: (column) => ColumnFilters(column), + ); +} + +class $$RecentProjectRecordsTableOrderingComposer + extends Composer<_$AppDatabase, $RecentProjectRecordsTable> { + $$RecentProjectRecordsTableOrderingComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + ColumnOrderings get id => $composableBuilder( + column: $table.id, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get name => $composableBuilder( + column: $table.name, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get path => $composableBuilder( + column: $table.path, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get position => $composableBuilder( + column: $table.position, + builder: (column) => ColumnOrderings(column), + ); +} + +class $$RecentProjectRecordsTableAnnotationComposer + extends Composer<_$AppDatabase, $RecentProjectRecordsTable> { + $$RecentProjectRecordsTableAnnotationComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + GeneratedColumn get id => + $composableBuilder(column: $table.id, builder: (column) => column); + + GeneratedColumn get name => + $composableBuilder(column: $table.name, builder: (column) => column); + + GeneratedColumn get path => + $composableBuilder(column: $table.path, builder: (column) => column); + + GeneratedColumn get position => + $composableBuilder(column: $table.position, builder: (column) => column); +} + +class $$RecentProjectRecordsTableTableManager + extends + RootTableManager< + _$AppDatabase, + $RecentProjectRecordsTable, + RecentProjectRecord, + $$RecentProjectRecordsTableFilterComposer, + $$RecentProjectRecordsTableOrderingComposer, + $$RecentProjectRecordsTableAnnotationComposer, + $$RecentProjectRecordsTableCreateCompanionBuilder, + $$RecentProjectRecordsTableUpdateCompanionBuilder, + ( + RecentProjectRecord, + BaseReferences< + _$AppDatabase, + $RecentProjectRecordsTable, + RecentProjectRecord + >, + ), + RecentProjectRecord, + PrefetchHooks Function() + > { + $$RecentProjectRecordsTableTableManager( + _$AppDatabase db, + $RecentProjectRecordsTable table, + ) : super( + TableManagerState( + db: db, + table: table, + createFilteringComposer: () => + $$RecentProjectRecordsTableFilterComposer($db: db, $table: table), + createOrderingComposer: () => + $$RecentProjectRecordsTableOrderingComposer( + $db: db, + $table: table, + ), + createComputedFieldComposer: () => + $$RecentProjectRecordsTableAnnotationComposer( + $db: db, + $table: table, + ), + updateCompanionCallback: + ({ + Value id = const Value.absent(), + Value name = const Value.absent(), + Value path = const Value.absent(), + Value position = const Value.absent(), + Value rowid = const Value.absent(), + }) => RecentProjectRecordsCompanion( + id: id, + name: name, + path: path, + position: position, + rowid: rowid, + ), + createCompanionCallback: + ({ + required String id, + required String name, + required String path, + required int position, + Value rowid = const Value.absent(), + }) => RecentProjectRecordsCompanion.insert( + id: id, + name: name, + path: path, + position: position, + rowid: rowid, + ), + withReferenceMapper: (p0) => p0 + .map( + (e) => ( + e.readTable<$RecentProjectRecordsTable, RecentProjectRecord>( + table, + ), + BaseReferences< + _$AppDatabase, + $RecentProjectRecordsTable, + RecentProjectRecord + >(db, table, e), + ), + ) + .toList(), + prefetchHooksCallback: null, + ), + ); +} + +typedef $$RecentProjectRecordsTableProcessedTableManager = + ProcessedTableManager< + _$AppDatabase, + $RecentProjectRecordsTable, + RecentProjectRecord, + $$RecentProjectRecordsTableFilterComposer, + $$RecentProjectRecordsTableOrderingComposer, + $$RecentProjectRecordsTableAnnotationComposer, + $$RecentProjectRecordsTableCreateCompanionBuilder, + $$RecentProjectRecordsTableUpdateCompanionBuilder, + ( + RecentProjectRecord, + BaseReferences< + _$AppDatabase, + $RecentProjectRecordsTable, + RecentProjectRecord + >, + ), + RecentProjectRecord, + PrefetchHooks Function() + >; +typedef $$LastOpenedTimelinesTableCreateCompanionBuilder = + LastOpenedTimelinesCompanion Function({ + required String projectId, + required String timelineId, + Value rowid, + }); +typedef $$LastOpenedTimelinesTableUpdateCompanionBuilder = + LastOpenedTimelinesCompanion Function({ + Value projectId, + Value timelineId, + Value rowid, + }); + +class $$LastOpenedTimelinesTableFilterComposer + extends Composer<_$AppDatabase, $LastOpenedTimelinesTable> { + $$LastOpenedTimelinesTableFilterComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + ColumnFilters get projectId => $composableBuilder( + column: $table.projectId, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get timelineId => $composableBuilder( + column: $table.timelineId, + builder: (column) => ColumnFilters(column), + ); +} + +class $$LastOpenedTimelinesTableOrderingComposer + extends Composer<_$AppDatabase, $LastOpenedTimelinesTable> { + $$LastOpenedTimelinesTableOrderingComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + ColumnOrderings get projectId => $composableBuilder( + column: $table.projectId, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get timelineId => $composableBuilder( + column: $table.timelineId, + builder: (column) => ColumnOrderings(column), + ); +} + +class $$LastOpenedTimelinesTableAnnotationComposer + extends Composer<_$AppDatabase, $LastOpenedTimelinesTable> { + $$LastOpenedTimelinesTableAnnotationComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + GeneratedColumn get projectId => + $composableBuilder(column: $table.projectId, builder: (column) => column); + + GeneratedColumn get timelineId => $composableBuilder( + column: $table.timelineId, + builder: (column) => column, + ); +} + +class $$LastOpenedTimelinesTableTableManager + extends + RootTableManager< + _$AppDatabase, + $LastOpenedTimelinesTable, + LastOpenedTimeline, + $$LastOpenedTimelinesTableFilterComposer, + $$LastOpenedTimelinesTableOrderingComposer, + $$LastOpenedTimelinesTableAnnotationComposer, + $$LastOpenedTimelinesTableCreateCompanionBuilder, + $$LastOpenedTimelinesTableUpdateCompanionBuilder, + ( + LastOpenedTimeline, + BaseReferences< + _$AppDatabase, + $LastOpenedTimelinesTable, + LastOpenedTimeline + >, + ), + LastOpenedTimeline, + PrefetchHooks Function() + > { + $$LastOpenedTimelinesTableTableManager( + _$AppDatabase db, + $LastOpenedTimelinesTable table, + ) : super( + TableManagerState( + db: db, + table: table, + createFilteringComposer: () => + $$LastOpenedTimelinesTableFilterComposer($db: db, $table: table), + createOrderingComposer: () => + $$LastOpenedTimelinesTableOrderingComposer( + $db: db, + $table: table, + ), + createComputedFieldComposer: () => + $$LastOpenedTimelinesTableAnnotationComposer( + $db: db, + $table: table, + ), + updateCompanionCallback: + ({ + Value projectId = const Value.absent(), + Value timelineId = const Value.absent(), + Value rowid = const Value.absent(), + }) => LastOpenedTimelinesCompanion( + projectId: projectId, + timelineId: timelineId, + rowid: rowid, + ), + createCompanionCallback: + ({ + required String projectId, + required String timelineId, + Value rowid = const Value.absent(), + }) => LastOpenedTimelinesCompanion.insert( + projectId: projectId, + timelineId: timelineId, + rowid: rowid, + ), + withReferenceMapper: (p0) => p0 + .map( + (e) => ( + e.readTable<$LastOpenedTimelinesTable, LastOpenedTimeline>( + table, + ), + BaseReferences< + _$AppDatabase, + $LastOpenedTimelinesTable, + LastOpenedTimeline + >(db, table, e), + ), + ) + .toList(), + prefetchHooksCallback: null, + ), + ); +} + +typedef $$LastOpenedTimelinesTableProcessedTableManager = + ProcessedTableManager< + _$AppDatabase, + $LastOpenedTimelinesTable, + LastOpenedTimeline, + $$LastOpenedTimelinesTableFilterComposer, + $$LastOpenedTimelinesTableOrderingComposer, + $$LastOpenedTimelinesTableAnnotationComposer, + $$LastOpenedTimelinesTableCreateCompanionBuilder, + $$LastOpenedTimelinesTableUpdateCompanionBuilder, + ( + LastOpenedTimeline, + BaseReferences< + _$AppDatabase, + $LastOpenedTimelinesTable, + LastOpenedTimeline + >, + ), + LastOpenedTimeline, + PrefetchHooks Function() + >; +typedef $$McpConfigurationsTableCreateCompanionBuilder = + McpConfigurationsCompanion Function({ + Value id, + required bool enabled, + required int port, + required String token, + }); +typedef $$McpConfigurationsTableUpdateCompanionBuilder = + McpConfigurationsCompanion Function({ + Value id, + Value enabled, + Value port, + Value token, + }); + +class $$McpConfigurationsTableFilterComposer + extends Composer<_$AppDatabase, $McpConfigurationsTable> { + $$McpConfigurationsTableFilterComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + ColumnFilters get id => $composableBuilder( + column: $table.id, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get enabled => $composableBuilder( + column: $table.enabled, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get port => $composableBuilder( + column: $table.port, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get token => $composableBuilder( + column: $table.token, + builder: (column) => ColumnFilters(column), + ); +} + +class $$McpConfigurationsTableOrderingComposer + extends Composer<_$AppDatabase, $McpConfigurationsTable> { + $$McpConfigurationsTableOrderingComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + ColumnOrderings get id => $composableBuilder( + column: $table.id, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get enabled => $composableBuilder( + column: $table.enabled, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get port => $composableBuilder( + column: $table.port, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get token => $composableBuilder( + column: $table.token, + builder: (column) => ColumnOrderings(column), + ); +} + +class $$McpConfigurationsTableAnnotationComposer + extends Composer<_$AppDatabase, $McpConfigurationsTable> { + $$McpConfigurationsTableAnnotationComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + GeneratedColumn get id => + $composableBuilder(column: $table.id, builder: (column) => column); + + GeneratedColumn get enabled => + $composableBuilder(column: $table.enabled, builder: (column) => column); + + GeneratedColumn get port => + $composableBuilder(column: $table.port, builder: (column) => column); + + GeneratedColumn get token => + $composableBuilder(column: $table.token, builder: (column) => column); +} + +class $$McpConfigurationsTableTableManager + extends + RootTableManager< + _$AppDatabase, + $McpConfigurationsTable, + McpConfiguration, + $$McpConfigurationsTableFilterComposer, + $$McpConfigurationsTableOrderingComposer, + $$McpConfigurationsTableAnnotationComposer, + $$McpConfigurationsTableCreateCompanionBuilder, + $$McpConfigurationsTableUpdateCompanionBuilder, + ( + McpConfiguration, + BaseReferences< + _$AppDatabase, + $McpConfigurationsTable, + McpConfiguration + >, + ), + McpConfiguration, + PrefetchHooks Function() + > { + $$McpConfigurationsTableTableManager( + _$AppDatabase db, + $McpConfigurationsTable table, + ) : super( + TableManagerState( + db: db, + table: table, + createFilteringComposer: () => + $$McpConfigurationsTableFilterComposer($db: db, $table: table), + createOrderingComposer: () => + $$McpConfigurationsTableOrderingComposer($db: db, $table: table), + createComputedFieldComposer: () => + $$McpConfigurationsTableAnnotationComposer( + $db: db, + $table: table, + ), + updateCompanionCallback: + ({ + Value id = const Value.absent(), + Value enabled = const Value.absent(), + Value port = const Value.absent(), + Value token = const Value.absent(), + }) => McpConfigurationsCompanion( + id: id, + enabled: enabled, + port: port, + token: token, + ), + createCompanionCallback: + ({ + Value id = const Value.absent(), + required bool enabled, + required int port, + required String token, + }) => McpConfigurationsCompanion.insert( + id: id, + enabled: enabled, + port: port, + token: token, + ), + withReferenceMapper: (p0) => p0 + .map( + (e) => ( + e.readTable<$McpConfigurationsTable, McpConfiguration>(table), + BaseReferences< + _$AppDatabase, + $McpConfigurationsTable, + McpConfiguration + >(db, table, e), + ), + ) + .toList(), + prefetchHooksCallback: null, + ), + ); +} + +typedef $$McpConfigurationsTableProcessedTableManager = + ProcessedTableManager< + _$AppDatabase, + $McpConfigurationsTable, + McpConfiguration, + $$McpConfigurationsTableFilterComposer, + $$McpConfigurationsTableOrderingComposer, + $$McpConfigurationsTableAnnotationComposer, + $$McpConfigurationsTableCreateCompanionBuilder, + $$McpConfigurationsTableUpdateCompanionBuilder, + ( + McpConfiguration, + BaseReferences< + _$AppDatabase, + $McpConfigurationsTable, + McpConfiguration + >, + ), + McpConfiguration, + PrefetchHooks Function() + >; +typedef $$AppearanceConfigurationsTableCreateCompanionBuilder = + AppearanceConfigurationsCompanion Function({ + Value id, + required String themeMode, + }); +typedef $$AppearanceConfigurationsTableUpdateCompanionBuilder = + AppearanceConfigurationsCompanion Function({ + Value id, + Value themeMode, + }); + +class $$AppearanceConfigurationsTableFilterComposer + extends Composer<_$AppDatabase, $AppearanceConfigurationsTable> { + $$AppearanceConfigurationsTableFilterComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + ColumnFilters get id => $composableBuilder( + column: $table.id, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get themeMode => $composableBuilder( + column: $table.themeMode, + builder: (column) => ColumnFilters(column), + ); +} + +class $$AppearanceConfigurationsTableOrderingComposer + extends Composer<_$AppDatabase, $AppearanceConfigurationsTable> { + $$AppearanceConfigurationsTableOrderingComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + ColumnOrderings get id => $composableBuilder( + column: $table.id, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get themeMode => $composableBuilder( + column: $table.themeMode, + builder: (column) => ColumnOrderings(column), + ); +} + +class $$AppearanceConfigurationsTableAnnotationComposer + extends Composer<_$AppDatabase, $AppearanceConfigurationsTable> { + $$AppearanceConfigurationsTableAnnotationComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + GeneratedColumn get id => + $composableBuilder(column: $table.id, builder: (column) => column); + + GeneratedColumn get themeMode => + $composableBuilder(column: $table.themeMode, builder: (column) => column); +} + +class $$AppearanceConfigurationsTableTableManager + extends + RootTableManager< + _$AppDatabase, + $AppearanceConfigurationsTable, + AppearanceConfiguration, + $$AppearanceConfigurationsTableFilterComposer, + $$AppearanceConfigurationsTableOrderingComposer, + $$AppearanceConfigurationsTableAnnotationComposer, + $$AppearanceConfigurationsTableCreateCompanionBuilder, + $$AppearanceConfigurationsTableUpdateCompanionBuilder, + ( + AppearanceConfiguration, + BaseReferences< + _$AppDatabase, + $AppearanceConfigurationsTable, + AppearanceConfiguration + >, + ), + AppearanceConfiguration, + PrefetchHooks Function() + > { + $$AppearanceConfigurationsTableTableManager( + _$AppDatabase db, + $AppearanceConfigurationsTable table, + ) : super( + TableManagerState( + db: db, + table: table, + createFilteringComposer: () => + $$AppearanceConfigurationsTableFilterComposer( + $db: db, + $table: table, + ), + createOrderingComposer: () => + $$AppearanceConfigurationsTableOrderingComposer( + $db: db, + $table: table, + ), + createComputedFieldComposer: () => + $$AppearanceConfigurationsTableAnnotationComposer( + $db: db, + $table: table, + ), + updateCompanionCallback: ({ + Value id = const Value.absent(), + Value themeMode = const Value.absent(), + }) => AppearanceConfigurationsCompanion(id: id, themeMode: themeMode), + createCompanionCallback: + ({ + Value id = const Value.absent(), + required String themeMode, + }) => AppearanceConfigurationsCompanion.insert( + id: id, + themeMode: themeMode, + ), + withReferenceMapper: (p0) => p0 + .map( + (e) => ( + e.readTable< + $AppearanceConfigurationsTable, + AppearanceConfiguration + >(table), + BaseReferences< + _$AppDatabase, + $AppearanceConfigurationsTable, + AppearanceConfiguration + >(db, table, e), + ), + ) + .toList(), + prefetchHooksCallback: null, + ), + ); +} + +typedef $$AppearanceConfigurationsTableProcessedTableManager = + ProcessedTableManager< + _$AppDatabase, + $AppearanceConfigurationsTable, + AppearanceConfiguration, + $$AppearanceConfigurationsTableFilterComposer, + $$AppearanceConfigurationsTableOrderingComposer, + $$AppearanceConfigurationsTableAnnotationComposer, + $$AppearanceConfigurationsTableCreateCompanionBuilder, + $$AppearanceConfigurationsTableUpdateCompanionBuilder, + ( + AppearanceConfiguration, + BaseReferences< + _$AppDatabase, + $AppearanceConfigurationsTable, + AppearanceConfiguration + >, + ), + AppearanceConfiguration, + PrefetchHooks Function() + >; +typedef $$LanguageConfigurationsTableCreateCompanionBuilder = + LanguageConfigurationsCompanion Function({ + Value id, + required String language, + }); +typedef $$LanguageConfigurationsTableUpdateCompanionBuilder = + LanguageConfigurationsCompanion Function({ + Value id, + Value language, + }); + +class $$LanguageConfigurationsTableFilterComposer + extends Composer<_$AppDatabase, $LanguageConfigurationsTable> { + $$LanguageConfigurationsTableFilterComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + ColumnFilters get id => $composableBuilder( + column: $table.id, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get language => $composableBuilder( + column: $table.language, + builder: (column) => ColumnFilters(column), + ); +} + +class $$LanguageConfigurationsTableOrderingComposer + extends Composer<_$AppDatabase, $LanguageConfigurationsTable> { + $$LanguageConfigurationsTableOrderingComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + ColumnOrderings get id => $composableBuilder( + column: $table.id, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get language => $composableBuilder( + column: $table.language, + builder: (column) => ColumnOrderings(column), + ); +} + +class $$LanguageConfigurationsTableAnnotationComposer + extends Composer<_$AppDatabase, $LanguageConfigurationsTable> { + $$LanguageConfigurationsTableAnnotationComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + GeneratedColumn get id => + $composableBuilder(column: $table.id, builder: (column) => column); + + GeneratedColumn get language => + $composableBuilder(column: $table.language, builder: (column) => column); +} + +class $$LanguageConfigurationsTableTableManager + extends + RootTableManager< + _$AppDatabase, + $LanguageConfigurationsTable, + LanguageConfiguration, + $$LanguageConfigurationsTableFilterComposer, + $$LanguageConfigurationsTableOrderingComposer, + $$LanguageConfigurationsTableAnnotationComposer, + $$LanguageConfigurationsTableCreateCompanionBuilder, + $$LanguageConfigurationsTableUpdateCompanionBuilder, + ( + LanguageConfiguration, + BaseReferences< + _$AppDatabase, + $LanguageConfigurationsTable, + LanguageConfiguration + >, + ), + LanguageConfiguration, + PrefetchHooks Function() + > { + $$LanguageConfigurationsTableTableManager( + _$AppDatabase db, + $LanguageConfigurationsTable table, + ) : super( + TableManagerState( + db: db, + table: table, + createFilteringComposer: () => + $$LanguageConfigurationsTableFilterComposer( + $db: db, + $table: table, + ), + createOrderingComposer: () => + $$LanguageConfigurationsTableOrderingComposer( + $db: db, + $table: table, + ), + createComputedFieldComposer: () => + $$LanguageConfigurationsTableAnnotationComposer( + $db: db, + $table: table, + ), + updateCompanionCallback: ({ + Value id = const Value.absent(), + Value language = const Value.absent(), + }) => LanguageConfigurationsCompanion(id: id, language: language), + createCompanionCallback: + ({ + Value id = const Value.absent(), + required String language, + }) => LanguageConfigurationsCompanion.insert( + id: id, + language: language, + ), + withReferenceMapper: (p0) => p0 + .map( + (e) => ( + e.readTable< + $LanguageConfigurationsTable, + LanguageConfiguration + >(table), + BaseReferences< + _$AppDatabase, + $LanguageConfigurationsTable, + LanguageConfiguration + >(db, table, e), + ), + ) + .toList(), + prefetchHooksCallback: null, + ), + ); +} + +typedef $$LanguageConfigurationsTableProcessedTableManager = + ProcessedTableManager< + _$AppDatabase, + $LanguageConfigurationsTable, + LanguageConfiguration, + $$LanguageConfigurationsTableFilterComposer, + $$LanguageConfigurationsTableOrderingComposer, + $$LanguageConfigurationsTableAnnotationComposer, + $$LanguageConfigurationsTableCreateCompanionBuilder, + $$LanguageConfigurationsTableUpdateCompanionBuilder, + ( + LanguageConfiguration, + BaseReferences< + _$AppDatabase, + $LanguageConfigurationsTable, + LanguageConfiguration + >, + ), + LanguageConfiguration, + PrefetchHooks Function() + >; +typedef $$ConversationLocationConfigurationsTableCreateCompanionBuilder = + ConversationLocationConfigurationsCompanion Function({ + Value id, + required String directory, + }); +typedef $$ConversationLocationConfigurationsTableUpdateCompanionBuilder = + ConversationLocationConfigurationsCompanion Function({ + Value id, + Value directory, + }); + +class $$ConversationLocationConfigurationsTableFilterComposer + extends Composer<_$AppDatabase, $ConversationLocationConfigurationsTable> { + $$ConversationLocationConfigurationsTableFilterComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + ColumnFilters get id => $composableBuilder( + column: $table.id, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get directory => $composableBuilder( + column: $table.directory, + builder: (column) => ColumnFilters(column), + ); +} + +class $$ConversationLocationConfigurationsTableOrderingComposer + extends Composer<_$AppDatabase, $ConversationLocationConfigurationsTable> { + $$ConversationLocationConfigurationsTableOrderingComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + ColumnOrderings get id => $composableBuilder( + column: $table.id, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get directory => $composableBuilder( + column: $table.directory, + builder: (column) => ColumnOrderings(column), + ); +} + +class $$ConversationLocationConfigurationsTableAnnotationComposer + extends Composer<_$AppDatabase, $ConversationLocationConfigurationsTable> { + $$ConversationLocationConfigurationsTableAnnotationComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + GeneratedColumn get id => + $composableBuilder(column: $table.id, builder: (column) => column); + + GeneratedColumn get directory => + $composableBuilder(column: $table.directory, builder: (column) => column); +} + +class $$ConversationLocationConfigurationsTableTableManager + extends + RootTableManager< + _$AppDatabase, + $ConversationLocationConfigurationsTable, + ConversationLocationConfiguration, + $$ConversationLocationConfigurationsTableFilterComposer, + $$ConversationLocationConfigurationsTableOrderingComposer, + $$ConversationLocationConfigurationsTableAnnotationComposer, + $$ConversationLocationConfigurationsTableCreateCompanionBuilder, + $$ConversationLocationConfigurationsTableUpdateCompanionBuilder, + ( + ConversationLocationConfiguration, + BaseReferences< + _$AppDatabase, + $ConversationLocationConfigurationsTable, + ConversationLocationConfiguration + >, + ), + ConversationLocationConfiguration, + PrefetchHooks Function() + > { + $$ConversationLocationConfigurationsTableTableManager( + _$AppDatabase db, + $ConversationLocationConfigurationsTable table, + ) : super( + TableManagerState( + db: db, + table: table, + createFilteringComposer: () => + $$ConversationLocationConfigurationsTableFilterComposer( + $db: db, + $table: table, + ), + createOrderingComposer: () => + $$ConversationLocationConfigurationsTableOrderingComposer( + $db: db, + $table: table, + ), + createComputedFieldComposer: () => + $$ConversationLocationConfigurationsTableAnnotationComposer( + $db: db, + $table: table, + ), + updateCompanionCallback: + ({ + Value id = const Value.absent(), + Value directory = const Value.absent(), + }) => ConversationLocationConfigurationsCompanion( + id: id, + directory: directory, + ), + createCompanionCallback: + ({ + Value id = const Value.absent(), + required String directory, + }) => ConversationLocationConfigurationsCompanion.insert( + id: id, + directory: directory, + ), + withReferenceMapper: (p0) => p0 + .map( + (e) => ( + e.readTable< + $ConversationLocationConfigurationsTable, + ConversationLocationConfiguration + >(table), + BaseReferences< + _$AppDatabase, + $ConversationLocationConfigurationsTable, + ConversationLocationConfiguration + >(db, table, e), + ), + ) + .toList(), + prefetchHooksCallback: null, + ), + ); +} + +typedef $$ConversationLocationConfigurationsTableProcessedTableManager = + ProcessedTableManager< + _$AppDatabase, + $ConversationLocationConfigurationsTable, + ConversationLocationConfiguration, + $$ConversationLocationConfigurationsTableFilterComposer, + $$ConversationLocationConfigurationsTableOrderingComposer, + $$ConversationLocationConfigurationsTableAnnotationComposer, + $$ConversationLocationConfigurationsTableCreateCompanionBuilder, + $$ConversationLocationConfigurationsTableUpdateCompanionBuilder, + ( + ConversationLocationConfiguration, + BaseReferences< + _$AppDatabase, + $ConversationLocationConfigurationsTable, + ConversationLocationConfiguration + >, + ), + ConversationLocationConfiguration, + PrefetchHooks Function() + >; +typedef $$ProjectLocationConfigurationsTableCreateCompanionBuilder = + ProjectLocationConfigurationsCompanion Function({ + Value id, + required String directory, + }); +typedef $$ProjectLocationConfigurationsTableUpdateCompanionBuilder = + ProjectLocationConfigurationsCompanion Function({ + Value id, + Value directory, + }); + +class $$ProjectLocationConfigurationsTableFilterComposer + extends Composer<_$AppDatabase, $ProjectLocationConfigurationsTable> { + $$ProjectLocationConfigurationsTableFilterComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + ColumnFilters get id => $composableBuilder( + column: $table.id, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get directory => $composableBuilder( + column: $table.directory, + builder: (column) => ColumnFilters(column), + ); +} + +class $$ProjectLocationConfigurationsTableOrderingComposer + extends Composer<_$AppDatabase, $ProjectLocationConfigurationsTable> { + $$ProjectLocationConfigurationsTableOrderingComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + ColumnOrderings get id => $composableBuilder( + column: $table.id, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get directory => $composableBuilder( + column: $table.directory, + builder: (column) => ColumnOrderings(column), + ); +} + +class $$ProjectLocationConfigurationsTableAnnotationComposer + extends Composer<_$AppDatabase, $ProjectLocationConfigurationsTable> { + $$ProjectLocationConfigurationsTableAnnotationComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + GeneratedColumn get id => + $composableBuilder(column: $table.id, builder: (column) => column); + + GeneratedColumn get directory => + $composableBuilder(column: $table.directory, builder: (column) => column); +} + +class $$ProjectLocationConfigurationsTableTableManager + extends + RootTableManager< + _$AppDatabase, + $ProjectLocationConfigurationsTable, + ProjectLocationConfiguration, + $$ProjectLocationConfigurationsTableFilterComposer, + $$ProjectLocationConfigurationsTableOrderingComposer, + $$ProjectLocationConfigurationsTableAnnotationComposer, + $$ProjectLocationConfigurationsTableCreateCompanionBuilder, + $$ProjectLocationConfigurationsTableUpdateCompanionBuilder, + ( + ProjectLocationConfiguration, + BaseReferences< + _$AppDatabase, + $ProjectLocationConfigurationsTable, + ProjectLocationConfiguration + >, + ), + ProjectLocationConfiguration, + PrefetchHooks Function() + > { + $$ProjectLocationConfigurationsTableTableManager( + _$AppDatabase db, + $ProjectLocationConfigurationsTable table, + ) : super( + TableManagerState( + db: db, + table: table, + createFilteringComposer: () => + $$ProjectLocationConfigurationsTableFilterComposer( + $db: db, + $table: table, + ), + createOrderingComposer: () => + $$ProjectLocationConfigurationsTableOrderingComposer( + $db: db, + $table: table, + ), + createComputedFieldComposer: () => + $$ProjectLocationConfigurationsTableAnnotationComposer( + $db: db, + $table: table, + ), + updateCompanionCallback: + ({ + Value id = const Value.absent(), + Value directory = const Value.absent(), + }) => ProjectLocationConfigurationsCompanion( + id: id, + directory: directory, + ), + createCompanionCallback: + ({ + Value id = const Value.absent(), + required String directory, + }) => ProjectLocationConfigurationsCompanion.insert( + id: id, + directory: directory, + ), + withReferenceMapper: (p0) => p0 + .map( + (e) => ( + e.readTable< + $ProjectLocationConfigurationsTable, + ProjectLocationConfiguration + >(table), + BaseReferences< + _$AppDatabase, + $ProjectLocationConfigurationsTable, + ProjectLocationConfiguration + >(db, table, e), + ), + ) + .toList(), + prefetchHooksCallback: null, + ), + ); +} + +typedef $$ProjectLocationConfigurationsTableProcessedTableManager = + ProcessedTableManager< + _$AppDatabase, + $ProjectLocationConfigurationsTable, + ProjectLocationConfiguration, + $$ProjectLocationConfigurationsTableFilterComposer, + $$ProjectLocationConfigurationsTableOrderingComposer, + $$ProjectLocationConfigurationsTableAnnotationComposer, + $$ProjectLocationConfigurationsTableCreateCompanionBuilder, + $$ProjectLocationConfigurationsTableUpdateCompanionBuilder, + ( + ProjectLocationConfiguration, + BaseReferences< + _$AppDatabase, + $ProjectLocationConfigurationsTable, + ProjectLocationConfiguration + >, + ), + ProjectLocationConfiguration, + PrefetchHooks Function() + >; +typedef $$ResourceLocationConfigurationsTableCreateCompanionBuilder = + ResourceLocationConfigurationsCompanion Function({ + Value id, + required String directory, + }); +typedef $$ResourceLocationConfigurationsTableUpdateCompanionBuilder = + ResourceLocationConfigurationsCompanion Function({ + Value id, + Value directory, + }); + +class $$ResourceLocationConfigurationsTableFilterComposer + extends Composer<_$AppDatabase, $ResourceLocationConfigurationsTable> { + $$ResourceLocationConfigurationsTableFilterComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + ColumnFilters get id => $composableBuilder( + column: $table.id, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get directory => $composableBuilder( + column: $table.directory, + builder: (column) => ColumnFilters(column), + ); +} + +class $$ResourceLocationConfigurationsTableOrderingComposer + extends Composer<_$AppDatabase, $ResourceLocationConfigurationsTable> { + $$ResourceLocationConfigurationsTableOrderingComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + ColumnOrderings get id => $composableBuilder( + column: $table.id, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get directory => $composableBuilder( + column: $table.directory, + builder: (column) => ColumnOrderings(column), + ); +} + +class $$ResourceLocationConfigurationsTableAnnotationComposer + extends Composer<_$AppDatabase, $ResourceLocationConfigurationsTable> { + $$ResourceLocationConfigurationsTableAnnotationComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + GeneratedColumn get id => + $composableBuilder(column: $table.id, builder: (column) => column); + + GeneratedColumn get directory => + $composableBuilder(column: $table.directory, builder: (column) => column); +} + +class $$ResourceLocationConfigurationsTableTableManager + extends + RootTableManager< + _$AppDatabase, + $ResourceLocationConfigurationsTable, + ResourceLocationConfiguration, + $$ResourceLocationConfigurationsTableFilterComposer, + $$ResourceLocationConfigurationsTableOrderingComposer, + $$ResourceLocationConfigurationsTableAnnotationComposer, + $$ResourceLocationConfigurationsTableCreateCompanionBuilder, + $$ResourceLocationConfigurationsTableUpdateCompanionBuilder, + ( + ResourceLocationConfiguration, + BaseReferences< + _$AppDatabase, + $ResourceLocationConfigurationsTable, + ResourceLocationConfiguration + >, + ), + ResourceLocationConfiguration, + PrefetchHooks Function() + > { + $$ResourceLocationConfigurationsTableTableManager( + _$AppDatabase db, + $ResourceLocationConfigurationsTable table, + ) : super( + TableManagerState( + db: db, + table: table, + createFilteringComposer: () => + $$ResourceLocationConfigurationsTableFilterComposer( + $db: db, + $table: table, + ), + createOrderingComposer: () => + $$ResourceLocationConfigurationsTableOrderingComposer( + $db: db, + $table: table, + ), + createComputedFieldComposer: () => + $$ResourceLocationConfigurationsTableAnnotationComposer( + $db: db, + $table: table, + ), + updateCompanionCallback: + ({ + Value id = const Value.absent(), + Value directory = const Value.absent(), + }) => ResourceLocationConfigurationsCompanion( + id: id, + directory: directory, + ), + createCompanionCallback: + ({ + Value id = const Value.absent(), + required String directory, + }) => ResourceLocationConfigurationsCompanion.insert( + id: id, + directory: directory, + ), + withReferenceMapper: (p0) => p0 + .map( + (e) => ( + e.readTable< + $ResourceLocationConfigurationsTable, + ResourceLocationConfiguration + >(table), + BaseReferences< + _$AppDatabase, + $ResourceLocationConfigurationsTable, + ResourceLocationConfiguration + >(db, table, e), + ), + ) + .toList(), + prefetchHooksCallback: null, + ), + ); +} + +typedef $$ResourceLocationConfigurationsTableProcessedTableManager = + ProcessedTableManager< + _$AppDatabase, + $ResourceLocationConfigurationsTable, + ResourceLocationConfiguration, + $$ResourceLocationConfigurationsTableFilterComposer, + $$ResourceLocationConfigurationsTableOrderingComposer, + $$ResourceLocationConfigurationsTableAnnotationComposer, + $$ResourceLocationConfigurationsTableCreateCompanionBuilder, + $$ResourceLocationConfigurationsTableUpdateCompanionBuilder, + ( + ResourceLocationConfiguration, + BaseReferences< + _$AppDatabase, + $ResourceLocationConfigurationsTable, + ResourceLocationConfiguration + >, + ), + ResourceLocationConfiguration, + PrefetchHooks Function() + >; +typedef $$AgentConfigurationsTableCreateCompanionBuilder = + AgentConfigurationsCompanion Function({ + Value id, + required bool enabled, + Value selectedProviderId, + Value selectedModelId, + required int revision, + }); +typedef $$AgentConfigurationsTableUpdateCompanionBuilder = + AgentConfigurationsCompanion Function({ + Value id, + Value enabled, + Value selectedProviderId, + Value selectedModelId, + Value revision, + }); + +class $$AgentConfigurationsTableFilterComposer + extends Composer<_$AppDatabase, $AgentConfigurationsTable> { + $$AgentConfigurationsTableFilterComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + ColumnFilters get id => $composableBuilder( + column: $table.id, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get enabled => $composableBuilder( + column: $table.enabled, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get selectedProviderId => $composableBuilder( + column: $table.selectedProviderId, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get selectedModelId => $composableBuilder( + column: $table.selectedModelId, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get revision => $composableBuilder( + column: $table.revision, + builder: (column) => ColumnFilters(column), + ); +} + +class $$AgentConfigurationsTableOrderingComposer + extends Composer<_$AppDatabase, $AgentConfigurationsTable> { + $$AgentConfigurationsTableOrderingComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + ColumnOrderings get id => $composableBuilder( + column: $table.id, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get enabled => $composableBuilder( + column: $table.enabled, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get selectedProviderId => $composableBuilder( + column: $table.selectedProviderId, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get selectedModelId => $composableBuilder( + column: $table.selectedModelId, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get revision => $composableBuilder( + column: $table.revision, + builder: (column) => ColumnOrderings(column), + ); +} + +class $$AgentConfigurationsTableAnnotationComposer + extends Composer<_$AppDatabase, $AgentConfigurationsTable> { + $$AgentConfigurationsTableAnnotationComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + GeneratedColumn get id => + $composableBuilder(column: $table.id, builder: (column) => column); + + GeneratedColumn get enabled => + $composableBuilder(column: $table.enabled, builder: (column) => column); + + GeneratedColumn get selectedProviderId => $composableBuilder( + column: $table.selectedProviderId, + builder: (column) => column, + ); + + GeneratedColumn get selectedModelId => $composableBuilder( + column: $table.selectedModelId, + builder: (column) => column, + ); + + GeneratedColumn get revision => + $composableBuilder(column: $table.revision, builder: (column) => column); +} + +class $$AgentConfigurationsTableTableManager + extends + RootTableManager< + _$AppDatabase, + $AgentConfigurationsTable, + AgentConfiguration, + $$AgentConfigurationsTableFilterComposer, + $$AgentConfigurationsTableOrderingComposer, + $$AgentConfigurationsTableAnnotationComposer, + $$AgentConfigurationsTableCreateCompanionBuilder, + $$AgentConfigurationsTableUpdateCompanionBuilder, + ( + AgentConfiguration, + BaseReferences< + _$AppDatabase, + $AgentConfigurationsTable, + AgentConfiguration + >, + ), + AgentConfiguration, + PrefetchHooks Function() + > { + $$AgentConfigurationsTableTableManager( + _$AppDatabase db, + $AgentConfigurationsTable table, + ) : super( + TableManagerState( + db: db, + table: table, + createFilteringComposer: () => + $$AgentConfigurationsTableFilterComposer($db: db, $table: table), + createOrderingComposer: () => + $$AgentConfigurationsTableOrderingComposer( + $db: db, + $table: table, + ), + createComputedFieldComposer: () => + $$AgentConfigurationsTableAnnotationComposer( + $db: db, + $table: table, + ), + updateCompanionCallback: + ({ + Value id = const Value.absent(), + Value enabled = const Value.absent(), + Value selectedProviderId = const Value.absent(), + Value selectedModelId = const Value.absent(), + Value revision = const Value.absent(), + }) => AgentConfigurationsCompanion( + id: id, + enabled: enabled, + selectedProviderId: selectedProviderId, + selectedModelId: selectedModelId, + revision: revision, + ), + createCompanionCallback: + ({ + Value id = const Value.absent(), + required bool enabled, + Value selectedProviderId = const Value.absent(), + Value selectedModelId = const Value.absent(), + required int revision, + }) => AgentConfigurationsCompanion.insert( + id: id, + enabled: enabled, + selectedProviderId: selectedProviderId, + selectedModelId: selectedModelId, + revision: revision, + ), + withReferenceMapper: (p0) => p0 + .map( + (e) => ( + e.readTable<$AgentConfigurationsTable, AgentConfiguration>( + table, + ), + BaseReferences< + _$AppDatabase, + $AgentConfigurationsTable, + AgentConfiguration + >(db, table, e), + ), + ) + .toList(), + prefetchHooksCallback: null, + ), + ); +} + +typedef $$AgentConfigurationsTableProcessedTableManager = + ProcessedTableManager< + _$AppDatabase, + $AgentConfigurationsTable, + AgentConfiguration, + $$AgentConfigurationsTableFilterComposer, + $$AgentConfigurationsTableOrderingComposer, + $$AgentConfigurationsTableAnnotationComposer, + $$AgentConfigurationsTableCreateCompanionBuilder, + $$AgentConfigurationsTableUpdateCompanionBuilder, + ( + AgentConfiguration, + BaseReferences< + _$AppDatabase, + $AgentConfigurationsTable, + AgentConfiguration + >, + ), + AgentConfiguration, + PrefetchHooks Function() + >; +typedef $$AgentProvidersTableCreateCompanionBuilder = + AgentProvidersCompanion Function({ + Value enabled, + required String id, + required String name, + required String apiType, + required String baseUrl, + Value credentialId, + Value rowid, + }); +typedef $$AgentProvidersTableUpdateCompanionBuilder = + AgentProvidersCompanion Function({ + Value enabled, + Value id, + Value name, + Value apiType, + Value baseUrl, + Value credentialId, + Value rowid, + }); + +class $$AgentProvidersTableFilterComposer + extends Composer<_$AppDatabase, $AgentProvidersTable> { + $$AgentProvidersTableFilterComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + ColumnFilters get enabled => $composableBuilder( + column: $table.enabled, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get id => $composableBuilder( + column: $table.id, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get name => $composableBuilder( + column: $table.name, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get apiType => $composableBuilder( + column: $table.apiType, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get baseUrl => $composableBuilder( + column: $table.baseUrl, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get credentialId => $composableBuilder( + column: $table.credentialId, + builder: (column) => ColumnFilters(column), + ); +} + +class $$AgentProvidersTableOrderingComposer + extends Composer<_$AppDatabase, $AgentProvidersTable> { + $$AgentProvidersTableOrderingComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + ColumnOrderings get enabled => $composableBuilder( + column: $table.enabled, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get id => $composableBuilder( + column: $table.id, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get name => $composableBuilder( + column: $table.name, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get apiType => $composableBuilder( + column: $table.apiType, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get baseUrl => $composableBuilder( + column: $table.baseUrl, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get credentialId => $composableBuilder( + column: $table.credentialId, + builder: (column) => ColumnOrderings(column), + ); +} + +class $$AgentProvidersTableAnnotationComposer + extends Composer<_$AppDatabase, $AgentProvidersTable> { + $$AgentProvidersTableAnnotationComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + GeneratedColumn get enabled => + $composableBuilder(column: $table.enabled, builder: (column) => column); + + GeneratedColumn get id => + $composableBuilder(column: $table.id, builder: (column) => column); + + GeneratedColumn get name => + $composableBuilder(column: $table.name, builder: (column) => column); + + GeneratedColumn get apiType => + $composableBuilder(column: $table.apiType, builder: (column) => column); + + GeneratedColumn get baseUrl => + $composableBuilder(column: $table.baseUrl, builder: (column) => column); + + GeneratedColumn get credentialId => $composableBuilder( + column: $table.credentialId, + builder: (column) => column, + ); +} + +class $$AgentProvidersTableTableManager + extends + RootTableManager< + _$AppDatabase, + $AgentProvidersTable, + AgentProvider, + $$AgentProvidersTableFilterComposer, + $$AgentProvidersTableOrderingComposer, + $$AgentProvidersTableAnnotationComposer, + $$AgentProvidersTableCreateCompanionBuilder, + $$AgentProvidersTableUpdateCompanionBuilder, + ( + AgentProvider, + BaseReferences<_$AppDatabase, $AgentProvidersTable, AgentProvider>, + ), + AgentProvider, + PrefetchHooks Function() + > { + $$AgentProvidersTableTableManager( + _$AppDatabase db, + $AgentProvidersTable table, + ) : super( + TableManagerState( + db: db, + table: table, + createFilteringComposer: () => + $$AgentProvidersTableFilterComposer($db: db, $table: table), + createOrderingComposer: () => + $$AgentProvidersTableOrderingComposer($db: db, $table: table), + createComputedFieldComposer: () => + $$AgentProvidersTableAnnotationComposer($db: db, $table: table), + updateCompanionCallback: + ({ + Value enabled = const Value.absent(), + Value id = const Value.absent(), + Value name = const Value.absent(), + Value apiType = const Value.absent(), + Value baseUrl = const Value.absent(), + Value credentialId = const Value.absent(), + Value rowid = const Value.absent(), + }) => AgentProvidersCompanion( + enabled: enabled, + id: id, + name: name, + apiType: apiType, + baseUrl: baseUrl, + credentialId: credentialId, + rowid: rowid, + ), + createCompanionCallback: + ({ + Value enabled = const Value.absent(), + required String id, + required String name, + required String apiType, + required String baseUrl, + Value credentialId = const Value.absent(), + Value rowid = const Value.absent(), + }) => AgentProvidersCompanion.insert( + enabled: enabled, + id: id, + name: name, + apiType: apiType, + baseUrl: baseUrl, + credentialId: credentialId, + rowid: rowid, + ), + withReferenceMapper: (p0) => p0 + .map( + (e) => ( + e.readTable<$AgentProvidersTable, AgentProvider>(table), + BaseReferences< + _$AppDatabase, + $AgentProvidersTable, + AgentProvider + >(db, table, e), + ), + ) + .toList(), + prefetchHooksCallback: null, + ), + ); +} + +typedef $$AgentProvidersTableProcessedTableManager = + ProcessedTableManager< + _$AppDatabase, + $AgentProvidersTable, + AgentProvider, + $$AgentProvidersTableFilterComposer, + $$AgentProvidersTableOrderingComposer, + $$AgentProvidersTableAnnotationComposer, + $$AgentProvidersTableCreateCompanionBuilder, + $$AgentProvidersTableUpdateCompanionBuilder, + ( + AgentProvider, + BaseReferences<_$AppDatabase, $AgentProvidersTable, AgentProvider>, + ), + AgentProvider, + PrefetchHooks Function() + >; +typedef $$AgentModelsTableCreateCompanionBuilder = + AgentModelsCompanion Function({ + required String providerId, + required String modelId, + Value contextWindow, + Value maxOutputTokens, + Value rowid, + }); +typedef $$AgentModelsTableUpdateCompanionBuilder = + AgentModelsCompanion Function({ + Value providerId, + Value modelId, + Value contextWindow, + Value maxOutputTokens, + Value rowid, + }); + +class $$AgentModelsTableFilterComposer + extends Composer<_$AppDatabase, $AgentModelsTable> { + $$AgentModelsTableFilterComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + ColumnFilters get providerId => $composableBuilder( + column: $table.providerId, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get modelId => $composableBuilder( + column: $table.modelId, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get contextWindow => $composableBuilder( + column: $table.contextWindow, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get maxOutputTokens => $composableBuilder( + column: $table.maxOutputTokens, + builder: (column) => ColumnFilters(column), + ); +} + +class $$AgentModelsTableOrderingComposer + extends Composer<_$AppDatabase, $AgentModelsTable> { + $$AgentModelsTableOrderingComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + ColumnOrderings get providerId => $composableBuilder( + column: $table.providerId, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get modelId => $composableBuilder( + column: $table.modelId, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get contextWindow => $composableBuilder( + column: $table.contextWindow, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get maxOutputTokens => $composableBuilder( + column: $table.maxOutputTokens, + builder: (column) => ColumnOrderings(column), + ); +} + +class $$AgentModelsTableAnnotationComposer + extends Composer<_$AppDatabase, $AgentModelsTable> { + $$AgentModelsTableAnnotationComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + GeneratedColumn get providerId => $composableBuilder( + column: $table.providerId, + builder: (column) => column, + ); + + GeneratedColumn get modelId => + $composableBuilder(column: $table.modelId, builder: (column) => column); + + GeneratedColumn get contextWindow => $composableBuilder( + column: $table.contextWindow, + builder: (column) => column, + ); + + GeneratedColumn get maxOutputTokens => $composableBuilder( + column: $table.maxOutputTokens, + builder: (column) => column, + ); +} + +class $$AgentModelsTableTableManager + extends + RootTableManager< + _$AppDatabase, + $AgentModelsTable, + AgentModel, + $$AgentModelsTableFilterComposer, + $$AgentModelsTableOrderingComposer, + $$AgentModelsTableAnnotationComposer, + $$AgentModelsTableCreateCompanionBuilder, + $$AgentModelsTableUpdateCompanionBuilder, + ( + AgentModel, + BaseReferences<_$AppDatabase, $AgentModelsTable, AgentModel>, + ), + AgentModel, + PrefetchHooks Function() + > { + $$AgentModelsTableTableManager(_$AppDatabase db, $AgentModelsTable table) + : super( + TableManagerState( + db: db, + table: table, + createFilteringComposer: () => + $$AgentModelsTableFilterComposer($db: db, $table: table), + createOrderingComposer: () => + $$AgentModelsTableOrderingComposer($db: db, $table: table), + createComputedFieldComposer: () => + $$AgentModelsTableAnnotationComposer($db: db, $table: table), + updateCompanionCallback: + ({ + Value providerId = const Value.absent(), + Value modelId = const Value.absent(), + Value contextWindow = const Value.absent(), + Value maxOutputTokens = const Value.absent(), + Value rowid = const Value.absent(), + }) => AgentModelsCompanion( + providerId: providerId, + modelId: modelId, + contextWindow: contextWindow, + maxOutputTokens: maxOutputTokens, + rowid: rowid, + ), + createCompanionCallback: + ({ + required String providerId, + required String modelId, + Value contextWindow = const Value.absent(), + Value maxOutputTokens = const Value.absent(), + Value rowid = const Value.absent(), + }) => AgentModelsCompanion.insert( + providerId: providerId, + modelId: modelId, + contextWindow: contextWindow, + maxOutputTokens: maxOutputTokens, + rowid: rowid, + ), + withReferenceMapper: (p0) => p0 + .map( + (e) => ( + e.readTable<$AgentModelsTable, AgentModel>(table), + BaseReferences<_$AppDatabase, $AgentModelsTable, AgentModel>( + db, + table, + e, + ), + ), + ) + .toList(), + prefetchHooksCallback: null, + ), + ); +} + +typedef $$AgentModelsTableProcessedTableManager = + ProcessedTableManager< + _$AppDatabase, + $AgentModelsTable, + AgentModel, + $$AgentModelsTableFilterComposer, + $$AgentModelsTableOrderingComposer, + $$AgentModelsTableAnnotationComposer, + $$AgentModelsTableCreateCompanionBuilder, + $$AgentModelsTableUpdateCompanionBuilder, + ( + AgentModel, + BaseReferences<_$AppDatabase, $AgentModelsTable, AgentModel>, + ), + AgentModel, + PrefetchHooks Function() + >; +typedef $$WorkspaceViewConfigurationsTableCreateCompanionBuilder = + WorkspaceViewConfigurationsCompanion Function({ + Value mode, + Value id, + Value activeProjectId, + required bool sidebarCollapsed, + Value sidebarWidth, + }); +typedef $$WorkspaceViewConfigurationsTableUpdateCompanionBuilder = + WorkspaceViewConfigurationsCompanion Function({ + Value mode, + Value id, + Value activeProjectId, + Value sidebarCollapsed, + Value sidebarWidth, + }); + +class $$WorkspaceViewConfigurationsTableFilterComposer + extends Composer<_$AppDatabase, $WorkspaceViewConfigurationsTable> { + $$WorkspaceViewConfigurationsTableFilterComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + ColumnFilters get mode => $composableBuilder( + column: $table.mode, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get id => $composableBuilder( + column: $table.id, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get activeProjectId => $composableBuilder( + column: $table.activeProjectId, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get sidebarCollapsed => $composableBuilder( + column: $table.sidebarCollapsed, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get sidebarWidth => $composableBuilder( + column: $table.sidebarWidth, + builder: (column) => ColumnFilters(column), + ); +} + +class $$WorkspaceViewConfigurationsTableOrderingComposer + extends Composer<_$AppDatabase, $WorkspaceViewConfigurationsTable> { + $$WorkspaceViewConfigurationsTableOrderingComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + ColumnOrderings get mode => $composableBuilder( + column: $table.mode, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get id => $composableBuilder( + column: $table.id, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get activeProjectId => $composableBuilder( + column: $table.activeProjectId, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get sidebarCollapsed => $composableBuilder( + column: $table.sidebarCollapsed, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get sidebarWidth => $composableBuilder( + column: $table.sidebarWidth, + builder: (column) => ColumnOrderings(column), + ); +} + +class $$WorkspaceViewConfigurationsTableAnnotationComposer + extends Composer<_$AppDatabase, $WorkspaceViewConfigurationsTable> { + $$WorkspaceViewConfigurationsTableAnnotationComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + GeneratedColumn get mode => + $composableBuilder(column: $table.mode, builder: (column) => column); + + GeneratedColumn get id => + $composableBuilder(column: $table.id, builder: (column) => column); + + GeneratedColumn get activeProjectId => $composableBuilder( + column: $table.activeProjectId, + builder: (column) => column, + ); + + GeneratedColumn get sidebarCollapsed => $composableBuilder( + column: $table.sidebarCollapsed, + builder: (column) => column, + ); + + GeneratedColumn get sidebarWidth => $composableBuilder( + column: $table.sidebarWidth, + builder: (column) => column, + ); +} + +class $$WorkspaceViewConfigurationsTableTableManager + extends + RootTableManager< + _$AppDatabase, + $WorkspaceViewConfigurationsTable, + WorkspaceViewConfiguration, + $$WorkspaceViewConfigurationsTableFilterComposer, + $$WorkspaceViewConfigurationsTableOrderingComposer, + $$WorkspaceViewConfigurationsTableAnnotationComposer, + $$WorkspaceViewConfigurationsTableCreateCompanionBuilder, + $$WorkspaceViewConfigurationsTableUpdateCompanionBuilder, + ( + WorkspaceViewConfiguration, + BaseReferences< + _$AppDatabase, + $WorkspaceViewConfigurationsTable, + WorkspaceViewConfiguration + >, + ), + WorkspaceViewConfiguration, + PrefetchHooks Function() + > { + $$WorkspaceViewConfigurationsTableTableManager( + _$AppDatabase db, + $WorkspaceViewConfigurationsTable table, + ) : super( + TableManagerState( + db: db, + table: table, + createFilteringComposer: () => + $$WorkspaceViewConfigurationsTableFilterComposer( + $db: db, + $table: table, + ), + createOrderingComposer: () => + $$WorkspaceViewConfigurationsTableOrderingComposer( + $db: db, + $table: table, + ), + createComputedFieldComposer: () => + $$WorkspaceViewConfigurationsTableAnnotationComposer( + $db: db, + $table: table, + ), + updateCompanionCallback: + ({ + Value mode = const Value.absent(), + Value id = const Value.absent(), + Value activeProjectId = const Value.absent(), + Value sidebarCollapsed = const Value.absent(), + Value sidebarWidth = const Value.absent(), + }) => WorkspaceViewConfigurationsCompanion( + mode: mode, + id: id, + activeProjectId: activeProjectId, + sidebarCollapsed: sidebarCollapsed, + sidebarWidth: sidebarWidth, + ), + createCompanionCallback: + ({ + Value mode = const Value.absent(), + Value id = const Value.absent(), + Value activeProjectId = const Value.absent(), + required bool sidebarCollapsed, + Value sidebarWidth = const Value.absent(), + }) => WorkspaceViewConfigurationsCompanion.insert( + mode: mode, + id: id, + activeProjectId: activeProjectId, + sidebarCollapsed: sidebarCollapsed, + sidebarWidth: sidebarWidth, + ), + withReferenceMapper: (p0) => p0 + .map( + (e) => ( + e.readTable< + $WorkspaceViewConfigurationsTable, + WorkspaceViewConfiguration + >(table), + BaseReferences< + _$AppDatabase, + $WorkspaceViewConfigurationsTable, + WorkspaceViewConfiguration + >(db, table, e), + ), + ) + .toList(), + prefetchHooksCallback: null, + ), + ); +} + +typedef $$WorkspaceViewConfigurationsTableProcessedTableManager = + ProcessedTableManager< + _$AppDatabase, + $WorkspaceViewConfigurationsTable, + WorkspaceViewConfiguration, + $$WorkspaceViewConfigurationsTableFilterComposer, + $$WorkspaceViewConfigurationsTableOrderingComposer, + $$WorkspaceViewConfigurationsTableAnnotationComposer, + $$WorkspaceViewConfigurationsTableCreateCompanionBuilder, + $$WorkspaceViewConfigurationsTableUpdateCompanionBuilder, + ( + WorkspaceViewConfiguration, + BaseReferences< + _$AppDatabase, + $WorkspaceViewConfigurationsTable, + WorkspaceViewConfiguration + >, + ), + WorkspaceViewConfiguration, + PrefetchHooks Function() + >; +typedef $$ProjectViewConfigurationsTableCreateCompanionBuilder = + ProjectViewConfigurationsCompanion Function({ + required String projectId, + required bool propertiesOpen, + Value timelineHeight, + Value rowid, + }); +typedef $$ProjectViewConfigurationsTableUpdateCompanionBuilder = + ProjectViewConfigurationsCompanion Function({ + Value projectId, + Value propertiesOpen, + Value timelineHeight, + Value rowid, + }); + +class $$ProjectViewConfigurationsTableFilterComposer + extends Composer<_$AppDatabase, $ProjectViewConfigurationsTable> { + $$ProjectViewConfigurationsTableFilterComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + ColumnFilters get projectId => $composableBuilder( + column: $table.projectId, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get propertiesOpen => $composableBuilder( + column: $table.propertiesOpen, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get timelineHeight => $composableBuilder( + column: $table.timelineHeight, + builder: (column) => ColumnFilters(column), + ); +} + +class $$ProjectViewConfigurationsTableOrderingComposer + extends Composer<_$AppDatabase, $ProjectViewConfigurationsTable> { + $$ProjectViewConfigurationsTableOrderingComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + ColumnOrderings get projectId => $composableBuilder( + column: $table.projectId, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get propertiesOpen => $composableBuilder( + column: $table.propertiesOpen, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get timelineHeight => $composableBuilder( + column: $table.timelineHeight, + builder: (column) => ColumnOrderings(column), + ); +} + +class $$ProjectViewConfigurationsTableAnnotationComposer + extends Composer<_$AppDatabase, $ProjectViewConfigurationsTable> { + $$ProjectViewConfigurationsTableAnnotationComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + GeneratedColumn get projectId => + $composableBuilder(column: $table.projectId, builder: (column) => column); + + GeneratedColumn get propertiesOpen => $composableBuilder( + column: $table.propertiesOpen, + builder: (column) => column, + ); + + GeneratedColumn get timelineHeight => $composableBuilder( + column: $table.timelineHeight, + builder: (column) => column, + ); +} + +class $$ProjectViewConfigurationsTableTableManager + extends + RootTableManager< + _$AppDatabase, + $ProjectViewConfigurationsTable, + ProjectViewConfiguration, + $$ProjectViewConfigurationsTableFilterComposer, + $$ProjectViewConfigurationsTableOrderingComposer, + $$ProjectViewConfigurationsTableAnnotationComposer, + $$ProjectViewConfigurationsTableCreateCompanionBuilder, + $$ProjectViewConfigurationsTableUpdateCompanionBuilder, + ( + ProjectViewConfiguration, + BaseReferences< + _$AppDatabase, + $ProjectViewConfigurationsTable, + ProjectViewConfiguration + >, + ), + ProjectViewConfiguration, + PrefetchHooks Function() + > { + $$ProjectViewConfigurationsTableTableManager( + _$AppDatabase db, + $ProjectViewConfigurationsTable table, + ) : super( + TableManagerState( + db: db, + table: table, + createFilteringComposer: () => + $$ProjectViewConfigurationsTableFilterComposer( + $db: db, + $table: table, + ), + createOrderingComposer: () => + $$ProjectViewConfigurationsTableOrderingComposer( + $db: db, + $table: table, + ), + createComputedFieldComposer: () => + $$ProjectViewConfigurationsTableAnnotationComposer( + $db: db, + $table: table, + ), + updateCompanionCallback: + ({ + Value projectId = const Value.absent(), + Value propertiesOpen = const Value.absent(), + Value timelineHeight = const Value.absent(), + Value rowid = const Value.absent(), + }) => ProjectViewConfigurationsCompanion( + projectId: projectId, + propertiesOpen: propertiesOpen, + timelineHeight: timelineHeight, + rowid: rowid, + ), + createCompanionCallback: + ({ + required String projectId, + required bool propertiesOpen, + Value timelineHeight = const Value.absent(), + Value rowid = const Value.absent(), + }) => ProjectViewConfigurationsCompanion.insert( + projectId: projectId, + propertiesOpen: propertiesOpen, + timelineHeight: timelineHeight, + rowid: rowid, + ), + withReferenceMapper: (p0) => p0 + .map( + (e) => ( + e.readTable< + $ProjectViewConfigurationsTable, + ProjectViewConfiguration + >(table), + BaseReferences< + _$AppDatabase, + $ProjectViewConfigurationsTable, + ProjectViewConfiguration + >(db, table, e), + ), + ) + .toList(), + prefetchHooksCallback: null, + ), + ); +} + +typedef $$ProjectViewConfigurationsTableProcessedTableManager = + ProcessedTableManager< + _$AppDatabase, + $ProjectViewConfigurationsTable, + ProjectViewConfiguration, + $$ProjectViewConfigurationsTableFilterComposer, + $$ProjectViewConfigurationsTableOrderingComposer, + $$ProjectViewConfigurationsTableAnnotationComposer, + $$ProjectViewConfigurationsTableCreateCompanionBuilder, + $$ProjectViewConfigurationsTableUpdateCompanionBuilder, + ( + ProjectViewConfiguration, + BaseReferences< + _$AppDatabase, + $ProjectViewConfigurationsTable, + ProjectViewConfiguration + >, + ), + ProjectViewConfiguration, + PrefetchHooks Function() + >; +typedef $$TimelineViewConfigurationsTableCreateCompanionBuilder = + TimelineViewConfigurationsCompanion Function({ + required String projectId, + required String timelineId, + required String sequenceId, + required bool active, + required int playheadTick, + required int baseTick, + required double fractionalTick, + required double pixelsPerTick, + required double verticalOffset, + Value rowid, + }); +typedef $$TimelineViewConfigurationsTableUpdateCompanionBuilder = + TimelineViewConfigurationsCompanion Function({ + Value projectId, + Value timelineId, + Value sequenceId, + Value active, + Value playheadTick, + Value baseTick, + Value fractionalTick, + Value pixelsPerTick, + Value verticalOffset, + Value rowid, + }); + +class $$TimelineViewConfigurationsTableFilterComposer + extends Composer<_$AppDatabase, $TimelineViewConfigurationsTable> { + $$TimelineViewConfigurationsTableFilterComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + ColumnFilters get projectId => $composableBuilder( + column: $table.projectId, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get timelineId => $composableBuilder( + column: $table.timelineId, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get sequenceId => $composableBuilder( + column: $table.sequenceId, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get active => $composableBuilder( + column: $table.active, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get playheadTick => $composableBuilder( + column: $table.playheadTick, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get baseTick => $composableBuilder( + column: $table.baseTick, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get fractionalTick => $composableBuilder( + column: $table.fractionalTick, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get pixelsPerTick => $composableBuilder( + column: $table.pixelsPerTick, + builder: (column) => ColumnFilters(column), + ); + + ColumnFilters get verticalOffset => $composableBuilder( + column: $table.verticalOffset, + builder: (column) => ColumnFilters(column), + ); +} + +class $$TimelineViewConfigurationsTableOrderingComposer + extends Composer<_$AppDatabase, $TimelineViewConfigurationsTable> { + $$TimelineViewConfigurationsTableOrderingComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + ColumnOrderings get projectId => $composableBuilder( + column: $table.projectId, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get timelineId => $composableBuilder( + column: $table.timelineId, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get sequenceId => $composableBuilder( + column: $table.sequenceId, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get active => $composableBuilder( + column: $table.active, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get playheadTick => $composableBuilder( + column: $table.playheadTick, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get baseTick => $composableBuilder( + column: $table.baseTick, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get fractionalTick => $composableBuilder( + column: $table.fractionalTick, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get pixelsPerTick => $composableBuilder( + column: $table.pixelsPerTick, + builder: (column) => ColumnOrderings(column), + ); + + ColumnOrderings get verticalOffset => $composableBuilder( + column: $table.verticalOffset, + builder: (column) => ColumnOrderings(column), + ); +} + +class $$TimelineViewConfigurationsTableAnnotationComposer + extends Composer<_$AppDatabase, $TimelineViewConfigurationsTable> { + $$TimelineViewConfigurationsTableAnnotationComposer({ + required super.$db, + required super.$table, + super.joinBuilder, + super.$addJoinBuilderToRootComposer, + super.$removeJoinBuilderFromRootComposer, + }); + GeneratedColumn get projectId => + $composableBuilder(column: $table.projectId, builder: (column) => column); + + GeneratedColumn get timelineId => $composableBuilder( + column: $table.timelineId, + builder: (column) => column, + ); + + GeneratedColumn get sequenceId => $composableBuilder( + column: $table.sequenceId, + builder: (column) => column, + ); + + GeneratedColumn get active => + $composableBuilder(column: $table.active, builder: (column) => column); + + GeneratedColumn get playheadTick => $composableBuilder( + column: $table.playheadTick, + builder: (column) => column, + ); + + GeneratedColumn get baseTick => + $composableBuilder(column: $table.baseTick, builder: (column) => column); + + GeneratedColumn get fractionalTick => $composableBuilder( + column: $table.fractionalTick, + builder: (column) => column, + ); + + GeneratedColumn get pixelsPerTick => $composableBuilder( + column: $table.pixelsPerTick, + builder: (column) => column, + ); + + GeneratedColumn get verticalOffset => $composableBuilder( + column: $table.verticalOffset, + builder: (column) => column, + ); +} + +class $$TimelineViewConfigurationsTableTableManager + extends + RootTableManager< + _$AppDatabase, + $TimelineViewConfigurationsTable, + TimelineViewConfiguration, + $$TimelineViewConfigurationsTableFilterComposer, + $$TimelineViewConfigurationsTableOrderingComposer, + $$TimelineViewConfigurationsTableAnnotationComposer, + $$TimelineViewConfigurationsTableCreateCompanionBuilder, + $$TimelineViewConfigurationsTableUpdateCompanionBuilder, + ( + TimelineViewConfiguration, + BaseReferences< + _$AppDatabase, + $TimelineViewConfigurationsTable, + TimelineViewConfiguration + >, + ), + TimelineViewConfiguration, + PrefetchHooks Function() + > { + $$TimelineViewConfigurationsTableTableManager( + _$AppDatabase db, + $TimelineViewConfigurationsTable table, + ) : super( + TableManagerState( + db: db, + table: table, + createFilteringComposer: () => + $$TimelineViewConfigurationsTableFilterComposer( + $db: db, + $table: table, + ), + createOrderingComposer: () => + $$TimelineViewConfigurationsTableOrderingComposer( + $db: db, + $table: table, + ), + createComputedFieldComposer: () => + $$TimelineViewConfigurationsTableAnnotationComposer( + $db: db, + $table: table, + ), + updateCompanionCallback: + ({ + Value projectId = const Value.absent(), + Value timelineId = const Value.absent(), + Value sequenceId = const Value.absent(), + Value active = const Value.absent(), + Value playheadTick = const Value.absent(), + Value baseTick = const Value.absent(), + Value fractionalTick = const Value.absent(), + Value pixelsPerTick = const Value.absent(), + Value verticalOffset = const Value.absent(), + Value rowid = const Value.absent(), + }) => TimelineViewConfigurationsCompanion( + projectId: projectId, + timelineId: timelineId, + sequenceId: sequenceId, + active: active, + playheadTick: playheadTick, + baseTick: baseTick, + fractionalTick: fractionalTick, + pixelsPerTick: pixelsPerTick, + verticalOffset: verticalOffset, + rowid: rowid, + ), + createCompanionCallback: + ({ + required String projectId, + required String timelineId, + required String sequenceId, + required bool active, + required int playheadTick, + required int baseTick, + required double fractionalTick, + required double pixelsPerTick, + required double verticalOffset, + Value rowid = const Value.absent(), + }) => TimelineViewConfigurationsCompanion.insert( + projectId: projectId, + timelineId: timelineId, + sequenceId: sequenceId, + active: active, + playheadTick: playheadTick, + baseTick: baseTick, + fractionalTick: fractionalTick, + pixelsPerTick: pixelsPerTick, + verticalOffset: verticalOffset, + rowid: rowid, + ), + withReferenceMapper: (p0) => p0 + .map( + (e) => ( + e.readTable< + $TimelineViewConfigurationsTable, + TimelineViewConfiguration + >(table), + BaseReferences< + _$AppDatabase, + $TimelineViewConfigurationsTable, + TimelineViewConfiguration + >(db, table, e), + ), + ) + .toList(), + prefetchHooksCallback: null, + ), + ); +} + +typedef $$TimelineViewConfigurationsTableProcessedTableManager = + ProcessedTableManager< + _$AppDatabase, + $TimelineViewConfigurationsTable, + TimelineViewConfiguration, + $$TimelineViewConfigurationsTableFilterComposer, + $$TimelineViewConfigurationsTableOrderingComposer, + $$TimelineViewConfigurationsTableAnnotationComposer, + $$TimelineViewConfigurationsTableCreateCompanionBuilder, + $$TimelineViewConfigurationsTableUpdateCompanionBuilder, + ( + TimelineViewConfiguration, + BaseReferences< + _$AppDatabase, + $TimelineViewConfigurationsTable, + TimelineViewConfiguration + >, + ), + TimelineViewConfiguration, + PrefetchHooks Function() + >; + +class $AppDatabaseManager { + final _$AppDatabase _db; + $AppDatabaseManager(this._db); + $$RecentProjectRecordsTableTableManager get recentProjectRecords => + $$RecentProjectRecordsTableTableManager(_db, _db.recentProjectRecords); + $$LastOpenedTimelinesTableTableManager get lastOpenedTimelines => + $$LastOpenedTimelinesTableTableManager(_db, _db.lastOpenedTimelines); + $$McpConfigurationsTableTableManager get mcpConfigurations => + $$McpConfigurationsTableTableManager(_db, _db.mcpConfigurations); + $$AppearanceConfigurationsTableTableManager get appearanceConfigurations => + $$AppearanceConfigurationsTableTableManager( + _db, + _db.appearanceConfigurations, + ); + $$LanguageConfigurationsTableTableManager get languageConfigurations => + $$LanguageConfigurationsTableTableManager( + _db, + _db.languageConfigurations, + ); + $$ConversationLocationConfigurationsTableTableManager + get conversationLocationConfigurations => + $$ConversationLocationConfigurationsTableTableManager( + _db, + _db.conversationLocationConfigurations, + ); + $$ProjectLocationConfigurationsTableTableManager + get projectLocationConfigurations => + $$ProjectLocationConfigurationsTableTableManager( + _db, + _db.projectLocationConfigurations, + ); + $$ResourceLocationConfigurationsTableTableManager + get resourceLocationConfigurations => + $$ResourceLocationConfigurationsTableTableManager( + _db, + _db.resourceLocationConfigurations, + ); + $$AgentConfigurationsTableTableManager get agentConfigurations => + $$AgentConfigurationsTableTableManager(_db, _db.agentConfigurations); + $$AgentProvidersTableTableManager get agentProviders => + $$AgentProvidersTableTableManager(_db, _db.agentProviders); + $$AgentModelsTableTableManager get agentModels => + $$AgentModelsTableTableManager(_db, _db.agentModels); + $$WorkspaceViewConfigurationsTableTableManager + get workspaceViewConfigurations => + $$WorkspaceViewConfigurationsTableTableManager( + _db, + _db.workspaceViewConfigurations, + ); + $$ProjectViewConfigurationsTableTableManager get projectViewConfigurations => + $$ProjectViewConfigurationsTableTableManager( + _db, + _db.projectViewConfigurations, + ); + $$TimelineViewConfigurationsTableTableManager + get timelineViewConfigurations => + $$TimelineViewConfigurationsTableTableManager( + _db, + _db.timelineViewConfigurations, + ); +} + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(appDatabase) +final appDatabaseProvider = AppDatabaseProvider._(); + +final class AppDatabaseProvider + extends $FunctionalProvider + with $Provider { + AppDatabaseProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'appDatabaseProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$appDatabaseHash(); + + @$internal + @override + $ProviderElement $createElement($ProviderPointer pointer) => + $ProviderElement(pointer); + + @override + AppDatabase create(Ref ref) { + return appDatabase(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(AppDatabase value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$appDatabaseHash() => r'6c9628c3a3f0cb7c304f7bc0b28aaf717a7f7fd6'; diff --git a/lib/persistence/app_settings_repositories.dart b/lib/persistence/app_settings_repositories.dart new file mode 100644 index 0000000..4fd30b8 --- /dev/null +++ b/lib/persistence/app_settings_repositories.dart @@ -0,0 +1,10 @@ +export '../settings/appearance.dart'; +export '../settings/language.dart'; +export '../settings/mcp_settings_value.dart'; + +export 'settings/agent_settings_repository.dart'; +export 'settings/appearance_settings_repository.dart'; +export 'settings/language_settings_repository.dart'; +export 'settings/location_settings_repositories.dart'; +export 'settings/mcp_settings_repository.dart'; +export 'settings/view_settings_repositories.dart'; diff --git a/lib/persistence/settings/agent_settings_repository.dart b/lib/persistence/settings/agent_settings_repository.dart new file mode 100644 index 0000000..f59749f --- /dev/null +++ b/lib/persistence/settings/agent_settings_repository.dart @@ -0,0 +1,101 @@ +import '../../integrations/agent/agent_models.dart'; + +import 'package:drift/drift.dart' hide JsonKey; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import '../app_database.dart'; + +part 'agent_settings_repository.g.dart'; + +@Riverpod(keepAlive: true) +AgentSettingsRepository agentSettingsRepository(Ref ref) => + DriftAgentSettingsRepository(ref.watch(appDatabaseProvider)); + +class DriftAgentSettingsRepository implements AgentSettingsRepository { + DriftAgentSettingsRepository(this._database); + + final AppDatabase _database; + + @override + Future load() async { + final configuration = await (_database.select( + _database.agentConfigurations, + )..where((table) => table.id.equals(0))).getSingleOrNull(); + final providerRows = await (_database.select( + _database.agentProviders, + )..orderBy([(table) => OrderingTerm.asc(table.name)])).get(); + final modelRows = await (_database.select( + _database.agentModels, + )..orderBy([(table) => OrderingTerm.asc(table.modelId)])).get(); + return AgentSettingsState( + enabled: configuration?.enabled ?? false, + selectedProviderId: configuration?.selectedProviderId, + selectedModelId: configuration?.selectedModelId, + revision: configuration?.revision ?? 0, + providers: [ + for (final provider in providerRows) + AgentProviderSettings( + id: provider.id, + enabled: provider.enabled, + name: provider.name, + apiType: provider.apiType, + baseUrl: provider.baseUrl, + credentialId: provider.credentialId, + models: [ + for (final model in modelRows) + if (model.providerId == provider.id) + AgentModelSettings( + id: model.modelId, + contextWindow: model.contextWindow, + maxOutputTokens: model.maxOutputTokens, + ), + ], + ), + ], + ); + } + + @override + Future save(AgentSettingsState settings) => + _database.transaction(() async { + await _database.delete(_database.agentModels).go(); + await _database.delete(_database.agentProviders).go(); + for (final provider in settings.providers) { + await _database + .into(_database.agentProviders) + .insert( + AgentProvidersCompanion.insert( + id: provider.id, + enabled: Value(provider.enabled), + name: provider.name, + apiType: provider.apiType, + baseUrl: provider.baseUrl, + credentialId: Value(provider.credentialId), + ), + ); + for (final model in provider.models) { + await _database + .into(_database.agentModels) + .insert( + AgentModelsCompanion.insert( + providerId: provider.id, + modelId: model.id, + contextWindow: Value(model.contextWindow), + maxOutputTokens: Value(model.maxOutputTokens), + ), + ); + } + } + await _database + .into(_database.agentConfigurations) + .insertOnConflictUpdate( + AgentConfigurationsCompanion.insert( + id: const Value(0), + enabled: settings.enabled, + selectedProviderId: Value(settings.selectedProviderId), + selectedModelId: Value(settings.selectedModelId), + revision: settings.revision, + ), + ); + }); +} diff --git a/lib/persistence/settings/agent_settings_repository.g.dart b/lib/persistence/settings/agent_settings_repository.g.dart new file mode 100644 index 0000000..7509215 --- /dev/null +++ b/lib/persistence/settings/agent_settings_repository.g.dart @@ -0,0 +1,58 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'agent_settings_repository.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(agentSettingsRepository) +final agentSettingsRepositoryProvider = AgentSettingsRepositoryProvider._(); + +final class AgentSettingsRepositoryProvider + extends + $FunctionalProvider< + AgentSettingsRepository, + AgentSettingsRepository, + AgentSettingsRepository + > + with $Provider { + AgentSettingsRepositoryProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'agentSettingsRepositoryProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$agentSettingsRepositoryHash(); + + @$internal + @override + $ProviderElement $createElement( + $ProviderPointer pointer, + ) => $ProviderElement(pointer); + + @override + AgentSettingsRepository create(Ref ref) { + return agentSettingsRepository(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(AgentSettingsRepository value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$agentSettingsRepositoryHash() => + r'33c12d1662339b5c6ea4265eacad1ef3b97fa912'; diff --git a/lib/persistence/settings/appearance_settings_repository.dart b/lib/persistence/settings/appearance_settings_repository.dart new file mode 100644 index 0000000..5b7f9c7 --- /dev/null +++ b/lib/persistence/settings/appearance_settings_repository.dart @@ -0,0 +1,45 @@ +import '../../settings/appearance.dart'; + +import 'package:drift/drift.dart' hide JsonKey; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import '../app_database.dart'; + +part 'appearance_settings_repository.g.dart'; + +abstract interface class AppearanceSettingsRepository { + Future load(); + Future save(AppAppearance mode); +} + +@Riverpod(keepAlive: true) +AppearanceSettingsRepository appearanceSettingsRepository(Ref ref) => + DriftAppearanceSettingsRepository(ref.watch(appDatabaseProvider)); + +class DriftAppearanceSettingsRepository + implements AppearanceSettingsRepository { + DriftAppearanceSettingsRepository(this._database); + + final AppDatabase _database; + + @override + Future load() async { + final row = await (_database.select( + _database.appearanceConfigurations, + )..where((table) => table.id.equals(0))).getSingleOrNull(); + return AppAppearance.values.firstWhere( + (mode) => mode.name == row?.themeMode, + orElse: () => AppAppearance.system, + ); + } + + @override + Future save(AppAppearance mode) => _database + .into(_database.appearanceConfigurations) + .insertOnConflictUpdate( + AppearanceConfigurationsCompanion.insert( + id: const Value(0), + themeMode: mode.name, + ), + ); +} diff --git a/lib/persistence/settings/appearance_settings_repository.g.dart b/lib/persistence/settings/appearance_settings_repository.g.dart new file mode 100644 index 0000000..b856cd5 --- /dev/null +++ b/lib/persistence/settings/appearance_settings_repository.g.dart @@ -0,0 +1,59 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'appearance_settings_repository.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(appearanceSettingsRepository) +final appearanceSettingsRepositoryProvider = + AppearanceSettingsRepositoryProvider._(); + +final class AppearanceSettingsRepositoryProvider + extends + $FunctionalProvider< + AppearanceSettingsRepository, + AppearanceSettingsRepository, + AppearanceSettingsRepository + > + with $Provider { + AppearanceSettingsRepositoryProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'appearanceSettingsRepositoryProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$appearanceSettingsRepositoryHash(); + + @$internal + @override + $ProviderElement $createElement( + $ProviderPointer pointer, + ) => $ProviderElement(pointer); + + @override + AppearanceSettingsRepository create(Ref ref) { + return appearanceSettingsRepository(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(AppearanceSettingsRepository value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$appearanceSettingsRepositoryHash() => + r'e296225dd2efd8b02ef34e37428619c6094cc57d'; diff --git a/lib/persistence/settings/language_settings_repository.dart b/lib/persistence/settings/language_settings_repository.dart new file mode 100644 index 0000000..ff6cfe7 --- /dev/null +++ b/lib/persistence/settings/language_settings_repository.dart @@ -0,0 +1,44 @@ +import '../../settings/language.dart'; + +import 'package:drift/drift.dart' hide JsonKey; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import '../app_database.dart'; + +part 'language_settings_repository.g.dart'; + +abstract interface class LanguageSettingsRepository { + Future load(); + Future save(AppLanguage language); +} + +@Riverpod(keepAlive: true) +LanguageSettingsRepository languageSettingsRepository(Ref ref) => + DriftLanguageSettingsRepository(ref.watch(appDatabaseProvider)); + +class DriftLanguageSettingsRepository implements LanguageSettingsRepository { + DriftLanguageSettingsRepository(this._database); + + final AppDatabase _database; + + @override + Future load() async { + final row = await (_database.select( + _database.languageConfigurations, + )..where((table) => table.id.equals(0))).getSingleOrNull(); + return AppLanguage.values.firstWhere( + (language) => language.name == row?.language, + orElse: () => AppLanguage.system, + ); + } + + @override + Future save(AppLanguage language) => _database + .into(_database.languageConfigurations) + .insertOnConflictUpdate( + LanguageConfigurationsCompanion.insert( + id: const Value(0), + language: language.name, + ), + ); +} diff --git a/lib/persistence/settings/language_settings_repository.g.dart b/lib/persistence/settings/language_settings_repository.g.dart new file mode 100644 index 0000000..b83f419 --- /dev/null +++ b/lib/persistence/settings/language_settings_repository.g.dart @@ -0,0 +1,59 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'language_settings_repository.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(languageSettingsRepository) +final languageSettingsRepositoryProvider = + LanguageSettingsRepositoryProvider._(); + +final class LanguageSettingsRepositoryProvider + extends + $FunctionalProvider< + LanguageSettingsRepository, + LanguageSettingsRepository, + LanguageSettingsRepository + > + with $Provider { + LanguageSettingsRepositoryProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'languageSettingsRepositoryProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$languageSettingsRepositoryHash(); + + @$internal + @override + $ProviderElement $createElement( + $ProviderPointer pointer, + ) => $ProviderElement(pointer); + + @override + LanguageSettingsRepository create(Ref ref) { + return languageSettingsRepository(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(LanguageSettingsRepository value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$languageSettingsRepositoryHash() => + r'5774fcc80ea5628bfe38562e0537b55b675b8f5f'; diff --git a/lib/persistence/settings/location_settings_repositories.dart b/lib/persistence/settings/location_settings_repositories.dart new file mode 100644 index 0000000..115eea3 --- /dev/null +++ b/lib/persistence/settings/location_settings_repositories.dart @@ -0,0 +1,202 @@ +import 'dart:io'; + +import 'package:path/path.dart' as p; +import 'package:path_provider/path_provider.dart'; + +import 'package:drift/drift.dart' hide JsonKey; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import '../app_database.dart'; + +part 'location_settings_repositories.g.dart'; + +abstract interface class ProjectLocationSettingsRepository { + Future load(); + Future save(String directory); +} + +class ProjectLocationUnavailableException implements Exception { + const ProjectLocationUnavailableException(); +} + +@Riverpod(keepAlive: true) +ProjectLocationSettingsRepository projectLocationSettingsRepository(Ref ref) => + DefaultingProjectLocationSettingsRepository( + DriftProjectLocationSettingsRepository(ref.watch(appDatabaseProvider)), + ); + +class DefaultingProjectLocationSettingsRepository + implements ProjectLocationSettingsRepository { + DefaultingProjectLocationSettingsRepository( + this._repository, { + Future Function()? documentsDirectory, + }) : _documentsDirectory = documentsDirectory ?? _systemDocumentsDirectory; + + final ProjectLocationSettingsRepository _repository; + final Future Function() _documentsDirectory; + + static Future _systemDocumentsDirectory() async { + if (Platform.environment.containsKey('FLUTTER_TEST')) { + return Directory.systemTemp; + } + return getApplicationDocumentsDirectory(); + } + + @override + Future load() async { + try { + final configured = await _repository.load(); + if (configured != null && configured.trim().isNotEmpty) { + return configured; + } + final documents = await _documentsDirectory(); + final directory = Directory(p.join(documents.path, 'Cutdex', 'Projects')); + await _repository.save(directory.path); + return directory.path; + } on FileSystemException { + throw const ProjectLocationUnavailableException(); + } on Exception { + throw const ProjectLocationUnavailableException(); + } + } + + @override + Future save(String directory) => _repository.save(directory); +} + +class DriftProjectLocationSettingsRepository + implements ProjectLocationSettingsRepository { + DriftProjectLocationSettingsRepository(this._database); + + final AppDatabase _database; + + @override + Future load() async { + final row = await (_database.select( + _database.projectLocationConfigurations, + )..where((table) => table.id.equals(0))).getSingleOrNull(); + return row?.directory; + } + + @override + Future save(String directory) => _database + .into(_database.projectLocationConfigurations) + .insertOnConflictUpdate( + ProjectLocationConfigurationsCompanion.insert( + id: const Value(0), + directory: directory, + ), + ); +} + +abstract interface class ConversationLocationSettingsRepository { + Future load(); + Future save(String directory); +} + +@Riverpod(keepAlive: true) +ConversationLocationSettingsRepository conversationLocationSettingsRepository( + Ref ref, +) => + DriftConversationLocationSettingsRepository(ref.watch(appDatabaseProvider)); + +class DriftConversationLocationSettingsRepository + implements ConversationLocationSettingsRepository { + DriftConversationLocationSettingsRepository(this._database); + + final AppDatabase _database; + + @override + Future load() async { + final row = await (_database.select( + _database.conversationLocationConfigurations, + )..where((table) => table.id.equals(0))).getSingleOrNull(); + return row?.directory; + } + + @override + Future save(String directory) => _database + .into(_database.conversationLocationConfigurations) + .insertOnConflictUpdate( + ConversationLocationConfigurationsCompanion.insert( + id: const Value(0), + directory: directory, + ), + ); +} + +abstract interface class ResourceLocationSettingsRepository { + Future load(); + Future save(String directory); +} + +@Riverpod(keepAlive: true) +ResourceLocationSettingsRepository resourceLocationSettingsRepository( + Ref ref, +) => DefaultingResourceLocationSettingsRepository( + DriftResourceLocationSettingsRepository(ref.watch(appDatabaseProvider)), +); + +class DriftResourceLocationSettingsRepository + implements ResourceLocationSettingsRepository { + DriftResourceLocationSettingsRepository(this._database); + + final AppDatabase _database; + + @override + Future load() async { + final row = await (_database.select( + _database.resourceLocationConfigurations, + )..where((table) => table.id.equals(0))).getSingleOrNull(); + return row?.directory; + } + + @override + Future save(String directory) => _database + .into(_database.resourceLocationConfigurations) + .insertOnConflictUpdate( + ResourceLocationConfigurationsCompanion.insert( + id: const Value(0), + directory: directory, + ), + ); +} + +class DefaultingResourceLocationSettingsRepository + implements ResourceLocationSettingsRepository { + DefaultingResourceLocationSettingsRepository( + this._repository, { + Future Function()? documentsDirectory, + }) : _documentsDirectory = + documentsDirectory ?? getApplicationDocumentsDirectory; + + final ResourceLocationSettingsRepository _repository; + final Future Function() _documentsDirectory; + + @override + Future load() async { + final configured = await _repository.load(); + final directory = configured != null && configured.trim().isNotEmpty + ? Directory(configured) + : Directory( + p.join((await _documentsDirectory()).path, 'Cutdex', 'Resources'), + ); + await directory.create(recursive: true); + for (final name in ['Processing', 'Downloads', 'Cache']) { + await Directory(p.join(directory.path, name)).create(recursive: true); + } + if (configured == null || configured.trim().isEmpty) { + await _repository.save(directory.path); + } + return directory.path; + } + + @override + Future save(String directory) async { + final root = Directory(directory); + for (final name in ['Processing', 'Downloads', 'Cache']) { + await Directory(p.join(root.path, name)).create(recursive: true); + } + await _repository.save(root.path); + } +} diff --git a/lib/persistence/settings/location_settings_repositories.g.dart b/lib/persistence/settings/location_settings_repositories.g.dart new file mode 100644 index 0000000..9dd3657 --- /dev/null +++ b/lib/persistence/settings/location_settings_repositories.g.dart @@ -0,0 +1,165 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'location_settings_repositories.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(projectLocationSettingsRepository) +final projectLocationSettingsRepositoryProvider = + ProjectLocationSettingsRepositoryProvider._(); + +final class ProjectLocationSettingsRepositoryProvider + extends + $FunctionalProvider< + ProjectLocationSettingsRepository, + ProjectLocationSettingsRepository, + ProjectLocationSettingsRepository + > + with $Provider { + ProjectLocationSettingsRepositoryProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'projectLocationSettingsRepositoryProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => + _$projectLocationSettingsRepositoryHash(); + + @$internal + @override + $ProviderElement $createElement( + $ProviderPointer pointer, + ) => $ProviderElement(pointer); + + @override + ProjectLocationSettingsRepository create(Ref ref) { + return projectLocationSettingsRepository(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(ProjectLocationSettingsRepository value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider( + value, + ), + ); + } +} + +String _$projectLocationSettingsRepositoryHash() => + r'b29f95c5922d86c094dc4aa000ce58dfec33e162'; + +@ProviderFor(conversationLocationSettingsRepository) +final conversationLocationSettingsRepositoryProvider = + ConversationLocationSettingsRepositoryProvider._(); + +final class ConversationLocationSettingsRepositoryProvider + extends + $FunctionalProvider< + ConversationLocationSettingsRepository, + ConversationLocationSettingsRepository, + ConversationLocationSettingsRepository + > + with $Provider { + ConversationLocationSettingsRepositoryProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'conversationLocationSettingsRepositoryProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => + _$conversationLocationSettingsRepositoryHash(); + + @$internal + @override + $ProviderElement $createElement( + $ProviderPointer pointer, + ) => $ProviderElement(pointer); + + @override + ConversationLocationSettingsRepository create(Ref ref) { + return conversationLocationSettingsRepository(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(ConversationLocationSettingsRepository value) { + return $ProviderOverride( + origin: this, + providerOverride: + $SyncValueProvider(value), + ); + } +} + +String _$conversationLocationSettingsRepositoryHash() => + r'6c6859eb5ef2539275475139a22dbfb84c35c5f2'; + +@ProviderFor(resourceLocationSettingsRepository) +final resourceLocationSettingsRepositoryProvider = + ResourceLocationSettingsRepositoryProvider._(); + +final class ResourceLocationSettingsRepositoryProvider + extends + $FunctionalProvider< + ResourceLocationSettingsRepository, + ResourceLocationSettingsRepository, + ResourceLocationSettingsRepository + > + with $Provider { + ResourceLocationSettingsRepositoryProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'resourceLocationSettingsRepositoryProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => + _$resourceLocationSettingsRepositoryHash(); + + @$internal + @override + $ProviderElement $createElement( + $ProviderPointer pointer, + ) => $ProviderElement(pointer); + + @override + ResourceLocationSettingsRepository create(Ref ref) { + return resourceLocationSettingsRepository(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(ResourceLocationSettingsRepository value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider( + value, + ), + ); + } +} + +String _$resourceLocationSettingsRepositoryHash() => + r'2e3e56e45187f1e62b9ad980f8816eddd47a6688'; diff --git a/lib/persistence/settings/mcp_settings_repository.dart b/lib/persistence/settings/mcp_settings_repository.dart new file mode 100644 index 0000000..062926c --- /dev/null +++ b/lib/persistence/settings/mcp_settings_repository.dart @@ -0,0 +1,49 @@ +import '../../settings/mcp_settings_value.dart'; + +import 'package:drift/drift.dart' hide JsonKey; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import '../app_database.dart'; + +part 'mcp_settings_repository.g.dart'; + +abstract interface class McpSettingsRepository { + Future load(); + Future save(McpSettingsValue configuration); +} + +@Riverpod(keepAlive: true) +McpSettingsRepository mcpSettingsRepository(Ref ref) => + DriftMcpSettingsRepository(ref.watch(appDatabaseProvider)); + +class DriftMcpSettingsRepository implements McpSettingsRepository { + DriftMcpSettingsRepository(this._database); + + final AppDatabase _database; + + @override + Future load() async { + final row = await (_database.select( + _database.mcpConfigurations, + )..where((table) => table.id.equals(0))).getSingleOrNull(); + return row == null + ? null + : McpSettingsValue( + enabled: row.enabled, + port: row.port, + token: row.token, + ); + } + + @override + Future save(McpSettingsValue configuration) => _database + .into(_database.mcpConfigurations) + .insertOnConflictUpdate( + McpConfigurationsCompanion.insert( + id: const Value(0), + enabled: configuration.enabled, + port: configuration.port, + token: configuration.token, + ), + ); +} diff --git a/lib/persistence/settings/mcp_settings_repository.g.dart b/lib/persistence/settings/mcp_settings_repository.g.dart new file mode 100644 index 0000000..bb367fd --- /dev/null +++ b/lib/persistence/settings/mcp_settings_repository.g.dart @@ -0,0 +1,58 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'mcp_settings_repository.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(mcpSettingsRepository) +final mcpSettingsRepositoryProvider = McpSettingsRepositoryProvider._(); + +final class McpSettingsRepositoryProvider + extends + $FunctionalProvider< + McpSettingsRepository, + McpSettingsRepository, + McpSettingsRepository + > + with $Provider { + McpSettingsRepositoryProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'mcpSettingsRepositoryProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$mcpSettingsRepositoryHash(); + + @$internal + @override + $ProviderElement $createElement( + $ProviderPointer pointer, + ) => $ProviderElement(pointer); + + @override + McpSettingsRepository create(Ref ref) { + return mcpSettingsRepository(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(McpSettingsRepository value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$mcpSettingsRepositoryHash() => + r'd499a1b78f95e0ee5416e9e9508e697b2e2c00d3'; diff --git a/lib/persistence/settings/view_settings_repositories.dart b/lib/persistence/settings/view_settings_repositories.dart new file mode 100644 index 0000000..d1bbb33 --- /dev/null +++ b/lib/persistence/settings/view_settings_repositories.dart @@ -0,0 +1,216 @@ +import 'package:cutdex_sdk/timeline/layout.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +import 'package:drift/drift.dart' hide JsonKey; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import '../app_database.dart'; +import '../../workspace/workspace_mode.dart'; + +part 'view_settings_repositories.g.dart'; +part 'view_settings_repositories.freezed.dart'; + +@freezed +abstract class WorkspaceViewSettingsData with _$WorkspaceViewSettingsData { + const WorkspaceViewSettingsData._(); + + const factory WorkspaceViewSettingsData({ + @Default(false) bool hasSavedState, + @Default(WorkspaceMode.agent) WorkspaceMode mode, + String? activeProjectId, + @Default(false) bool sidebarCollapsed, + double? sidebarWidth, + }) = _WorkspaceViewSettingsData; +} + +abstract interface class WorkspaceViewSettingsRepository { + Future load(); + Future save(WorkspaceViewSettingsData settings); +} + +@Riverpod(keepAlive: true) +WorkspaceViewSettingsRepository workspaceViewSettingsRepository(Ref ref) => + DriftWorkspaceViewSettingsRepository(ref.watch(appDatabaseProvider)); + +class DriftWorkspaceViewSettingsRepository + implements WorkspaceViewSettingsRepository { + DriftWorkspaceViewSettingsRepository(this._database); + final AppDatabase _database; + + @override + Future load() async { + final row = await (_database.select( + _database.workspaceViewConfigurations, + )..where((table) => table.id.equals(0))).getSingleOrNull(); + if (row == null) return const WorkspaceViewSettingsData(); + return WorkspaceViewSettingsData( + hasSavedState: true, + mode: WorkspaceMode.values.byName(row.mode), + activeProjectId: row.activeProjectId, + sidebarCollapsed: row.sidebarCollapsed, + sidebarWidth: row.sidebarWidth, + ); + } + + @override + Future save(WorkspaceViewSettingsData settings) => _database + .into(_database.workspaceViewConfigurations) + .insertOnConflictUpdate( + WorkspaceViewConfigurationsCompanion.insert( + id: const Value(0), + mode: Value(settings.mode.name), + activeProjectId: Value(settings.activeProjectId), + sidebarCollapsed: settings.sidebarCollapsed, + sidebarWidth: Value(settings.sidebarWidth), + ), + ); +} + +@freezed +abstract class ProjectViewSettingsData with _$ProjectViewSettingsData { + const ProjectViewSettingsData._(); + + const factory ProjectViewSettingsData({ + @Default(false) bool propertiesOpen, + double? timelineHeight, + }) = _ProjectViewSettingsData; +} + +abstract interface class ProjectViewSettingsRepository { + Future load(String projectId); + Future save(String projectId, ProjectViewSettingsData settings); +} + +@Riverpod(keepAlive: true) +ProjectViewSettingsRepository projectViewSettingsRepository(Ref ref) => + DriftProjectViewSettingsRepository(ref.watch(appDatabaseProvider)); + +class DriftProjectViewSettingsRepository + implements ProjectViewSettingsRepository { + DriftProjectViewSettingsRepository(this._database); + final AppDatabase _database; + + @override + Future load(String projectId) async { + final row = await (_database.select( + _database.projectViewConfigurations, + )..where((table) => table.projectId.equals(projectId))).getSingleOrNull(); + return row == null + ? const ProjectViewSettingsData() + : ProjectViewSettingsData( + propertiesOpen: row.propertiesOpen, + timelineHeight: row.timelineHeight, + ); + } + + @override + Future save(String projectId, ProjectViewSettingsData settings) => + _database + .into(_database.projectViewConfigurations) + .insertOnConflictUpdate( + ProjectViewConfigurationsCompanion.insert( + projectId: projectId, + propertiesOpen: settings.propertiesOpen, + timelineHeight: Value(settings.timelineHeight), + ), + ); +} + +@freezed +abstract class TimelineSequenceViewState with _$TimelineSequenceViewState { + const TimelineSequenceViewState._(); + + const factory TimelineSequenceViewState({ + required int playheadTick, + required TimelineCamera camera, + }) = _TimelineSequenceViewState; +} + +@freezed +abstract class TimelineViewState with _$TimelineViewState { + const factory TimelineViewState({ + SequenceId? activeSequenceId, + @Default({}) Map sequences, + }) = _TimelineViewState; +} + +abstract interface class TimelineViewSettingsRepository { + Future load(String projectId, String timelineId); + Future save( + String projectId, + String timelineId, + SequenceId sequenceId, + TimelineSequenceViewState state, + ); +} + +@Riverpod(keepAlive: true) +TimelineViewSettingsRepository timelineViewSettingsRepository(Ref ref) => + DriftTimelineViewSettingsRepository(ref.watch(appDatabaseProvider)); + +class DriftTimelineViewSettingsRepository + implements TimelineViewSettingsRepository { + DriftTimelineViewSettingsRepository(this._database); + + final AppDatabase _database; + + @override + Future load(String projectId, String timelineId) async { + final rows = + await (_database.select(_database.timelineViewConfigurations)..where( + (table) => + table.projectId.equals(projectId) & + table.timelineId.equals(timelineId), + )) + .get(); + final activeRow = rows.where((row) => row.active).firstOrNull; + return TimelineViewState( + activeSequenceId: activeRow == null + ? null + : SequenceId(activeRow.sequenceId), + sequences: { + for (final row in rows) + SequenceId(row.sequenceId): TimelineSequenceViewState( + playheadTick: row.playheadTick, + camera: TimelineCamera( + baseTick: row.baseTick, + fractionalTick: row.fractionalTick, + pixelsPerTick: row.pixelsPerTick, + verticalOffset: row.verticalOffset, + ), + ), + }, + ); + } + + @override + Future save( + String projectId, + String timelineId, + SequenceId sequenceId, + TimelineSequenceViewState state, + ) => _database.transaction(() async { + await (_database.update(_database.timelineViewConfigurations)..where( + (table) => + table.projectId.equals(projectId) & + table.timelineId.equals(timelineId), + )) + .write(const TimelineViewConfigurationsCompanion(active: Value(false))); + await _database + .into(_database.timelineViewConfigurations) + .insertOnConflictUpdate( + TimelineViewConfigurationsCompanion.insert( + projectId: projectId, + timelineId: timelineId, + sequenceId: sequenceId.value, + active: true, + playheadTick: state.playheadTick, + baseTick: state.camera.baseTick, + fractionalTick: state.camera.fractionalTick, + pixelsPerTick: state.camera.pixelsPerTick, + verticalOffset: state.camera.verticalOffset, + ), + ); + }); +} diff --git a/lib/persistence/settings/view_settings_repositories.freezed.dart b/lib/persistence/settings/view_settings_repositories.freezed.dart new file mode 100644 index 0000000..86998cb --- /dev/null +++ b/lib/persistence/settings/view_settings_repositories.freezed.dart @@ -0,0 +1,1455 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'view_settings_repositories.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +T _$identity(T value) => value; + +/// @nodoc +mixin _$WorkspaceViewSettingsData { + bool get hasSavedState; + WorkspaceMode get mode; + String? get activeProjectId; + bool get sidebarCollapsed; + double? get sidebarWidth; + + /// Create a copy of WorkspaceViewSettingsData + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $WorkspaceViewSettingsDataCopyWith get copyWith => + _$WorkspaceViewSettingsDataCopyWithImpl( + this as WorkspaceViewSettingsData, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as WorkspaceViewSettingsData; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is WorkspaceViewSettingsData && + (identical(other.hasSavedState, _this.hasSavedState) || + other.hasSavedState == _this.hasSavedState) && + (identical(other.mode, _this.mode) || other.mode == _this.mode) && + (identical(other.activeProjectId, _this.activeProjectId) || + other.activeProjectId == _this.activeProjectId) && + (identical(other.sidebarCollapsed, _this.sidebarCollapsed) || + other.sidebarCollapsed == _this.sidebarCollapsed) && + (identical(other.sidebarWidth, _this.sidebarWidth) || + other.sidebarWidth == _this.sidebarWidth)); + } + + @override + int get hashCode { + final _this = this as WorkspaceViewSettingsData; + return Object.hash( + runtimeType, + _this.hasSavedState, + _this.mode, + _this.activeProjectId, + _this.sidebarCollapsed, + _this.sidebarWidth, + ); + } + + @override + String toString() { + final _this = this as WorkspaceViewSettingsData; + return 'WorkspaceViewSettingsData(hasSavedState: ${_this.hasSavedState}, mode: ${_this.mode}, activeProjectId: ${_this.activeProjectId}, sidebarCollapsed: ${_this.sidebarCollapsed}, sidebarWidth: ${_this.sidebarWidth})'; + } +} + +/// @nodoc +abstract mixin class $WorkspaceViewSettingsDataCopyWith<$Res> { + factory $WorkspaceViewSettingsDataCopyWith( + WorkspaceViewSettingsData value, + $Res Function(WorkspaceViewSettingsData) _then, + ) = _$WorkspaceViewSettingsDataCopyWithImpl; + @useResult + $Res call({ + bool hasSavedState, + WorkspaceMode mode, + String? activeProjectId, + bool sidebarCollapsed, + double? sidebarWidth, + }); +} + +/// @nodoc +class _$WorkspaceViewSettingsDataCopyWithImpl<$Res> + implements $WorkspaceViewSettingsDataCopyWith<$Res> { + _$WorkspaceViewSettingsDataCopyWithImpl(this._self, this._then); + + final WorkspaceViewSettingsData _self; + final $Res Function(WorkspaceViewSettingsData) _then; + + /// Create a copy of WorkspaceViewSettingsData + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? hasSavedState = null, + Object? mode = null, + Object? activeProjectId = freezed, + Object? sidebarCollapsed = null, + Object? sidebarWidth = freezed, + }) { + return _then( + WorkspaceViewSettingsData( + hasSavedState: null == hasSavedState + ? _self.hasSavedState + : hasSavedState // ignore: cast_nullable_to_non_nullable + as bool, + mode: null == mode + ? _self.mode + : mode // ignore: cast_nullable_to_non_nullable + as WorkspaceMode, + activeProjectId: freezed == activeProjectId + ? _self.activeProjectId + : activeProjectId // ignore: cast_nullable_to_non_nullable + as String?, + sidebarCollapsed: null == sidebarCollapsed + ? _self.sidebarCollapsed + : sidebarCollapsed // ignore: cast_nullable_to_non_nullable + as bool, + sidebarWidth: freezed == sidebarWidth + ? _self.sidebarWidth + : sidebarWidth // ignore: cast_nullable_to_non_nullable + as double?, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [WorkspaceViewSettingsData]. +extension WorkspaceViewSettingsDataPatterns on WorkspaceViewSettingsData { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_WorkspaceViewSettingsData value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _WorkspaceViewSettingsData() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_WorkspaceViewSettingsData value) $default, + ) { + final _that = this; + switch (_that) { + case _WorkspaceViewSettingsData(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_WorkspaceViewSettingsData value)? $default, + ) { + final _that = this; + switch (_that) { + case _WorkspaceViewSettingsData() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + bool hasSavedState, + WorkspaceMode mode, + String? activeProjectId, + bool sidebarCollapsed, + double? sidebarWidth, + )? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _WorkspaceViewSettingsData() when $default != null: + return $default( + _that.hasSavedState, + _that.mode, + _that.activeProjectId, + _that.sidebarCollapsed, + _that.sidebarWidth, + ); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function( + bool hasSavedState, + WorkspaceMode mode, + String? activeProjectId, + bool sidebarCollapsed, + double? sidebarWidth, + ) + $default, + ) { + final _that = this; + switch (_that) { + case _WorkspaceViewSettingsData(): + return $default( + _that.hasSavedState, + _that.mode, + _that.activeProjectId, + _that.sidebarCollapsed, + _that.sidebarWidth, + ); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + bool hasSavedState, + WorkspaceMode mode, + String? activeProjectId, + bool sidebarCollapsed, + double? sidebarWidth, + )? + $default, + ) { + final _that = this; + switch (_that) { + case _WorkspaceViewSettingsData() when $default != null: + return $default( + _that.hasSavedState, + _that.mode, + _that.activeProjectId, + _that.sidebarCollapsed, + _that.sidebarWidth, + ); + case _: + return null; + } + } +} + +/// @nodoc + +class _WorkspaceViewSettingsData extends WorkspaceViewSettingsData { + const _WorkspaceViewSettingsData({ + this.hasSavedState = false, + this.mode = WorkspaceMode.agent, + this.activeProjectId, + this.sidebarCollapsed = false, + this.sidebarWidth, + }) : super._(); + + @override + @JsonKey() + final bool hasSavedState; + @override + @JsonKey() + final WorkspaceMode mode; + @override + final String? activeProjectId; + @override + @JsonKey() + final bool sidebarCollapsed; + @override + final double? sidebarWidth; + + /// Create a copy of WorkspaceViewSettingsData + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$WorkspaceViewSettingsDataCopyWith<_WorkspaceViewSettingsData> + get copyWith => + __$WorkspaceViewSettingsDataCopyWithImpl<_WorkspaceViewSettingsData>( + this, + _$identity, + ); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _WorkspaceViewSettingsData && + (identical(other.hasSavedState, hasSavedState) || + other.hasSavedState == hasSavedState) && + (identical(other.mode, mode) || other.mode == mode) && + (identical(other.activeProjectId, activeProjectId) || + other.activeProjectId == activeProjectId) && + (identical(other.sidebarCollapsed, sidebarCollapsed) || + other.sidebarCollapsed == sidebarCollapsed) && + (identical(other.sidebarWidth, sidebarWidth) || + other.sidebarWidth == sidebarWidth)); + } + + @override + int get hashCode { + return Object.hash( + runtimeType, + hasSavedState, + mode, + activeProjectId, + sidebarCollapsed, + sidebarWidth, + ); + } + + @override + String toString() { + return 'WorkspaceViewSettingsData(hasSavedState: $hasSavedState, mode: $mode, activeProjectId: $activeProjectId, sidebarCollapsed: $sidebarCollapsed, sidebarWidth: $sidebarWidth)'; + } +} + +/// @nodoc +abstract mixin class _$WorkspaceViewSettingsDataCopyWith<$Res> + implements $WorkspaceViewSettingsDataCopyWith<$Res> { + factory _$WorkspaceViewSettingsDataCopyWith( + _WorkspaceViewSettingsData value, + $Res Function(_WorkspaceViewSettingsData) _then, + ) = __$WorkspaceViewSettingsDataCopyWithImpl; + @override + @useResult + $Res call({ + bool hasSavedState, + WorkspaceMode mode, + String? activeProjectId, + bool sidebarCollapsed, + double? sidebarWidth, + }); +} + +/// @nodoc +class __$WorkspaceViewSettingsDataCopyWithImpl<$Res> + implements _$WorkspaceViewSettingsDataCopyWith<$Res> { + __$WorkspaceViewSettingsDataCopyWithImpl(this._self, this._then); + + final _WorkspaceViewSettingsData _self; + final $Res Function(_WorkspaceViewSettingsData) _then; + + /// Create a copy of WorkspaceViewSettingsData + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? hasSavedState = null, + Object? mode = null, + Object? activeProjectId = freezed, + Object? sidebarCollapsed = null, + Object? sidebarWidth = freezed, + }) { + return _then( + _WorkspaceViewSettingsData( + hasSavedState: null == hasSavedState + ? _self.hasSavedState + : hasSavedState // ignore: cast_nullable_to_non_nullable + as bool, + mode: null == mode + ? _self.mode + : mode // ignore: cast_nullable_to_non_nullable + as WorkspaceMode, + activeProjectId: freezed == activeProjectId + ? _self.activeProjectId + : activeProjectId // ignore: cast_nullable_to_non_nullable + as String?, + sidebarCollapsed: null == sidebarCollapsed + ? _self.sidebarCollapsed + : sidebarCollapsed // ignore: cast_nullable_to_non_nullable + as bool, + sidebarWidth: freezed == sidebarWidth + ? _self.sidebarWidth + : sidebarWidth // ignore: cast_nullable_to_non_nullable + as double?, + ), + ); + } +} + +/// @nodoc +mixin _$ProjectViewSettingsData { + bool get propertiesOpen; + double? get timelineHeight; + + /// Create a copy of ProjectViewSettingsData + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $ProjectViewSettingsDataCopyWith get copyWith => + _$ProjectViewSettingsDataCopyWithImpl( + this as ProjectViewSettingsData, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as ProjectViewSettingsData; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is ProjectViewSettingsData && + (identical(other.propertiesOpen, _this.propertiesOpen) || + other.propertiesOpen == _this.propertiesOpen) && + (identical(other.timelineHeight, _this.timelineHeight) || + other.timelineHeight == _this.timelineHeight)); + } + + @override + int get hashCode { + final _this = this as ProjectViewSettingsData; + return Object.hash(runtimeType, _this.propertiesOpen, _this.timelineHeight); + } + + @override + String toString() { + final _this = this as ProjectViewSettingsData; + return 'ProjectViewSettingsData(propertiesOpen: ${_this.propertiesOpen}, timelineHeight: ${_this.timelineHeight})'; + } +} + +/// @nodoc +abstract mixin class $ProjectViewSettingsDataCopyWith<$Res> { + factory $ProjectViewSettingsDataCopyWith( + ProjectViewSettingsData value, + $Res Function(ProjectViewSettingsData) _then, + ) = _$ProjectViewSettingsDataCopyWithImpl; + @useResult + $Res call({bool propertiesOpen, double? timelineHeight}); +} + +/// @nodoc +class _$ProjectViewSettingsDataCopyWithImpl<$Res> + implements $ProjectViewSettingsDataCopyWith<$Res> { + _$ProjectViewSettingsDataCopyWithImpl(this._self, this._then); + + final ProjectViewSettingsData _self; + final $Res Function(ProjectViewSettingsData) _then; + + /// Create a copy of ProjectViewSettingsData + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({Object? propertiesOpen = null, Object? timelineHeight = freezed}) { + return _then( + ProjectViewSettingsData( + propertiesOpen: null == propertiesOpen + ? _self.propertiesOpen + : propertiesOpen // ignore: cast_nullable_to_non_nullable + as bool, + timelineHeight: freezed == timelineHeight + ? _self.timelineHeight + : timelineHeight // ignore: cast_nullable_to_non_nullable + as double?, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [ProjectViewSettingsData]. +extension ProjectViewSettingsDataPatterns on ProjectViewSettingsData { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_ProjectViewSettingsData value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ProjectViewSettingsData() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_ProjectViewSettingsData value) $default, + ) { + final _that = this; + switch (_that) { + case _ProjectViewSettingsData(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_ProjectViewSettingsData value)? $default, + ) { + final _that = this; + switch (_that) { + case _ProjectViewSettingsData() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function(bool propertiesOpen, double? timelineHeight)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ProjectViewSettingsData() when $default != null: + return $default(_that.propertiesOpen, _that.timelineHeight); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function(bool propertiesOpen, double? timelineHeight) $default, + ) { + final _that = this; + switch (_that) { + case _ProjectViewSettingsData(): + return $default(_that.propertiesOpen, _that.timelineHeight); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function(bool propertiesOpen, double? timelineHeight)? $default, + ) { + final _that = this; + switch (_that) { + case _ProjectViewSettingsData() when $default != null: + return $default(_that.propertiesOpen, _that.timelineHeight); + case _: + return null; + } + } +} + +/// @nodoc + +class _ProjectViewSettingsData extends ProjectViewSettingsData { + const _ProjectViewSettingsData({ + this.propertiesOpen = false, + this.timelineHeight, + }) : super._(); + + @override + @JsonKey() + final bool propertiesOpen; + @override + final double? timelineHeight; + + /// Create a copy of ProjectViewSettingsData + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$ProjectViewSettingsDataCopyWith<_ProjectViewSettingsData> get copyWith => + __$ProjectViewSettingsDataCopyWithImpl<_ProjectViewSettingsData>( + this, + _$identity, + ); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _ProjectViewSettingsData && + (identical(other.propertiesOpen, propertiesOpen) || + other.propertiesOpen == propertiesOpen) && + (identical(other.timelineHeight, timelineHeight) || + other.timelineHeight == timelineHeight)); + } + + @override + int get hashCode { + return Object.hash(runtimeType, propertiesOpen, timelineHeight); + } + + @override + String toString() { + return 'ProjectViewSettingsData(propertiesOpen: $propertiesOpen, timelineHeight: $timelineHeight)'; + } +} + +/// @nodoc +abstract mixin class _$ProjectViewSettingsDataCopyWith<$Res> + implements $ProjectViewSettingsDataCopyWith<$Res> { + factory _$ProjectViewSettingsDataCopyWith( + _ProjectViewSettingsData value, + $Res Function(_ProjectViewSettingsData) _then, + ) = __$ProjectViewSettingsDataCopyWithImpl; + @override + @useResult + $Res call({bool propertiesOpen, double? timelineHeight}); +} + +/// @nodoc +class __$ProjectViewSettingsDataCopyWithImpl<$Res> + implements _$ProjectViewSettingsDataCopyWith<$Res> { + __$ProjectViewSettingsDataCopyWithImpl(this._self, this._then); + + final _ProjectViewSettingsData _self; + final $Res Function(_ProjectViewSettingsData) _then; + + /// Create a copy of ProjectViewSettingsData + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({Object? propertiesOpen = null, Object? timelineHeight = freezed}) { + return _then( + _ProjectViewSettingsData( + propertiesOpen: null == propertiesOpen + ? _self.propertiesOpen + : propertiesOpen // ignore: cast_nullable_to_non_nullable + as bool, + timelineHeight: freezed == timelineHeight + ? _self.timelineHeight + : timelineHeight // ignore: cast_nullable_to_non_nullable + as double?, + ), + ); + } +} + +/// @nodoc +mixin _$TimelineSequenceViewState { + int get playheadTick; + TimelineCamera get camera; + + /// Create a copy of TimelineSequenceViewState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $TimelineSequenceViewStateCopyWith get copyWith => + _$TimelineSequenceViewStateCopyWithImpl( + this as TimelineSequenceViewState, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as TimelineSequenceViewState; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is TimelineSequenceViewState && + (identical(other.playheadTick, _this.playheadTick) || + other.playheadTick == _this.playheadTick) && + (identical(other.camera, _this.camera) || + other.camera == _this.camera)); + } + + @override + int get hashCode { + final _this = this as TimelineSequenceViewState; + return Object.hash(runtimeType, _this.playheadTick, _this.camera); + } + + @override + String toString() { + final _this = this as TimelineSequenceViewState; + return 'TimelineSequenceViewState(playheadTick: ${_this.playheadTick}, camera: ${_this.camera})'; + } +} + +/// @nodoc +abstract mixin class $TimelineSequenceViewStateCopyWith<$Res> { + factory $TimelineSequenceViewStateCopyWith( + TimelineSequenceViewState value, + $Res Function(TimelineSequenceViewState) _then, + ) = _$TimelineSequenceViewStateCopyWithImpl; + @useResult + $Res call({int playheadTick, TimelineCamera camera}); +} + +/// @nodoc +class _$TimelineSequenceViewStateCopyWithImpl<$Res> + implements $TimelineSequenceViewStateCopyWith<$Res> { + _$TimelineSequenceViewStateCopyWithImpl(this._self, this._then); + + final TimelineSequenceViewState _self; + final $Res Function(TimelineSequenceViewState) _then; + + /// Create a copy of TimelineSequenceViewState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({Object? playheadTick = null, Object? camera = null}) { + return _then( + TimelineSequenceViewState( + playheadTick: null == playheadTick + ? _self.playheadTick + : playheadTick // ignore: cast_nullable_to_non_nullable + as int, + camera: null == camera + ? _self.camera + : camera // ignore: cast_nullable_to_non_nullable + as TimelineCamera, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [TimelineSequenceViewState]. +extension TimelineSequenceViewStatePatterns on TimelineSequenceViewState { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_TimelineSequenceViewState value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _TimelineSequenceViewState() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_TimelineSequenceViewState value) $default, + ) { + final _that = this; + switch (_that) { + case _TimelineSequenceViewState(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_TimelineSequenceViewState value)? $default, + ) { + final _that = this; + switch (_that) { + case _TimelineSequenceViewState() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function(int playheadTick, TimelineCamera camera)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _TimelineSequenceViewState() when $default != null: + return $default(_that.playheadTick, _that.camera); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function(int playheadTick, TimelineCamera camera) $default, + ) { + final _that = this; + switch (_that) { + case _TimelineSequenceViewState(): + return $default(_that.playheadTick, _that.camera); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function(int playheadTick, TimelineCamera camera)? $default, + ) { + final _that = this; + switch (_that) { + case _TimelineSequenceViewState() when $default != null: + return $default(_that.playheadTick, _that.camera); + case _: + return null; + } + } +} + +/// @nodoc + +class _TimelineSequenceViewState extends TimelineSequenceViewState { + const _TimelineSequenceViewState({ + required this.playheadTick, + required this.camera, + }) : super._(); + + @override + final int playheadTick; + @override + final TimelineCamera camera; + + /// Create a copy of TimelineSequenceViewState + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$TimelineSequenceViewStateCopyWith<_TimelineSequenceViewState> + get copyWith => + __$TimelineSequenceViewStateCopyWithImpl<_TimelineSequenceViewState>( + this, + _$identity, + ); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _TimelineSequenceViewState && + (identical(other.playheadTick, playheadTick) || + other.playheadTick == playheadTick) && + (identical(other.camera, camera) || other.camera == camera)); + } + + @override + int get hashCode { + return Object.hash(runtimeType, playheadTick, camera); + } + + @override + String toString() { + return 'TimelineSequenceViewState(playheadTick: $playheadTick, camera: $camera)'; + } +} + +/// @nodoc +abstract mixin class _$TimelineSequenceViewStateCopyWith<$Res> + implements $TimelineSequenceViewStateCopyWith<$Res> { + factory _$TimelineSequenceViewStateCopyWith( + _TimelineSequenceViewState value, + $Res Function(_TimelineSequenceViewState) _then, + ) = __$TimelineSequenceViewStateCopyWithImpl; + @override + @useResult + $Res call({int playheadTick, TimelineCamera camera}); +} + +/// @nodoc +class __$TimelineSequenceViewStateCopyWithImpl<$Res> + implements _$TimelineSequenceViewStateCopyWith<$Res> { + __$TimelineSequenceViewStateCopyWithImpl(this._self, this._then); + + final _TimelineSequenceViewState _self; + final $Res Function(_TimelineSequenceViewState) _then; + + /// Create a copy of TimelineSequenceViewState + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({Object? playheadTick = null, Object? camera = null}) { + return _then( + _TimelineSequenceViewState( + playheadTick: null == playheadTick + ? _self.playheadTick + : playheadTick // ignore: cast_nullable_to_non_nullable + as int, + camera: null == camera + ? _self.camera + : camera // ignore: cast_nullable_to_non_nullable + as TimelineCamera, + ), + ); + } +} + +/// @nodoc +mixin _$TimelineViewState { + SequenceId? get activeSequenceId; + Map get sequences; + + /// Create a copy of TimelineViewState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $TimelineViewStateCopyWith get copyWith => + _$TimelineViewStateCopyWithImpl( + this as TimelineViewState, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as TimelineViewState; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is TimelineViewState && + (identical(other.activeSequenceId, _this.activeSequenceId) || + other.activeSequenceId == _this.activeSequenceId) && + const DeepCollectionEquality().equals( + other.sequences, + _this.sequences, + )); + } + + @override + int get hashCode { + final _this = this as TimelineViewState; + return Object.hash( + runtimeType, + _this.activeSequenceId, + const DeepCollectionEquality().hash(_this.sequences), + ); + } + + @override + String toString() { + final _this = this as TimelineViewState; + return 'TimelineViewState(activeSequenceId: ${_this.activeSequenceId}, sequences: ${_this.sequences})'; + } +} + +/// @nodoc +abstract mixin class $TimelineViewStateCopyWith<$Res> { + factory $TimelineViewStateCopyWith( + TimelineViewState value, + $Res Function(TimelineViewState) _then, + ) = _$TimelineViewStateCopyWithImpl; + @useResult + $Res call({ + SequenceId? activeSequenceId, + Map sequences, + }); +} + +/// @nodoc +class _$TimelineViewStateCopyWithImpl<$Res> + implements $TimelineViewStateCopyWith<$Res> { + _$TimelineViewStateCopyWithImpl(this._self, this._then); + + final TimelineViewState _self; + final $Res Function(TimelineViewState) _then; + + /// Create a copy of TimelineViewState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({Object? activeSequenceId = freezed, Object? sequences = null}) { + return _then( + TimelineViewState( + activeSequenceId: freezed == activeSequenceId + ? _self.activeSequenceId + : activeSequenceId // ignore: cast_nullable_to_non_nullable + as SequenceId?, + sequences: null == sequences + ? _self.sequences + : sequences // ignore: cast_nullable_to_non_nullable + as Map, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [TimelineViewState]. +extension TimelineViewStatePatterns on TimelineViewState { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_TimelineViewState value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _TimelineViewState() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_TimelineViewState value) $default, + ) { + final _that = this; + switch (_that) { + case _TimelineViewState(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_TimelineViewState value)? $default, + ) { + final _that = this; + switch (_that) { + case _TimelineViewState() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + SequenceId? activeSequenceId, + Map sequences, + )? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _TimelineViewState() when $default != null: + return $default(_that.activeSequenceId, _that.sequences); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function( + SequenceId? activeSequenceId, + Map sequences, + ) + $default, + ) { + final _that = this; + switch (_that) { + case _TimelineViewState(): + return $default(_that.activeSequenceId, _that.sequences); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + SequenceId? activeSequenceId, + Map sequences, + )? + $default, + ) { + final _that = this; + switch (_that) { + case _TimelineViewState() when $default != null: + return $default(_that.activeSequenceId, _that.sequences); + case _: + return null; + } + } +} + +/// @nodoc + +class _TimelineViewState implements TimelineViewState { + const _TimelineViewState({ + this.activeSequenceId, + Map sequences = const {}, + }) : _sequences = sequences; + + @override + final SequenceId? activeSequenceId; + final Map _sequences; + @override + @JsonKey() + Map get sequences { + if (_sequences is EqualUnmodifiableMapView) return _sequences; + // ignore: implicit_dynamic_type + return EqualUnmodifiableMapView(_sequences); + } + + /// Create a copy of TimelineViewState + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$TimelineViewStateCopyWith<_TimelineViewState> get copyWith => + __$TimelineViewStateCopyWithImpl<_TimelineViewState>(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _TimelineViewState && + (identical(other.activeSequenceId, activeSequenceId) || + other.activeSequenceId == activeSequenceId) && + const DeepCollectionEquality().equals(other.sequences, _sequences)); + } + + @override + int get hashCode { + return Object.hash( + runtimeType, + activeSequenceId, + const DeepCollectionEquality().hash(_sequences), + ); + } + + @override + String toString() { + return 'TimelineViewState(activeSequenceId: $activeSequenceId, sequences: $sequences)'; + } +} + +/// @nodoc +abstract mixin class _$TimelineViewStateCopyWith<$Res> + implements $TimelineViewStateCopyWith<$Res> { + factory _$TimelineViewStateCopyWith( + _TimelineViewState value, + $Res Function(_TimelineViewState) _then, + ) = __$TimelineViewStateCopyWithImpl; + @override + @useResult + $Res call({ + SequenceId? activeSequenceId, + Map sequences, + }); +} + +/// @nodoc +class __$TimelineViewStateCopyWithImpl<$Res> + implements _$TimelineViewStateCopyWith<$Res> { + __$TimelineViewStateCopyWithImpl(this._self, this._then); + + final _TimelineViewState _self; + final $Res Function(_TimelineViewState) _then; + + /// Create a copy of TimelineViewState + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({Object? activeSequenceId = freezed, Object? sequences = null}) { + return _then( + _TimelineViewState( + activeSequenceId: freezed == activeSequenceId + ? _self.activeSequenceId + : activeSequenceId // ignore: cast_nullable_to_non_nullable + as SequenceId?, + sequences: null == sequences + ? _self._sequences + : sequences // ignore: cast_nullable_to_non_nullable + as Map, + ), + ); + } +} diff --git a/lib/persistence/settings/view_settings_repositories.g.dart b/lib/persistence/settings/view_settings_repositories.g.dart new file mode 100644 index 0000000..bf9b235 --- /dev/null +++ b/lib/persistence/settings/view_settings_repositories.g.dart @@ -0,0 +1,163 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'view_settings_repositories.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(workspaceViewSettingsRepository) +final workspaceViewSettingsRepositoryProvider = + WorkspaceViewSettingsRepositoryProvider._(); + +final class WorkspaceViewSettingsRepositoryProvider + extends + $FunctionalProvider< + WorkspaceViewSettingsRepository, + WorkspaceViewSettingsRepository, + WorkspaceViewSettingsRepository + > + with $Provider { + WorkspaceViewSettingsRepositoryProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'workspaceViewSettingsRepositoryProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$workspaceViewSettingsRepositoryHash(); + + @$internal + @override + $ProviderElement $createElement( + $ProviderPointer pointer, + ) => $ProviderElement(pointer); + + @override + WorkspaceViewSettingsRepository create(Ref ref) { + return workspaceViewSettingsRepository(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(WorkspaceViewSettingsRepository value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider( + value, + ), + ); + } +} + +String _$workspaceViewSettingsRepositoryHash() => + r'9e601615e4b1f4a7f28c0c54a8772ed8bad34468'; + +@ProviderFor(projectViewSettingsRepository) +final projectViewSettingsRepositoryProvider = + ProjectViewSettingsRepositoryProvider._(); + +final class ProjectViewSettingsRepositoryProvider + extends + $FunctionalProvider< + ProjectViewSettingsRepository, + ProjectViewSettingsRepository, + ProjectViewSettingsRepository + > + with $Provider { + ProjectViewSettingsRepositoryProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'projectViewSettingsRepositoryProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$projectViewSettingsRepositoryHash(); + + @$internal + @override + $ProviderElement $createElement( + $ProviderPointer pointer, + ) => $ProviderElement(pointer); + + @override + ProjectViewSettingsRepository create(Ref ref) { + return projectViewSettingsRepository(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(ProjectViewSettingsRepository value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider( + value, + ), + ); + } +} + +String _$projectViewSettingsRepositoryHash() => + r'db045471cacb93fa0fdf2f533e02004928f86e99'; + +@ProviderFor(timelineViewSettingsRepository) +final timelineViewSettingsRepositoryProvider = + TimelineViewSettingsRepositoryProvider._(); + +final class TimelineViewSettingsRepositoryProvider + extends + $FunctionalProvider< + TimelineViewSettingsRepository, + TimelineViewSettingsRepository, + TimelineViewSettingsRepository + > + with $Provider { + TimelineViewSettingsRepositoryProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'timelineViewSettingsRepositoryProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$timelineViewSettingsRepositoryHash(); + + @$internal + @override + $ProviderElement $createElement( + $ProviderPointer pointer, + ) => $ProviderElement(pointer); + + @override + TimelineViewSettingsRepository create(Ref ref) { + return timelineViewSettingsRepository(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(TimelineViewSettingsRepository value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider( + value, + ), + ); + } +} + +String _$timelineViewSettingsRepositoryHash() => + r'6ca35cb13ed23fe9b63cae9011152f644c147132'; diff --git a/lib/settings/appearance.dart b/lib/settings/appearance.dart new file mode 100644 index 0000000..084a9ca --- /dev/null +++ b/lib/settings/appearance.dart @@ -0,0 +1 @@ +enum AppAppearance { system, penLight, penDark } diff --git a/lib/settings/language.dart b/lib/settings/language.dart new file mode 100644 index 0000000..5d7ec95 --- /dev/null +++ b/lib/settings/language.dart @@ -0,0 +1,14 @@ +enum AppLanguage { + system, + english, + simplifiedChinese, + traditionalChinese, + japanese, + korean, + french, + german, + spanish, + portuguese, + italian, + russian, +} diff --git a/lib/settings/mcp_settings_value.dart b/lib/settings/mcp_settings_value.dart new file mode 100644 index 0000000..b8bded3 --- /dev/null +++ b/lib/settings/mcp_settings_value.dart @@ -0,0 +1,14 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'mcp_settings_value.freezed.dart'; + +@Freezed(toStringOverride: false) +abstract class McpSettingsValue with _$McpSettingsValue { + const McpSettingsValue._(); + + const factory McpSettingsValue({ + required bool enabled, + required int port, + required String token, + }) = _McpSettingsValue; +} diff --git a/lib/settings/mcp_settings_value.freezed.dart b/lib/settings/mcp_settings_value.freezed.dart new file mode 100644 index 0000000..48ef28e --- /dev/null +++ b/lib/settings/mcp_settings_value.freezed.dart @@ -0,0 +1,340 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'mcp_settings_value.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +T _$identity(T value) => value; + +/// @nodoc +mixin _$McpSettingsValue { + bool get enabled; + int get port; + String get token; + + /// Create a copy of McpSettingsValue + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $McpSettingsValueCopyWith get copyWith => + _$McpSettingsValueCopyWithImpl( + this as McpSettingsValue, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as McpSettingsValue; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is McpSettingsValue && + (identical(other.enabled, _this.enabled) || + other.enabled == _this.enabled) && + (identical(other.port, _this.port) || other.port == _this.port) && + (identical(other.token, _this.token) || + other.token == _this.token)); + } + + @override + int get hashCode { + final _this = this as McpSettingsValue; + return Object.hash(runtimeType, _this.enabled, _this.port, _this.token); + } +} + +/// @nodoc +abstract mixin class $McpSettingsValueCopyWith<$Res> { + factory $McpSettingsValueCopyWith( + McpSettingsValue value, + $Res Function(McpSettingsValue) _then, + ) = _$McpSettingsValueCopyWithImpl; + @useResult + $Res call({bool enabled, int port, String token}); +} + +/// @nodoc +class _$McpSettingsValueCopyWithImpl<$Res> + implements $McpSettingsValueCopyWith<$Res> { + _$McpSettingsValueCopyWithImpl(this._self, this._then); + + final McpSettingsValue _self; + final $Res Function(McpSettingsValue) _then; + + /// Create a copy of McpSettingsValue + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? enabled = null, + Object? port = null, + Object? token = null, + }) { + return _then( + McpSettingsValue( + enabled: null == enabled + ? _self.enabled + : enabled // ignore: cast_nullable_to_non_nullable + as bool, + port: null == port + ? _self.port + : port // ignore: cast_nullable_to_non_nullable + as int, + token: null == token + ? _self.token + : token // ignore: cast_nullable_to_non_nullable + as String, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [McpSettingsValue]. +extension McpSettingsValuePatterns on McpSettingsValue { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_McpSettingsValue value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _McpSettingsValue() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_McpSettingsValue value) $default, + ) { + final _that = this; + switch (_that) { + case _McpSettingsValue(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_McpSettingsValue value)? $default, + ) { + final _that = this; + switch (_that) { + case _McpSettingsValue() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function(bool enabled, int port, String token)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _McpSettingsValue() when $default != null: + return $default(_that.enabled, _that.port, _that.token); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function(bool enabled, int port, String token) $default, + ) { + final _that = this; + switch (_that) { + case _McpSettingsValue(): + return $default(_that.enabled, _that.port, _that.token); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function(bool enabled, int port, String token)? $default, + ) { + final _that = this; + switch (_that) { + case _McpSettingsValue() when $default != null: + return $default(_that.enabled, _that.port, _that.token); + case _: + return null; + } + } +} + +/// @nodoc + +class _McpSettingsValue extends McpSettingsValue { + const _McpSettingsValue({ + required this.enabled, + required this.port, + required this.token, + }) : super._(); + + @override + final bool enabled; + @override + final int port; + @override + final String token; + + /// Create a copy of McpSettingsValue + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$McpSettingsValueCopyWith<_McpSettingsValue> get copyWith => + __$McpSettingsValueCopyWithImpl<_McpSettingsValue>(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _McpSettingsValue && + (identical(other.enabled, enabled) || other.enabled == enabled) && + (identical(other.port, port) || other.port == port) && + (identical(other.token, token) || other.token == token)); + } + + @override + int get hashCode { + return Object.hash(runtimeType, enabled, port, token); + } +} + +/// @nodoc +abstract mixin class _$McpSettingsValueCopyWith<$Res> + implements $McpSettingsValueCopyWith<$Res> { + factory _$McpSettingsValueCopyWith( + _McpSettingsValue value, + $Res Function(_McpSettingsValue) _then, + ) = __$McpSettingsValueCopyWithImpl; + @override + @useResult + $Res call({bool enabled, int port, String token}); +} + +/// @nodoc +class __$McpSettingsValueCopyWithImpl<$Res> + implements _$McpSettingsValueCopyWith<$Res> { + __$McpSettingsValueCopyWithImpl(this._self, this._then); + + final _McpSettingsValue _self; + final $Res Function(_McpSettingsValue) _then; + + /// Create a copy of McpSettingsValue + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? enabled = null, + Object? port = null, + Object? token = null, + }) { + return _then( + _McpSettingsValue( + enabled: null == enabled + ? _self.enabled + : enabled // ignore: cast_nullable_to_non_nullable + as bool, + port: null == port + ? _self.port + : port // ignore: cast_nullable_to_non_nullable + as int, + token: null == token + ? _self.token + : token // ignore: cast_nullable_to_non_nullable + as String, + ), + ); + } +} diff --git a/lib/settings/settings_operation.dart b/lib/settings/settings_operation.dart new file mode 100644 index 0000000..c562841 --- /dev/null +++ b/lib/settings/settings_operation.dart @@ -0,0 +1,29 @@ +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import '../diagnostics/app_diagnostics.dart'; + +part 'settings_operation.g.dart'; + +/// Tracks an operation independently of the configuration currently in effect. +@riverpod +class SettingsOperation extends _$SettingsOperation { + @override + AsyncValue build(String operation) => const AsyncData(null); + + Future run(Future Function() action) async { + if (state.isLoading) return false; + final lease = ref.keepAlive(); + state = const AsyncLoading(); + try { + await action(); + if (ref.mounted) state = const AsyncData(null); + return true; + } catch (error, stack) { + AppDiagnostics.failure('settings', operation, error, stack); + if (ref.mounted) state = AsyncError(error, stack); + return false; + } finally { + lease.close(); + } + } +} diff --git a/lib/settings/settings_operation.g.dart b/lib/settings/settings_operation.g.dart new file mode 100644 index 0000000..429c8b0 --- /dev/null +++ b/lib/settings/settings_operation.g.dart @@ -0,0 +1,116 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'settings_operation.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning +/// Tracks an operation independently of the configuration currently in effect. + +@ProviderFor(SettingsOperation) +final settingsOperationProvider = SettingsOperationFamily._(); + +/// Tracks an operation independently of the configuration currently in effect. +final class SettingsOperationProvider + extends $NotifierProvider> { + /// Tracks an operation independently of the configuration currently in effect. + SettingsOperationProvider._({ + required SettingsOperationFamily super.from, + required String super.argument, + }) : super( + retry: null, + name: r'settingsOperationProvider', + isAutoDispose: true, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$settingsOperationHash(); + + @override + String toString() { + return r'settingsOperationProvider' + '' + '($argument)'; + } + + @$internal + @override + SettingsOperation create() => SettingsOperation(); + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(AsyncValue value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider>(value), + ); + } + + @override + bool operator ==(Object other) { + return other is SettingsOperationProvider && other.argument == argument; + } + + @override + int get hashCode { + return argument.hashCode; + } +} + +String _$settingsOperationHash() => r'af6f16d1729e3729b0f6707862eeb5c8d5654fa2'; + +/// Tracks an operation independently of the configuration currently in effect. + +final class SettingsOperationFamily extends $Family + with + $ClassFamilyOverride< + SettingsOperation, + AsyncValue, + AsyncValue, + AsyncValue, + String + > { + SettingsOperationFamily._() + : super( + retry: null, + name: r'settingsOperationProvider', + dependencies: null, + $allTransitiveDependencies: null, + isAutoDispose: true, + ); + + /// Tracks an operation independently of the configuration currently in effect. + + SettingsOperationProvider call(String operation) => + SettingsOperationProvider._(argument: operation, from: this); + + @override + String toString() => r'settingsOperationProvider'; +} + +/// Tracks an operation independently of the configuration currently in effect. + +abstract class _$SettingsOperation extends $Notifier> { + late final _$args = ref.$arg as String; + String get operation => _$args; + + AsyncValue build(String operation); + @$mustCallSuper + @override + WhenComplete runBuild() { + final ref = this.ref as $Ref, AsyncValue>; + final element = + ref.element + as $ClassProviderElement< + AnyNotifier, AsyncValue>, + AsyncValue, + Object?, + Object? + >; + return element.handleCreate(ref, () => build(_$args)); + } +} diff --git a/lib/settings/settings_write_queue.dart b/lib/settings/settings_write_queue.dart new file mode 100644 index 0000000..8758bf5 --- /dev/null +++ b/lib/settings/settings_write_queue.dart @@ -0,0 +1,10 @@ +/// Runs settings writes in order and allows later writes after a failure. +class SettingsWriteQueue { + Future _tail = Future.value(); + + Future run(Future Function() write) { + final result = _tail.then((_) => write()); + _tail = result.then((_) {}, onError: (Object _, StackTrace _) {}); + return result; + } +} diff --git a/lib/shared/layout/composer_layout.dart b/lib/shared/layout/composer_layout.dart new file mode 100644 index 0000000..403a3c0 --- /dev/null +++ b/lib/shared/layout/composer_layout.dart @@ -0,0 +1,31 @@ +import 'package:cutdex_ui/theme.dart'; + +/// Geometry shared by the composer and its attached project selector. +abstract final class ComposerLayout { + static const maxWidth = 768.0; + static const horizontalInset = 16.0; + static const bottomInset = 16.0; + static const radius = 22.0; + static const controlSize = 28.0; + static const iconSize = 16.0; + static const controlGap = 5.0; + static const inputMinHeight = 62.0; + static const inputMaxHeightFraction = 0.25; + static const utilityInset = 13.0; + static const utilityTopGap = 4.0; + static const utilityVerticalPadding = 5.0; + static const utilityVisibleHeight = controlSize + utilityVerticalPadding * 2; + static const utilityOverlap = radius; + static const composerTopWithUtility = utilityTopGap + utilityVisibleHeight; + static const utilityRadius = 20.0; + + static const menuWidth = 262.0; + static const menuGutter = AppMenuMetrics.gutter; + static const menuContentWidth = menuWidth - menuGutter * 2; + static const menuRowHeight = AppMenuMetrics.rowHeight; + static const menuIconSize = AppMenuMetrics.iconSize; + static const menuIconGap = AppMenuMetrics.iconGap; + static const menuRadius = AppMenuMetrics.radius; + static const menuItemRadius = AppMenuMetrics.itemRadius; + static const menuListMaxHeight = 200.0; +} diff --git a/lib/shared/layout/workspace_layout_metrics.dart b/lib/shared/layout/workspace_layout_metrics.dart new file mode 100644 index 0000000..f8b8c40 --- /dev/null +++ b/lib/shared/layout/workspace_layout_metrics.dart @@ -0,0 +1,20 @@ +abstract final class WorkspaceLayoutMetrics { + static const dualPaneMinimumWidth = 840.0; + + static const sidebarDefaultWidth = 260.0; + static const sidebarMinimumWidth = 240.0; + static const sidebarWidthLimit = 360.0; + static const contentMinimumWidth = 320.0; + + static const timelineDefaultHeightFraction = 0.4; + static const timelineMinimumHeight = 160.0; + + static const mediaPanelWidth = 260.0; + static const propertiesPanelWidth = 320.0; + static const previewMinimumWidth = 160.0; + + static double sidebarMaximumWidth(double availableWidth) => + (availableWidth - contentMinimumWidth) + .clamp(sidebarMinimumWidth, sidebarWidthLimit) + .toDouble(); +} diff --git a/lib/shared/theme/composer_style.dart b/lib/shared/theme/composer_style.dart new file mode 100644 index 0000000..c952ca0 --- /dev/null +++ b/lib/shared/theme/composer_style.dart @@ -0,0 +1,141 @@ +import 'package:flutter/material.dart'; + +import '../layout/composer_layout.dart'; + +import 'package:cutdex_ui/widgets.dart'; +import 'package:cutdex_ui/theme.dart'; + +/// Shared presentation for the composer and its project menu. +abstract final class AppComposerStyle { + static ButtonStyle composerSendButtonStyle(BuildContext context) { + final colors = Theme.of(context).colorScheme; + return ButtonStyle( + minimumSize: const WidgetStatePropertyAll( + Size.square(ComposerLayout.controlSize), + ), + fixedSize: const WidgetStatePropertyAll( + Size.square(ComposerLayout.controlSize), + ), + shape: const WidgetStatePropertyAll(CircleBorder()), + backgroundColor: WidgetStateProperty.resolveWith( + (states) => states.contains(WidgetState.disabled) + ? colors.onSurface.withValues(alpha: 0.12) + : Colors.white, + ), + foregroundColor: WidgetStateProperty.resolveWith( + (states) => states.contains(WidgetState.disabled) + ? colors.onSurface.withValues(alpha: 0.38) + : Colors.black, + ), + ); + } + + static const inputPadding = EdgeInsets.fromLTRB(12, 14, 12, 4); + static const controlsPadding = EdgeInsets.fromLTRB(8, 0, 8, 8); + static const utilityPadding = EdgeInsets.fromLTRB( + 4, + ComposerLayout.utilityVerticalPadding, + 4, + ComposerLayout.utilityVerticalPadding + ComposerLayout.utilityOverlap, + ); + static const menuSeparatorPadding = EdgeInsets.symmetric( + horizontal: 8, + vertical: 4, + ); + static const menuSeparatorThickness = 1.0; + static const menuEmptyPadding = EdgeInsets.all(12); + + static InputDecoration inputDecoration( + BuildContext context, { + required String hintText, + }) => AppTheme.composerInputDecoration.copyWith( + isDense: true, + constraints: const BoxConstraints(minHeight: ComposerLayout.inputMinHeight), + contentPadding: inputPadding, + hintText: hintText, + hintStyle: AppTheme.composerHintStyle(context), + ); + + static ButtonStyle projectMenuItem( + BuildContext context, { + bool secondary = false, + }) { + final colors = Theme.of(context).colorScheme; + return AppMenuStyle.item(context).copyWith( + foregroundColor: WidgetStateProperty.resolveWith( + (states) => states.contains(WidgetState.disabled) + ? Theme.of(context).disabledColor + : secondary + ? colors.onSurfaceVariant + : colors.onSurface, + ), + maximumSize: const WidgetStatePropertyAll( + Size(double.infinity, ComposerLayout.menuRowHeight), + ), + ); + } + + static MenuStyle projectMenu(BuildContext context) { + return AppMenuStyle.panel( + context, + minWidth: ComposerLayout.menuWidth, + ).copyWith( + maximumSize: const WidgetStatePropertyAll( + Size(ComposerLayout.menuWidth, double.infinity), + ), + ); + } + + static InputDecoration projectSearchDecoration( + BuildContext context, { + required String hintText, + }) { + return InputDecoration( + hintText: hintText, + prefixIcon: const Icon(Icons.search, size: ComposerLayout.menuIconSize), + prefixIconConstraints: const BoxConstraints( + minWidth: ComposerLayout.controlSize, + minHeight: ComposerLayout.controlSize, + ), + contentPadding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + isDense: true, + filled: false, + border: InputBorder.none, + enabledBorder: InputBorder.none, + focusedBorder: InputBorder.none, + disabledBorder: InputBorder.none, + hintStyle: AppTheme.composerTextStyle(context) + .copyWith(color: AppSidebarColors.of(context).tertiary), + ); + } + + static ButtonStyle projectTrigger(BuildContext context) { + final colors = Theme.of(context).colorScheme; + return TextButton.styleFrom( + foregroundColor: colors.onSurfaceVariant, + minimumSize: const Size(0, ComposerLayout.controlSize), + maximumSize: const Size(double.infinity, ComposerLayout.controlSize), + visualDensity: VisualDensity.standard, + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + padding: const EdgeInsets.symmetric(horizontal: 10), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), + textStyle: AppTheme.composerTextStyle(context), + ); + } + + static ButtonStyle controlButton(BuildContext context) => + TextButton.styleFrom( + minimumSize: const Size(0, ComposerLayout.controlSize), + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + padding: const EdgeInsets.symmetric(horizontal: 6), + textStyle: AppTheme.composerTextStyle(context), + foregroundColor: AppSidebarColors.of(context).secondary, + ); + static ButtonStyle controlIcon(BuildContext context) => IconButton.styleFrom( + minimumSize: const Size.square(ComposerLayout.controlSize), + maximumSize: const Size.square(ComposerLayout.controlSize), + padding: EdgeInsets.zero, + iconSize: ComposerLayout.iconSize, + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + ); +} diff --git a/lib/shared/widgets/confirm_resource_download_cancel.dart b/lib/shared/widgets/confirm_resource_download_cancel.dart new file mode 100644 index 0000000..94ee994 --- /dev/null +++ b/lib/shared/widgets/confirm_resource_download_cancel.dart @@ -0,0 +1,30 @@ +import 'package:cutdex/l10n/l10n.dart'; +import 'package:flutter/material.dart'; + +import 'package:cutdex_ui/widgets.dart'; + +Future confirmResourceDownloadCancellation(BuildContext context) async { + final confirmed = await showAppDialog( + context: context, + builder: (dialogContext) => AppDialog( + title: dialogContext.l10n.cancelResourceDownloadTitle, + width: 400, + actions: [ + TextButton( + onPressed: () => Navigator.of(dialogContext).pop(false), + child: Text(dialogContext.l10n.continueDownload), + ), + TextButton( + key: const Key('confirm-resource-download-cancel'), + onPressed: () => Navigator.of(dialogContext).pop(true), + style: TextButton.styleFrom( + foregroundColor: Theme.of(dialogContext).colorScheme.error, + ), + child: Text(dialogContext.l10n.cancelDownload), + ), + ], + child: Text(dialogContext.l10n.cancelResourceDownloadMessage), + ), + ); + return confirmed == true; +} diff --git a/lib/shared/widgets/drop_to_add_overlay.dart b/lib/shared/widgets/drop_to_add_overlay.dart new file mode 100644 index 0000000..7542c5e --- /dev/null +++ b/lib/shared/widgets/drop_to_add_overlay.dart @@ -0,0 +1,25 @@ +import 'package:cutdex/l10n/l10n.dart'; +import 'package:flutter/material.dart'; + +import 'package:cutdex_ui/theme.dart'; + +/// Shared drag feedback for the Agent and media panels. +class DropToAddOverlay extends StatelessWidget { + const DropToAddOverlay({super.key}); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return IgnorePointer( + child: ColoredBox( + color: AppTheme.dropOverlayBackground(context), + child: Center( + child: Text( + context.l10n.dropToAdd, + style: theme.textTheme.titleMedium?.copyWith(color: Colors.white), + ), + ), + ), + ); + } +} diff --git a/lib/shared/widgets/processing_resource_download_dialog.dart b/lib/shared/widgets/processing_resource_download_dialog.dart new file mode 100644 index 0000000..fa61724 --- /dev/null +++ b/lib/shared/widgets/processing_resource_download_dialog.dart @@ -0,0 +1,130 @@ +import 'package:cutdex/l10n/l10n.dart'; +import 'package:flutter/material.dart'; + +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex_ui/widgets.dart'; + + +/// Shared layout for downloading a processing resource before a task starts. +class ProcessingResourceDownloadDialog extends StatelessWidget { + const ProcessingResourceDownloadDialog({ + super.key, + required this.title, + required this.description, + required this.resourceName, + required this.downloadSize, + required this.downloading, + required this.paused, + required this.downloadedBytes, + required this.totalBytes, + required this.bytesPerSecond, + required this.onCancel, + required this.onDownload, + required this.onTogglePause, + required this.onBackground, + this.error, + this.downloadButtonKey, + this.pauseButtonKey, + this.backgroundButtonKey, + }); + + final String title; + final String description; + final String resourceName; + final String downloadSize; + final bool downloading; + final bool paused; + final int downloadedBytes; + final int totalBytes; + final int bytesPerSecond; + final VoidCallback onCancel; + final VoidCallback onDownload; + final VoidCallback onTogglePause; + final VoidCallback onBackground; + final String? error; + final Key? downloadButtonKey; + final Key? pauseButtonKey; + final Key? backgroundButtonKey; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final percentage = totalBytes <= 0 + ? 0 + : (downloadedBytes * 100 / totalBytes).floor().clamp(0, 100); + return AppDialog( + title: title, + description: description, + width: 440, + closeLabel: downloading ? context.l10n.downloadInBackground : null, + actions: [ + TextButton( + onPressed: onCancel, + child: Text( + downloading ? context.l10n.cancelDownload : context.l10n.cancel, + ), + ), + if (downloading) + TextButton( + key: pauseButtonKey, + onPressed: onTogglePause, + child: Text( + paused ? context.l10n.resumeDownload : context.l10n.pauseDownload, + ), + ), + FilledButton( + key: downloading ? backgroundButtonKey : downloadButtonKey, + onPressed: downloading ? onBackground : onDownload, + child: Text( + downloading + ? context.l10n.downloadInBackground + : context.l10n.downloadModelAction, + ), + ), + ], + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (!downloading) Text(downloadSize), + if (downloading) ...[ + Row( + children: [ + Expanded( + child: Text( + resourceName, + style: theme.textTheme.bodyMedium?.copyWith( + fontWeight: FontWeight.w500, + ), + ), + ), + Text( + paused ? context.l10n.downloadPaused : '$percentage%', + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + const SizedBox(height: AppSpacing.small), + ResourceDownloadProgress( + downloadedBytes: downloadedBytes, + totalBytes: totalBytes, + bytesPerSecond: bytesPerSecond, + status: '', + paused: paused, + ), + ], + if (error != null) + Padding( + padding: const EdgeInsets.only(top: AppSpacing.compact), + child: Text( + error!, + style: TextStyle(color: theme.colorScheme.error), + ), + ), + ], + ), + ); + } +} diff --git a/lib/workspace/background_task_registry.dart b/lib/workspace/background_task_registry.dart new file mode 100644 index 0000000..c9f6448 --- /dev/null +++ b/lib/workspace/background_task_registry.dart @@ -0,0 +1,81 @@ +import 'package:flutter/foundation.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import 'timeline_session.dart'; + +part 'background_task_registry.g.dart'; +part 'background_task_registry.freezed.dart'; + +@Riverpod(keepAlive: true) +Raw backgroundTaskRegistry(Ref ref) { + final registry = BackgroundTaskRegistry(); + ref.onDispose(registry.dispose); + return registry; +} + +@freezed +abstract class BackgroundTaskSession with _$BackgroundTaskSession { + const factory BackgroundTaskSession({ + required String projectId, + required String projectName, + required String timelineId, + required String timelineName, + required EditorTimelineSession session, + }) = _BackgroundTaskSession; +} + +/// Application-level index of task owners. Tasks remain owned by their editor +/// session; global UI observes them without depending on the visible timeline. +final class BackgroundTaskRegistry extends ChangeNotifier { + final _entries = {}; + bool _disposed = false; + + List get entries => List.unmodifiable(_entries.values); + + int get runningCount => _entries.values.fold( + 0, + (count, entry) => + count + + entry.session.subtitleWorkflows.runningCount + + entry.session.backgroundRemovals.runningCount, + ); + + void register({ + required String projectId, + required String projectName, + required EditorTimelineSession session, + }) { + if (_disposed || _entries.containsKey(session)) return; + _entries[session] = BackgroundTaskSession( + projectId: projectId, + projectName: projectName, + timelineId: session.document.id, + timelineName: session.document.name, + session: session, + ); + session.addListener(_changed); + notifyListeners(); + } + + void unregister(EditorTimelineSession session) { + if (_entries.remove(session) == null) return; + session.removeListener(_changed); + if (!_disposed) notifyListeners(); + } + + void _changed() { + if (!_disposed) notifyListeners(); + } + + @override + void dispose() { + if (_disposed) return; + _disposed = true; + for (final session in _entries.keys) { + session.removeListener(_changed); + } + _entries.clear(); + super.dispose(); + } +} diff --git a/lib/workspace/background_task_registry.freezed.dart b/lib/workspace/background_task_registry.freezed.dart new file mode 100644 index 0000000..319a6ed --- /dev/null +++ b/lib/workspace/background_task_registry.freezed.dart @@ -0,0 +1,483 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'background_task_registry.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +T _$identity(T value) => value; + +/// @nodoc +mixin _$BackgroundTaskSession implements DiagnosticableTreeMixin { + String get projectId; + String get projectName; + String get timelineId; + String get timelineName; + EditorTimelineSession get session; + + /// Create a copy of BackgroundTaskSession + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $BackgroundTaskSessionCopyWith get copyWith => + _$BackgroundTaskSessionCopyWithImpl( + this as BackgroundTaskSession, + _$identity, + ); + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + final _this = this as BackgroundTaskSession; + properties + ..add(DiagnosticsProperty('type', 'BackgroundTaskSession')) + ..add(DiagnosticsProperty('projectId', _this.projectId)) + ..add(DiagnosticsProperty('projectName', _this.projectName)) + ..add(DiagnosticsProperty('timelineId', _this.timelineId)) + ..add(DiagnosticsProperty('timelineName', _this.timelineName)) + ..add(DiagnosticsProperty('session', _this.session)); + } + + @override + bool operator ==(Object other) { + final _this = this as BackgroundTaskSession; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is BackgroundTaskSession && + (identical(other.projectId, _this.projectId) || + other.projectId == _this.projectId) && + (identical(other.projectName, _this.projectName) || + other.projectName == _this.projectName) && + (identical(other.timelineId, _this.timelineId) || + other.timelineId == _this.timelineId) && + (identical(other.timelineName, _this.timelineName) || + other.timelineName == _this.timelineName) && + (identical(other.session, _this.session) || + other.session == _this.session)); + } + + @override + int get hashCode { + final _this = this as BackgroundTaskSession; + return Object.hash( + runtimeType, + _this.projectId, + _this.projectName, + _this.timelineId, + _this.timelineName, + _this.session, + ); + } + + @override + String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { + final _this = this as BackgroundTaskSession; + return 'BackgroundTaskSession(projectId: ${_this.projectId}, projectName: ${_this.projectName}, timelineId: ${_this.timelineId}, timelineName: ${_this.timelineName}, session: ${_this.session})'; + } +} + +/// @nodoc +abstract mixin class $BackgroundTaskSessionCopyWith<$Res> { + factory $BackgroundTaskSessionCopyWith( + BackgroundTaskSession value, + $Res Function(BackgroundTaskSession) _then, + ) = _$BackgroundTaskSessionCopyWithImpl; + @useResult + $Res call({ + String projectId, + String projectName, + String timelineId, + String timelineName, + EditorTimelineSession session, + }); +} + +/// @nodoc +class _$BackgroundTaskSessionCopyWithImpl<$Res> + implements $BackgroundTaskSessionCopyWith<$Res> { + _$BackgroundTaskSessionCopyWithImpl(this._self, this._then); + + final BackgroundTaskSession _self; + final $Res Function(BackgroundTaskSession) _then; + + /// Create a copy of BackgroundTaskSession + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? projectId = null, + Object? projectName = null, + Object? timelineId = null, + Object? timelineName = null, + Object? session = null, + }) { + return _then( + BackgroundTaskSession( + projectId: null == projectId + ? _self.projectId + : projectId // ignore: cast_nullable_to_non_nullable + as String, + projectName: null == projectName + ? _self.projectName + : projectName // ignore: cast_nullable_to_non_nullable + as String, + timelineId: null == timelineId + ? _self.timelineId + : timelineId // ignore: cast_nullable_to_non_nullable + as String, + timelineName: null == timelineName + ? _self.timelineName + : timelineName // ignore: cast_nullable_to_non_nullable + as String, + session: null == session + ? _self.session + : session // ignore: cast_nullable_to_non_nullable + as EditorTimelineSession, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [BackgroundTaskSession]. +extension BackgroundTaskSessionPatterns on BackgroundTaskSession { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_BackgroundTaskSession value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _BackgroundTaskSession() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_BackgroundTaskSession value) $default, + ) { + final _that = this; + switch (_that) { + case _BackgroundTaskSession(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_BackgroundTaskSession value)? $default, + ) { + final _that = this; + switch (_that) { + case _BackgroundTaskSession() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + String projectId, + String projectName, + String timelineId, + String timelineName, + EditorTimelineSession session, + )? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _BackgroundTaskSession() when $default != null: + return $default( + _that.projectId, + _that.projectName, + _that.timelineId, + _that.timelineName, + _that.session, + ); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function( + String projectId, + String projectName, + String timelineId, + String timelineName, + EditorTimelineSession session, + ) + $default, + ) { + final _that = this; + switch (_that) { + case _BackgroundTaskSession(): + return $default( + _that.projectId, + _that.projectName, + _that.timelineId, + _that.timelineName, + _that.session, + ); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + String projectId, + String projectName, + String timelineId, + String timelineName, + EditorTimelineSession session, + )? + $default, + ) { + final _that = this; + switch (_that) { + case _BackgroundTaskSession() when $default != null: + return $default( + _that.projectId, + _that.projectName, + _that.timelineId, + _that.timelineName, + _that.session, + ); + case _: + return null; + } + } +} + +/// @nodoc + +class _BackgroundTaskSession + with DiagnosticableTreeMixin + implements BackgroundTaskSession { + const _BackgroundTaskSession({ + required this.projectId, + required this.projectName, + required this.timelineId, + required this.timelineName, + required this.session, + }); + + @override + final String projectId; + @override + final String projectName; + @override + final String timelineId; + @override + final String timelineName; + @override + final EditorTimelineSession session; + + /// Create a copy of BackgroundTaskSession + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$BackgroundTaskSessionCopyWith<_BackgroundTaskSession> get copyWith => + __$BackgroundTaskSessionCopyWithImpl<_BackgroundTaskSession>( + this, + _$identity, + ); + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + properties + ..add(DiagnosticsProperty('type', 'BackgroundTaskSession')) + ..add(DiagnosticsProperty('projectId', projectId)) + ..add(DiagnosticsProperty('projectName', projectName)) + ..add(DiagnosticsProperty('timelineId', timelineId)) + ..add(DiagnosticsProperty('timelineName', timelineName)) + ..add(DiagnosticsProperty('session', session)); + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _BackgroundTaskSession && + (identical(other.projectId, projectId) || + other.projectId == projectId) && + (identical(other.projectName, projectName) || + other.projectName == projectName) && + (identical(other.timelineId, timelineId) || + other.timelineId == timelineId) && + (identical(other.timelineName, timelineName) || + other.timelineName == timelineName) && + (identical(other.session, session) || other.session == session)); + } + + @override + int get hashCode { + return Object.hash( + runtimeType, + projectId, + projectName, + timelineId, + timelineName, + session, + ); + } + + @override + String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { + return 'BackgroundTaskSession(projectId: $projectId, projectName: $projectName, timelineId: $timelineId, timelineName: $timelineName, session: $session)'; + } +} + +/// @nodoc +abstract mixin class _$BackgroundTaskSessionCopyWith<$Res> + implements $BackgroundTaskSessionCopyWith<$Res> { + factory _$BackgroundTaskSessionCopyWith( + _BackgroundTaskSession value, + $Res Function(_BackgroundTaskSession) _then, + ) = __$BackgroundTaskSessionCopyWithImpl; + @override + @useResult + $Res call({ + String projectId, + String projectName, + String timelineId, + String timelineName, + EditorTimelineSession session, + }); +} + +/// @nodoc +class __$BackgroundTaskSessionCopyWithImpl<$Res> + implements _$BackgroundTaskSessionCopyWith<$Res> { + __$BackgroundTaskSessionCopyWithImpl(this._self, this._then); + + final _BackgroundTaskSession _self; + final $Res Function(_BackgroundTaskSession) _then; + + /// Create a copy of BackgroundTaskSession + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? projectId = null, + Object? projectName = null, + Object? timelineId = null, + Object? timelineName = null, + Object? session = null, + }) { + return _then( + _BackgroundTaskSession( + projectId: null == projectId + ? _self.projectId + : projectId // ignore: cast_nullable_to_non_nullable + as String, + projectName: null == projectName + ? _self.projectName + : projectName // ignore: cast_nullable_to_non_nullable + as String, + timelineId: null == timelineId + ? _self.timelineId + : timelineId // ignore: cast_nullable_to_non_nullable + as String, + timelineName: null == timelineName + ? _self.timelineName + : timelineName // ignore: cast_nullable_to_non_nullable + as String, + session: null == session + ? _self.session + : session // ignore: cast_nullable_to_non_nullable + as EditorTimelineSession, + ), + ); + } +} diff --git a/lib/workspace/background_task_registry.g.dart b/lib/workspace/background_task_registry.g.dart new file mode 100644 index 0000000..ea4d4f3 --- /dev/null +++ b/lib/workspace/background_task_registry.g.dart @@ -0,0 +1,58 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'background_task_registry.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(backgroundTaskRegistry) +final backgroundTaskRegistryProvider = BackgroundTaskRegistryProvider._(); + +final class BackgroundTaskRegistryProvider + extends + $FunctionalProvider< + Raw, + Raw, + Raw + > + with $Provider> { + BackgroundTaskRegistryProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'backgroundTaskRegistryProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$backgroundTaskRegistryHash(); + + @$internal + @override + $ProviderElement> $createElement( + $ProviderPointer pointer, + ) => $ProviderElement(pointer); + + @override + Raw create(Ref ref) { + return backgroundTaskRegistry(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(Raw value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider>(value), + ); + } +} + +String _$backgroundTaskRegistryHash() => + r'efee10c01b9a917cbf9b5692c633d13c8de4394c'; diff --git a/lib/workspace/background_task_state.dart b/lib/workspace/background_task_state.dart new file mode 100644 index 0000000..5d81c14 --- /dev/null +++ b/lib/workspace/background_task_state.dart @@ -0,0 +1,205 @@ +import 'package:cutdex_sdk/editor.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import 'background_task_registry.dart'; +import 'timeline_session.dart'; + +part 'background_task_state.g.dart'; +part 'background_task_state.freezed.dart'; + +@freezed +abstract class SubtitleTaskEntry with _$SubtitleTaskEntry { + const factory SubtitleTaskEntry({ + required BackgroundTaskSession owner, + required SubtitleBackgroundTask job, + required TranscriptionStatus status, + required bool terminal, + required bool followingUp, + required String name, + required String sourceLanguage, + required String targetLanguage, + required bool hasTranslation, + required bool recognitionTerminal, + required bool recognitionAvailable, + required bool translationAvailable, + @Default([]) List recentCues, + @Default([]) List resultCues, + int? completed, + int? total, + String? error, + @Default(0) int recognizedCues, + @Default(0) int translatedCues, + }) = _SubtitleTaskEntry; +} + +@freezed +abstract class RemovalTaskEntry with _$RemovalTaskEntry { + const factory RemovalTaskEntry({ + required BackgroundTaskSession owner, + required BackgroundRemovalTask task, + required BackgroundRemovalStatus status, + required String name, + required bool terminal, + int? completed, + int? total, + String? error, + }) = _RemovalTaskEntry; +} + +@freezed +abstract class BackgroundTasksSnapshot with _$BackgroundTasksSnapshot { + const factory BackgroundTasksSnapshot({ + @Default([]) List subtitles, + @Default([]) List removals, + @Default(0) int runningCount, + }) = _BackgroundTasksSnapshot; +} + +@riverpod +class BackgroundTasks extends _$BackgroundTasks { + final _observed = {}; + @override + BackgroundTasksSnapshot build({ + BackgroundTaskRegistry? registry, + EditorTimelineSession? session, + }) { + assert(registry != null || session != null); + registry?.addListener(_changed); + ref.onDispose(() { + registry?.removeListener(_changed); + for (final owner in _observed) { + owner.removeListener(_changed); + } + _observed.clear(); + }); + return _snapshot(); + } + + void _changed() { + if (ref.mounted) state = _snapshot(); + } + + BackgroundTasksSnapshot _snapshot() { + final owners = + registry?.entries ?? + [ + BackgroundTaskSession( + projectId: '', + projectName: '', + timelineId: session!.document.id, + timelineName: session!.document.name, + session: session!, + ), + ]; + // Registry already observes its sessions; a standalone task view needs its own listener. + final next = registry == null + ? owners.map((owner) => owner.session).toSet() + : {}; + for (final owner in _observed.difference(next)) { + owner.removeListener(_changed); + } + for (final owner in next.difference(_observed)) { + owner.addListener(_changed); + } + _observed + ..clear() + ..addAll(next); + final subtitles = []; + final removals = []; + var runningCount = 0; + for (final owner in owners) { + final timeline = owner.session; + runningCount += + timeline.subtitleWorkflows.runningCount + + timeline.backgroundRemovals.runningCount; + final jobs = timeline.subtitleWorkflows.tasks; + final ids = jobs.map((job) => job.recognition.id).toSet(); + final sequence = timeline.activeSequenceId; + if (sequence != null) { + for (final task + in timeline.transcriptions?.tasks ?? []) { + if (ids.contains(task.id)) continue; + final translation = timeline.transcriptions?.translationTasks + .where( + (item) => + item.command.source == task.result?.subtitles.toFilePath(), + ) + .lastOrNull; + subtitles.add( + _subtitle( + owner, + SubtitleBackgroundTask( + id: task.id, + sequence: sequence, + name: task.command.mediaId, + recognition: task, + targetLanguage: translation?.command.targetLanguage ?? 'none', + translation: translation, + ), + ), + ); + } + } + subtitles.addAll(jobs.map((job) => _subtitle(owner, job))); + removals.addAll( + timeline.backgroundRemovals.tasks.reversed.map( + (task) => RemovalTaskEntry( + owner: owner, + task: task, + status: task.status, + name: task.name, + terminal: task.terminal, + completed: task.progress?.completed, + total: task.progress?.total, + error: task.error, + ), + ), + ); + } + return BackgroundTasksSnapshot( + subtitles: subtitles, + removals: removals, + runningCount: runningCount, + ); + } + + SubtitleTaskEntry _subtitle( + BackgroundTaskSession owner, + SubtitleBackgroundTask job, + ) => SubtitleTaskEntry( + owner: owner, + job: job, + status: job.status, + terminal: job.terminal, + followingUp: job.followingUp, + name: job.name, + sourceLanguage: job.recognition.command.language, + targetLanguage: job.targetLanguage, + hasTranslation: job.translation != null, + recognitionTerminal: job.recognition.terminal, + recognitionAvailable: job.recognition.result != null, + translationAvailable: job.translation?.result != null, + recentCues: job.recognition.timelineCues.reversed + .take(3) + .toList() + .reversed + .map((cue) => cue.text) + .toList(), + resultCues: + job.translation?.result?.document.cues + .map((cue) => cue.text) + .toList() ?? + job.recognition.result?.cues.map((cue) => cue.text).toList() ?? + [], + completed: + job.translation?.progress?.completed ?? + job.recognition.progress?.completed, + total: job.translation?.progress?.total ?? job.recognition.progress?.total, + error: job.error ?? job.translation?.error ?? job.recognition.error, + recognizedCues: + job.recognition.result?.cues.length ?? + job.recognition.timelineCues.length, + translatedCues: job.translation?.result?.document.cues.length ?? 0, + ); +} diff --git a/lib/workspace/background_task_state.freezed.dart b/lib/workspace/background_task_state.freezed.dart new file mode 100644 index 0000000..61acd6b --- /dev/null +++ b/lib/workspace/background_task_state.freezed.dart @@ -0,0 +1,1839 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'background_task_state.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +T _$identity(T value) => value; + +/// @nodoc +mixin _$SubtitleTaskEntry { + BackgroundTaskSession get owner; + SubtitleBackgroundTask get job; + TranscriptionStatus get status; + bool get terminal; + bool get followingUp; + String get name; + String get sourceLanguage; + String get targetLanguage; + bool get hasTranslation; + bool get recognitionTerminal; + bool get recognitionAvailable; + bool get translationAvailable; + List get recentCues; + List get resultCues; + int? get completed; + int? get total; + String? get error; + int get recognizedCues; + int get translatedCues; + + /// Create a copy of SubtitleTaskEntry + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $SubtitleTaskEntryCopyWith get copyWith => + _$SubtitleTaskEntryCopyWithImpl( + this as SubtitleTaskEntry, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as SubtitleTaskEntry; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is SubtitleTaskEntry && + (identical(other.owner, _this.owner) || + other.owner == _this.owner) && + (identical(other.job, _this.job) || other.job == _this.job) && + (identical(other.status, _this.status) || + other.status == _this.status) && + (identical(other.terminal, _this.terminal) || + other.terminal == _this.terminal) && + (identical(other.followingUp, _this.followingUp) || + other.followingUp == _this.followingUp) && + (identical(other.name, _this.name) || other.name == _this.name) && + (identical(other.sourceLanguage, _this.sourceLanguage) || + other.sourceLanguage == _this.sourceLanguage) && + (identical(other.targetLanguage, _this.targetLanguage) || + other.targetLanguage == _this.targetLanguage) && + (identical(other.hasTranslation, _this.hasTranslation) || + other.hasTranslation == _this.hasTranslation) && + (identical(other.recognitionTerminal, _this.recognitionTerminal) || + other.recognitionTerminal == _this.recognitionTerminal) && + (identical( + other.recognitionAvailable, + _this.recognitionAvailable, + ) || + other.recognitionAvailable == _this.recognitionAvailable) && + (identical( + other.translationAvailable, + _this.translationAvailable, + ) || + other.translationAvailable == _this.translationAvailable) && + const DeepCollectionEquality().equals( + other.recentCues, + _this.recentCues, + ) && + const DeepCollectionEquality().equals( + other.resultCues, + _this.resultCues, + ) && + (identical(other.completed, _this.completed) || + other.completed == _this.completed) && + (identical(other.total, _this.total) || + other.total == _this.total) && + (identical(other.error, _this.error) || + other.error == _this.error) && + (identical(other.recognizedCues, _this.recognizedCues) || + other.recognizedCues == _this.recognizedCues) && + (identical(other.translatedCues, _this.translatedCues) || + other.translatedCues == _this.translatedCues)); + } + + @override + int get hashCode { + final _this = this as SubtitleTaskEntry; + return Object.hashAll([ + runtimeType, + _this.owner, + _this.job, + _this.status, + _this.terminal, + _this.followingUp, + _this.name, + _this.sourceLanguage, + _this.targetLanguage, + _this.hasTranslation, + _this.recognitionTerminal, + _this.recognitionAvailable, + _this.translationAvailable, + const DeepCollectionEquality().hash(_this.recentCues), + const DeepCollectionEquality().hash(_this.resultCues), + _this.completed, + _this.total, + _this.error, + _this.recognizedCues, + _this.translatedCues, + ]); + } + + @override + String toString() { + final _this = this as SubtitleTaskEntry; + return 'SubtitleTaskEntry(owner: ${_this.owner}, job: ${_this.job}, status: ${_this.status}, terminal: ${_this.terminal}, followingUp: ${_this.followingUp}, name: ${_this.name}, sourceLanguage: ${_this.sourceLanguage}, targetLanguage: ${_this.targetLanguage}, hasTranslation: ${_this.hasTranslation}, recognitionTerminal: ${_this.recognitionTerminal}, recognitionAvailable: ${_this.recognitionAvailable}, translationAvailable: ${_this.translationAvailable}, recentCues: ${_this.recentCues}, resultCues: ${_this.resultCues}, completed: ${_this.completed}, total: ${_this.total}, error: ${_this.error}, recognizedCues: ${_this.recognizedCues}, translatedCues: ${_this.translatedCues})'; + } +} + +/// @nodoc +abstract mixin class $SubtitleTaskEntryCopyWith<$Res> { + factory $SubtitleTaskEntryCopyWith( + SubtitleTaskEntry value, + $Res Function(SubtitleTaskEntry) _then, + ) = _$SubtitleTaskEntryCopyWithImpl; + @useResult + $Res call({ + BackgroundTaskSession owner, + SubtitleBackgroundTask job, + TranscriptionStatus status, + bool terminal, + bool followingUp, + String name, + String sourceLanguage, + String targetLanguage, + bool hasTranslation, + bool recognitionTerminal, + bool recognitionAvailable, + bool translationAvailable, + List recentCues, + List resultCues, + int? completed, + int? total, + String? error, + int recognizedCues, + int translatedCues, + }); + + $BackgroundTaskSessionCopyWith<$Res> get owner; +} + +/// @nodoc +class _$SubtitleTaskEntryCopyWithImpl<$Res> + implements $SubtitleTaskEntryCopyWith<$Res> { + _$SubtitleTaskEntryCopyWithImpl(this._self, this._then); + + final SubtitleTaskEntry _self; + final $Res Function(SubtitleTaskEntry) _then; + + /// Create a copy of SubtitleTaskEntry + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? owner = null, + Object? job = null, + Object? status = null, + Object? terminal = null, + Object? followingUp = null, + Object? name = null, + Object? sourceLanguage = null, + Object? targetLanguage = null, + Object? hasTranslation = null, + Object? recognitionTerminal = null, + Object? recognitionAvailable = null, + Object? translationAvailable = null, + Object? recentCues = null, + Object? resultCues = null, + Object? completed = freezed, + Object? total = freezed, + Object? error = freezed, + Object? recognizedCues = null, + Object? translatedCues = null, + }) { + return _then( + SubtitleTaskEntry( + owner: null == owner + ? _self.owner + : owner // ignore: cast_nullable_to_non_nullable + as BackgroundTaskSession, + job: null == job + ? _self.job + : job // ignore: cast_nullable_to_non_nullable + as SubtitleBackgroundTask, + status: null == status + ? _self.status + : status // ignore: cast_nullable_to_non_nullable + as TranscriptionStatus, + terminal: null == terminal + ? _self.terminal + : terminal // ignore: cast_nullable_to_non_nullable + as bool, + followingUp: null == followingUp + ? _self.followingUp + : followingUp // ignore: cast_nullable_to_non_nullable + as bool, + name: null == name + ? _self.name + : name // ignore: cast_nullable_to_non_nullable + as String, + sourceLanguage: null == sourceLanguage + ? _self.sourceLanguage + : sourceLanguage // ignore: cast_nullable_to_non_nullable + as String, + targetLanguage: null == targetLanguage + ? _self.targetLanguage + : targetLanguage // ignore: cast_nullable_to_non_nullable + as String, + hasTranslation: null == hasTranslation + ? _self.hasTranslation + : hasTranslation // ignore: cast_nullable_to_non_nullable + as bool, + recognitionTerminal: null == recognitionTerminal + ? _self.recognitionTerminal + : recognitionTerminal // ignore: cast_nullable_to_non_nullable + as bool, + recognitionAvailable: null == recognitionAvailable + ? _self.recognitionAvailable + : recognitionAvailable // ignore: cast_nullable_to_non_nullable + as bool, + translationAvailable: null == translationAvailable + ? _self.translationAvailable + : translationAvailable // ignore: cast_nullable_to_non_nullable + as bool, + recentCues: null == recentCues + ? _self.recentCues + : recentCues // ignore: cast_nullable_to_non_nullable + as List, + resultCues: null == resultCues + ? _self.resultCues + : resultCues // ignore: cast_nullable_to_non_nullable + as List, + completed: freezed == completed + ? _self.completed + : completed // ignore: cast_nullable_to_non_nullable + as int?, + total: freezed == total + ? _self.total + : total // ignore: cast_nullable_to_non_nullable + as int?, + error: freezed == error + ? _self.error + : error // ignore: cast_nullable_to_non_nullable + as String?, + recognizedCues: null == recognizedCues + ? _self.recognizedCues + : recognizedCues // ignore: cast_nullable_to_non_nullable + as int, + translatedCues: null == translatedCues + ? _self.translatedCues + : translatedCues // ignore: cast_nullable_to_non_nullable + as int, + ), + ); + } + + /// Create a copy of SubtitleTaskEntry + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $BackgroundTaskSessionCopyWith<$Res> get owner { + return $BackgroundTaskSessionCopyWith<$Res>(_self.owner, (value) { + return _then(_self.copyWith(owner: value)); + }); + } +} + +/// Adds pattern-matching-related methods to [SubtitleTaskEntry]. +extension SubtitleTaskEntryPatterns on SubtitleTaskEntry { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_SubtitleTaskEntry value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _SubtitleTaskEntry() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_SubtitleTaskEntry value) $default, + ) { + final _that = this; + switch (_that) { + case _SubtitleTaskEntry(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_SubtitleTaskEntry value)? $default, + ) { + final _that = this; + switch (_that) { + case _SubtitleTaskEntry() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + BackgroundTaskSession owner, + SubtitleBackgroundTask job, + TranscriptionStatus status, + bool terminal, + bool followingUp, + String name, + String sourceLanguage, + String targetLanguage, + bool hasTranslation, + bool recognitionTerminal, + bool recognitionAvailable, + bool translationAvailable, + List recentCues, + List resultCues, + int? completed, + int? total, + String? error, + int recognizedCues, + int translatedCues, + )? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _SubtitleTaskEntry() when $default != null: + return $default( + _that.owner, + _that.job, + _that.status, + _that.terminal, + _that.followingUp, + _that.name, + _that.sourceLanguage, + _that.targetLanguage, + _that.hasTranslation, + _that.recognitionTerminal, + _that.recognitionAvailable, + _that.translationAvailable, + _that.recentCues, + _that.resultCues, + _that.completed, + _that.total, + _that.error, + _that.recognizedCues, + _that.translatedCues, + ); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function( + BackgroundTaskSession owner, + SubtitleBackgroundTask job, + TranscriptionStatus status, + bool terminal, + bool followingUp, + String name, + String sourceLanguage, + String targetLanguage, + bool hasTranslation, + bool recognitionTerminal, + bool recognitionAvailable, + bool translationAvailable, + List recentCues, + List resultCues, + int? completed, + int? total, + String? error, + int recognizedCues, + int translatedCues, + ) + $default, + ) { + final _that = this; + switch (_that) { + case _SubtitleTaskEntry(): + return $default( + _that.owner, + _that.job, + _that.status, + _that.terminal, + _that.followingUp, + _that.name, + _that.sourceLanguage, + _that.targetLanguage, + _that.hasTranslation, + _that.recognitionTerminal, + _that.recognitionAvailable, + _that.translationAvailable, + _that.recentCues, + _that.resultCues, + _that.completed, + _that.total, + _that.error, + _that.recognizedCues, + _that.translatedCues, + ); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + BackgroundTaskSession owner, + SubtitleBackgroundTask job, + TranscriptionStatus status, + bool terminal, + bool followingUp, + String name, + String sourceLanguage, + String targetLanguage, + bool hasTranslation, + bool recognitionTerminal, + bool recognitionAvailable, + bool translationAvailable, + List recentCues, + List resultCues, + int? completed, + int? total, + String? error, + int recognizedCues, + int translatedCues, + )? + $default, + ) { + final _that = this; + switch (_that) { + case _SubtitleTaskEntry() when $default != null: + return $default( + _that.owner, + _that.job, + _that.status, + _that.terminal, + _that.followingUp, + _that.name, + _that.sourceLanguage, + _that.targetLanguage, + _that.hasTranslation, + _that.recognitionTerminal, + _that.recognitionAvailable, + _that.translationAvailable, + _that.recentCues, + _that.resultCues, + _that.completed, + _that.total, + _that.error, + _that.recognizedCues, + _that.translatedCues, + ); + case _: + return null; + } + } +} + +/// @nodoc + +class _SubtitleTaskEntry implements SubtitleTaskEntry { + const _SubtitleTaskEntry({ + required this.owner, + required this.job, + required this.status, + required this.terminal, + required this.followingUp, + required this.name, + required this.sourceLanguage, + required this.targetLanguage, + required this.hasTranslation, + required this.recognitionTerminal, + required this.recognitionAvailable, + required this.translationAvailable, + List recentCues = const [], + List resultCues = const [], + this.completed, + this.total, + this.error, + this.recognizedCues = 0, + this.translatedCues = 0, + }) : _recentCues = recentCues, + _resultCues = resultCues; + + @override + final BackgroundTaskSession owner; + @override + final SubtitleBackgroundTask job; + @override + final TranscriptionStatus status; + @override + final bool terminal; + @override + final bool followingUp; + @override + final String name; + @override + final String sourceLanguage; + @override + final String targetLanguage; + @override + final bool hasTranslation; + @override + final bool recognitionTerminal; + @override + final bool recognitionAvailable; + @override + final bool translationAvailable; + final List _recentCues; + @override + @JsonKey() + List get recentCues { + if (_recentCues is EqualUnmodifiableListView) return _recentCues; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_recentCues); + } + + final List _resultCues; + @override + @JsonKey() + List get resultCues { + if (_resultCues is EqualUnmodifiableListView) return _resultCues; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_resultCues); + } + + @override + final int? completed; + @override + final int? total; + @override + final String? error; + @override + @JsonKey() + final int recognizedCues; + @override + @JsonKey() + final int translatedCues; + + /// Create a copy of SubtitleTaskEntry + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$SubtitleTaskEntryCopyWith<_SubtitleTaskEntry> get copyWith => + __$SubtitleTaskEntryCopyWithImpl<_SubtitleTaskEntry>(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _SubtitleTaskEntry && + (identical(other.owner, owner) || other.owner == owner) && + (identical(other.job, job) || other.job == job) && + (identical(other.status, status) || other.status == status) && + (identical(other.terminal, terminal) || + other.terminal == terminal) && + (identical(other.followingUp, followingUp) || + other.followingUp == followingUp) && + (identical(other.name, name) || other.name == name) && + (identical(other.sourceLanguage, sourceLanguage) || + other.sourceLanguage == sourceLanguage) && + (identical(other.targetLanguage, targetLanguage) || + other.targetLanguage == targetLanguage) && + (identical(other.hasTranslation, hasTranslation) || + other.hasTranslation == hasTranslation) && + (identical(other.recognitionTerminal, recognitionTerminal) || + other.recognitionTerminal == recognitionTerminal) && + (identical(other.recognitionAvailable, recognitionAvailable) || + other.recognitionAvailable == recognitionAvailable) && + (identical(other.translationAvailable, translationAvailable) || + other.translationAvailable == translationAvailable) && + const DeepCollectionEquality().equals( + other.recentCues, + _recentCues, + ) && + const DeepCollectionEquality().equals( + other.resultCues, + _resultCues, + ) && + (identical(other.completed, completed) || + other.completed == completed) && + (identical(other.total, total) || other.total == total) && + (identical(other.error, error) || other.error == error) && + (identical(other.recognizedCues, recognizedCues) || + other.recognizedCues == recognizedCues) && + (identical(other.translatedCues, translatedCues) || + other.translatedCues == translatedCues)); + } + + @override + int get hashCode { + return Object.hashAll([ + runtimeType, + owner, + job, + status, + terminal, + followingUp, + name, + sourceLanguage, + targetLanguage, + hasTranslation, + recognitionTerminal, + recognitionAvailable, + translationAvailable, + const DeepCollectionEquality().hash(_recentCues), + const DeepCollectionEquality().hash(_resultCues), + completed, + total, + error, + recognizedCues, + translatedCues, + ]); + } + + @override + String toString() { + return 'SubtitleTaskEntry(owner: $owner, job: $job, status: $status, terminal: $terminal, followingUp: $followingUp, name: $name, sourceLanguage: $sourceLanguage, targetLanguage: $targetLanguage, hasTranslation: $hasTranslation, recognitionTerminal: $recognitionTerminal, recognitionAvailable: $recognitionAvailable, translationAvailable: $translationAvailable, recentCues: $recentCues, resultCues: $resultCues, completed: $completed, total: $total, error: $error, recognizedCues: $recognizedCues, translatedCues: $translatedCues)'; + } +} + +/// @nodoc +abstract mixin class _$SubtitleTaskEntryCopyWith<$Res> + implements $SubtitleTaskEntryCopyWith<$Res> { + factory _$SubtitleTaskEntryCopyWith( + _SubtitleTaskEntry value, + $Res Function(_SubtitleTaskEntry) _then, + ) = __$SubtitleTaskEntryCopyWithImpl; + @override + @useResult + $Res call({ + BackgroundTaskSession owner, + SubtitleBackgroundTask job, + TranscriptionStatus status, + bool terminal, + bool followingUp, + String name, + String sourceLanguage, + String targetLanguage, + bool hasTranslation, + bool recognitionTerminal, + bool recognitionAvailable, + bool translationAvailable, + List recentCues, + List resultCues, + int? completed, + int? total, + String? error, + int recognizedCues, + int translatedCues, + }); + + @override + $BackgroundTaskSessionCopyWith<$Res> get owner; +} + +/// @nodoc +class __$SubtitleTaskEntryCopyWithImpl<$Res> + implements _$SubtitleTaskEntryCopyWith<$Res> { + __$SubtitleTaskEntryCopyWithImpl(this._self, this._then); + + final _SubtitleTaskEntry _self; + final $Res Function(_SubtitleTaskEntry) _then; + + /// Create a copy of SubtitleTaskEntry + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? owner = null, + Object? job = null, + Object? status = null, + Object? terminal = null, + Object? followingUp = null, + Object? name = null, + Object? sourceLanguage = null, + Object? targetLanguage = null, + Object? hasTranslation = null, + Object? recognitionTerminal = null, + Object? recognitionAvailable = null, + Object? translationAvailable = null, + Object? recentCues = null, + Object? resultCues = null, + Object? completed = freezed, + Object? total = freezed, + Object? error = freezed, + Object? recognizedCues = null, + Object? translatedCues = null, + }) { + return _then( + _SubtitleTaskEntry( + owner: null == owner + ? _self.owner + : owner // ignore: cast_nullable_to_non_nullable + as BackgroundTaskSession, + job: null == job + ? _self.job + : job // ignore: cast_nullable_to_non_nullable + as SubtitleBackgroundTask, + status: null == status + ? _self.status + : status // ignore: cast_nullable_to_non_nullable + as TranscriptionStatus, + terminal: null == terminal + ? _self.terminal + : terminal // ignore: cast_nullable_to_non_nullable + as bool, + followingUp: null == followingUp + ? _self.followingUp + : followingUp // ignore: cast_nullable_to_non_nullable + as bool, + name: null == name + ? _self.name + : name // ignore: cast_nullable_to_non_nullable + as String, + sourceLanguage: null == sourceLanguage + ? _self.sourceLanguage + : sourceLanguage // ignore: cast_nullable_to_non_nullable + as String, + targetLanguage: null == targetLanguage + ? _self.targetLanguage + : targetLanguage // ignore: cast_nullable_to_non_nullable + as String, + hasTranslation: null == hasTranslation + ? _self.hasTranslation + : hasTranslation // ignore: cast_nullable_to_non_nullable + as bool, + recognitionTerminal: null == recognitionTerminal + ? _self.recognitionTerminal + : recognitionTerminal // ignore: cast_nullable_to_non_nullable + as bool, + recognitionAvailable: null == recognitionAvailable + ? _self.recognitionAvailable + : recognitionAvailable // ignore: cast_nullable_to_non_nullable + as bool, + translationAvailable: null == translationAvailable + ? _self.translationAvailable + : translationAvailable // ignore: cast_nullable_to_non_nullable + as bool, + recentCues: null == recentCues + ? _self._recentCues + : recentCues // ignore: cast_nullable_to_non_nullable + as List, + resultCues: null == resultCues + ? _self._resultCues + : resultCues // ignore: cast_nullable_to_non_nullable + as List, + completed: freezed == completed + ? _self.completed + : completed // ignore: cast_nullable_to_non_nullable + as int?, + total: freezed == total + ? _self.total + : total // ignore: cast_nullable_to_non_nullable + as int?, + error: freezed == error + ? _self.error + : error // ignore: cast_nullable_to_non_nullable + as String?, + recognizedCues: null == recognizedCues + ? _self.recognizedCues + : recognizedCues // ignore: cast_nullable_to_non_nullable + as int, + translatedCues: null == translatedCues + ? _self.translatedCues + : translatedCues // ignore: cast_nullable_to_non_nullable + as int, + ), + ); + } + + /// Create a copy of SubtitleTaskEntry + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $BackgroundTaskSessionCopyWith<$Res> get owner { + return $BackgroundTaskSessionCopyWith<$Res>(_self.owner, (value) { + return _then(_self.copyWith(owner: value)); + }); + } +} + +/// @nodoc +mixin _$RemovalTaskEntry { + BackgroundTaskSession get owner; + BackgroundRemovalTask get task; + BackgroundRemovalStatus get status; + String get name; + bool get terminal; + int? get completed; + int? get total; + String? get error; + + /// Create a copy of RemovalTaskEntry + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $RemovalTaskEntryCopyWith get copyWith => + _$RemovalTaskEntryCopyWithImpl( + this as RemovalTaskEntry, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as RemovalTaskEntry; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is RemovalTaskEntry && + (identical(other.owner, _this.owner) || + other.owner == _this.owner) && + (identical(other.task, _this.task) || other.task == _this.task) && + (identical(other.status, _this.status) || + other.status == _this.status) && + (identical(other.name, _this.name) || other.name == _this.name) && + (identical(other.terminal, _this.terminal) || + other.terminal == _this.terminal) && + (identical(other.completed, _this.completed) || + other.completed == _this.completed) && + (identical(other.total, _this.total) || + other.total == _this.total) && + (identical(other.error, _this.error) || + other.error == _this.error)); + } + + @override + int get hashCode { + final _this = this as RemovalTaskEntry; + return Object.hash( + runtimeType, + _this.owner, + _this.task, + _this.status, + _this.name, + _this.terminal, + _this.completed, + _this.total, + _this.error, + ); + } + + @override + String toString() { + final _this = this as RemovalTaskEntry; + return 'RemovalTaskEntry(owner: ${_this.owner}, task: ${_this.task}, status: ${_this.status}, name: ${_this.name}, terminal: ${_this.terminal}, completed: ${_this.completed}, total: ${_this.total}, error: ${_this.error})'; + } +} + +/// @nodoc +abstract mixin class $RemovalTaskEntryCopyWith<$Res> { + factory $RemovalTaskEntryCopyWith( + RemovalTaskEntry value, + $Res Function(RemovalTaskEntry) _then, + ) = _$RemovalTaskEntryCopyWithImpl; + @useResult + $Res call({ + BackgroundTaskSession owner, + BackgroundRemovalTask task, + BackgroundRemovalStatus status, + String name, + bool terminal, + int? completed, + int? total, + String? error, + }); + + $BackgroundTaskSessionCopyWith<$Res> get owner; +} + +/// @nodoc +class _$RemovalTaskEntryCopyWithImpl<$Res> + implements $RemovalTaskEntryCopyWith<$Res> { + _$RemovalTaskEntryCopyWithImpl(this._self, this._then); + + final RemovalTaskEntry _self; + final $Res Function(RemovalTaskEntry) _then; + + /// Create a copy of RemovalTaskEntry + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? owner = null, + Object? task = null, + Object? status = null, + Object? name = null, + Object? terminal = null, + Object? completed = freezed, + Object? total = freezed, + Object? error = freezed, + }) { + return _then( + RemovalTaskEntry( + owner: null == owner + ? _self.owner + : owner // ignore: cast_nullable_to_non_nullable + as BackgroundTaskSession, + task: null == task + ? _self.task + : task // ignore: cast_nullable_to_non_nullable + as BackgroundRemovalTask, + status: null == status + ? _self.status + : status // ignore: cast_nullable_to_non_nullable + as BackgroundRemovalStatus, + name: null == name + ? _self.name + : name // ignore: cast_nullable_to_non_nullable + as String, + terminal: null == terminal + ? _self.terminal + : terminal // ignore: cast_nullable_to_non_nullable + as bool, + completed: freezed == completed + ? _self.completed + : completed // ignore: cast_nullable_to_non_nullable + as int?, + total: freezed == total + ? _self.total + : total // ignore: cast_nullable_to_non_nullable + as int?, + error: freezed == error + ? _self.error + : error // ignore: cast_nullable_to_non_nullable + as String?, + ), + ); + } + + /// Create a copy of RemovalTaskEntry + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $BackgroundTaskSessionCopyWith<$Res> get owner { + return $BackgroundTaskSessionCopyWith<$Res>(_self.owner, (value) { + return _then(_self.copyWith(owner: value)); + }); + } +} + +/// Adds pattern-matching-related methods to [RemovalTaskEntry]. +extension RemovalTaskEntryPatterns on RemovalTaskEntry { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_RemovalTaskEntry value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _RemovalTaskEntry() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_RemovalTaskEntry value) $default, + ) { + final _that = this; + switch (_that) { + case _RemovalTaskEntry(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_RemovalTaskEntry value)? $default, + ) { + final _that = this; + switch (_that) { + case _RemovalTaskEntry() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + BackgroundTaskSession owner, + BackgroundRemovalTask task, + BackgroundRemovalStatus status, + String name, + bool terminal, + int? completed, + int? total, + String? error, + )? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _RemovalTaskEntry() when $default != null: + return $default( + _that.owner, + _that.task, + _that.status, + _that.name, + _that.terminal, + _that.completed, + _that.total, + _that.error, + ); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function( + BackgroundTaskSession owner, + BackgroundRemovalTask task, + BackgroundRemovalStatus status, + String name, + bool terminal, + int? completed, + int? total, + String? error, + ) + $default, + ) { + final _that = this; + switch (_that) { + case _RemovalTaskEntry(): + return $default( + _that.owner, + _that.task, + _that.status, + _that.name, + _that.terminal, + _that.completed, + _that.total, + _that.error, + ); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + BackgroundTaskSession owner, + BackgroundRemovalTask task, + BackgroundRemovalStatus status, + String name, + bool terminal, + int? completed, + int? total, + String? error, + )? + $default, + ) { + final _that = this; + switch (_that) { + case _RemovalTaskEntry() when $default != null: + return $default( + _that.owner, + _that.task, + _that.status, + _that.name, + _that.terminal, + _that.completed, + _that.total, + _that.error, + ); + case _: + return null; + } + } +} + +/// @nodoc + +class _RemovalTaskEntry implements RemovalTaskEntry { + const _RemovalTaskEntry({ + required this.owner, + required this.task, + required this.status, + required this.name, + required this.terminal, + this.completed, + this.total, + this.error, + }); + + @override + final BackgroundTaskSession owner; + @override + final BackgroundRemovalTask task; + @override + final BackgroundRemovalStatus status; + @override + final String name; + @override + final bool terminal; + @override + final int? completed; + @override + final int? total; + @override + final String? error; + + /// Create a copy of RemovalTaskEntry + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$RemovalTaskEntryCopyWith<_RemovalTaskEntry> get copyWith => + __$RemovalTaskEntryCopyWithImpl<_RemovalTaskEntry>(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _RemovalTaskEntry && + (identical(other.owner, owner) || other.owner == owner) && + (identical(other.task, task) || other.task == task) && + (identical(other.status, status) || other.status == status) && + (identical(other.name, name) || other.name == name) && + (identical(other.terminal, terminal) || + other.terminal == terminal) && + (identical(other.completed, completed) || + other.completed == completed) && + (identical(other.total, total) || other.total == total) && + (identical(other.error, error) || other.error == error)); + } + + @override + int get hashCode { + return Object.hash( + runtimeType, + owner, + task, + status, + name, + terminal, + completed, + total, + error, + ); + } + + @override + String toString() { + return 'RemovalTaskEntry(owner: $owner, task: $task, status: $status, name: $name, terminal: $terminal, completed: $completed, total: $total, error: $error)'; + } +} + +/// @nodoc +abstract mixin class _$RemovalTaskEntryCopyWith<$Res> + implements $RemovalTaskEntryCopyWith<$Res> { + factory _$RemovalTaskEntryCopyWith( + _RemovalTaskEntry value, + $Res Function(_RemovalTaskEntry) _then, + ) = __$RemovalTaskEntryCopyWithImpl; + @override + @useResult + $Res call({ + BackgroundTaskSession owner, + BackgroundRemovalTask task, + BackgroundRemovalStatus status, + String name, + bool terminal, + int? completed, + int? total, + String? error, + }); + + @override + $BackgroundTaskSessionCopyWith<$Res> get owner; +} + +/// @nodoc +class __$RemovalTaskEntryCopyWithImpl<$Res> + implements _$RemovalTaskEntryCopyWith<$Res> { + __$RemovalTaskEntryCopyWithImpl(this._self, this._then); + + final _RemovalTaskEntry _self; + final $Res Function(_RemovalTaskEntry) _then; + + /// Create a copy of RemovalTaskEntry + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? owner = null, + Object? task = null, + Object? status = null, + Object? name = null, + Object? terminal = null, + Object? completed = freezed, + Object? total = freezed, + Object? error = freezed, + }) { + return _then( + _RemovalTaskEntry( + owner: null == owner + ? _self.owner + : owner // ignore: cast_nullable_to_non_nullable + as BackgroundTaskSession, + task: null == task + ? _self.task + : task // ignore: cast_nullable_to_non_nullable + as BackgroundRemovalTask, + status: null == status + ? _self.status + : status // ignore: cast_nullable_to_non_nullable + as BackgroundRemovalStatus, + name: null == name + ? _self.name + : name // ignore: cast_nullable_to_non_nullable + as String, + terminal: null == terminal + ? _self.terminal + : terminal // ignore: cast_nullable_to_non_nullable + as bool, + completed: freezed == completed + ? _self.completed + : completed // ignore: cast_nullable_to_non_nullable + as int?, + total: freezed == total + ? _self.total + : total // ignore: cast_nullable_to_non_nullable + as int?, + error: freezed == error + ? _self.error + : error // ignore: cast_nullable_to_non_nullable + as String?, + ), + ); + } + + /// Create a copy of RemovalTaskEntry + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $BackgroundTaskSessionCopyWith<$Res> get owner { + return $BackgroundTaskSessionCopyWith<$Res>(_self.owner, (value) { + return _then(_self.copyWith(owner: value)); + }); + } +} + +/// @nodoc +mixin _$BackgroundTasksSnapshot { + List get subtitles; + List get removals; + int get runningCount; + + /// Create a copy of BackgroundTasksSnapshot + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $BackgroundTasksSnapshotCopyWith get copyWith => + _$BackgroundTasksSnapshotCopyWithImpl( + this as BackgroundTasksSnapshot, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as BackgroundTasksSnapshot; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is BackgroundTasksSnapshot && + const DeepCollectionEquality().equals( + other.subtitles, + _this.subtitles, + ) && + const DeepCollectionEquality().equals( + other.removals, + _this.removals, + ) && + (identical(other.runningCount, _this.runningCount) || + other.runningCount == _this.runningCount)); + } + + @override + int get hashCode { + final _this = this as BackgroundTasksSnapshot; + return Object.hash( + runtimeType, + const DeepCollectionEquality().hash(_this.subtitles), + const DeepCollectionEquality().hash(_this.removals), + _this.runningCount, + ); + } + + @override + String toString() { + final _this = this as BackgroundTasksSnapshot; + return 'BackgroundTasksSnapshot(subtitles: ${_this.subtitles}, removals: ${_this.removals}, runningCount: ${_this.runningCount})'; + } +} + +/// @nodoc +abstract mixin class $BackgroundTasksSnapshotCopyWith<$Res> { + factory $BackgroundTasksSnapshotCopyWith( + BackgroundTasksSnapshot value, + $Res Function(BackgroundTasksSnapshot) _then, + ) = _$BackgroundTasksSnapshotCopyWithImpl; + @useResult + $Res call({ + List subtitles, + List removals, + int runningCount, + }); +} + +/// @nodoc +class _$BackgroundTasksSnapshotCopyWithImpl<$Res> + implements $BackgroundTasksSnapshotCopyWith<$Res> { + _$BackgroundTasksSnapshotCopyWithImpl(this._self, this._then); + + final BackgroundTasksSnapshot _self; + final $Res Function(BackgroundTasksSnapshot) _then; + + /// Create a copy of BackgroundTasksSnapshot + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? subtitles = null, + Object? removals = null, + Object? runningCount = null, + }) { + return _then( + BackgroundTasksSnapshot( + subtitles: null == subtitles + ? _self.subtitles + : subtitles // ignore: cast_nullable_to_non_nullable + as List, + removals: null == removals + ? _self.removals + : removals // ignore: cast_nullable_to_non_nullable + as List, + runningCount: null == runningCount + ? _self.runningCount + : runningCount // ignore: cast_nullable_to_non_nullable + as int, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [BackgroundTasksSnapshot]. +extension BackgroundTasksSnapshotPatterns on BackgroundTasksSnapshot { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_BackgroundTasksSnapshot value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _BackgroundTasksSnapshot() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_BackgroundTasksSnapshot value) $default, + ) { + final _that = this; + switch (_that) { + case _BackgroundTasksSnapshot(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_BackgroundTasksSnapshot value)? $default, + ) { + final _that = this; + switch (_that) { + case _BackgroundTasksSnapshot() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + List subtitles, + List removals, + int runningCount, + )? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _BackgroundTasksSnapshot() when $default != null: + return $default(_that.subtitles, _that.removals, _that.runningCount); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function( + List subtitles, + List removals, + int runningCount, + ) + $default, + ) { + final _that = this; + switch (_that) { + case _BackgroundTasksSnapshot(): + return $default(_that.subtitles, _that.removals, _that.runningCount); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + List subtitles, + List removals, + int runningCount, + )? + $default, + ) { + final _that = this; + switch (_that) { + case _BackgroundTasksSnapshot() when $default != null: + return $default(_that.subtitles, _that.removals, _that.runningCount); + case _: + return null; + } + } +} + +/// @nodoc + +class _BackgroundTasksSnapshot implements BackgroundTasksSnapshot { + const _BackgroundTasksSnapshot({ + List subtitles = const [], + List removals = const [], + this.runningCount = 0, + }) : _subtitles = subtitles, + _removals = removals; + + final List _subtitles; + @override + @JsonKey() + List get subtitles { + if (_subtitles is EqualUnmodifiableListView) return _subtitles; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_subtitles); + } + + final List _removals; + @override + @JsonKey() + List get removals { + if (_removals is EqualUnmodifiableListView) return _removals; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_removals); + } + + @override + @JsonKey() + final int runningCount; + + /// Create a copy of BackgroundTasksSnapshot + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$BackgroundTasksSnapshotCopyWith<_BackgroundTasksSnapshot> get copyWith => + __$BackgroundTasksSnapshotCopyWithImpl<_BackgroundTasksSnapshot>( + this, + _$identity, + ); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _BackgroundTasksSnapshot && + const DeepCollectionEquality().equals( + other.subtitles, + _subtitles, + ) && + const DeepCollectionEquality().equals(other.removals, _removals) && + (identical(other.runningCount, runningCount) || + other.runningCount == runningCount)); + } + + @override + int get hashCode { + return Object.hash( + runtimeType, + const DeepCollectionEquality().hash(_subtitles), + const DeepCollectionEquality().hash(_removals), + runningCount, + ); + } + + @override + String toString() { + return 'BackgroundTasksSnapshot(subtitles: $subtitles, removals: $removals, runningCount: $runningCount)'; + } +} + +/// @nodoc +abstract mixin class _$BackgroundTasksSnapshotCopyWith<$Res> + implements $BackgroundTasksSnapshotCopyWith<$Res> { + factory _$BackgroundTasksSnapshotCopyWith( + _BackgroundTasksSnapshot value, + $Res Function(_BackgroundTasksSnapshot) _then, + ) = __$BackgroundTasksSnapshotCopyWithImpl; + @override + @useResult + $Res call({ + List subtitles, + List removals, + int runningCount, + }); +} + +/// @nodoc +class __$BackgroundTasksSnapshotCopyWithImpl<$Res> + implements _$BackgroundTasksSnapshotCopyWith<$Res> { + __$BackgroundTasksSnapshotCopyWithImpl(this._self, this._then); + + final _BackgroundTasksSnapshot _self; + final $Res Function(_BackgroundTasksSnapshot) _then; + + /// Create a copy of BackgroundTasksSnapshot + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? subtitles = null, + Object? removals = null, + Object? runningCount = null, + }) { + return _then( + _BackgroundTasksSnapshot( + subtitles: null == subtitles + ? _self._subtitles + : subtitles // ignore: cast_nullable_to_non_nullable + as List, + removals: null == removals + ? _self._removals + : removals // ignore: cast_nullable_to_non_nullable + as List, + runningCount: null == runningCount + ? _self.runningCount + : runningCount // ignore: cast_nullable_to_non_nullable + as int, + ), + ); + } +} diff --git a/lib/workspace/background_task_state.g.dart b/lib/workspace/background_task_state.g.dart new file mode 100644 index 0000000..9ad73cf --- /dev/null +++ b/lib/workspace/background_task_state.g.dart @@ -0,0 +1,129 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'background_task_state.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(BackgroundTasks) +final backgroundTasksProvider = BackgroundTasksFamily._(); + +final class BackgroundTasksProvider + extends $NotifierProvider { + BackgroundTasksProvider._({ + required BackgroundTasksFamily super.from, + required ({ + BackgroundTaskRegistry? registry, + EditorTimelineSession? session, + }) + super.argument, + }) : super( + retry: null, + name: r'backgroundTasksProvider', + isAutoDispose: true, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$backgroundTasksHash(); + + @override + String toString() { + return r'backgroundTasksProvider' + '' + '$argument'; + } + + @$internal + @override + BackgroundTasks create() => BackgroundTasks(); + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(BackgroundTasksSnapshot value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } + + @override + bool operator ==(Object other) { + return other is BackgroundTasksProvider && other.argument == argument; + } + + @override + int get hashCode { + return argument.hashCode; + } +} + +String _$backgroundTasksHash() => r'fad7fdf299e66a594525ca8b215e57e460a135d0'; + +final class BackgroundTasksFamily extends $Family + with + $ClassFamilyOverride< + BackgroundTasks, + BackgroundTasksSnapshot, + BackgroundTasksSnapshot, + BackgroundTasksSnapshot, + ({BackgroundTaskRegistry? registry, EditorTimelineSession? session}) + > { + BackgroundTasksFamily._() + : super( + retry: null, + name: r'backgroundTasksProvider', + dependencies: null, + $allTransitiveDependencies: null, + isAutoDispose: true, + ); + + BackgroundTasksProvider call({ + BackgroundTaskRegistry? registry, + EditorTimelineSession? session, + }) => BackgroundTasksProvider._( + argument: (registry: registry, session: session), + from: this, + ); + + @override + String toString() => r'backgroundTasksProvider'; +} + +abstract class _$BackgroundTasks extends $Notifier { + late final _$args = + ref.$arg + as ({ + BackgroundTaskRegistry? registry, + EditorTimelineSession? session, + }); + BackgroundTaskRegistry? get registry => _$args.registry; + EditorTimelineSession? get session => _$args.session; + + BackgroundTasksSnapshot build({ + BackgroundTaskRegistry? registry, + EditorTimelineSession? session, + }); + @$mustCallSuper + @override + WhenComplete runBuild() { + final ref = + this.ref as $Ref; + final element = + ref.element + as $ClassProviderElement< + AnyNotifier, + BackgroundTasksSnapshot, + Object?, + Object? + >; + return element.handleCreate( + ref, + () => build(registry: _$args.registry, session: _$args.session), + ); + } +} diff --git a/lib/workspace/external_media_import.dart b/lib/workspace/external_media_import.dart new file mode 100644 index 0000000..926b347 --- /dev/null +++ b/lib/workspace/external_media_import.dart @@ -0,0 +1,121 @@ +import 'dart:io'; + +import 'package:cutdex_sdk/project.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import 'media_import.dart'; +import 'projects.dart'; + +part 'external_media_import.g.dart'; +part 'external_media_import.freezed.dart'; + +@freezed +abstract class ExternalMediaSelection with _$ExternalMediaSelection { + const factory ExternalMediaSelection({ + required List selected, + MediaImportResult? result, + @Default(false) bool failed, + }) = _ExternalMediaSelection; +} + +@riverpod +MediaFileResolver mediaFileResolver(Ref ref) => const MediaFileResolver(); + +/// Resolves aliases once for both the media browser and the attachment composer. +class MediaFileResolver { + const MediaFileResolver(); + + Future>> resolve( + List files, + List assets, + ) async { + final locations = >{}; + for (final file in files) { + final candidates = {file.sourceUri.toString()}; + final path = file.localPath; + if (path != null && + !assets.any( + (asset) => candidates.contains(mediaSourceLocation(asset)), + ) && + File(path).existsSync()) { + try { + candidates.add( + Uri.file(await File(path).resolveSymbolicLinks()).toString(), + ); + } on FileSystemException { + // Unavailable sources are reported by the importer. + } + } + locations[file] = candidates; + } + return locations; + } +} + +@riverpod +class ExternalMediaImport extends _$ExternalMediaImport { + @override + AsyncValue build(String projectId) => + const AsyncData(null); + + Future importFiles( + List files, + ) async { + if (state.isLoading || files.isEmpty) return null; + final workspace = ref.read(projectsProvider).value; + if (workspace?.activeProject?.id != projectId || workspace!.projectBusy) { + return null; + } + final lease = ref.keepAlive(); + final projects = ref.read(projectsProvider.notifier); + final resolver = ref.read(mediaFileResolverProvider); + state = const AsyncLoading(); + try { + final locations = await resolver.resolve(files, workspace.assets); + if (!ref.mounted || + ref.read(projectsProvider).value?.activeProject?.id != projectId) { + return null; + } + final existing = []; + final missing = []; + for (final file in files) { + final asset = workspace.assets + .where( + (asset) => locations[file]!.contains(mediaSourceLocation(asset)), + ) + .firstOrNull; + if (asset == null) { + missing.add(file); + } else if (!existing.any((item) => item.id == asset.id)) { + existing.add(asset); + } + } + final result = missing.isEmpty + ? null + : await projects.importExternalMedia(projectId, missing); + final importedLocations = { + for (final file in missing) ...locations[file]!, + }; + final selected = { + for (final asset in existing) asset.id: asset, + for (final asset in result?.assets ?? []) + if (importedLocations.contains(mediaSourceLocation(asset))) + asset.id: asset, + }; + final value = ExternalMediaSelection( + selected: selected.values.toList(), + result: result, + failed: missing.isNotEmpty && result == null, + ); + if (ref.mounted) state = AsyncData(value); + return value; + } catch (error, stack) { + if (ref.mounted) state = AsyncError(error, stack); + rethrow; + } finally { + if (ref.mounted && state.isLoading) state = const AsyncData(null); + lease.close(); + } + } +} diff --git a/lib/workspace/external_media_import.freezed.dart b/lib/workspace/external_media_import.freezed.dart new file mode 100644 index 0000000..7893b17 --- /dev/null +++ b/lib/workspace/external_media_import.freezed.dart @@ -0,0 +1,430 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'external_media_import.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +T _$identity(T value) => value; + +/// @nodoc +mixin _$ExternalMediaSelection { + List get selected; + MediaImportResult? get result; + bool get failed; + + /// Create a copy of ExternalMediaSelection + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $ExternalMediaSelectionCopyWith get copyWith => + _$ExternalMediaSelectionCopyWithImpl( + this as ExternalMediaSelection, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as ExternalMediaSelection; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is ExternalMediaSelection && + const DeepCollectionEquality().equals( + other.selected, + _this.selected, + ) && + (identical(other.result, _this.result) || + other.result == _this.result) && + (identical(other.failed, _this.failed) || + other.failed == _this.failed)); + } + + @override + int get hashCode { + final _this = this as ExternalMediaSelection; + return Object.hash( + runtimeType, + const DeepCollectionEquality().hash(_this.selected), + _this.result, + _this.failed, + ); + } + + @override + String toString() { + final _this = this as ExternalMediaSelection; + return 'ExternalMediaSelection(selected: ${_this.selected}, result: ${_this.result}, failed: ${_this.failed})'; + } +} + +/// @nodoc +abstract mixin class $ExternalMediaSelectionCopyWith<$Res> { + factory $ExternalMediaSelectionCopyWith( + ExternalMediaSelection value, + $Res Function(ExternalMediaSelection) _then, + ) = _$ExternalMediaSelectionCopyWithImpl; + @useResult + $Res call({ + List selected, + MediaImportResult? result, + bool failed, + }); + + $MediaImportResultCopyWith<$Res>? get result; +} + +/// @nodoc +class _$ExternalMediaSelectionCopyWithImpl<$Res> + implements $ExternalMediaSelectionCopyWith<$Res> { + _$ExternalMediaSelectionCopyWithImpl(this._self, this._then); + + final ExternalMediaSelection _self; + final $Res Function(ExternalMediaSelection) _then; + + /// Create a copy of ExternalMediaSelection + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? selected = null, + Object? result = freezed, + Object? failed = null, + }) { + return _then( + ExternalMediaSelection( + selected: null == selected + ? _self.selected + : selected // ignore: cast_nullable_to_non_nullable + as List, + result: freezed == result + ? _self.result + : result // ignore: cast_nullable_to_non_nullable + as MediaImportResult?, + failed: null == failed + ? _self.failed + : failed // ignore: cast_nullable_to_non_nullable + as bool, + ), + ); + } + + /// Create a copy of ExternalMediaSelection + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $MediaImportResultCopyWith<$Res>? get result { + if (_self.result == null) { + return null; + } + + return $MediaImportResultCopyWith<$Res>(_self.result!, (value) { + return _then(_self.copyWith(result: value)); + }); + } +} + +/// Adds pattern-matching-related methods to [ExternalMediaSelection]. +extension ExternalMediaSelectionPatterns on ExternalMediaSelection { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_ExternalMediaSelection value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ExternalMediaSelection() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_ExternalMediaSelection value) $default, + ) { + final _that = this; + switch (_that) { + case _ExternalMediaSelection(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_ExternalMediaSelection value)? $default, + ) { + final _that = this; + switch (_that) { + case _ExternalMediaSelection() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + List selected, + MediaImportResult? result, + bool failed, + )? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ExternalMediaSelection() when $default != null: + return $default(_that.selected, _that.result, _that.failed); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function( + List selected, + MediaImportResult? result, + bool failed, + ) + $default, + ) { + final _that = this; + switch (_that) { + case _ExternalMediaSelection(): + return $default(_that.selected, _that.result, _that.failed); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + List selected, + MediaImportResult? result, + bool failed, + )? + $default, + ) { + final _that = this; + switch (_that) { + case _ExternalMediaSelection() when $default != null: + return $default(_that.selected, _that.result, _that.failed); + case _: + return null; + } + } +} + +/// @nodoc + +class _ExternalMediaSelection implements ExternalMediaSelection { + const _ExternalMediaSelection({ + required List selected, + this.result, + this.failed = false, + }) : _selected = selected; + + final List _selected; + @override + List get selected { + if (_selected is EqualUnmodifiableListView) return _selected; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_selected); + } + + @override + final MediaImportResult? result; + @override + @JsonKey() + final bool failed; + + /// Create a copy of ExternalMediaSelection + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$ExternalMediaSelectionCopyWith<_ExternalMediaSelection> get copyWith => + __$ExternalMediaSelectionCopyWithImpl<_ExternalMediaSelection>( + this, + _$identity, + ); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _ExternalMediaSelection && + const DeepCollectionEquality().equals(other.selected, _selected) && + (identical(other.result, result) || other.result == result) && + (identical(other.failed, failed) || other.failed == failed)); + } + + @override + int get hashCode { + return Object.hash( + runtimeType, + const DeepCollectionEquality().hash(_selected), + result, + failed, + ); + } + + @override + String toString() { + return 'ExternalMediaSelection(selected: $selected, result: $result, failed: $failed)'; + } +} + +/// @nodoc +abstract mixin class _$ExternalMediaSelectionCopyWith<$Res> + implements $ExternalMediaSelectionCopyWith<$Res> { + factory _$ExternalMediaSelectionCopyWith( + _ExternalMediaSelection value, + $Res Function(_ExternalMediaSelection) _then, + ) = __$ExternalMediaSelectionCopyWithImpl; + @override + @useResult + $Res call({ + List selected, + MediaImportResult? result, + bool failed, + }); + + @override + $MediaImportResultCopyWith<$Res>? get result; +} + +/// @nodoc +class __$ExternalMediaSelectionCopyWithImpl<$Res> + implements _$ExternalMediaSelectionCopyWith<$Res> { + __$ExternalMediaSelectionCopyWithImpl(this._self, this._then); + + final _ExternalMediaSelection _self; + final $Res Function(_ExternalMediaSelection) _then; + + /// Create a copy of ExternalMediaSelection + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? selected = null, + Object? result = freezed, + Object? failed = null, + }) { + return _then( + _ExternalMediaSelection( + selected: null == selected + ? _self._selected + : selected // ignore: cast_nullable_to_non_nullable + as List, + result: freezed == result + ? _self.result + : result // ignore: cast_nullable_to_non_nullable + as MediaImportResult?, + failed: null == failed + ? _self.failed + : failed // ignore: cast_nullable_to_non_nullable + as bool, + ), + ); + } + + /// Create a copy of ExternalMediaSelection + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $MediaImportResultCopyWith<$Res>? get result { + if (_self.result == null) { + return null; + } + + return $MediaImportResultCopyWith<$Res>(_self.result!, (value) { + return _then(_self.copyWith(result: value)); + }); + } +} diff --git a/lib/workspace/external_media_import.g.dart b/lib/workspace/external_media_import.g.dart new file mode 100644 index 0000000..032daa0 --- /dev/null +++ b/lib/workspace/external_media_import.g.dart @@ -0,0 +1,170 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'external_media_import.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(mediaFileResolver) +final mediaFileResolverProvider = MediaFileResolverProvider._(); + +final class MediaFileResolverProvider + extends + $FunctionalProvider< + MediaFileResolver, + MediaFileResolver, + MediaFileResolver + > + with $Provider { + MediaFileResolverProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'mediaFileResolverProvider', + isAutoDispose: true, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$mediaFileResolverHash(); + + @$internal + @override + $ProviderElement $createElement( + $ProviderPointer pointer, + ) => $ProviderElement(pointer); + + @override + MediaFileResolver create(Ref ref) { + return mediaFileResolver(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(MediaFileResolver value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$mediaFileResolverHash() => r'429dfc500e860cdc0bee600c538901466b8e5375'; + +@ProviderFor(ExternalMediaImport) +final externalMediaImportProvider = ExternalMediaImportFamily._(); + +final class ExternalMediaImportProvider + extends + $NotifierProvider< + ExternalMediaImport, + AsyncValue + > { + ExternalMediaImportProvider._({ + required ExternalMediaImportFamily super.from, + required String super.argument, + }) : super( + retry: null, + name: r'externalMediaImportProvider', + isAutoDispose: true, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$externalMediaImportHash(); + + @override + String toString() { + return r'externalMediaImportProvider' + '' + '($argument)'; + } + + @$internal + @override + ExternalMediaImport create() => ExternalMediaImport(); + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(AsyncValue value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider>( + value, + ), + ); + } + + @override + bool operator ==(Object other) { + return other is ExternalMediaImportProvider && other.argument == argument; + } + + @override + int get hashCode { + return argument.hashCode; + } +} + +String _$externalMediaImportHash() => + r'48bf943d1132cec15af783c748bbe2a096b65196'; + +final class ExternalMediaImportFamily extends $Family + with + $ClassFamilyOverride< + ExternalMediaImport, + AsyncValue, + AsyncValue, + AsyncValue, + String + > { + ExternalMediaImportFamily._() + : super( + retry: null, + name: r'externalMediaImportProvider', + dependencies: null, + $allTransitiveDependencies: null, + isAutoDispose: true, + ); + + ExternalMediaImportProvider call(String projectId) => + ExternalMediaImportProvider._(argument: projectId, from: this); + + @override + String toString() => r'externalMediaImportProvider'; +} + +abstract class _$ExternalMediaImport + extends $Notifier> { + late final _$args = ref.$arg as String; + String get projectId => _$args; + + AsyncValue build(String projectId); + @$mustCallSuper + @override + WhenComplete runBuild() { + final ref = + this.ref + as $Ref< + AsyncValue, + AsyncValue + >; + final element = + ref.element + as $ClassProviderElement< + AnyNotifier< + AsyncValue, + AsyncValue + >, + AsyncValue, + Object?, + Object? + >; + return element.handleCreate(ref, () => build(_$args)); + } +} diff --git a/lib/workspace/media_availability.dart b/lib/workspace/media_availability.dart new file mode 100644 index 0000000..08893e5 --- /dev/null +++ b/lib/workspace/media_availability.dart @@ -0,0 +1,49 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:cutdex_sdk/project.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import 'projects.dart'; + +part 'media_availability.g.dart'; + +enum MediaAvailability { available, missing, inaccessible } + +@riverpod +FutureOr mediaAvailability( + Ref ref, + String projectId, + AssetDocument asset, +) async { + try { + return await ref + .read(projectsProvider.notifier) + .withAssetMedia( + projectId, + asset, + (media) => checkMediaAvailability(media.uri), + ); + } on FileSystemException catch (error) { + return error.osError?.errorCode == 2 + ? MediaAvailability.missing + : MediaAvailability.inaccessible; + } catch (_) { + return MediaAvailability.inaccessible; + } +} + +Future checkMediaAvailability(Uri uri) async { + if (uri.scheme != 'file') return MediaAvailability.inaccessible; + try { + final file = await File.fromUri(uri).open(); + await file.close(); + return MediaAvailability.available; + } on FileSystemException catch (error) { + // ENOENT on POSIX and ERROR_FILE/PATH_NOT_FOUND on Windows. + return (error.osError?.errorCode == 2 || + (Platform.isWindows && error.osError?.errorCode == 3)) + ? MediaAvailability.missing + : MediaAvailability.inaccessible; + } +} diff --git a/lib/workspace/media_availability.g.dart b/lib/workspace/media_availability.g.dart new file mode 100644 index 0000000..0debaea --- /dev/null +++ b/lib/workspace/media_availability.g.dart @@ -0,0 +1,91 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'media_availability.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(mediaAvailability) +final mediaAvailabilityProvider = MediaAvailabilityFamily._(); + +final class MediaAvailabilityProvider + extends + $FunctionalProvider< + AsyncValue, + MediaAvailability, + FutureOr + > + with + $FutureModifier, + $FutureProvider { + MediaAvailabilityProvider._({ + required MediaAvailabilityFamily super.from, + required (String, AssetDocument) super.argument, + }) : super( + retry: null, + name: r'mediaAvailabilityProvider', + isAutoDispose: true, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$mediaAvailabilityHash(); + + @override + String toString() { + return r'mediaAvailabilityProvider' + '' + '$argument'; + } + + @$internal + @override + $FutureProviderElement $createElement( + $ProviderPointer pointer, + ) => $FutureProviderElement(pointer); + + @override + FutureOr create(Ref ref) { + final argument = this.argument as (String, AssetDocument); + return mediaAvailability(ref, argument.$1, argument.$2); + } + + @override + bool operator ==(Object other) { + return other is MediaAvailabilityProvider && other.argument == argument; + } + + @override + int get hashCode { + return argument.hashCode; + } +} + +String _$mediaAvailabilityHash() => r'e579c9b0cff0bfce1a719014d0298bf229809702'; + +final class MediaAvailabilityFamily extends $Family + with + $FunctionalFamilyOverride< + FutureOr, + (String, AssetDocument) + > { + MediaAvailabilityFamily._() + : super( + retry: null, + name: r'mediaAvailabilityProvider', + dependencies: null, + $allTransitiveDependencies: null, + isAutoDispose: true, + ); + + MediaAvailabilityProvider call(String projectId, AssetDocument asset) => + MediaAvailabilityProvider._(argument: (projectId, asset), from: this); + + @override + String toString() => r'mediaAvailabilityProvider'; +} diff --git a/lib/workspace/media_binding.dart b/lib/workspace/media_binding.dart new file mode 100644 index 0000000..a360882 --- /dev/null +++ b/lib/workspace/media_binding.dart @@ -0,0 +1,8 @@ +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/runtime.dart'; + +/// Runs generation while the workspace retains the owning project and grants. +typedef AssetMediaLoader = Future Function( + AssetDocument asset, + Future Function(MediaReference media) action, +); diff --git a/lib/workspace/media_color_interpretation.dart b/lib/workspace/media_color_interpretation.dart new file mode 100644 index 0000000..8f9878f --- /dev/null +++ b/lib/workspace/media_color_interpretation.dart @@ -0,0 +1,23 @@ +import 'package:cutdex_sdk/runtime.dart'; + +import '../l10n/app_localizations.dart'; + +extension MediaColorLabel on RenderColorSpace { + String label(AppLocalizations l10n) => switch (this) { + RenderColorSpace.rec709 => 'Rec.709', + RenderColorSpace.sRGB => 'sRGB', + RenderColorSpace.displayP3 => 'Display P3', + RenderColorSpace.rec2020HLG => 'Rec.2020 HLG', + RenderColorSpace.rec2020PQ => 'Rec.2020 PQ', + RenderColorSpace.linearRec2020 => l10n.linearRec2020, + }; +} + +/// A viewing assumption is separate from detected metadata and authored overrides. +RenderColorSpace? resolveMediaColor({ + required RenderColorSpace? detected, + required RenderColorSpace? override, + required bool metadataReported, +}) => + override ?? + (metadataReported && detected == null ? RenderColorSpace.rec709 : null); diff --git a/lib/workspace/media_file_extensions.dart b/lib/workspace/media_file_extensions.dart new file mode 100644 index 0000000..d2296b8 --- /dev/null +++ b/lib/workspace/media_file_extensions.dart @@ -0,0 +1,85 @@ +import 'package:flutter/foundation.dart' + show TargetPlatform, defaultTargetPlatform, kIsWeb; +import 'package:path/path.dart' as p; + +const supportedVideoFileExtensions = [ + 'mp4', + 'mov', + 'm4v', + 'mkv', + 'webm', + 'avi', + 'wmv', + 'asf', + 'flv', + 'rm', + 'rmvb', + 'ts', + 'mts', + 'm2ts', + 'mpeg', + 'mpg', + 'mxf', + '3gp', +]; + +/// Windows can probe video streams embedded in some optical-disc files. +/// Listing a candidate does not imply DVD filesystem or menu support. +List get selectableVideoFileExtensions => + !kIsWeb && defaultTargetPlatform == TargetPlatform.windows + ? const [...supportedVideoFileExtensions, 'iso'] + : supportedVideoFileExtensions; + +const supportedAudioFileExtensions = [ + 'mp3', + 'wav', + 'aif', + 'aiff', + 'm4a', + 'aac', + 'flac', + 'ogg', + 'opus', + 'caf', + 'wma', + 'amr', + 'ac3', + 'ape', + 'wv', + 'dts', +]; + +const supportedImageFileExtensions = [ + 'jpg', + 'jpeg', + 'png', + 'webp', + 'heic', + 'heif', + 'tif', + 'tiff', + 'bmp', + 'gif', + 'avif', +]; + +/// Timeline drops accept playable media; images use project asset insertion. +List get selectableTimelineFileExtensions => List.unmodifiable([ + ...selectableVideoFileExtensions, + ...supportedAudioFileExtensions, +]); + +/// File pickers in the media library and composer share the same candidates. +List get selectableMediaFileExtensions => List.unmodifiable([ + ...selectableTimelineFileExtensions, + ...supportedImageFileExtensions, +]); + +/// A supported browser category, not a decoder capability verification. +String? mediaKindForPath(String path) { + final extension = p.extension(path).toLowerCase().replaceFirst('.', ''); + if (selectableVideoFileExtensions.contains(extension)) return 'video'; + if (supportedAudioFileExtensions.contains(extension)) return 'audio'; + if (supportedImageFileExtensions.contains(extension)) return 'image'; + return null; +} diff --git a/lib/workspace/media_import.dart b/lib/workspace/media_import.dart new file mode 100644 index 0000000..12dd396 --- /dev/null +++ b/lib/workspace/media_import.dart @@ -0,0 +1,59 @@ +import 'package:cutdex_sdk/project.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:path/path.dart' as p; + +import '../errors/app_failure.dart'; + +part 'media_import.freezed.dart'; + +/// A selected local file or document supplied by a platform provider. +@freezed +sealed class ExternalMediaFile with _$ExternalMediaFile { + const ExternalMediaFile._(); + const factory ExternalMediaFile({required String path}) = LocalMediaFile; + const factory ExternalMediaFile.content({ + required Uri uri, + required String name, + int? byteLength, + }) = ContentMediaFile; + + String? get localPath => switch (this) { + LocalMediaFile(:final path) => path, + ContentMediaFile() => null, + }; + + Uri get sourceUri => switch (this) { + LocalMediaFile(:final path) => p.toUri(path), + ContentMediaFile(:final uri) => uri, + }; + + String get displayName => switch (this) { + LocalMediaFile(:final path) => p.basename(path), + ContentMediaFile(:final name) => name, + }; +} + +const mediaSourceUriKey = 'cutdex.sourceUri'; + +String? mediaSourceLocation(AssetDocument asset) => switch (asset.storage) { + AssetStorage.external => asset.location, + AssetStorage.managed => asset.metadata[mediaSourceUriKey] as String?, +}; + +@freezed +abstract class MediaImportFailure with _$MediaImportFailure { + const factory MediaImportFailure({ + required String name, + required AppFailure failure, + }) = _MediaImportFailure; +} + +@freezed +abstract class MediaImportResult with _$MediaImportResult { + const factory MediaImportResult({ + required List assets, + required int added, + required int duplicates, + required List failures, + }) = _MediaImportResult; +} diff --git a/lib/workspace/media_import.freezed.dart b/lib/workspace/media_import.freezed.dart new file mode 100644 index 0000000..fb948fb --- /dev/null +++ b/lib/workspace/media_import.freezed.dart @@ -0,0 +1,1101 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'media_import.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +T _$identity(T value) => value; + +/// @nodoc +mixin _$ExternalMediaFile { + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is ExternalMediaFile); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + String toString() { + return 'ExternalMediaFile()'; + } +} + +/// @nodoc +class $ExternalMediaFileCopyWith<$Res> { + $ExternalMediaFileCopyWith( + ExternalMediaFile _, + $Res Function(ExternalMediaFile) __, + ); +} + +/// Adds pattern-matching-related methods to [ExternalMediaFile]. +extension ExternalMediaFilePatterns on ExternalMediaFile { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(LocalMediaFile value)? $default, { + TResult Function(ContentMediaFile value)? content, + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case LocalMediaFile() when $default != null: + return $default(_that); + case ContentMediaFile() when content != null: + return content(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(LocalMediaFile value) $default, { + required TResult Function(ContentMediaFile value) content, + }) { + final _that = this; + switch (_that) { + case LocalMediaFile(): + return $default(_that); + case ContentMediaFile(): + return content(_that); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(LocalMediaFile value)? $default, { + TResult? Function(ContentMediaFile value)? content, + }) { + final _that = this; + switch (_that) { + case LocalMediaFile() when $default != null: + return $default(_that); + case ContentMediaFile() when content != null: + return content(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function(String path)? $default, { + TResult Function(Uri uri, String name, int? byteLength)? content, + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case LocalMediaFile() when $default != null: + return $default(_that.path); + case ContentMediaFile() when content != null: + return content(_that.uri, _that.name, _that.byteLength); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function(String path) $default, { + required TResult Function(Uri uri, String name, int? byteLength) content, + }) { + final _that = this; + switch (_that) { + case LocalMediaFile(): + return $default(_that.path); + case ContentMediaFile(): + return content(_that.uri, _that.name, _that.byteLength); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function(String path)? $default, { + TResult? Function(Uri uri, String name, int? byteLength)? content, + }) { + final _that = this; + switch (_that) { + case LocalMediaFile() when $default != null: + return $default(_that.path); + case ContentMediaFile() when content != null: + return content(_that.uri, _that.name, _that.byteLength); + case _: + return null; + } + } +} + +/// @nodoc + +class LocalMediaFile extends ExternalMediaFile { + const LocalMediaFile({required this.path}) : super._(); + + final String path; + + /// Create a copy of ExternalMediaFile + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $LocalMediaFileCopyWith get copyWith => + _$LocalMediaFileCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is LocalMediaFile && + (identical(other.path, path) || other.path == path)); + } + + @override + int get hashCode { + return Object.hash(runtimeType, path); + } + + @override + String toString() { + return 'ExternalMediaFile(path: $path)'; + } +} + +/// @nodoc +abstract mixin class $LocalMediaFileCopyWith<$Res> + implements $ExternalMediaFileCopyWith<$Res> { + factory $LocalMediaFileCopyWith( + LocalMediaFile value, + $Res Function(LocalMediaFile) _then, + ) = _$LocalMediaFileCopyWithImpl; + @useResult + $Res call({String path}); +} + +/// @nodoc +class _$LocalMediaFileCopyWithImpl<$Res> + implements $LocalMediaFileCopyWith<$Res> { + _$LocalMediaFileCopyWithImpl(this._self, this._then); + + final LocalMediaFile _self; + final $Res Function(LocalMediaFile) _then; + + /// Create a copy of ExternalMediaFile + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({Object? path = null}) { + return _then( + LocalMediaFile( + path: null == path + ? _self.path + : path // ignore: cast_nullable_to_non_nullable + as String, + ), + ); + } +} + +/// @nodoc + +class ContentMediaFile extends ExternalMediaFile { + const ContentMediaFile({ + required this.uri, + required this.name, + this.byteLength, + }) : super._(); + + final Uri uri; + final String name; + final int? byteLength; + + /// Create a copy of ExternalMediaFile + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $ContentMediaFileCopyWith get copyWith => + _$ContentMediaFileCopyWithImpl(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is ContentMediaFile && + (identical(other.uri, uri) || other.uri == uri) && + (identical(other.name, name) || other.name == name) && + (identical(other.byteLength, byteLength) || + other.byteLength == byteLength)); + } + + @override + int get hashCode { + return Object.hash(runtimeType, uri, name, byteLength); + } + + @override + String toString() { + return 'ExternalMediaFile.content(uri: $uri, name: $name, byteLength: $byteLength)'; + } +} + +/// @nodoc +abstract mixin class $ContentMediaFileCopyWith<$Res> + implements $ExternalMediaFileCopyWith<$Res> { + factory $ContentMediaFileCopyWith( + ContentMediaFile value, + $Res Function(ContentMediaFile) _then, + ) = _$ContentMediaFileCopyWithImpl; + @useResult + $Res call({Uri uri, String name, int? byteLength}); +} + +/// @nodoc +class _$ContentMediaFileCopyWithImpl<$Res> + implements $ContentMediaFileCopyWith<$Res> { + _$ContentMediaFileCopyWithImpl(this._self, this._then); + + final ContentMediaFile _self; + final $Res Function(ContentMediaFile) _then; + + /// Create a copy of ExternalMediaFile + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({ + Object? uri = null, + Object? name = null, + Object? byteLength = freezed, + }) { + return _then( + ContentMediaFile( + uri: null == uri + ? _self.uri + : uri // ignore: cast_nullable_to_non_nullable + as Uri, + name: null == name + ? _self.name + : name // ignore: cast_nullable_to_non_nullable + as String, + byteLength: freezed == byteLength + ? _self.byteLength + : byteLength // ignore: cast_nullable_to_non_nullable + as int?, + ), + ); + } +} + +/// @nodoc +mixin _$MediaImportFailure { + String get name; + AppFailure get failure; + + /// Create a copy of MediaImportFailure + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $MediaImportFailureCopyWith get copyWith => + _$MediaImportFailureCopyWithImpl( + this as MediaImportFailure, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as MediaImportFailure; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is MediaImportFailure && + (identical(other.name, _this.name) || other.name == _this.name) && + (identical(other.failure, _this.failure) || + other.failure == _this.failure)); + } + + @override + int get hashCode { + final _this = this as MediaImportFailure; + return Object.hash(runtimeType, _this.name, _this.failure); + } + + @override + String toString() { + final _this = this as MediaImportFailure; + return 'MediaImportFailure(name: ${_this.name}, failure: ${_this.failure})'; + } +} + +/// @nodoc +abstract mixin class $MediaImportFailureCopyWith<$Res> { + factory $MediaImportFailureCopyWith( + MediaImportFailure value, + $Res Function(MediaImportFailure) _then, + ) = _$MediaImportFailureCopyWithImpl; + @useResult + $Res call({String name, AppFailure failure}); +} + +/// @nodoc +class _$MediaImportFailureCopyWithImpl<$Res> + implements $MediaImportFailureCopyWith<$Res> { + _$MediaImportFailureCopyWithImpl(this._self, this._then); + + final MediaImportFailure _self; + final $Res Function(MediaImportFailure) _then; + + /// Create a copy of MediaImportFailure + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({Object? name = null, Object? failure = null}) { + return _then( + MediaImportFailure( + name: null == name + ? _self.name + : name // ignore: cast_nullable_to_non_nullable + as String, + failure: null == failure + ? _self.failure + : failure // ignore: cast_nullable_to_non_nullable + as AppFailure, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [MediaImportFailure]. +extension MediaImportFailurePatterns on MediaImportFailure { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_MediaImportFailure value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _MediaImportFailure() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_MediaImportFailure value) $default, + ) { + final _that = this; + switch (_that) { + case _MediaImportFailure(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_MediaImportFailure value)? $default, + ) { + final _that = this; + switch (_that) { + case _MediaImportFailure() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function(String name, AppFailure failure)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _MediaImportFailure() when $default != null: + return $default(_that.name, _that.failure); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function(String name, AppFailure failure) $default, + ) { + final _that = this; + switch (_that) { + case _MediaImportFailure(): + return $default(_that.name, _that.failure); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function(String name, AppFailure failure)? $default, + ) { + final _that = this; + switch (_that) { + case _MediaImportFailure() when $default != null: + return $default(_that.name, _that.failure); + case _: + return null; + } + } +} + +/// @nodoc + +class _MediaImportFailure implements MediaImportFailure { + const _MediaImportFailure({required this.name, required this.failure}); + + @override + final String name; + @override + final AppFailure failure; + + /// Create a copy of MediaImportFailure + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$MediaImportFailureCopyWith<_MediaImportFailure> get copyWith => + __$MediaImportFailureCopyWithImpl<_MediaImportFailure>(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _MediaImportFailure && + (identical(other.name, name) || other.name == name) && + (identical(other.failure, failure) || other.failure == failure)); + } + + @override + int get hashCode { + return Object.hash(runtimeType, name, failure); + } + + @override + String toString() { + return 'MediaImportFailure(name: $name, failure: $failure)'; + } +} + +/// @nodoc +abstract mixin class _$MediaImportFailureCopyWith<$Res> + implements $MediaImportFailureCopyWith<$Res> { + factory _$MediaImportFailureCopyWith( + _MediaImportFailure value, + $Res Function(_MediaImportFailure) _then, + ) = __$MediaImportFailureCopyWithImpl; + @override + @useResult + $Res call({String name, AppFailure failure}); +} + +/// @nodoc +class __$MediaImportFailureCopyWithImpl<$Res> + implements _$MediaImportFailureCopyWith<$Res> { + __$MediaImportFailureCopyWithImpl(this._self, this._then); + + final _MediaImportFailure _self; + final $Res Function(_MediaImportFailure) _then; + + /// Create a copy of MediaImportFailure + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({Object? name = null, Object? failure = null}) { + return _then( + _MediaImportFailure( + name: null == name + ? _self.name + : name // ignore: cast_nullable_to_non_nullable + as String, + failure: null == failure + ? _self.failure + : failure // ignore: cast_nullable_to_non_nullable + as AppFailure, + ), + ); + } +} + +/// @nodoc +mixin _$MediaImportResult { + List get assets; + int get added; + int get duplicates; + List get failures; + + /// Create a copy of MediaImportResult + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $MediaImportResultCopyWith get copyWith => + _$MediaImportResultCopyWithImpl( + this as MediaImportResult, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as MediaImportResult; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is MediaImportResult && + const DeepCollectionEquality().equals(other.assets, _this.assets) && + (identical(other.added, _this.added) || + other.added == _this.added) && + (identical(other.duplicates, _this.duplicates) || + other.duplicates == _this.duplicates) && + const DeepCollectionEquality().equals( + other.failures, + _this.failures, + )); + } + + @override + int get hashCode { + final _this = this as MediaImportResult; + return Object.hash( + runtimeType, + const DeepCollectionEquality().hash(_this.assets), + _this.added, + _this.duplicates, + const DeepCollectionEquality().hash(_this.failures), + ); + } + + @override + String toString() { + final _this = this as MediaImportResult; + return 'MediaImportResult(assets: ${_this.assets}, added: ${_this.added}, duplicates: ${_this.duplicates}, failures: ${_this.failures})'; + } +} + +/// @nodoc +abstract mixin class $MediaImportResultCopyWith<$Res> { + factory $MediaImportResultCopyWith( + MediaImportResult value, + $Res Function(MediaImportResult) _then, + ) = _$MediaImportResultCopyWithImpl; + @useResult + $Res call({ + List assets, + int added, + int duplicates, + List failures, + }); +} + +/// @nodoc +class _$MediaImportResultCopyWithImpl<$Res> + implements $MediaImportResultCopyWith<$Res> { + _$MediaImportResultCopyWithImpl(this._self, this._then); + + final MediaImportResult _self; + final $Res Function(MediaImportResult) _then; + + /// Create a copy of MediaImportResult + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? assets = null, + Object? added = null, + Object? duplicates = null, + Object? failures = null, + }) { + return _then( + MediaImportResult( + assets: null == assets + ? _self.assets + : assets // ignore: cast_nullable_to_non_nullable + as List, + added: null == added + ? _self.added + : added // ignore: cast_nullable_to_non_nullable + as int, + duplicates: null == duplicates + ? _self.duplicates + : duplicates // ignore: cast_nullable_to_non_nullable + as int, + failures: null == failures + ? _self.failures + : failures // ignore: cast_nullable_to_non_nullable + as List, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [MediaImportResult]. +extension MediaImportResultPatterns on MediaImportResult { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_MediaImportResult value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _MediaImportResult() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_MediaImportResult value) $default, + ) { + final _that = this; + switch (_that) { + case _MediaImportResult(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_MediaImportResult value)? $default, + ) { + final _that = this; + switch (_that) { + case _MediaImportResult() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + List assets, + int added, + int duplicates, + List failures, + )? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _MediaImportResult() when $default != null: + return $default( + _that.assets, + _that.added, + _that.duplicates, + _that.failures, + ); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function( + List assets, + int added, + int duplicates, + List failures, + ) + $default, + ) { + final _that = this; + switch (_that) { + case _MediaImportResult(): + return $default( + _that.assets, + _that.added, + _that.duplicates, + _that.failures, + ); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + List assets, + int added, + int duplicates, + List failures, + )? + $default, + ) { + final _that = this; + switch (_that) { + case _MediaImportResult() when $default != null: + return $default( + _that.assets, + _that.added, + _that.duplicates, + _that.failures, + ); + case _: + return null; + } + } +} + +/// @nodoc + +class _MediaImportResult implements MediaImportResult { + const _MediaImportResult({ + required List assets, + required this.added, + required this.duplicates, + required List failures, + }) : _assets = assets, + _failures = failures; + + final List _assets; + @override + List get assets { + if (_assets is EqualUnmodifiableListView) return _assets; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_assets); + } + + @override + final int added; + @override + final int duplicates; + final List _failures; + @override + List get failures { + if (_failures is EqualUnmodifiableListView) return _failures; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_failures); + } + + /// Create a copy of MediaImportResult + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$MediaImportResultCopyWith<_MediaImportResult> get copyWith => + __$MediaImportResultCopyWithImpl<_MediaImportResult>(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _MediaImportResult && + const DeepCollectionEquality().equals(other.assets, _assets) && + (identical(other.added, added) || other.added == added) && + (identical(other.duplicates, duplicates) || + other.duplicates == duplicates) && + const DeepCollectionEquality().equals(other.failures, _failures)); + } + + @override + int get hashCode { + return Object.hash( + runtimeType, + const DeepCollectionEquality().hash(_assets), + added, + duplicates, + const DeepCollectionEquality().hash(_failures), + ); + } + + @override + String toString() { + return 'MediaImportResult(assets: $assets, added: $added, duplicates: $duplicates, failures: $failures)'; + } +} + +/// @nodoc +abstract mixin class _$MediaImportResultCopyWith<$Res> + implements $MediaImportResultCopyWith<$Res> { + factory _$MediaImportResultCopyWith( + _MediaImportResult value, + $Res Function(_MediaImportResult) _then, + ) = __$MediaImportResultCopyWithImpl; + @override + @useResult + $Res call({ + List assets, + int added, + int duplicates, + List failures, + }); +} + +/// @nodoc +class __$MediaImportResultCopyWithImpl<$Res> + implements _$MediaImportResultCopyWith<$Res> { + __$MediaImportResultCopyWithImpl(this._self, this._then); + + final _MediaImportResult _self; + final $Res Function(_MediaImportResult) _then; + + /// Create a copy of MediaImportResult + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? assets = null, + Object? added = null, + Object? duplicates = null, + Object? failures = null, + }) { + return _then( + _MediaImportResult( + assets: null == assets + ? _self._assets + : assets // ignore: cast_nullable_to_non_nullable + as List, + added: null == added + ? _self.added + : added // ignore: cast_nullable_to_non_nullable + as int, + duplicates: null == duplicates + ? _self.duplicates + : duplicates // ignore: cast_nullable_to_non_nullable + as int, + failures: null == failures + ? _self._failures + : failures // ignore: cast_nullable_to_non_nullable + as List, + ), + ); + } +} diff --git a/lib/workspace/media_import_feedback.dart b/lib/workspace/media_import_feedback.dart new file mode 100644 index 0000000..cca50e4 --- /dev/null +++ b/lib/workspace/media_import_feedback.dart @@ -0,0 +1,29 @@ +import 'package:flutter/foundation.dart'; + +import 'external_media_import.dart'; + +/// Import failures remain available until a visible presentation consumes them. +class MediaImportFeedbackController extends ChangeNotifier { + final _pending = []; + bool get hasPending => _pending.isNotEmpty; + + void recordResult(ExternalMediaSelection? result) { + if (result == null || + !result.failed && result.result?.failures.isNotEmpty != true) { + return; + } + _pending.add(result); + notifyListeners(); + } + + void recordFailure() { + _pending.add(null); + notifyListeners(); + } + + List takePending() { + final notices = List.of(_pending); + _pending.clear(); + return notices; + } +} diff --git a/lib/workspace/media_timeline_duration.dart b/lib/workspace/media_timeline_duration.dart new file mode 100644 index 0000000..8ac3e5b --- /dev/null +++ b/lib/workspace/media_timeline_duration.dart @@ -0,0 +1,19 @@ +import 'package:cutdex/errors/app_failure.dart'; + +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; + +/// Convert source metadata once, without extending the range past its end. +RationalTime mediaTimelineDuration(MediaTime duration) { + final ticks = + BigInt.from(duration.numerator) * + BigInt.from(TimelineClock.ticksPerSecond) ~/ + BigInt.from(duration.denominator); + if (ticks <= BigInt.zero) { + throw AppException(AppErrorCode.invalidMediaDuration); + } + if (ticks > BigInt.from(0x7fffffffffffffff)) { + throw AppException(AppErrorCode.mediaDurationOutOfRange); + } + return RationalTime.timelineTicks(ticks.toInt()); +} diff --git a/lib/workspace/persistence/project_location_directory.dart b/lib/workspace/persistence/project_location_directory.dart new file mode 100644 index 0000000..19a2c26 --- /dev/null +++ b/lib/workspace/persistence/project_location_directory.dart @@ -0,0 +1,101 @@ +import 'package:cutdex/errors/app_failure.dart'; + +import 'dart:io'; + +import 'package:path/path.dart' as p; + +enum ProjectLocationStatus { ready, missing, unavailable, notWritable } + +class ProjectLocationDirectory { + const ProjectLocationDirectory(); + + Future inspect(String path) async { + if (!p.isAbsolute(path)) return ProjectLocationStatus.unavailable; + try { + final directory = Directory(path); + if (await directory.exists()) { + await _checkWritable(directory); + return ProjectLocationStatus.ready; + } + // Never recreate a missing external/network location on the system disk. + // Its mount point may still exist even though the volume is disconnected. + if (_isExternalPath(path)) return ProjectLocationStatus.unavailable; + var ancestor = directory; + while (!await ancestor.exists()) { + if (await FileSystemEntity.type(ancestor.path, followLinks: false) != + FileSystemEntityType.notFound) { + return ProjectLocationStatus.unavailable; + } + final parent = ancestor.parent; + if (parent.path == ancestor.path) { + return ProjectLocationStatus.unavailable; + } + ancestor = parent; + } + await _checkWritable(ancestor); + return ProjectLocationStatus.missing; + } on FileSystemException catch (error) { + return _isPermissionError(error) + ? ProjectLocationStatus.notWritable + : ProjectLocationStatus.unavailable; + } + } + + Future prepare(String path) async { + final status = await inspect(path); + if (status == ProjectLocationStatus.notWritable) { + throw AppException(AppErrorCode.projectLocationNotWritable); + } + if (status == ProjectLocationStatus.unavailable) { + throw AppException(AppErrorCode.projectLocationUnavailable); + } + try { + final directory = Directory(path); + if (status == ProjectLocationStatus.missing) { + await directory.create(recursive: true); + } + await _checkWritable(directory); + } on FileSystemException { + throw AppException(AppErrorCode.projectLocationCreateFailed); + } + } + + bool _isExternalPath(String path) { + if (Platform.isWindows) { + // Only the system drive is known to be local without a volume query. + final systemDrive = Platform.environment['SystemDrive']; + return systemDrive == null || + p.windows.rootPrefix(path).toLowerCase() != + '${systemDrive.toLowerCase()}\\'; + } + final normalized = p.normalize(path); + return const [ + '/Volumes', + '/mnt', + '/media', + '/run/media', + '/net', + ].any((root) => normalized == root || p.isWithin(root, normalized)); + } + + bool _isPermissionError(FileSystemException error) => + (Platform.isWindows ? const [5, 19] : const [1, 13, 30]).contains( + error.osError?.errorCode, + ); + + Future _checkWritable(Directory directory) async { + final probe = File( + p.join( + directory.path, + '.cutdex-write-$pid-${DateTime.now().microsecondsSinceEpoch}', + ), + ); + var created = false; + try { + await probe.create(exclusive: true); + created = true; + } finally { + if (created) await probe.delete(); + } + } +} diff --git a/lib/workspace/persistence/project_locator.dart b/lib/workspace/persistence/project_locator.dart new file mode 100644 index 0000000..e94617b --- /dev/null +++ b/lib/workspace/persistence/project_locator.dart @@ -0,0 +1,54 @@ +import 'dart:io'; + +import 'package:freezed_annotation/freezed_annotation.dart'; + +import 'package:path/path.dart' as p; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import '../project_state.dart'; + +part 'project_locator.g.dart'; +part 'project_locator.freezed.dart'; + +@Riverpod(keepAlive: true) +ProjectLocator projectLocator(Ref ref) => ProjectLocator(); + +/// Resolves a persisted location without opening the project database. +class ProjectLocator { + Future locate(RecentProject project) async { + final type = await FileSystemEntity.type(project.path, followLinks: true); + return switch (type) { + FileSystemEntityType.directory => ProjectLocation.available(project), + FileSystemEntityType.notFound => ProjectLocation.unavailable( + project, + _missingAvailability(project.path), + ), + _ => ProjectLocation.unavailable(project, .invalid), + }; + } + + ProjectAvailability _missingAvailability(String path) { + final parts = p.split(path); + if (parts.length >= 3 && parts[1] == 'Volumes') { + final volume = p.join(parts[0], parts[1], parts[2]); + if (!Directory(volume).existsSync()) return .volumeOffline; + } + return .missing; + } +} + +@freezed +abstract class ProjectLocation with _$ProjectLocation { + const ProjectLocation._(); + const factory ProjectLocation(RecentProject project) = _ProjectLocation; + + factory ProjectLocation.available(RecentProject project) => + ProjectLocation(project.copyWith(availability: .available)); + + factory ProjectLocation.unavailable( + RecentProject project, + ProjectAvailability availability, + ) => ProjectLocation(project.copyWith(availability: availability)); + + ProjectAvailability get availability => project.availability; +} diff --git a/lib/workspace/persistence/project_locator.freezed.dart b/lib/workspace/persistence/project_locator.freezed.dart new file mode 100644 index 0000000..c95c301 --- /dev/null +++ b/lib/workspace/persistence/project_locator.freezed.dart @@ -0,0 +1,337 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'project_locator.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +T _$identity(T value) => value; + +/// @nodoc +mixin _$ProjectLocation { + RecentProject get project; + + /// Create a copy of ProjectLocation + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $ProjectLocationCopyWith get copyWith => + _$ProjectLocationCopyWithImpl( + this as ProjectLocation, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as ProjectLocation; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is ProjectLocation && + (identical(other.project, _this.project) || + other.project == _this.project)); + } + + @override + int get hashCode { + final _this = this as ProjectLocation; + return Object.hash(runtimeType, _this.project); + } + + @override + String toString() { + final _this = this as ProjectLocation; + return 'ProjectLocation(project: ${_this.project})'; + } +} + +/// @nodoc +abstract mixin class $ProjectLocationCopyWith<$Res> { + factory $ProjectLocationCopyWith( + ProjectLocation value, + $Res Function(ProjectLocation) _then, + ) = _$ProjectLocationCopyWithImpl; + @useResult + $Res call({RecentProject project}); + + $RecentProjectCopyWith<$Res> get project; +} + +/// @nodoc +class _$ProjectLocationCopyWithImpl<$Res> + implements $ProjectLocationCopyWith<$Res> { + _$ProjectLocationCopyWithImpl(this._self, this._then); + + final ProjectLocation _self; + final $Res Function(ProjectLocation) _then; + + /// Create a copy of ProjectLocation + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({Object? project = null}) { + return _then( + ProjectLocation( + null == project + ? _self.project + : project // ignore: cast_nullable_to_non_nullable + as RecentProject, + ), + ); + } + + /// Create a copy of ProjectLocation + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $RecentProjectCopyWith<$Res> get project { + return $RecentProjectCopyWith<$Res>(_self.project, (value) { + return _then(_self.copyWith(project: value)); + }); + } +} + +/// Adds pattern-matching-related methods to [ProjectLocation]. +extension ProjectLocationPatterns on ProjectLocation { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_ProjectLocation value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ProjectLocation() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_ProjectLocation value) $default, + ) { + final _that = this; + switch (_that) { + case _ProjectLocation(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_ProjectLocation value)? $default, + ) { + final _that = this; + switch (_that) { + case _ProjectLocation() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function(RecentProject project)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ProjectLocation() when $default != null: + return $default(_that.project); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function(RecentProject project) $default, + ) { + final _that = this; + switch (_that) { + case _ProjectLocation(): + return $default(_that.project); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function(RecentProject project)? $default, + ) { + final _that = this; + switch (_that) { + case _ProjectLocation() when $default != null: + return $default(_that.project); + case _: + return null; + } + } +} + +/// @nodoc + +class _ProjectLocation extends ProjectLocation { + const _ProjectLocation(this.project) : super._(); + + @override + final RecentProject project; + + /// Create a copy of ProjectLocation + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$ProjectLocationCopyWith<_ProjectLocation> get copyWith => + __$ProjectLocationCopyWithImpl<_ProjectLocation>(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _ProjectLocation && + (identical(other.project, project) || other.project == project)); + } + + @override + int get hashCode { + return Object.hash(runtimeType, project); + } + + @override + String toString() { + return 'ProjectLocation(project: $project)'; + } +} + +/// @nodoc +abstract mixin class _$ProjectLocationCopyWith<$Res> + implements $ProjectLocationCopyWith<$Res> { + factory _$ProjectLocationCopyWith( + _ProjectLocation value, + $Res Function(_ProjectLocation) _then, + ) = __$ProjectLocationCopyWithImpl; + @override + @useResult + $Res call({RecentProject project}); + + @override + $RecentProjectCopyWith<$Res> get project; +} + +/// @nodoc +class __$ProjectLocationCopyWithImpl<$Res> + implements _$ProjectLocationCopyWith<$Res> { + __$ProjectLocationCopyWithImpl(this._self, this._then); + + final _ProjectLocation _self; + final $Res Function(_ProjectLocation) _then; + + /// Create a copy of ProjectLocation + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({Object? project = null}) { + return _then( + _ProjectLocation( + null == project + ? _self.project + : project // ignore: cast_nullable_to_non_nullable + as RecentProject, + ), + ); + } + + /// Create a copy of ProjectLocation + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $RecentProjectCopyWith<$Res> get project { + return $RecentProjectCopyWith<$Res>(_self.project, (value) { + return _then(_self.copyWith(project: value)); + }); + } +} diff --git a/lib/workspace/persistence/project_locator.g.dart b/lib/workspace/persistence/project_locator.g.dart new file mode 100644 index 0000000..b13d8b9 --- /dev/null +++ b/lib/workspace/persistence/project_locator.g.dart @@ -0,0 +1,51 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'project_locator.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(projectLocator) +final projectLocatorProvider = ProjectLocatorProvider._(); + +final class ProjectLocatorProvider + extends $FunctionalProvider + with $Provider { + ProjectLocatorProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'projectLocatorProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$projectLocatorHash(); + + @$internal + @override + $ProviderElement $createElement($ProviderPointer pointer) => + $ProviderElement(pointer); + + @override + ProjectLocator create(Ref ref) { + return projectLocator(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(ProjectLocator value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$projectLocatorHash() => r'b20be00ffdfc988f6e3eacd3af000be913568322'; diff --git a/lib/workspace/persistence/project_workspace.dart b/lib/workspace/persistence/project_workspace.dart new file mode 100644 index 0000000..e54d433 --- /dev/null +++ b/lib/workspace/persistence/project_workspace.dart @@ -0,0 +1,1049 @@ +import 'package:cutdex/errors/app_failure.dart'; + +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import '../../diagnostics/app_diagnostics.dart'; + +import 'timeline_creation_names.dart'; + +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:path/path.dart' as p; +import 'package:uuid/uuid.dart'; + +import 'package:cutdex_sdk/editor.dart'; + +import '../project_assets_changed.dart'; +import '../project_state.dart'; + +import '../media_file_extensions.dart'; +import '../media_import.dart'; +import '../prepared_media_metadata.dart'; +import '../timeline_session.dart'; +import '../background_task_registry.dart'; +import '../../integrations/runtime/editor_export.dart'; +import '../../integrations/runtime/processing_configuration.dart'; +import '../../integrations/platform/media_source_reader.dart'; + +class ProjectOpenSuperseded implements Exception {} + +class WorkspaceTimelineLease { + const WorkspaceTimelineLease(this.session, this.release, this.validate); + final EditorTimelineSession session; + final Future Function() release; + final Future Function() validate; +} + +typedef CreatedTimeline = ({ + List timelines, + TimelineDocument document, + EditorTimelineSession session, +}); + +/// Owns the active file and serializes operations, including close. +class ProjectWorkspace { + ProjectWorkspace({ + required this._creationNames, + CutdexRuntime? runtime, + ProcessingConfiguration? processing, + BackgroundTaskRegistry? backgroundTasks, + this.mediaSourceReader = const MediaSourceReader(), + }) : _runtime = runtime ?? CutdexRuntime(diagnostics: AppDiagnostics.report), + _processingOverride = processing, + backgroundTasks = backgroundTasks ?? BackgroundTaskRegistry(), + _ownsBackgroundTasks = backgroundTasks == null; + + final _assetChanges = StreamController.broadcast(); + Stream get assetChanges => _assetChanges.stream; + + final TimelineCreationNames _creationNames; + final CutdexRuntime _runtime; + final MediaSourceReader mediaSourceReader; + final ProcessingConfiguration? _processingOverride; + final BackgroundTaskRegistry backgroundTasks; + final bool _ownsBackgroundTasks; + ProcessingConfiguration? get _processing => + _processingOverride ?? + ProcessingConfiguration.configured(diagnostics: AppDiagnostics.report); + + ProjectFile? _project; + final _documents = {}; + final _documentVersions = {}; + final _sessions = {}; + final _retainedProjects = {}; + final _warmProjects = []; + + Set get cachedProjectIds => { + if (_project != null) _project!.info.id, + for (final file in _warmProjects) file.info.id, + }; + final _retainedTimelines = {}; + final _timelineLeases = {}; + Future _tail = Future.value(); + bool _closed = false; + Future? _closing; + static const _uuid = Uuid(); + + ProjectFile? get project => _project; + + EditorTimelineSession? cachedTimelineSession( + String projectId, + String timelineId, + ) { + if (_project?.info.id != projectId) return null; + final session = _sessions[timelineId]; + return session?.acceptsEdits == true ? session : null; + } + + TimelineDocument? cachedTimelineDocument( + String projectId, + String timelineId, + ) => _project?.info.id == projectId ? _documents[timelineId] : null; + + ProjectFile? _fileFor(String projectId) { + final active = _project; + if (active?.info.id == projectId) return active; + for (final file in _retainedProjects) { + if (file.info.id == projectId) return file; + } + return null; + } + + Future _retireProject() async { + final file = _project; + if (file == null) return; + for (final timeline in _sessions.values) { + await timeline.flush(); + } + for (final timeline in _sessions.values) { + _retainedTimelines[timeline] = file; + } + _retainedProjects.add(file); + _warmProjects.remove(file); + _warmProjects.add(file); + _sessions.clear(); + _documents.clear(); + _documentVersions.clear(); + _project = null; + } + + Future _trimWarmProjects() async { + while (_warmProjects.length > 2) { + final file = _warmProjects.removeAt(0); + final sessions = _retainedTimelines.entries + .where((entry) => entry.value == file) + .map((entry) => entry.key) + .toList(); + for (final session in sessions) { + final hasTasks = + session.subtitleWorkflows.tasks.isNotEmpty || + (session.transcriptions?.tasks.isNotEmpty ?? false) || + session.backgroundRemovals.tasks.isNotEmpty; + if ((_timelineLeases[session] ?? 0) > 0 || hasTasks) continue; + await session.flush(); + backgroundTasks.unregister(session); + await session.close(); + _retainedTimelines.remove(session); + } + if (!_retainedTimelines.containsValue(file)) { + _retainedProjects.remove(file); + await file.close(); + } + } + } + + Future leaseTimeline( + String projectId, + String timelineId, + ) => _run(() async { + final session = _sessions[timelineId]; + if (_project?.info.id != projectId || session == null) { + throw AppException(AppErrorCode.openTimelineFailed); + } + _timelineLeases[session] = (_timelineLeases[session] ?? 0) + 1; + final file = _project!; + var released = false; + Future validate() async { + if (!session.acceptsEdits) { + throw AppException(AppErrorCode.timelineSessionClosed); + } + final manifest = File(p.join(file.directory.path, 'manifest.json')); + final value = jsonDecode(await manifest.readAsString()); + if (value is! Map || value['projectId'] != projectId) { + throw AppException(AppErrorCode.projectMismatch); + } + } + + return WorkspaceTimelineLease( + session, + () => _run(() async { + if (released) return; + released = true; + final remaining = (_timelineLeases[session] ?? 1) - 1; + if (remaining > 0) { + _timelineLeases[session] = remaining; + return; + } + _timelineLeases.remove(session); + final retainedFile = _retainedTimelines[session]; + if (retainedFile == null || _warmProjects.contains(retainedFile)) { + return; + } + final file = _retainedTimelines.remove(session)!; + backgroundTasks.unregister(session); + await session.close(); + if (file != _project && !_retainedTimelines.containsValue(file)) { + _retainedProjects.remove(file); + await file.close(); + } + }), + validate, + ); + }); + + bool get hasBackgroundTasks => + {..._sessions.values, ..._retainedTimelines.keys}.any( + (timeline) => + timeline.subtitleWorkflows.runningCount > 0 || + (timeline.transcriptions?.translationTasks.any( + (task) => !task.terminal, + ) ?? + false) || + (timeline.vocalSeparations?.tasks.any((task) => !task.terminal) ?? + false), + ); + + Future _run(Future Function() action) { + if (_closed) { + return Future.error(AppException(AppErrorCode.projectSessionClosed)); + } + final result = _tail.then((_) => action()); + _tail = result.then((_) {}, onError: (Object _, StackTrace _) {}); + return result; + } + + Future> open( + String path, { + String? name, + String? expectedId, + TimelineCreationNames? creationNames, + bool Function()? isCurrent, + }) => _run(() async { + void checkCurrent() { + if (isCurrent?.call() == false) throw ProjectOpenSuperseded(); + } + + checkCurrent(); + final directory = Directory(path); + ProjectFile? candidate; + var installed = false; + try { + if (_project != null && + name == null && + await directory.resolveSymbolicLinks() == _project!.directory.path) { + if (expectedId != null && expectedId != _project!.info.id) { + throw AppException(AppErrorCode.projectMismatch); + } + return await _project!.listTimelines(); + } + final canonicalPath = name == null + ? await directory.resolveSymbolicLinks() + : null; + final retained = name == null + ? _retainedProjects + .where((file) => file.directory.path == canonicalPath) + .firstOrNull + : null; + candidate = + retained ?? + (name == null + ? await ProjectFile.open(directory) + : await ProjectFile.create( + directory, + name: name, + initialTimeline: _newTimelineDocument( + (creationNames ?? _creationNames).timeline, + creationNames ?? _creationNames, + ), + )); + if (expectedId != null && candidate.info.id != expectedId) { + throw AppException(AppErrorCode.projectMismatch); + } + var timelines = await candidate.listTimelines(); + if (timelines.isEmpty) { + final initial = _newTimelineDocument( + (creationNames ?? _creationNames).timeline, + creationNames ?? _creationNames, + ); + await candidate.saveTimeline(initial); + await candidate.setTimelinePinned(initial.id, true); + timelines = await candidate.listTimelines(); + } + checkCurrent(); + final documents = {}; + for (final timeline in timelines) { + checkCurrent(); + documents[timeline.id] = await candidate.loadTimeline(timeline.id); + } + checkCurrent(); + // Saving the previous project is deliberately not cancellable. + await _retireProject(); + _retainedProjects.remove(candidate); + _warmProjects.remove(candidate); + _project = candidate; + _documents.addAll(documents); + installed = true; + await _trimWarmProjects(); + return timelines; + } finally { + if (!installed) { + if (candidate != null && !_retainedProjects.contains(candidate)) { + await candidate.close(); + } + } + } + }); + + /// Reads timelines from any project without installing it as the active one. + /// + /// This intentionally shares the workspace queue with [open] and all active + /// project operations. A restored expansion and a restored active project + /// can otherwise try to open the same SQLite files at the same time. + Future> listProjectTimelines( + String path, { + required String expectedId, + }) => _run(() async { + final available = _fileFor(expectedId); + if (available != null) { + return available.listTimelines(); + } + final candidate = await ProjectFile.open(Directory(path)); + try { + if (candidate.info.id != expectedId) { + throw AppException(AppErrorCode.projectMismatch); + } + return await candidate.listTimelines(); + } finally { + await candidate.close(); + } + }); + + Future renameProject(RecentProject project, String name) => + _withProject(project, (file) => file.rename(name)); + + Future renameTimeline( + RecentProject project, + String timelineId, + String name, + ) => _withProject(project, (file) async { + await file.renameTimeline(timelineId, name); + if (file != _project) return; + final document = _documents[timelineId]; + if (document == null) return; + _documents[timelineId] = TimelineDocument( + id: document.id, + name: name, + sequences: document.sequences, + defaultSequenceId: document.defaultSequenceId, + payloads: document.payloads, + settings: document.settings, + revision: document.revision, + ); + }); + + Future> setTimelinePinned( + RecentProject project, + String timelineId, + bool pinned, + ) => _withProject(project, (file) async { + await file.setTimelinePinned(timelineId, pinned); + return file.listTimelines(); + }); + + Future> deleteTimeline( + RecentProject project, + String timelineId, + ) => _withProject(project, (file) async { + final session = file == _project ? _sessions[timelineId] : null; + if (session != null) { + if ((_timelineLeases[session] ?? 0) > 0) { + throw AppException(AppErrorCode.timelineInUse); + } + if (session.subtitleWorkflows.runningCount > 0 || + session.backgroundRemovals.runningCount > 0 || + (session.vocalSeparations?.tasks.any((task) => !task.terminal) ?? + false)) { + throw AppException(AppErrorCode.timelineHasBackgroundTasks); + } + await session.flush(); + } + final summaries = await file.listTimelines(); + final target = summaries.where((item) => item.id == timelineId).firstOrNull; + if (target == null) throw AppException(AppErrorCode.timelineMissing); + await file.deleteTimeline(timelineId, expectedRevision: target.revision); + if (session != null) { + backgroundTasks.unregister(session); + await session.close(); + } + if (file == _project) { + _sessions.remove(timelineId); + _documents.remove(timelineId); + _documentVersions.remove(timelineId); + } + return file.listTimelines(); + }); + + Future _withProject( + RecentProject project, + Future Function(ProjectFile file) action, + ) => _run(() async { + final available = _fileFor(project.id); + if (available != null) return action(available); + final candidate = await ProjectFile.open(Directory(project.path)); + try { + if (candidate.info.id != project.id) { + throw AppException(AppErrorCode.projectMismatch); + } + return await action(candidate); + } finally { + await candidate.close(); + } + }); + + Future> createTimeline( + String name, { + TimelineCreationNames? creationNames, + }) => _run(() async { + await _createTimelineDocument(name, creationNames ?? _creationNames); + return _project!.listTimelines(); + }); + + Future createPreparedTimeline( + String name, { + TimelineCreationNames? creationNames, + }) => _run(() async { + final saved = await _createTimelineDocument( + name, + creationNames ?? _creationNames, + ); + final project = _project!; + final session = await _openTimelineSession(project.info.id, saved); + return ( + timelines: await project.listTimelines(), + document: saved, + session: session, + ); + }); + + Future _createTimelineDocument( + String name, + TimelineCreationNames creationNames, + ) async { + final project = _project; + if (project == null) throw AppException(AppErrorCode.openProjectFirst); + final document = _newTimelineDocument(name, creationNames); + await project.saveTimeline(document); + final saved = await project.loadTimeline(document.id); + _documents[document.id] = saved; + return saved; + } + + TimelineDocument _newTimelineDocument( + String name, + TimelineCreationNames creationNames, + ) { + final sequence = TimelineDto( + id: SequenceId(_uuid.v4()), + name: creationNames.sequence, + format: TimelineFormat(frameDuration: RationalTime(1, 30)), + primaryStorylineId: StorylineId('primary'), + storylines: [ + StorylineDto( + id: StorylineId('primary'), + elementIds: [], + name: creationNames.storyline, + ), + ], + elements: [], + ); + return TimelineDocument( + id: _uuid.v4(), + name: name, + sequences: [sequence], + defaultSequenceId: sequence.id, + ); + } + + Future loadTimeline(String projectId, String timelineId) => + _run(() async { + if (_project?.info.id != projectId) { + throw AppException(AppErrorCode.openMatchingProject); + } + for (final session in _retainedTimelines.keys) { + if (session.document.id == timelineId && + _retainedTimelines[session] == _project) { + return _documents[timelineId] ?? session.document; + } + } + final session = _sessions[timelineId]; + if (session != null && + _documentVersions[timelineId] != session.version) { + await session.flush(); + _documents[timelineId] = await _project!.loadTimeline(timelineId); + _documentVersions[timelineId] = session.version; + } + final document = + _documents[timelineId] ?? await _project!.loadTimeline(timelineId); + _documents[timelineId] = document; + return document; + }); + + Future> listAssets(String projectId) => _run(() async { + final project = _fileFor(projectId); + if (project == null) throw AppException(AppErrorCode.openMatchingProject); + return _visibleAssets(await project.listAssets()); + }); + + static const _hiddenAssetKey = 'cutdex.catalogHidden'; + + static List _visibleAssets(List assets) => [ + for (final asset in assets) + if (asset.metadata[_hiddenAssetKey] != true) asset, + ]; + + static AssetDocument _catalogAsset( + AssetDocument asset, { + String? name, + bool? hidden, + }) => AssetDocument( + id: asset.id, + name: name ?? asset.name, + storage: asset.storage, + location: asset.location, + byteLength: asset.byteLength, + contentHash: asset.contentHash, + metadata: { + for (final entry in asset.metadata.entries) + if (entry.key != _hiddenAssetKey || hidden == null) + entry.key: entry.value, + if (hidden == true) _hiddenAssetKey: true, + }, + accessData: asset.accessData, + ); + + Future> editAsset( + String projectId, + String assetId, { + String? name, + }) => _run( + () async => (await _editCatalog(projectId, assetId, name: name)).assets, + ); + + Future editCatalog(String projectId, String assetId, {String? name}) => + _run( + () async => + (await _editCatalog(projectId, assetId, name: name)).changed, + ); + + Future<({List assets, bool changed})> _editCatalog( + String projectId, + String assetId, { + String? name, + }) async { + final project = _fileFor(projectId); + if (project == null) { + throw const CommandRejected('closed', 'Media project has changed'); + } + final all = await project.listAssets(); + final asset = all.where((a) => a.id == assetId).firstOrNull; + if (asset == null) { + throw const CommandRejected('missingMedia', 'Media does not exist'); + } + if (name != null && name.trim().isEmpty) { + throw const CommandRejected('invalidArguments', 'Name is empty'); + } + final changed = name == null + ? asset.metadata[_hiddenAssetKey] != true + : asset.name != name.trim(); + if (changed) { + await project.saveAsset( + name == null + ? _catalogAsset(asset, hidden: true) + : _catalogAsset(asset, name: name.trim()), + ); + } + final visible = _visibleAssets(await project.listAssets()); + if (changed) _assetChanges.add(ProjectAssetsChanged(projectId, visible)); + return (assets: visible, changed: changed); + } + + Future withAssetMedia( + String projectId, + AssetDocument asset, + Future Function(MediaReference media) action, + ) async { + final media = await _run(() async { + final project = _fileFor(projectId); + if (project == null) { + throw AppException(AppErrorCode.projectSwitched); + } + final uri = await project.resolveAsset(asset); + return MediaReference( + id: asset.id, + uri: uri, + isImage: asset.metadata['kind'] == 'image', + ); + }); + return action(media); + } + + /// Registers local references and imports provider documents into the project. + Future importExternalMedia( + String projectId, + Iterable files, { + bool Function()? isCancelled, + }) { + final batch = files.toList(growable: false); + return _run(() async { + final project = _fileFor(projectId); + if (project == null) { + throw AppException(AppErrorCode.openMatchingProject); + } + final assets = await project.listAssets(); + final locations = { + for (final asset in assets) + if (asset.metadata[_hiddenAssetKey] != true) + ?mediaSourceLocation(asset), + }; + final hiddenByLocation = { + for (final asset in assets) + if (asset.metadata[_hiddenAssetKey] == true) + ?mediaSourceLocation(asset): asset, + }; + final failures = []; + var added = 0; + var duplicates = 0; + for (final source in batch) { + try { + if (source case ContentMediaFile()) { + final location = source.sourceUri.toString(); + if (locations.contains(location)) { + duplicates++; + continue; + } + final hidden = hiddenByLocation[location]; + if (hidden != null) { + if (isCancelled?.call() == true) { + throw AppException(AppErrorCode.mediaImportCancelled); + } + await project.saveAsset(_catalogAsset(hidden, hidden: false)); + } else { + await _importProviderMedia(project, source, isCancelled); + } + locations.add(location); + added++; + continue; + } + final sourcePath = source.localPath!; + if (!p.isAbsolute(sourcePath)) { + throw AppException(AppErrorCode.localFilesOnly); + } + // The native runtime verifies the selected file's actual media tracks. + final kind = mediaKindForPath(sourcePath); + if (kind == null) { + throw AppException(AppErrorCode.unsupportedMediaType); + } + final file = File(await File(sourcePath).resolveSymbolicLinks()); + final stat = await file.stat(); + if (stat.type != FileSystemEntityType.file) { + throw AppException(AppErrorCode.foldersUnsupported); + } + // Check read access without reading the file into memory. + final handle = await file.open(); + await handle.close(); + final location = file.uri.toString(); + if (locations.contains(location)) { + duplicates++; + continue; + } + if (p.extension(file.path).toLowerCase() == '.iso') { + final metadata = PreparedMediaMetadata.fromInfo( + await _runtime.probe(MediaReference(id: location, uri: file.uri)), + ); + if (metadata.kind != EditorMediaKind.video) { + throw AppException(AppErrorCode.mediaNoVideoTracks); + } + } + final hidden = hiddenByLocation[location]; + if (hidden != null) { + if (isCancelled?.call() == true) { + throw AppException(AppErrorCode.mediaImportCancelled); + } + await project.saveAsset(_catalogAsset(hidden, hidden: false)); + locations.add(location); + added++; + continue; + } + final asset = AssetDocument( + id: _uuid.v4(), + name: source.displayName, + storage: AssetStorage.external, + location: location, + byteLength: stat.size, + metadata: {'kind': kind}, + ); + if (isCancelled?.call() == true) { + throw AppException(AppErrorCode.mediaImportCancelled); + } + await project.saveAsset(asset); + locations.add(location); + added++; + } catch (error) { + failures.add( + MediaImportFailure( + name: source.displayName, + failure: switch (error) { + AppException(:final failure) => failure, + FileSystemException() => AppFailure( + AppErrorCode.fileAccessFailed, + diagnostic: error.toString(), + ), + _ => AppFailure( + AppErrorCode.registerMediaFailed, + diagnostic: error.toString(), + ), + }, + ), + ); + } + } + final visible = _visibleAssets(await project.listAssets()); + _assetChanges.add(ProjectAssetsChanged(projectId, visible)); + return MediaImportResult( + assets: visible, + added: added, + duplicates: duplicates, + failures: failures, + ); + }); + } + + Future _importProviderMedia( + ProjectFile project, + ContentMediaFile source, + bool Function()? isCancelled, + ) async { + final kind = mediaKindForPath(source.name); + if (source.uri.scheme != 'content' || source.uri.host.isEmpty) { + throw AppException( + AppErrorCode.fileAccessFailed, + diagnostic: 'Invalid provider URI', + ); + } + if (kind == null) throw AppException(AppErrorCode.unsupportedMediaType); + if (isCancelled?.call() == true) { + throw AppException(AppErrorCode.mediaImportCancelled); + } + final staging = await Directory.systemTemp.createTemp( + 'cutdex-media-import-', + ); + try { + final file = File( + p.join(staging.path, 'source${p.extension(source.name)}'), + ); + final handle = await file.open(mode: FileMode.write); + var bytes = 0; + try { + await for (final chunk in mediaSourceReader.openRead(source.uri)) { + if (isCancelled?.call() == true) { + throw AppException(AppErrorCode.mediaImportCancelled); + } + await handle.writeFrom(chunk); + bytes += chunk.length; + } + await handle.flush(); + } finally { + await handle.close(); + } + if (source.byteLength != null && source.byteLength != bytes) { + throw AppException( + AppErrorCode.mediaReadFailed, + diagnostic: 'Expected ${source.byteLength} bytes, received $bytes', + ); + } + if (isCancelled?.call() == true) { + throw AppException(AppErrorCode.mediaImportCancelled); + } + await project.importFile( + file, + name: source.name, + metadata: {'kind': kind, mediaSourceUriKey: source.uri.toString()}, + ); + } finally { + await staging.delete(recursive: true); + } + } + + Future openTimelineSession( + String projectId, + TimelineDocument document, + ) => _run(() => _openTimelineSession(projectId, document)); + + Future _openTimelineSession( + String projectId, + TimelineDocument document, + ) async { + if (_project?.info.id != projectId) { + throw AppException(AppErrorCode.openMatchingProject); + } + final existing = _sessions[document.id]; + if (existing != null) return existing; + for (final session in _retainedTimelines.keys.toList()) { + if (session.document.id == document.id && + _retainedTimelines[session] == _project) { + _retainedTimelines.remove(session); + _sessions[document.id] = session; + _documentVersions[document.id] = session.version; + return session; + } + } + final persistence = await _project!.openTimelineSaveSession(document.id); + EditorSession.validateCheckpoint(document, persistence); + final referencedAssets = document.payloads + .expand((payload) => payload.assetIds) + .toSet(); + final assetUris = {}; + for (final asset in await _project!.listAssets()) { + if (referencedAssets.contains(asset.id)) { + assetUris[asset.id] = await _project!.resolveAsset(asset); + } + } + final processing = _processing; + final session = EditorTimelineSession( + diagnostics: (event) => withDiagnosticContext({ + 'projectId': projectId, + }, () => reportDiagnostic(AppDiagnostics.report, event)), + document: document, + persistence: persistence, + assetUris: Map.unmodifiable(assetUris), + media: _WorkspaceEditorMedia(this, projectId), + exportService: RuntimeEditorExport(_runtime), + captionFiles: Platform.isMacOS || Platform.isIOS || Platform.isWindows + ? _runtime + : null, + transcriptionBackend: processing?.transcriptionModel == null + ? null + : processing!.backend, + transcriptionModel: processing?.transcriptionModel, + translationBackend: processing?.translationModel == null + ? null + : processing!.backend, + translationModel: processing?.translationModel, + vocalSeparationBackend: processing?.vocalSeparationModel == null + ? null + : processing!.backend, + vocalSeparationModel: processing?.vocalSeparationModel, + ); + if (processing?.backgroundRemovalModel case final model?) { + session.backgroundRemovals.configure( + backend: processing!.backend.execute, + model: model, + ); + } + await session.restoreProcessingTasks(); + _sessions[document.id] = session; + backgroundTasks.register( + projectId: projectId, + projectName: _project!.info.name, + session: session, + ); + _documents[document.id] = document; + _documentVersions[document.id] = session.version; + return session; + } + + Future prepareMedia( + String projectId, + String assetId, + ) => _run(() async { + final project = _fileFor(projectId); + if (project == null) throw AppException(AppErrorCode.openMatchingProject); + final asset = (await project.listAssets()) + .where((asset) => asset.id == assetId) + .firstOrNull; + if (asset == null) throw AppException(AppErrorCode.mediaNoLongerExists); + final uri = await project.resolveAsset(asset); + final PreparedMediaMetadata metadata; + if (asset.metadata['kind'] == 'image') { + metadata = PreparedMediaMetadata.image(); + } else { + try { + final source = MediaReference(id: asset.id, uri: uri); + metadata = PreparedMediaMetadata.fromInfo(await _runtime.probe(source)); + } on RuntimeException catch (e) { + throw AppException( + e.code == 'unsupported' + ? AppErrorCode.mediaInfoUnsupported + : AppErrorCode.mediaInfoFailed, + diagnostic: e.toString(), + ); + } + } + return PreparedEditorMedia( + asset: _editorAsset(asset), + uri: uri, + duration: metadata.duration, + kind: metadata.kind, + hasAudio: metadata.hasAudio, + audioTracks: metadata.audioTracks, + ); + }); + + Future importGeneratedMedia( + String projectId, + String path, { + required String name, + }) async { + final asset = await _run(() async { + final project = _fileFor(projectId); + if (project == null) { + throw const CommandRejected('closed', 'Media project has changed'); + } + final imported = await project.importFile( + File(path), + name: name, + recoveryKey: 'generated:${File(path).absolute.path}', + ); + final visible = _visibleAssets(await project.listAssets()); + _assetChanges.add(ProjectAssetsChanged(projectId, visible)); + return imported; + }); + return prepareMedia(projectId, asset.id); + } + + Future close() { + if (_closing case final pending?) return pending; + _closed = true; + final operation = _tail.then((_) async { + try { + for (final session in _sessions.values) { + await session.flush(); + } + for (final session in _retainedTimelines.keys) { + await session.flush(); + } + for (final session in _sessions.values) { + backgroundTasks.unregister(session); + await session.close(); + } + for (final session in _retainedTimelines.keys) { + backgroundTasks.unregister(session); + await session.close(); + } + } catch (_) { + // Nothing has been released yet. Keep the workspace usable so the + // caller can recover an unsuccessful save without losing the edits. + _closed = false; + rethrow; + } + _sessions.clear(); + _documents.clear(); + _documentVersions.clear(); + _retainedTimelines.clear(); + _timelineLeases.clear(); + await _project?.close(); + for (final file in _retainedProjects) { + await file.close(); + } + _project = null; + _retainedProjects.clear(); + _warmProjects.clear(); + await _assetChanges.close(); + if (_ownsBackgroundTasks) backgroundTasks.dispose(); + }); + final closing = operation.onError((Object error, StackTrace stack) { + _closing = null; + Error.throwWithStackTrace(error, stack); + }); + _closing = closing; + // A failed close must not poison the queue or prevent cleanup retries. + _tail = closing.then((_) {}, onError: (Object _, StackTrace _) {}); + return closing; + } +} + +final class _WorkspaceEditorMedia + implements + EditorMediaService, + EditorAudioSource, + EditorMediaCatalog, + EditorGeneratedMediaCatalog { + const _WorkspaceEditorMedia(this.workspace, this.projectId); + final ProjectWorkspace workspace; + final String projectId; + @override + Future> query() async => [ + for (final asset in await workspace.listAssets(projectId)) + _editorAsset(asset), + ]; + @override + Future importFile( + String path, { + bool Function()? isCancelled, + }) async { + final result = await workspace.importExternalMedia(projectId, [ + ExternalMediaFile(path: path), + ], isCancelled: isCancelled); + if (result.failures.isNotEmpty) { + throw AppException.fromFailure(result.failures.first.failure); + } + return EditorMediaImportResult( + assets: [for (final asset in result.assets) _editorAsset(asset)], + added: result.added, + duplicates: result.duplicates, + ); + } + + @override + Future rename(String assetId, String name) => + workspace.editCatalog(projectId, assetId, name: name); + @override + Future remove(String assetId) => + workspace.editCatalog(projectId, assetId); + @override + Future waveform(String assetId, int audioTrackIndex) async { + final asset = (await workspace.listAssets(projectId)) + .where((a) => a.id == assetId) + .firstOrNull; + if (asset == null) { + throw const CommandRejected('missingMedia', 'Audio asset is unavailable'); + } + return workspace.withAssetMedia( + projectId, + asset, + (media) => CutdexRuntime(diagnostics: AppDiagnostics.report).waveform( + WaveformRequest( + media: media, + trackSelection: TrackSelection.index(audioTrackIndex), + baseBucketCount: 32768, + levelCount: 1, + ), + ), + ); + } + + @override + Future prepare(String assetId) => + workspace.prepareMedia(projectId, assetId); + @override + Future importGenerated( + String path, { + required String name, + }) => workspace.importGeneratedMedia(projectId, path, name: name); +} + +EditorMediaAsset _editorAsset(AssetDocument asset) => + EditorMediaAsset(id: asset.id, name: asset.name, metadata: asset.metadata); diff --git a/lib/workspace/persistence/recent_projects.dart b/lib/workspace/persistence/recent_projects.dart new file mode 100644 index 0000000..84d4d23 --- /dev/null +++ b/lib/workspace/persistence/recent_projects.dart @@ -0,0 +1,70 @@ +import 'package:drift/drift.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import '../../persistence/app_database.dart'; +import '../project_state.dart'; + +part 'recent_projects.g.dart'; + +@Riverpod(keepAlive: true) +RecentProjectsRepository recentProjects(Ref ref) => + DriftRecentProjectsRepository(ref.watch(appDatabaseProvider)); + +abstract interface class RecentProjectsRepository { + Future lastTimeline(String projectId); + Future rememberTimeline(String projectId, String timelineId); + Future> load(); + Future save(List projects); +} + +class DriftRecentProjectsRepository implements RecentProjectsRepository { + DriftRecentProjectsRepository(this._database); + + final AppDatabase _database; + + @override + Future lastTimeline(String projectId) => + (_database.select(_database.lastOpenedTimelines) + ..where((table) => table.projectId.equals(projectId))) + .getSingleOrNull() + .then((row) => row?.timelineId); + + @override + Future rememberTimeline(String projectId, String timelineId) => + _database + .into(_database.lastOpenedTimelines) + .insertOnConflictUpdate( + LastOpenedTimelinesCompanion.insert( + projectId: projectId, + timelineId: timelineId, + ), + ); + + @override + Future> load() async { + final rows = await (_database.select( + _database.recentProjectRecords, + )..orderBy([(table) => OrderingTerm.asc(table.position)])).get(); + return [ + for (final row in rows) + RecentProject(id: row.id, name: row.name, path: row.path), + ]; + } + + @override + Future save(List projects) => + _database.transaction(() async { + await _database.delete(_database.recentProjectRecords).go(); + await _database.batch((batch) { + batch.insertAll(_database.recentProjectRecords, [ + for (final (position, project) in projects.indexed) + RecentProjectRecordsCompanion.insert( + id: project.id, + name: project.name, + path: project.path, + position: position, + ), + ]); + }); + }); +} diff --git a/lib/workspace/persistence/recent_projects.g.dart b/lib/workspace/persistence/recent_projects.g.dart new file mode 100644 index 0000000..b0d01f6 --- /dev/null +++ b/lib/workspace/persistence/recent_projects.g.dart @@ -0,0 +1,57 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'recent_projects.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(recentProjects) +final recentProjectsProvider = RecentProjectsProvider._(); + +final class RecentProjectsProvider + extends + $FunctionalProvider< + RecentProjectsRepository, + RecentProjectsRepository, + RecentProjectsRepository + > + with $Provider { + RecentProjectsProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'recentProjectsProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$recentProjectsHash(); + + @$internal + @override + $ProviderElement $createElement( + $ProviderPointer pointer, + ) => $ProviderElement(pointer); + + @override + RecentProjectsRepository create(Ref ref) { + return recentProjects(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(RecentProjectsRepository value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$recentProjectsHash() => r'ca0054cd01bba053c99058ffadd6342bae057ed6'; diff --git a/lib/workspace/persistence/timeline_creation_names.dart b/lib/workspace/persistence/timeline_creation_names.dart new file mode 100644 index 0000000..6048291 --- /dev/null +++ b/lib/workspace/persistence/timeline_creation_names.dart @@ -0,0 +1,12 @@ +/// Names already chosen by the caller, persisted verbatim on creation. +final class TimelineCreationNames { + const TimelineCreationNames({ + required this.timeline, + required this.sequence, + required this.storyline, + }); + + final String timeline; + final String sequence; + final String storyline; +} diff --git a/lib/workspace/prepared_media_metadata.dart b/lib/workspace/prepared_media_metadata.dart new file mode 100644 index 0000000..f966fdf --- /dev/null +++ b/lib/workspace/prepared_media_metadata.dart @@ -0,0 +1,44 @@ +import 'package:cutdex/errors/app_failure.dart'; + +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; + +import 'media_timeline_duration.dart'; + +/// Validated source metadata shared by timeline insertion entry points. +final class PreparedMediaMetadata { + PreparedMediaMetadata._({ + required this.duration, + required this.kind, + required this.hasAudio, + required List audioTracks, + }) : audioTracks = List.unmodifiable(audioTracks); + + factory PreparedMediaMetadata.image() => PreparedMediaMetadata._( + duration: RationalTime.seconds(5), + kind: EditorMediaKind.image, + hasAudio: false, + audioTracks: const [], + ); + + factory PreparedMediaMetadata.fromInfo(MediaInfo info) { + if (info.isProtected || + (info.videoTrackCount == 0 && info.audioTrackCount == 0)) { + throw AppException(AppErrorCode.mediaNoTracks); + } + return PreparedMediaMetadata._( + duration: mediaTimelineDuration(info.duration), + kind: info.videoTrackCount > 0 + ? EditorMediaKind.video + : EditorMediaKind.audio, + hasAudio: info.audioTrackCount > 0, + audioTracks: info.audioTracks, + ); + } + + final RationalTime duration; + final EditorMediaKind kind; + final bool hasAudio; + final List audioTracks; +} diff --git a/lib/workspace/preview_controller_registry.dart b/lib/workspace/preview_controller_registry.dart new file mode 100644 index 0000000..09d2940 --- /dev/null +++ b/lib/workspace/preview_controller_registry.dart @@ -0,0 +1,109 @@ +import 'dart:async'; + +import 'package:cutdex_sdk/preview.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import 'preview_target.dart'; +import 'timeline_session.dart'; + +part 'preview_controller_registry.g.dart'; + +@Riverpod(keepAlive: true) +PreviewControllerRegistry previewControllerRegistry(Ref ref) { + final registry = PreviewControllerRegistry( + ref.read(runtimeConnectionProvider), + ); + ref.onDispose(registry.dispose); + return registry; +} + +/// Owns native preview controllers independently of the currently visible +/// timeline. Prepared controllers make timeline selection a synchronous swap. +final class PreviewControllerRegistry { + PreviewControllerRegistry(this._runtime); + + final CutdexRuntime _runtime; + final _controllers = <(String, String), PreviewController>{}; + final _preparing = <(String, String), Future>{}; + bool _disposed = false; + + PreviewController? cached((String, String) ids) => _controllers[ids]; + + FutureOr prepare( + (String, String) ids, + EditorTimelineSession timeline, + ) { + if (_disposed) throw StateError('Preview registry is closed'); + final sequence = timeline.activeSequenceId; + if (sequence == null || timeline.sequenceDurationTicks(sequence) == 0) { + return null; + } + final cached = _controllers[ids]; + if (cached != null) return cached; + final pending = _preparing[ids]; + if (pending != null) return pending; + final future = _initialize(ids, timeline); + _preparing[ids] = future; + return future; + } + + Future _initialize( + (String, String) ids, + EditorTimelineSession timeline, + ) async { + final controller = PreviewController( + timeline: timeline, + activeSequence: () => timeline.activeSequenceId, + viewForSequence: timeline.view, + runtime: _runtime, + ); + try { + await controller.initialize(); + if (_disposed) { + await controller.close(); + throw StateError('Preview registry is closed'); + } + _controllers[ids] = controller; + return controller; + } catch (_) { + await controller.close().catchError((Object _) {}); + rethrow; + } finally { + _preparing.remove(ids); + } + } + + Future invalidate((String, String) ids) async { + final controller = _controllers.remove(ids); + if (controller != null) await controller.close(); + } + + Future retainProject( + String projectId, { + Set keep = const {}, + }) async { + for (final entry in _controllers.entries.toList()) { + if (entry.key.$1 != projectId && keep.contains(entry.key.$1)) { + await entry.value.pauseForCanvasInteraction(); + } + } + final stale = _controllers.keys + .where((ids) => ids.$1 != projectId && !keep.contains(ids.$1)) + .toList(); + for (final ids in stale) { + await invalidate(ids); + } + } + + void dispose() { + if (_disposed) return; + _disposed = true; + final controllers = _controllers.values.toList(); + _controllers.clear(); + _preparing.clear(); + for (final controller in controllers) { + unawaited(controller.close().catchError((Object _) {})); + } + } +} diff --git a/lib/workspace/preview_controller_registry.g.dart b/lib/workspace/preview_controller_registry.g.dart new file mode 100644 index 0000000..ccd1513 --- /dev/null +++ b/lib/workspace/preview_controller_registry.g.dart @@ -0,0 +1,58 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'preview_controller_registry.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(previewControllerRegistry) +final previewControllerRegistryProvider = PreviewControllerRegistryProvider._(); + +final class PreviewControllerRegistryProvider + extends + $FunctionalProvider< + PreviewControllerRegistry, + PreviewControllerRegistry, + PreviewControllerRegistry + > + with $Provider { + PreviewControllerRegistryProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'previewControllerRegistryProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$previewControllerRegistryHash(); + + @$internal + @override + $ProviderElement $createElement( + $ProviderPointer pointer, + ) => $ProviderElement(pointer); + + @override + PreviewControllerRegistry create(Ref ref) { + return previewControllerRegistry(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(PreviewControllerRegistry value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$previewControllerRegistryHash() => + r'ec6788d52acb279d31cd745f0e244d604f09a890'; diff --git a/lib/workspace/preview_target.dart b/lib/workspace/preview_target.dart new file mode 100644 index 0000000..4721523 --- /dev/null +++ b/lib/workspace/preview_target.dart @@ -0,0 +1,244 @@ +import 'dart:async'; + +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/preview.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter/foundation.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import 'projects.dart'; +import '../diagnostics/app_diagnostics.dart'; + +part 'preview_target.g.dart'; +part 'preview_target.freezed.dart'; + +@Riverpod(keepAlive: true) +CutdexRuntime runtimeConnection(Ref ref) => + CutdexRuntime(diagnostics: AppDiagnostics.report); + +@Riverpod(keepAlive: true) +Raw previewTarget(Ref ref, String projectId, String timelineId) { + final target = PreviewTarget( + createSource: (asset, tick, remember) { + final timeline = ref + .read(projectsProvider.notifier) + .cachedTimelineSession(projectId, timelineId); + final sequence = timeline?.activeSequenceId; + return SourcePreviewController( + loadMedia: (action) => ref + .read(projectsProvider.notifier) + .withAssetMedia(projectId, asset, action), + frameDuration: sequence == null + ? TimelineFormat.fps30.frameDuration + : timeline!.persistence.timeline(sequence).format.frameDuration, + positionTick: tick, + rememberPosition: remember, + runtime: ref.read(runtimeConnectionProvider), + ); + }, + beforeOpen: () async { + final session = await ref + .read(projectsProvider.notifier) + .openTimelineSession(projectId, timelineId); + final sequence = session.activeSequenceId; + if (sequence != null && + session.preview?.queryPreview(sequence).available == true) { + await session.preview!.controlPreview(sequence, PreviewAction.pause); + } + }, + ); + ref.listen(projectsProvider, (_, next) { + final state = next.asData?.value; + if (state != null && + (state.activeProject?.id != projectId || + state.timeline?.id != timelineId)) { + unawaited(target.closeSource().catchError((Object _) {})); + } + }); + ref.onDispose(target.dispose); + return target; +} + +@freezed +sealed class PreviewTargetState with _$PreviewTargetState { + const factory PreviewTargetState.timeline() = TimelinePreviewTarget; + const factory PreviewTargetState.source( + AssetDocument asset, + SourcePreviewController? controller, { + @Default(true) bool opening, + Object? error, + }) = SourcePreviewTarget; +} + +@Riverpod(keepAlive: true) +class PreviewNavigation extends _$PreviewNavigation { + late PreviewTarget _target; + @override + PreviewTargetState build(String projectId, String timelineId) { + final target = _target = ref.watch( + previewTargetProvider(projectId, timelineId), + ); + void changed() { + if (ref.mounted) state = target.state; + } + + target.addListener(changed); + ref.onDispose(() => target.removeListener(changed)); + return target.state; + } + + void showAsset(AssetDocument asset) => _target.showAsset(asset); + Future openSource(AssetDocument asset) => _target.openSource(asset); + void showTimeline() => _target.showTimeline(); +} + +typedef SourcePreviewFactory = SourcePreviewController Function( + AssetDocument asset, + int position, + void Function(int) remember, +); + +/// Owns source navigation and its one controller; widgets only render it. +class PreviewTarget extends ChangeNotifier { + PreviewTarget({this.createSource, this.beforeOpen}); + final SourcePreviewFactory? createSource; + final Future Function()? beforeOpen; + PreviewTargetState _state = const PreviewTargetState.timeline(); + PreviewTargetState get state => _state; + AssetDocument? get asset => switch (_state) { + SourcePreviewTarget(:final asset) => asset, + _ => null, + }; + SourcePreviewController? get source => switch (_state) { + SourcePreviewTarget(:final controller) => controller, + _ => null, + }; + VoidCallback? togglePlayback; + final positions = {}; + Future _opening = Future.value(); + Future _closing = Future.value(); + bool _disposed = false; + + void showAsset(AssetDocument value) { + unawaited(openSource(value).catchError((Object _) {})); + } + + Future openSource(AssetDocument value) { + if (_disposed) return Future.error(StateError('Preview target is closed')); + if (asset?.id == value.id && source?.error == null) return _opening; + final previous = source; + final closing = previous == null + ? Future.value() + : previous.close().whenComplete(previous.dispose); + _closing = Future.wait([_closing.catchError((Object _) {}), closing]) + .then((_) {}); + unawaited(_closing.catchError((Object _) {})); + final created = createSource?.call( + value, + positions[value.id] ?? 0, + (tick) => positions[value.id] = tick, + ); + _state = PreviewTargetState.source(value, created); + togglePlayback = created == null + ? null + : () => unawaited(created.togglePlayback()); + _opening = + () async { + await _closing; + if (created == null) { + if (!_disposed && asset?.id == value.id) { + _state = PreviewTargetState.source( + value, + created, + opening: false, + ); + notifyListeners(); + } + return; + } + if (_disposed || !identical(source, created)) { + throw StateError('Source preview changed'); + } + await created.initialize(beforeOpen?.call() ?? Future.value()); + if (_disposed || !identical(source, created)) { + throw StateError('Source preview changed'); + } + if (created.error != null) throw StateError('Source preview failed'); + _state = PreviewTargetState.source(value, created, opening: false); + notifyListeners(); + }().catchError((Object error, StackTrace stack) { + AppDiagnostics.failure( + 'preview', + 'openSource', + error, + stack, + context: {'mediaId': value.id}, + ); + if (!_disposed && + identical(source, created) && + asset?.id == value.id) { + _state = PreviewTargetState.source( + value, + created, + opening: false, + error: error, + ); + notifyListeners(); + } + Error.throwWithStackTrace(error, stack); + }); + notifyListeners(); + return _opening; + } + + void showTimeline() { + unawaited(closeSource().catchError((Object _) {})); + } + + Future closeSource() { + final previous = source; + _state = const PreviewTargetState.timeline(); + togglePlayback = null; + if (!_disposed) notifyListeners(); + final closing = previous == null + ? Future.value() + : previous.close().whenComplete(previous.dispose); + _closing = Future.wait([_closing.catchError((Object _) {}), closing]) + .then((_) {}); + unawaited(_closing.catchError((Object _) {})); + return _closing; + } + + Future control( + String mediaId, + SourcePreviewAction action, { + CommandTime? at, + }) async { + if (asset?.id != mediaId || source == null) { + throw const CommandRejected( + 'sourceUnavailable', + 'Open the addressed source first', + ); + } + final current = source!; + await _opening; + if (!identical(source, current) || asset?.id != mediaId) { + throw const CommandRejected('sourceChanged', 'Source preview changed'); + } + await current.control(action, at: at); + if (!identical(source, current)) { + throw StateError('Source changed during control'); + } + } + + @override + void dispose() { + if (_disposed) return; + _disposed = true; + unawaited(closeSource().catchError((Object _) {})); + super.dispose(); + } +} diff --git a/lib/workspace/preview_target.freezed.dart b/lib/workspace/preview_target.freezed.dart new file mode 100644 index 0000000..b616908 --- /dev/null +++ b/lib/workspace/preview_target.freezed.dart @@ -0,0 +1,391 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'preview_target.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +T _$identity(T value) => value; + +/// @nodoc +mixin _$PreviewTargetState implements DiagnosticableTreeMixin { + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + properties..add(DiagnosticsProperty('type', 'PreviewTargetState')); + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is PreviewTargetState); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { + return 'PreviewTargetState()'; + } +} + +/// @nodoc +class $PreviewTargetStateCopyWith<$Res> { + $PreviewTargetStateCopyWith( + PreviewTargetState _, + $Res Function(PreviewTargetState) __, + ); +} + +/// Adds pattern-matching-related methods to [PreviewTargetState]. +extension PreviewTargetStatePatterns on PreviewTargetState { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap({ + TResult Function(TimelinePreviewTarget value)? timeline, + TResult Function(SourcePreviewTarget value)? source, + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case TimelinePreviewTarget() when timeline != null: + return timeline(_that); + case SourcePreviewTarget() when source != null: + return source(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map({ + required TResult Function(TimelinePreviewTarget value) timeline, + required TResult Function(SourcePreviewTarget value) source, + }) { + final _that = this; + switch (_that) { + case TimelinePreviewTarget(): + return timeline(_that); + case SourcePreviewTarget(): + return source(_that); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(TimelinePreviewTarget value)? timeline, + TResult? Function(SourcePreviewTarget value)? source, + }) { + final _that = this; + switch (_that) { + case TimelinePreviewTarget() when timeline != null: + return timeline(_that); + case SourcePreviewTarget() when source != null: + return source(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen({ + TResult Function()? timeline, + TResult Function( + AssetDocument asset, + SourcePreviewController? controller, + bool opening, + Object? error, + )? + source, + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case TimelinePreviewTarget() when timeline != null: + return timeline(); + case SourcePreviewTarget() when source != null: + return source( + _that.asset, + _that.controller, + _that.opening, + _that.error, + ); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when({ + required TResult Function() timeline, + required TResult Function( + AssetDocument asset, + SourcePreviewController? controller, + bool opening, + Object? error, + ) + source, + }) { + final _that = this; + switch (_that) { + case TimelinePreviewTarget(): + return timeline(); + case SourcePreviewTarget(): + return source( + _that.asset, + _that.controller, + _that.opening, + _that.error, + ); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function()? timeline, + TResult? Function( + AssetDocument asset, + SourcePreviewController? controller, + bool opening, + Object? error, + )? + source, + }) { + final _that = this; + switch (_that) { + case TimelinePreviewTarget() when timeline != null: + return timeline(); + case SourcePreviewTarget() when source != null: + return source( + _that.asset, + _that.controller, + _that.opening, + _that.error, + ); + case _: + return null; + } + } +} + +/// @nodoc + +class TimelinePreviewTarget + with DiagnosticableTreeMixin + implements PreviewTargetState { + const TimelinePreviewTarget(); + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + properties..add(DiagnosticsProperty('type', 'PreviewTargetState.timeline')); + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && other is TimelinePreviewTarget); + } + + @override + int get hashCode => runtimeType.hashCode; + + @override + String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { + return 'PreviewTargetState.timeline()'; + } +} + +/// @nodoc + +class SourcePreviewTarget + with DiagnosticableTreeMixin + implements PreviewTargetState { + const SourcePreviewTarget( + this.asset, + this.controller, { + this.opening = true, + this.error, + }); + + final AssetDocument asset; + final SourcePreviewController? controller; + @JsonKey() + final bool opening; + final Object? error; + + /// Create a copy of PreviewTargetState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $SourcePreviewTargetCopyWith get copyWith => + _$SourcePreviewTargetCopyWithImpl(this, _$identity); + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + properties + ..add(DiagnosticsProperty('type', 'PreviewTargetState.source')) + ..add(DiagnosticsProperty('asset', asset)) + ..add(DiagnosticsProperty('controller', controller)) + ..add(DiagnosticsProperty('opening', opening)) + ..add(DiagnosticsProperty('error', error)); + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is SourcePreviewTarget && + (identical(other.asset, asset) || other.asset == asset) && + (identical(other.controller, controller) || + other.controller == controller) && + (identical(other.opening, opening) || other.opening == opening) && + const DeepCollectionEquality().equals(other.error, error)); + } + + @override + int get hashCode { + return Object.hash( + runtimeType, + asset, + controller, + opening, + const DeepCollectionEquality().hash(error), + ); + } + + @override + String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { + return 'PreviewTargetState.source(asset: $asset, controller: $controller, opening: $opening, error: $error)'; + } +} + +/// @nodoc +abstract mixin class $SourcePreviewTargetCopyWith<$Res> + implements $PreviewTargetStateCopyWith<$Res> { + factory $SourcePreviewTargetCopyWith( + SourcePreviewTarget value, + $Res Function(SourcePreviewTarget) _then, + ) = _$SourcePreviewTargetCopyWithImpl; + @useResult + $Res call({ + AssetDocument asset, + SourcePreviewController? controller, + bool opening, + Object? error, + }); +} + +/// @nodoc +class _$SourcePreviewTargetCopyWithImpl<$Res> + implements $SourcePreviewTargetCopyWith<$Res> { + _$SourcePreviewTargetCopyWithImpl(this._self, this._then); + + final SourcePreviewTarget _self; + final $Res Function(SourcePreviewTarget) _then; + + /// Create a copy of PreviewTargetState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + $Res call({ + Object? asset = null, + Object? controller = freezed, + Object? opening = null, + Object? error = freezed, + }) { + return _then( + SourcePreviewTarget( + null == asset + ? _self.asset + : asset // ignore: cast_nullable_to_non_nullable + as AssetDocument, + freezed == controller + ? _self.controller + : controller // ignore: cast_nullable_to_non_nullable + as SourcePreviewController?, + opening: null == opening + ? _self.opening + : opening // ignore: cast_nullable_to_non_nullable + as bool, + error: freezed == error ? _self.error : error, + ), + ); + } +} diff --git a/lib/workspace/preview_target.g.dart b/lib/workspace/preview_target.g.dart new file mode 100644 index 0000000..4a0e07c --- /dev/null +++ b/lib/workspace/preview_target.g.dart @@ -0,0 +1,235 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'preview_target.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(runtimeConnection) +final runtimeConnectionProvider = RuntimeConnectionProvider._(); + +final class RuntimeConnectionProvider + extends $FunctionalProvider + with $Provider { + RuntimeConnectionProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'runtimeConnectionProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$runtimeConnectionHash(); + + @$internal + @override + $ProviderElement $createElement($ProviderPointer pointer) => + $ProviderElement(pointer); + + @override + CutdexRuntime create(Ref ref) { + return runtimeConnection(ref); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(CutdexRuntime value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$runtimeConnectionHash() => r'd185bc1cb6bb09b060b1d53ccf09097ac56f910c'; + +@ProviderFor(previewTarget) +final previewTargetProvider = PreviewTargetFamily._(); + +final class PreviewTargetProvider + extends + $FunctionalProvider< + Raw, + Raw, + Raw + > + with $Provider> { + PreviewTargetProvider._({ + required PreviewTargetFamily super.from, + required (String, String) super.argument, + }) : super( + retry: null, + name: r'previewTargetProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$previewTargetHash(); + + @override + String toString() { + return r'previewTargetProvider' + '' + '$argument'; + } + + @$internal + @override + $ProviderElement> $createElement( + $ProviderPointer pointer, + ) => $ProviderElement(pointer); + + @override + Raw create(Ref ref) { + final argument = this.argument as (String, String); + return previewTarget(ref, argument.$1, argument.$2); + } + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(Raw value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider>(value), + ); + } + + @override + bool operator ==(Object other) { + return other is PreviewTargetProvider && other.argument == argument; + } + + @override + int get hashCode { + return argument.hashCode; + } +} + +String _$previewTargetHash() => r'89b3bfb214aa3bebed0086d73b15c5f9fd5cfea1'; + +final class PreviewTargetFamily extends $Family + with $FunctionalFamilyOverride, (String, String)> { + PreviewTargetFamily._() + : super( + retry: null, + name: r'previewTargetProvider', + dependencies: null, + $allTransitiveDependencies: null, + isAutoDispose: false, + ); + + PreviewTargetProvider call(String projectId, String timelineId) => + PreviewTargetProvider._(argument: (projectId, timelineId), from: this); + + @override + String toString() => r'previewTargetProvider'; +} + +@ProviderFor(PreviewNavigation) +final previewNavigationProvider = PreviewNavigationFamily._(); + +final class PreviewNavigationProvider + extends $NotifierProvider { + PreviewNavigationProvider._({ + required PreviewNavigationFamily super.from, + required (String, String) super.argument, + }) : super( + retry: null, + name: r'previewNavigationProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$previewNavigationHash(); + + @override + String toString() { + return r'previewNavigationProvider' + '' + '$argument'; + } + + @$internal + @override + PreviewNavigation create() => PreviewNavigation(); + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(PreviewTargetState value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } + + @override + bool operator ==(Object other) { + return other is PreviewNavigationProvider && other.argument == argument; + } + + @override + int get hashCode { + return argument.hashCode; + } +} + +String _$previewNavigationHash() => r'c19564d7ba2764444380bceb154c9d7e06431f80'; + +final class PreviewNavigationFamily extends $Family + with + $ClassFamilyOverride< + PreviewNavigation, + PreviewTargetState, + PreviewTargetState, + PreviewTargetState, + (String, String) + > { + PreviewNavigationFamily._() + : super( + retry: null, + name: r'previewNavigationProvider', + dependencies: null, + $allTransitiveDependencies: null, + isAutoDispose: false, + ); + + PreviewNavigationProvider call(String projectId, String timelineId) => + PreviewNavigationProvider._( + argument: (projectId, timelineId), + from: this, + ); + + @override + String toString() => r'previewNavigationProvider'; +} + +abstract class _$PreviewNavigation extends $Notifier { + late final _$args = ref.$arg as (String, String); + String get projectId => _$args.$1; + String get timelineId => _$args.$2; + + PreviewTargetState build(String projectId, String timelineId); + @$mustCallSuper + @override + WhenComplete runBuild() { + final ref = this.ref as $Ref; + final element = + ref.element + as $ClassProviderElement< + AnyNotifier, + PreviewTargetState, + Object?, + Object? + >; + return element.handleCreate(ref, () => build(_$args.$1, _$args.$2)); + } +} diff --git a/lib/workspace/project_assets_changed.dart b/lib/workspace/project_assets_changed.dart new file mode 100644 index 0000000..3c9a833 --- /dev/null +++ b/lib/workspace/project_assets_changed.dart @@ -0,0 +1,14 @@ +import 'package:cutdex_sdk/project.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +part 'project_assets_changed.freezed.dart'; + +@freezed +abstract class ProjectAssetsChanged with _$ProjectAssetsChanged { + factory ProjectAssetsChanged(String projectId, List assets) => + ProjectAssetsChanged.snapshot(projectId, List.unmodifiable(assets)); + const factory ProjectAssetsChanged.snapshot( + String projectId, + List assets, + ) = _ProjectAssetsChanged; +} diff --git a/lib/workspace/project_assets_changed.freezed.dart b/lib/workspace/project_assets_changed.freezed.dart new file mode 100644 index 0000000..74c37a3 --- /dev/null +++ b/lib/workspace/project_assets_changed.freezed.dart @@ -0,0 +1,344 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'project_assets_changed.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +T _$identity(T value) => value; + +/// @nodoc +mixin _$ProjectAssetsChanged { + String get projectId; + List get assets; + + /// Create a copy of ProjectAssetsChanged + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $ProjectAssetsChangedCopyWith get copyWith => + _$ProjectAssetsChangedCopyWithImpl( + this as ProjectAssetsChanged, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as ProjectAssetsChanged; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is ProjectAssetsChanged && + (identical(other.projectId, _this.projectId) || + other.projectId == _this.projectId) && + const DeepCollectionEquality().equals(other.assets, _this.assets)); + } + + @override + int get hashCode { + final _this = this as ProjectAssetsChanged; + return Object.hash( + runtimeType, + _this.projectId, + const DeepCollectionEquality().hash(_this.assets), + ); + } + + @override + String toString() { + final _this = this as ProjectAssetsChanged; + return 'ProjectAssetsChanged(projectId: ${_this.projectId}, assets: ${_this.assets})'; + } +} + +/// @nodoc +abstract mixin class $ProjectAssetsChangedCopyWith<$Res> { + factory $ProjectAssetsChangedCopyWith( + ProjectAssetsChanged value, + $Res Function(ProjectAssetsChanged) _then, + ) = _$ProjectAssetsChangedCopyWithImpl; + @useResult + $Res call({String projectId, List assets}); +} + +/// @nodoc +class _$ProjectAssetsChangedCopyWithImpl<$Res> + implements $ProjectAssetsChangedCopyWith<$Res> { + _$ProjectAssetsChangedCopyWithImpl(this._self, this._then); + + final ProjectAssetsChanged _self; + final $Res Function(ProjectAssetsChanged) _then; + + /// Create a copy of ProjectAssetsChanged + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({Object? projectId = null, Object? assets = null}) { + return _then( + ProjectAssetsChanged( + null == projectId + ? _self.projectId + : projectId // ignore: cast_nullable_to_non_nullable + as String, + null == assets + ? _self.assets + : assets // ignore: cast_nullable_to_non_nullable + as List, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [ProjectAssetsChanged]. +extension ProjectAssetsChangedPatterns on ProjectAssetsChanged { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap({ + TResult Function(_ProjectAssetsChanged value)? snapshot, + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ProjectAssetsChanged() when snapshot != null: + return snapshot(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map({ + required TResult Function(_ProjectAssetsChanged value) snapshot, + }) { + final _that = this; + switch (_that) { + case _ProjectAssetsChanged(): + return snapshot(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull({ + TResult? Function(_ProjectAssetsChanged value)? snapshot, + }) { + final _that = this; + switch (_that) { + case _ProjectAssetsChanged() when snapshot != null: + return snapshot(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen({ + TResult Function(String projectId, List assets)? snapshot, + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ProjectAssetsChanged() when snapshot != null: + return snapshot(_that.projectId, _that.assets); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when({ + required TResult Function(String projectId, List assets) + snapshot, + }) { + final _that = this; + switch (_that) { + case _ProjectAssetsChanged(): + return snapshot(_that.projectId, _that.assets); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull({ + TResult? Function(String projectId, List assets)? snapshot, + }) { + final _that = this; + switch (_that) { + case _ProjectAssetsChanged() when snapshot != null: + return snapshot(_that.projectId, _that.assets); + case _: + return null; + } + } +} + +/// @nodoc + +class _ProjectAssetsChanged implements ProjectAssetsChanged { + const _ProjectAssetsChanged(this.projectId, List assets) + : _assets = assets; + + @override + final String projectId; + final List _assets; + @override + List get assets { + if (_assets is EqualUnmodifiableListView) return _assets; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_assets); + } + + /// Create a copy of ProjectAssetsChanged + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$ProjectAssetsChangedCopyWith<_ProjectAssetsChanged> get copyWith => + __$ProjectAssetsChangedCopyWithImpl<_ProjectAssetsChanged>( + this, + _$identity, + ); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _ProjectAssetsChanged && + (identical(other.projectId, projectId) || + other.projectId == projectId) && + const DeepCollectionEquality().equals(other.assets, _assets)); + } + + @override + int get hashCode { + return Object.hash( + runtimeType, + projectId, + const DeepCollectionEquality().hash(_assets), + ); + } + + @override + String toString() { + return 'ProjectAssetsChanged.snapshot(projectId: $projectId, assets: $assets)'; + } +} + +/// @nodoc +abstract mixin class _$ProjectAssetsChangedCopyWith<$Res> + implements $ProjectAssetsChangedCopyWith<$Res> { + factory _$ProjectAssetsChangedCopyWith( + _ProjectAssetsChanged value, + $Res Function(_ProjectAssetsChanged) _then, + ) = __$ProjectAssetsChangedCopyWithImpl; + @override + @useResult + $Res call({String projectId, List assets}); +} + +/// @nodoc +class __$ProjectAssetsChangedCopyWithImpl<$Res> + implements _$ProjectAssetsChangedCopyWith<$Res> { + __$ProjectAssetsChangedCopyWithImpl(this._self, this._then); + + final _ProjectAssetsChanged _self; + final $Res Function(_ProjectAssetsChanged) _then; + + /// Create a copy of ProjectAssetsChanged + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({Object? projectId = null, Object? assets = null}) { + return _then( + _ProjectAssetsChanged( + null == projectId + ? _self.projectId + : projectId // ignore: cast_nullable_to_non_nullable + as String, + null == assets + ? _self._assets + : assets // ignore: cast_nullable_to_non_nullable + as List, + ), + ); + } +} diff --git a/lib/workspace/project_state.dart b/lib/workspace/project_state.dart new file mode 100644 index 0000000..c93b512 --- /dev/null +++ b/lib/workspace/project_state.dart @@ -0,0 +1,41 @@ +import 'package:cutdex_sdk/project.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +import '../errors/app_failure.dart'; + +part 'project_state.freezed.dart'; + +enum ProjectAvailability { + available, + missing, + volumeOffline, + invalid, + unavailable; + + bool get canOpen => this == available; +} + +@freezed +abstract class RecentProject with _$RecentProject { + const factory RecentProject({ + required String id, + required String name, + required String path, + @Default(ProjectAvailability.available) ProjectAvailability availability, + }) = _RecentProject; +} + +@freezed +abstract class ProjectState with _$ProjectState { + const factory ProjectState({ + @Default([]) List recent, + RecentProject? activeProject, + @Default([]) List timelines, + @Default([]) List assets, + TimelineDocument? timeline, + @Default(false) bool projectBusy, + String? openingTimelineId, + @Default(false) bool creatingTimeline, + AppFailure? error, + }) = _ProjectState; +} diff --git a/lib/workspace/project_state.freezed.dart b/lib/workspace/project_state.freezed.dart new file mode 100644 index 0000000..1841025 --- /dev/null +++ b/lib/workspace/project_state.freezed.dart @@ -0,0 +1,1013 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'project_state.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +T _$identity(T value) => value; + +/// @nodoc +mixin _$RecentProject { + String get id; + String get name; + String get path; + ProjectAvailability get availability; + + /// Create a copy of RecentProject + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $RecentProjectCopyWith get copyWith => + _$RecentProjectCopyWithImpl( + this as RecentProject, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as RecentProject; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is RecentProject && + (identical(other.id, _this.id) || other.id == _this.id) && + (identical(other.name, _this.name) || other.name == _this.name) && + (identical(other.path, _this.path) || other.path == _this.path) && + (identical(other.availability, _this.availability) || + other.availability == _this.availability)); + } + + @override + int get hashCode { + final _this = this as RecentProject; + return Object.hash( + runtimeType, + _this.id, + _this.name, + _this.path, + _this.availability, + ); + } + + @override + String toString() { + final _this = this as RecentProject; + return 'RecentProject(id: ${_this.id}, name: ${_this.name}, path: ${_this.path}, availability: ${_this.availability})'; + } +} + +/// @nodoc +abstract mixin class $RecentProjectCopyWith<$Res> { + factory $RecentProjectCopyWith( + RecentProject value, + $Res Function(RecentProject) _then, + ) = _$RecentProjectCopyWithImpl; + @useResult + $Res call({ + String id, + String name, + String path, + ProjectAvailability availability, + }); +} + +/// @nodoc +class _$RecentProjectCopyWithImpl<$Res> + implements $RecentProjectCopyWith<$Res> { + _$RecentProjectCopyWithImpl(this._self, this._then); + + final RecentProject _self; + final $Res Function(RecentProject) _then; + + /// Create a copy of RecentProject + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? id = null, + Object? name = null, + Object? path = null, + Object? availability = null, + }) { + return _then( + RecentProject( + id: null == id + ? _self.id + : id // ignore: cast_nullable_to_non_nullable + as String, + name: null == name + ? _self.name + : name // ignore: cast_nullable_to_non_nullable + as String, + path: null == path + ? _self.path + : path // ignore: cast_nullable_to_non_nullable + as String, + availability: null == availability + ? _self.availability + : availability // ignore: cast_nullable_to_non_nullable + as ProjectAvailability, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [RecentProject]. +extension RecentProjectPatterns on RecentProject { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_RecentProject value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _RecentProject() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_RecentProject value) $default, + ) { + final _that = this; + switch (_that) { + case _RecentProject(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_RecentProject value)? $default, + ) { + final _that = this; + switch (_that) { + case _RecentProject() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + String id, + String name, + String path, + ProjectAvailability availability, + )? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _RecentProject() when $default != null: + return $default(_that.id, _that.name, _that.path, _that.availability); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function( + String id, + String name, + String path, + ProjectAvailability availability, + ) + $default, + ) { + final _that = this; + switch (_that) { + case _RecentProject(): + return $default(_that.id, _that.name, _that.path, _that.availability); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + String id, + String name, + String path, + ProjectAvailability availability, + )? + $default, + ) { + final _that = this; + switch (_that) { + case _RecentProject() when $default != null: + return $default(_that.id, _that.name, _that.path, _that.availability); + case _: + return null; + } + } +} + +/// @nodoc + +class _RecentProject implements RecentProject { + const _RecentProject({ + required this.id, + required this.name, + required this.path, + this.availability = ProjectAvailability.available, + }); + + @override + final String id; + @override + final String name; + @override + final String path; + @override + @JsonKey() + final ProjectAvailability availability; + + /// Create a copy of RecentProject + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$RecentProjectCopyWith<_RecentProject> get copyWith => + __$RecentProjectCopyWithImpl<_RecentProject>(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _RecentProject && + (identical(other.id, id) || other.id == id) && + (identical(other.name, name) || other.name == name) && + (identical(other.path, path) || other.path == path) && + (identical(other.availability, availability) || + other.availability == availability)); + } + + @override + int get hashCode { + return Object.hash(runtimeType, id, name, path, availability); + } + + @override + String toString() { + return 'RecentProject(id: $id, name: $name, path: $path, availability: $availability)'; + } +} + +/// @nodoc +abstract mixin class _$RecentProjectCopyWith<$Res> + implements $RecentProjectCopyWith<$Res> { + factory _$RecentProjectCopyWith( + _RecentProject value, + $Res Function(_RecentProject) _then, + ) = __$RecentProjectCopyWithImpl; + @override + @useResult + $Res call({ + String id, + String name, + String path, + ProjectAvailability availability, + }); +} + +/// @nodoc +class __$RecentProjectCopyWithImpl<$Res> + implements _$RecentProjectCopyWith<$Res> { + __$RecentProjectCopyWithImpl(this._self, this._then); + + final _RecentProject _self; + final $Res Function(_RecentProject) _then; + + /// Create a copy of RecentProject + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? id = null, + Object? name = null, + Object? path = null, + Object? availability = null, + }) { + return _then( + _RecentProject( + id: null == id + ? _self.id + : id // ignore: cast_nullable_to_non_nullable + as String, + name: null == name + ? _self.name + : name // ignore: cast_nullable_to_non_nullable + as String, + path: null == path + ? _self.path + : path // ignore: cast_nullable_to_non_nullable + as String, + availability: null == availability + ? _self.availability + : availability // ignore: cast_nullable_to_non_nullable + as ProjectAvailability, + ), + ); + } +} + +/// @nodoc +mixin _$ProjectState { + List get recent; + RecentProject? get activeProject; + List get timelines; + List get assets; + TimelineDocument? get timeline; + bool get projectBusy; + String? get openingTimelineId; + bool get creatingTimeline; + AppFailure? get error; + + /// Create a copy of ProjectState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $ProjectStateCopyWith get copyWith => + _$ProjectStateCopyWithImpl( + this as ProjectState, + _$identity, + ); + + @override + bool operator ==(Object other) { + final _this = this as ProjectState; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is ProjectState && + const DeepCollectionEquality().equals(other.recent, _this.recent) && + (identical(other.activeProject, _this.activeProject) || + other.activeProject == _this.activeProject) && + const DeepCollectionEquality().equals( + other.timelines, + _this.timelines, + ) && + const DeepCollectionEquality().equals(other.assets, _this.assets) && + (identical(other.timeline, _this.timeline) || + other.timeline == _this.timeline) && + (identical(other.projectBusy, _this.projectBusy) || + other.projectBusy == _this.projectBusy) && + (identical(other.openingTimelineId, _this.openingTimelineId) || + other.openingTimelineId == _this.openingTimelineId) && + (identical(other.creatingTimeline, _this.creatingTimeline) || + other.creatingTimeline == _this.creatingTimeline) && + (identical(other.error, _this.error) || + other.error == _this.error)); + } + + @override + int get hashCode { + final _this = this as ProjectState; + return Object.hash( + runtimeType, + const DeepCollectionEquality().hash(_this.recent), + _this.activeProject, + const DeepCollectionEquality().hash(_this.timelines), + const DeepCollectionEquality().hash(_this.assets), + _this.timeline, + _this.projectBusy, + _this.openingTimelineId, + _this.creatingTimeline, + _this.error, + ); + } + + @override + String toString() { + final _this = this as ProjectState; + return 'ProjectState(recent: ${_this.recent}, activeProject: ${_this.activeProject}, timelines: ${_this.timelines}, assets: ${_this.assets}, timeline: ${_this.timeline}, projectBusy: ${_this.projectBusy}, openingTimelineId: ${_this.openingTimelineId}, creatingTimeline: ${_this.creatingTimeline}, error: ${_this.error})'; + } +} + +/// @nodoc +abstract mixin class $ProjectStateCopyWith<$Res> { + factory $ProjectStateCopyWith( + ProjectState value, + $Res Function(ProjectState) _then, + ) = _$ProjectStateCopyWithImpl; + @useResult + $Res call({ + List recent, + RecentProject? activeProject, + List timelines, + List assets, + TimelineDocument? timeline, + bool projectBusy, + String? openingTimelineId, + bool creatingTimeline, + AppFailure? error, + }); + + $RecentProjectCopyWith<$Res>? get activeProject; +} + +/// @nodoc +class _$ProjectStateCopyWithImpl<$Res> implements $ProjectStateCopyWith<$Res> { + _$ProjectStateCopyWithImpl(this._self, this._then); + + final ProjectState _self; + final $Res Function(ProjectState) _then; + + /// Create a copy of ProjectState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? recent = null, + Object? activeProject = freezed, + Object? timelines = null, + Object? assets = null, + Object? timeline = freezed, + Object? projectBusy = null, + Object? openingTimelineId = freezed, + Object? creatingTimeline = null, + Object? error = freezed, + }) { + return _then( + ProjectState( + recent: null == recent + ? _self.recent + : recent // ignore: cast_nullable_to_non_nullable + as List, + activeProject: freezed == activeProject + ? _self.activeProject + : activeProject // ignore: cast_nullable_to_non_nullable + as RecentProject?, + timelines: null == timelines + ? _self.timelines + : timelines // ignore: cast_nullable_to_non_nullable + as List, + assets: null == assets + ? _self.assets + : assets // ignore: cast_nullable_to_non_nullable + as List, + timeline: freezed == timeline + ? _self.timeline + : timeline // ignore: cast_nullable_to_non_nullable + as TimelineDocument?, + projectBusy: null == projectBusy + ? _self.projectBusy + : projectBusy // ignore: cast_nullable_to_non_nullable + as bool, + openingTimelineId: freezed == openingTimelineId + ? _self.openingTimelineId + : openingTimelineId // ignore: cast_nullable_to_non_nullable + as String?, + creatingTimeline: null == creatingTimeline + ? _self.creatingTimeline + : creatingTimeline // ignore: cast_nullable_to_non_nullable + as bool, + error: freezed == error + ? _self.error + : error // ignore: cast_nullable_to_non_nullable + as AppFailure?, + ), + ); + } + + /// Create a copy of ProjectState + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $RecentProjectCopyWith<$Res>? get activeProject { + if (_self.activeProject == null) { + return null; + } + + return $RecentProjectCopyWith<$Res>(_self.activeProject!, (value) { + return _then(_self.copyWith(activeProject: value)); + }); + } +} + +/// Adds pattern-matching-related methods to [ProjectState]. +extension ProjectStatePatterns on ProjectState { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_ProjectState value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ProjectState() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_ProjectState value) $default, + ) { + final _that = this; + switch (_that) { + case _ProjectState(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_ProjectState value)? $default, + ) { + final _that = this; + switch (_that) { + case _ProjectState() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + List recent, + RecentProject? activeProject, + List timelines, + List assets, + TimelineDocument? timeline, + bool projectBusy, + String? openingTimelineId, + bool creatingTimeline, + AppFailure? error, + )? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _ProjectState() when $default != null: + return $default( + _that.recent, + _that.activeProject, + _that.timelines, + _that.assets, + _that.timeline, + _that.projectBusy, + _that.openingTimelineId, + _that.creatingTimeline, + _that.error, + ); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function( + List recent, + RecentProject? activeProject, + List timelines, + List assets, + TimelineDocument? timeline, + bool projectBusy, + String? openingTimelineId, + bool creatingTimeline, + AppFailure? error, + ) + $default, + ) { + final _that = this; + switch (_that) { + case _ProjectState(): + return $default( + _that.recent, + _that.activeProject, + _that.timelines, + _that.assets, + _that.timeline, + _that.projectBusy, + _that.openingTimelineId, + _that.creatingTimeline, + _that.error, + ); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + List recent, + RecentProject? activeProject, + List timelines, + List assets, + TimelineDocument? timeline, + bool projectBusy, + String? openingTimelineId, + bool creatingTimeline, + AppFailure? error, + )? + $default, + ) { + final _that = this; + switch (_that) { + case _ProjectState() when $default != null: + return $default( + _that.recent, + _that.activeProject, + _that.timelines, + _that.assets, + _that.timeline, + _that.projectBusy, + _that.openingTimelineId, + _that.creatingTimeline, + _that.error, + ); + case _: + return null; + } + } +} + +/// @nodoc + +class _ProjectState implements ProjectState { + const _ProjectState({ + List recent = const [], + this.activeProject, + List timelines = const [], + List assets = const [], + this.timeline, + this.projectBusy = false, + this.openingTimelineId, + this.creatingTimeline = false, + this.error, + }) : _recent = recent, + _timelines = timelines, + _assets = assets; + + final List _recent; + @override + @JsonKey() + List get recent { + if (_recent is EqualUnmodifiableListView) return _recent; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_recent); + } + + @override + final RecentProject? activeProject; + final List _timelines; + @override + @JsonKey() + List get timelines { + if (_timelines is EqualUnmodifiableListView) return _timelines; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_timelines); + } + + final List _assets; + @override + @JsonKey() + List get assets { + if (_assets is EqualUnmodifiableListView) return _assets; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_assets); + } + + @override + final TimelineDocument? timeline; + @override + @JsonKey() + final bool projectBusy; + @override + final String? openingTimelineId; + @override + @JsonKey() + final bool creatingTimeline; + @override + final AppFailure? error; + + /// Create a copy of ProjectState + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$ProjectStateCopyWith<_ProjectState> get copyWith => + __$ProjectStateCopyWithImpl<_ProjectState>(this, _$identity); + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _ProjectState && + const DeepCollectionEquality().equals(other.recent, _recent) && + (identical(other.activeProject, activeProject) || + other.activeProject == activeProject) && + const DeepCollectionEquality().equals( + other.timelines, + _timelines, + ) && + const DeepCollectionEquality().equals(other.assets, _assets) && + (identical(other.timeline, timeline) || + other.timeline == timeline) && + (identical(other.projectBusy, projectBusy) || + other.projectBusy == projectBusy) && + (identical(other.openingTimelineId, openingTimelineId) || + other.openingTimelineId == openingTimelineId) && + (identical(other.creatingTimeline, creatingTimeline) || + other.creatingTimeline == creatingTimeline) && + (identical(other.error, error) || other.error == error)); + } + + @override + int get hashCode { + return Object.hash( + runtimeType, + const DeepCollectionEquality().hash(_recent), + activeProject, + const DeepCollectionEquality().hash(_timelines), + const DeepCollectionEquality().hash(_assets), + timeline, + projectBusy, + openingTimelineId, + creatingTimeline, + error, + ); + } + + @override + String toString() { + return 'ProjectState(recent: $recent, activeProject: $activeProject, timelines: $timelines, assets: $assets, timeline: $timeline, projectBusy: $projectBusy, openingTimelineId: $openingTimelineId, creatingTimeline: $creatingTimeline, error: $error)'; + } +} + +/// @nodoc +abstract mixin class _$ProjectStateCopyWith<$Res> + implements $ProjectStateCopyWith<$Res> { + factory _$ProjectStateCopyWith( + _ProjectState value, + $Res Function(_ProjectState) _then, + ) = __$ProjectStateCopyWithImpl; + @override + @useResult + $Res call({ + List recent, + RecentProject? activeProject, + List timelines, + List assets, + TimelineDocument? timeline, + bool projectBusy, + String? openingTimelineId, + bool creatingTimeline, + AppFailure? error, + }); + + @override + $RecentProjectCopyWith<$Res>? get activeProject; +} + +/// @nodoc +class __$ProjectStateCopyWithImpl<$Res> + implements _$ProjectStateCopyWith<$Res> { + __$ProjectStateCopyWithImpl(this._self, this._then); + + final _ProjectState _self; + final $Res Function(_ProjectState) _then; + + /// Create a copy of ProjectState + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? recent = null, + Object? activeProject = freezed, + Object? timelines = null, + Object? assets = null, + Object? timeline = freezed, + Object? projectBusy = null, + Object? openingTimelineId = freezed, + Object? creatingTimeline = null, + Object? error = freezed, + }) { + return _then( + _ProjectState( + recent: null == recent + ? _self._recent + : recent // ignore: cast_nullable_to_non_nullable + as List, + activeProject: freezed == activeProject + ? _self.activeProject + : activeProject // ignore: cast_nullable_to_non_nullable + as RecentProject?, + timelines: null == timelines + ? _self._timelines + : timelines // ignore: cast_nullable_to_non_nullable + as List, + assets: null == assets + ? _self._assets + : assets // ignore: cast_nullable_to_non_nullable + as List, + timeline: freezed == timeline + ? _self.timeline + : timeline // ignore: cast_nullable_to_non_nullable + as TimelineDocument?, + projectBusy: null == projectBusy + ? _self.projectBusy + : projectBusy // ignore: cast_nullable_to_non_nullable + as bool, + openingTimelineId: freezed == openingTimelineId + ? _self.openingTimelineId + : openingTimelineId // ignore: cast_nullable_to_non_nullable + as String?, + creatingTimeline: null == creatingTimeline + ? _self.creatingTimeline + : creatingTimeline // ignore: cast_nullable_to_non_nullable + as bool, + error: freezed == error + ? _self.error + : error // ignore: cast_nullable_to_non_nullable + as AppFailure?, + ), + ); + } + + /// Create a copy of ProjectState + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $RecentProjectCopyWith<$Res>? get activeProject { + if (_self.activeProject == null) { + return null; + } + + return $RecentProjectCopyWith<$Res>(_self.activeProject!, (value) { + return _then(_self.copyWith(activeProject: value)); + }); + } +} diff --git a/lib/workspace/projects.dart b/lib/workspace/projects.dart new file mode 100644 index 0000000..1997154 --- /dev/null +++ b/lib/workspace/projects.dart @@ -0,0 +1,754 @@ +import 'package:cutdex/errors/app_failure.dart'; + +import 'dart:async'; +import 'dart:io'; +import 'dart:ui' show PlatformDispatcher; + +import '../diagnostics/app_diagnostics.dart'; + +import 'package:flutter/services.dart'; +import 'package:path/path.dart' as p; + +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import '../features/settings/language_settings.dart'; +import '../l10n/app_localizations.dart'; +import '../integrations/app_failure_adapter.dart'; + +import 'project_state.dart'; +import 'media_import.dart'; +import 'timeline_session.dart'; +import 'background_task_registry.dart'; +import 'timeline_view_state.dart'; +import 'preview_controller_registry.dart'; + +import 'package:cutdex_sdk/editor.dart'; + +import '../integrations/runtime/processing_configuration.dart'; +import 'persistence/project_workspace.dart'; +import 'persistence/timeline_creation_names.dart'; +import 'persistence/project_locator.dart'; +import 'persistence/recent_projects.dart'; +import 'persistence/project_location_directory.dart'; +import '../persistence/app_settings_repositories.dart'; + +part 'projects.g.dart'; + +@Riverpod(keepAlive: true) +class Projects extends _$Projects { + static const maxTimelineCount = 50; + + late ProjectWorkspace _workspace; + bool _workspaceReady = false; + + AppLocalizations get _localizations { + final configured = ref.read(languageSettingsProvider).asData?.value; + final locale = + configured?.locale ?? + resolveAppLocale( + PlatformDispatcher.instance.locales, + AppLocalizations.supportedLocales, + ); + return lookupAppLocalizations(locale); + } + + TimelineCreationNames _creationNames([String? timelineName]) { + final l10n = _localizations; + return TimelineCreationNames( + timeline: timelineName ?? l10n.defaultTimelineName(1), + sequence: l10n.primarySequence, + storyline: l10n.primaryStoryline, + ); + } + + EditorTimelineSession? cachedTimelineSession( + String projectId, + String timelineId, + ) { + if (!_workspaceReady || state.value?.activeProject?.id != projectId) { + return null; + } + return _workspace.cachedTimelineSession(projectId, timelineId); + } + + Future withAssetMedia( + String? projectId, + AssetDocument asset, + Future Function(MediaReference media) action, + ) async { + await future; + if (projectId == null) throw AppException(AppErrorCode.openProjectFirst); + return _workspace.withAssetMedia(projectId, asset, action); + } + + @override + Future build() async { + try { + await ref.read(languageSettingsProvider.future); + } catch (error, stackTrace) { + AppDiagnostics.failure('project', 'loadLanguage', error, stackTrace); + } + String? resources; + try { + resources = await ref + .read(resourceLocationSettingsRepositoryProvider) + .load(); + } catch (error, stackTrace) { + AppDiagnostics.failure( + 'project', + 'loadResourceLocation', + error, + stackTrace, + ); + } + final workspace = ProjectWorkspace( + creationNames: _creationNames(), + processing: ProcessingConfiguration.configured( + diagnostics: AppDiagnostics.report, + resourcesRoot: resources, + ), + backgroundTasks: ref.read(backgroundTaskRegistryProvider), + ); + _workspace = workspace; + _workspaceReady = true; + ref.onDispose(() => unawaited(workspace.close())); + final assetSubscription = workspace.assetChanges.listen((event) { + final current = state.value; + if (ref.mounted && current?.activeProject?.id == event.projectId) { + state = AsyncData(current!.copyWith(assets: event.assets)); + } + }); + ref.onDispose(() => unawaited(assetSubscription.cancel())); + try { + final repository = ref.read(recentProjectsProvider); + final recent = await repository.load(); + final locations = await Future.wait([ + for (final project in recent) + ref.read(projectLocatorProvider).locate(project), + ]); + final resolved = [for (final location in locations) location.project]; + return ProjectState(recent: resolved); + } catch (error, stackTrace) { + AppDiagnostics.failure( + 'project', + 'loadRecentProjects', + error, + stackTrace, + ); + return const ProjectState( + error: AppFailure(AppErrorCode.loadRecentProjectsFailed), + ); + } + } + + /// Freeze workspace commands before closing; failed saves leave it recoverable. + Future prepareToQuit() async { + await future; + final current = state.requireValue; + if (current.projectBusy || + current.creatingTimeline || + current.openingTimelineId != null || + _workspace.hasBackgroundTasks) { + throw PlatformException(code: 'workspaceBusy'); + } + state = AsyncData(state.requireValue.copyWith(projectBusy: true)); + try { + await _workspace.close(); + await AppDiagnostics.instance?.store.flush(); + return true; + } catch (error, stack) { + AppDiagnostics.failure('project', 'close', error, stack); + state = AsyncData(state.requireValue.copyWith(projectBusy: false)); + throw PlatformException(code: 'saveFailed'); + } + } + + Future _perform(Future Function() action) async { + await future; + if (!ref.mounted || state.requireValue.projectBusy) return false; + state = AsyncData( + state.requireValue.copyWith(projectBusy: true, error: null), + ); + try { + await action(); + return true; + } on ProjectOpenSuperseded { + return false; + } catch (error, stackTrace) { + AppDiagnostics.failure('project', 'operation', error, stackTrace); + if (ref.mounted) { + final failure = projectFailureFromError(error); + state = AsyncData(state.requireValue.copyWith(error: failure)); + } + return false; + } finally { + if (ref.mounted) { + state = AsyncData(state.requireValue.copyWith(projectBusy: false)); + } + } + } + + Future open( + String path, { + String? name, + String? expectedId, + String? timelineId, + String? initialTimelineName, + bool Function()? isCurrent, + }) => _perform(() async { + final previous = state.requireValue; + var published = false; + void checkCurrent() { + if (!ref.mounted || isCurrent?.call() == false) { + throw ProjectOpenSuperseded(); + } + } + + try { + checkCurrent(); + final timelines = await _workspace.open( + path, + name: name, + expectedId: expectedId, + creationNames: _creationNames(initialTimelineName), + isCurrent: isCurrent, + ); + checkCurrent(); + final file = _workspace.project!; + final assets = await _workspace.listAssets(file.info.id); + checkCurrent(); + final active = RecentProject( + id: file.info.id, + name: file.info.name, + path: file.directory.path, + availability: ProjectAvailability.available, + ); + final previousRecent = state.requireValue.recent; + final existingIndex = previousRecent.indexWhere( + (item) => item.id == active.id || item.path == active.path, + ); + final recent = [ + if (existingIndex == -1) active, + for (final (index, item) in previousRecent.indexed) + if (index == existingIndex) + active + else if (item.id != active.id && item.path != active.path) + item, + ].take(20).toList(); + TimelineDocument? selectedDocument; + if (timelines.isNotEmpty) { + var selectedId = timelineId; + if (selectedId == null) { + try { + selectedId = await ref + .read(recentProjectsProvider) + .lastTimeline(active.id); + } catch (_) { + // App settings storage must not block opening the project. + } + } + final selected = + timelines + .where((timeline) => timeline.id == selectedId) + .firstOrNull ?? + (timelineId == null ? timelines.first : null); + if (timelineId != null && selected == null) { + throw AppException(AppErrorCode.timelineMissing); + } + if (selected != null) { + selectedDocument = await _workspace.loadTimeline( + active.id, + selected.id, + ); + } + } + checkCurrent(); + if (selectedDocument != null) { + await _prepareTimeline(active.id, selectedDocument); + } + checkCurrent(); + await ref + .read(previewControllerRegistryProvider) + .retainProject(active.id, keep: _workspace.cachedProjectIds); + checkCurrent(); + state = AsyncData( + state.requireValue.copyWith( + activeProject: active, + recent: recent, + timelines: timelines, + assets: assets, + timeline: selectedDocument, + ), + ); + published = true; + if (selectedDocument != null) { + await _rememberTimeline(active.id, selectedDocument.id); + } + try { + await ref.read(recentProjectsProvider).save(recent); + } catch (_) { + if (ref.mounted) { + state = AsyncData( + state.requireValue.copyWith( + error: const AppFailure(AppErrorCode.recentProjectSaveFailed), + ), + ); + } + } + } catch (_) { + checkCurrent(); + rethrow; + } finally { + final old = previous.activeProject; + if (!published && + ref.mounted && + old != null && + _workspace.project?.info.id != old.id) { + await _workspace.open(old.path, expectedId: old.id); + if (previous.timeline != null) { + await _prepareTimeline(old.id, previous.timeline!); + } + await ref + .read(previewControllerRegistryProvider) + .retainProject(old.id, keep: _workspace.cachedProjectIds); + } + } + }); + + Future createProject( + String name, { + required String initialTimelineName, + }) async { + final value = name.trim(); + if (value.isEmpty || + RegExp(r'[/\\\x00-\x1F]').hasMatch(value) || + const {'.', '..'}.contains(value)) { + await future; + if (ref.mounted) { + state = AsyncData( + state.requireValue.copyWith( + error: const AppFailure(AppErrorCode.projectNameInvalid), + ), + ); + } + return false; + } + String? root; + try { + root = await ref.read(projectLocationSettingsRepositoryProvider).load(); + } on ProjectLocationUnavailableException { + await future; + if (ref.mounted) { + state = AsyncData( + state.requireValue.copyWith( + error: const AppFailure( + AppErrorCode.projectLocationDefaultUnavailable, + ), + ), + ); + } + return false; + } + if (root == null || root.trim().isEmpty) { + await future; + if (ref.mounted) { + state = AsyncData( + state.requireValue.copyWith( + error: const AppFailure(AppErrorCode.chooseProjectLocation), + ), + ); + } + return false; + } + try { + await const ProjectLocationDirectory().prepare(root); + } on StateError catch (error) { + await future; + if (ref.mounted) { + state = AsyncData( + state.requireValue.copyWith(error: projectFailureFromError(error)), + ); + } + return false; + } + return open( + p.join(root, '$value.cutdex'), + name: value, + initialTimelineName: initialTimelineName, + ); + } + + Future> listProjectTimelines( + RecentProject project, + ) async { + await future; + return _workspace.listProjectTimelines( + project.path, + expectedId: project.id, + ); + } + + Future removeRecentProject(String projectId) => _perform(() async { + final recent = state.requireValue.recent + .where((project) => project.id != projectId) + .toList(); + await ref.read(recentProjectsProvider).save(recent); + if (!ref.mounted) return; + state = AsyncData(state.requireValue.copyWith(recent: recent)); + }); + + Future restoreRecentProject(RecentProject project, int index) => + _perform(() async { + final recent = [...state.requireValue.recent]; + if (recent.any((item) => item.id == project.id)) return; + recent.insert(index.clamp(0, recent.length), project); + await ref.read(recentProjectsProvider).save(recent); + if (!ref.mounted) return; + state = AsyncData(state.requireValue.copyWith(recent: recent)); + }); + + Future renameProject(RecentProject project, String name) => + _perform(() async { + final value = name.trim(); + await _workspace.renameProject(project, value); + if (!ref.mounted) return; + final current = state.requireValue; + final renamed = project.copyWith(name: value); + final recent = [ + for (final item in current.recent) + if (item.id == project.id) renamed else item, + ]; + state = AsyncData( + current.copyWith( + recent: recent, + activeProject: current.activeProject?.id == project.id + ? current.activeProject!.copyWith(name: value) + : current.activeProject, + ), + ); + await ref.read(recentProjectsProvider).save(recent); + }); + + Future renameTimeline( + RecentProject project, + String timelineId, + String name, + ) => _perform(() async { + final value = name.trim(); + await _workspace.renameTimeline(project, timelineId, value); + if (!ref.mounted || state.requireValue.activeProject?.id != project.id) { + return; + } + final current = state.requireValue; + state = AsyncData( + current.copyWith( + timelines: [ + for (final timeline in current.timelines) + if (timeline.id == timelineId) + TimelineSummary( + id: timeline.id, + name: value, + revision: timeline.revision, + pinned: timeline.pinned, + ) + else + timeline, + ], + timeline: current.timeline?.id == timelineId + ? TimelineDocument( + id: current.timeline!.id, + name: value, + sequences: current.timeline!.sequences, + defaultSequenceId: current.timeline!.defaultSequenceId, + payloads: current.timeline!.payloads, + settings: current.timeline!.settings, + revision: current.timeline!.revision, + ) + : current.timeline, + ), + ); + }); + + Future setTimelinePinned(String timelineId, bool pinned) => + _perform(() async { + final current = state.requireValue; + final project = current.activeProject; + if (project == null) throw AppException(AppErrorCode.openProjectFirst); + final timelines = await _workspace.setTimelinePinned( + project, + timelineId, + pinned, + ); + if (ref.mounted && state.requireValue.activeProject?.id == project.id) { + state = AsyncData(state.requireValue.copyWith(timelines: timelines)); + } + }); + + Future deleteTimeline(String timelineId) => _perform(() async { + final current = state.requireValue; + final project = current.activeProject; + if (project == null) throw AppException(AppErrorCode.openProjectFirst); + if (current.timelines.length <= 1) { + throw AppException(AppErrorCode.timelineRequired); + } + final deletedIndex = current.timelines.indexWhere( + (timeline) => timeline.id == timelineId, + ); + if (deletedIndex < 0) throw AppException(AppErrorCode.timelineMissing); + final replacementId = + current.timelines[deletedIndex > 0 ? deletedIndex - 1 : 1].id; + final timelines = await _workspace.deleteTimeline(project, timelineId); + if (!ref.mounted || state.requireValue.activeProject?.id != project.id) { + return; + } + TimelineDocument? selected = state.requireValue.timeline; + if (selected?.id == timelineId) { + selected = await _workspace.loadTimeline(project.id, replacementId); + await _prepareTimeline(project.id, selected); + } + if (!ref.mounted || state.requireValue.activeProject?.id != project.id) { + return; + } + state = AsyncData( + state.requireValue.copyWith(timelines: timelines, timeline: selected), + ); + if (selected != null) await _rememberTimeline(project.id, selected.id); + }); + + Future createTimeline({String? name}) async { + await future; + final current = state.requireValue; + if (current.projectBusy || + current.creatingTimeline || + current.openingTimelineId != null || + current.activeProject == null) { + return false; + } + if (current.timelines.length >= maxTimelineCount) return false; + state = AsyncData(current.copyWith(creatingTimeline: true, error: null)); + try { + final timelineName = name?.trim().isNotEmpty == true + ? name!.trim() + : _nextUntitledTimelineName(current.timelines); + final created = await _workspace.createPreparedTimeline( + timelineName, + creationNames: _creationNames(timelineName), + ); + await _prepareTimeline(current.activeProject!.id, created.document); + if (!ref.mounted) return true; + state = AsyncData( + state.requireValue.copyWith( + timelines: created.timelines, + timeline: created.document, + creatingTimeline: false, + ), + ); + await _rememberTimeline(current.activeProject!.id, created.document.id); + return true; + } catch (error) { + if (ref.mounted) { + state = AsyncData( + state.requireValue.copyWith( + creatingTimeline: false, + error: _failureFor(error), + ), + ); + } + return false; + } + } + + String _nextUntitledTimelineName(List timelines) { + final names = timelines.map((timeline) => timeline.name).toSet(); + final base = _localizations.untitledTimeline; + if (!names.contains(base)) return base; + for (var suffix = 2; ; suffix++) { + final candidate = '$base ($suffix)'; + if (!names.contains(candidate)) return candidate; + } + } + + Future importExternalMedia( + String projectId, + List files, { + bool Function()? isCancelled, + }) async { + MediaImportResult? result; + await _perform(() async { + result = await _workspace.importExternalMedia( + projectId, + files, + isCancelled: isCancelled, + ); + }); + return result; + } + + Future insertTimelineAsset({ + required String projectId, + required EditorTimelineSession session, + required SequenceId sequenceId, + required String assetId, + required int position, + }) => _perform(() async { + final current = state.requireValue; + if (current.activeProject?.id != projectId || + current.timeline?.id != session.document.id) { + throw AppException(AppErrorCode.projectSwitched); + } + await session.commands.insertMedia( + sequence: sequenceId, + assetId: assetId, + position: position, + ); + }); + + Future editMediaAsset( + String projectId, + String assetId, { + String? name, + }) => _perform(() async { + final assets = await _workspace.editAsset(projectId, assetId, name: name); + if (ref.mounted && state.requireValue.activeProject?.id == projectId) { + state = AsyncData(state.requireValue.copyWith(assets: assets)); + } + }); + + Future revealMediaAsset(String projectId, AssetDocument asset) => + _perform(() async { + await _workspace.withAssetMedia(projectId, asset, (media) async { + if (media.uri.scheme != 'file') { + throw AppException(AppErrorCode.notLocalMedia); + } + final path = media.uri.toFilePath(); + final result = Platform.isMacOS + ? await Process.run('/usr/bin/open', ['-R', path]) + : Platform.isWindows + ? await Process.run('explorer.exe', ['/select,', path]) + : await Process.run('xdg-open', [File(path).parent.path]); + if (result.exitCode != 0) { + throw AppException(AppErrorCode.revealMediaFailed); + } + }); + }); + + Future openTimelineSession( + String projectId, + String timelineId, + ) async { + final current = await future; + if (current.activeProject?.id != projectId || + current.timeline?.id != timelineId) { + throw AppException( + current.activeProject?.id != projectId + ? AppErrorCode.openMatchingProject + : AppErrorCode.openTimelineFailed, + ); + } + return _workspace.openTimelineSession(projectId, current.timeline!); + } + + Future _prepareTimeline( + String projectId, + TimelineDocument document, + ) async { + final session = await _workspace.openTimelineSession(projectId, document); + await TimelineViewStateBinding.prepare( + projectId: projectId, + timelineId: document.id, + session: session, + repository: ref.read(timelineViewSettingsRepositoryProvider), + ); + try { + await ref.read(previewControllerRegistryProvider).prepare(( + projectId, + document.id, + ), session); + } catch (error, stackTrace) { + AppDiagnostics.failure('preview', 'prepare', error, stackTrace); + } + return session; + } + + Future leaseTimeline( + String projectId, + String timelineId, + ) async { + await future; + return _workspace.leaseTimeline(projectId, timelineId); + } + + Future openTimeline(String projectId, String timelineId) async { + await future; + final current = state.requireValue; + if (current.projectBusy || + current.creatingTimeline || + current.openingTimelineId != null || + current.activeProject?.id != projectId) { + return false; + } + if (current.timeline?.id == timelineId) return true; + final cachedTimeline = _workspace.cachedTimelineDocument( + projectId, + timelineId, + ); + final cachedSession = _workspace.cachedTimelineSession( + projectId, + timelineId, + ); + if (cachedTimeline != null && cachedSession != null) { + state = AsyncData( + current.copyWith(timeline: cachedTimeline, error: null), + ); + await _rememberTimeline(projectId, timelineId); + return true; + } + state = AsyncData( + current.copyWith(openingTimelineId: timelineId, error: null), + ); + try { + final timeline = await _workspace.loadTimeline(projectId, timelineId); + await _prepareTimeline(projectId, timeline); + if (!ref.mounted) return true; + state = AsyncData( + state.requireValue.copyWith( + timeline: timeline, + openingTimelineId: null, + ), + ); + await _rememberTimeline(projectId, timelineId); + return true; + } catch (error) { + if (ref.mounted) { + state = AsyncData( + state.requireValue.copyWith( + openingTimelineId: null, + error: _failureFor(error), + ), + ); + } + return false; + } + } + + Future _rememberTimeline(String projectId, String timelineId) async { + try { + await ref + .read(recentProjectsProvider) + .rememberTimeline(projectId, timelineId); + } catch (_) { + if (ref.mounted) { + state = AsyncData( + state.requireValue.copyWith( + error: const AppFailure(AppErrorCode.lastProjectSaveFailed), + ), + ); + } + } + } + + AppFailure _failureFor(Object error) => projectFailureFromError(error); +} diff --git a/lib/workspace/projects.g.dart b/lib/workspace/projects.g.dart new file mode 100644 index 0000000..fecabca --- /dev/null +++ b/lib/workspace/projects.g.dart @@ -0,0 +1,54 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'projects.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(Projects) +final projectsProvider = ProjectsProvider._(); + +final class ProjectsProvider + extends $AsyncNotifierProvider { + ProjectsProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'projectsProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$projectsHash(); + + @$internal + @override + Projects create() => Projects(); +} + +String _$projectsHash() => r'7112bbc5f1f4389d91f20aa9ec2ac5d28136eefe'; + +abstract class _$Projects extends $AsyncNotifier { + FutureOr build(); + @$mustCallSuper + @override + WhenComplete runBuild() { + final ref = this.ref as $Ref, ProjectState>; + final element = + ref.element + as $ClassProviderElement< + AnyNotifier, ProjectState>, + AsyncValue, + Object?, + Object? + >; + return element.handleCreate(ref, build); + } +} diff --git a/lib/workspace/timeline_provider.dart b/lib/workspace/timeline_provider.dart new file mode 100644 index 0000000..0286de3 --- /dev/null +++ b/lib/workspace/timeline_provider.dart @@ -0,0 +1,61 @@ +import 'dart:async'; + +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import '../persistence/app_settings_repositories.dart'; +import 'projects.dart'; +import 'timeline_session.dart'; +import 'timeline_view_state.dart'; + +part 'timeline_provider.g.dart'; + +@riverpod +FutureOr editorTimeline( + Ref ref, + String projectId, + String timelineId, +) { + final ids = (projectId, timelineId); + + final projects = ref.read(projectsProvider.notifier); + final cached = projects.cachedTimelineSession(projectId, timelineId); + if (cached != null) return _bindTimeline(ref, ids, cached); + return projects.openTimelineSession(projectId, timelineId).then((session) { + if (!ref.mounted) return session; + return _bindTimeline(ref, ids, session); + }); +} + +FutureOr _bindTimeline( + Ref ref, + (String, String) ids, + EditorTimelineSession session, +) { + final binding = TimelineViewStateBinding.attach( + projectId: ids.$1, + timelineId: ids.$2, + session: session, + repository: ref.read(timelineViewSettingsRepositoryProvider), + ); + if (binding is TimelineViewStateBinding) { + return _retainTimeline(ref, session, binding); + } + return binding.then((resolved) => _retainTimeline(ref, session, resolved)); +} + +EditorTimelineSession _retainTimeline( + Ref ref, + EditorTimelineSession session, + TimelineViewStateBinding binding, +) { + if (ref.mounted) { + final releaseViews = session.retainViews(); + ref.onDispose(() { + unawaited(binding.close()); + releaseViews(); + }); + } else { + unawaited(binding.close()); + } + return session; +} diff --git a/lib/workspace/timeline_provider.g.dart b/lib/workspace/timeline_provider.g.dart new file mode 100644 index 0000000..5e99fc2 --- /dev/null +++ b/lib/workspace/timeline_provider.g.dart @@ -0,0 +1,91 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'timeline_provider.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(editorTimeline) +final editorTimelineProvider = EditorTimelineFamily._(); + +final class EditorTimelineProvider + extends + $FunctionalProvider< + AsyncValue, + EditorTimelineSession, + FutureOr + > + with + $FutureModifier, + $FutureProvider { + EditorTimelineProvider._({ + required EditorTimelineFamily super.from, + required (String, String) super.argument, + }) : super( + retry: null, + name: r'editorTimelineProvider', + isAutoDispose: true, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$editorTimelineHash(); + + @override + String toString() { + return r'editorTimelineProvider' + '' + '$argument'; + } + + @$internal + @override + $FutureProviderElement $createElement( + $ProviderPointer pointer, + ) => $FutureProviderElement(pointer); + + @override + FutureOr create(Ref ref) { + final argument = this.argument as (String, String); + return editorTimeline(ref, argument.$1, argument.$2); + } + + @override + bool operator ==(Object other) { + return other is EditorTimelineProvider && other.argument == argument; + } + + @override + int get hashCode { + return argument.hashCode; + } +} + +String _$editorTimelineHash() => r'7c6aceb0f85c2e6508c78d62568a45fdd46bc075'; + +final class EditorTimelineFamily extends $Family + with + $FunctionalFamilyOverride< + FutureOr, + (String, String) + > { + EditorTimelineFamily._() + : super( + retry: null, + name: r'editorTimelineProvider', + dependencies: null, + $allTransitiveDependencies: null, + isAutoDispose: true, + ); + + EditorTimelineProvider call(String projectId, String timelineId) => + EditorTimelineProvider._(argument: (projectId, timelineId), from: this); + + @override + String toString() => r'editorTimelineProvider'; +} diff --git a/lib/workspace/timeline_session.dart b/lib/workspace/timeline_session.dart new file mode 100644 index 0000000..b65b81f --- /dev/null +++ b/lib/workspace/timeline_session.dart @@ -0,0 +1,323 @@ +import 'package:cutdex/errors/app_failure.dart'; + +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/timeline/engine.dart'; +import 'package:cutdex_sdk/timeline/layout.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:cutdex_sdk/timeline_ui.dart'; +import 'package:flutter/foundation.dart'; +import 'package:uuid/uuid.dart'; + +/// Flutter presentation resources for an SDK-owned editor session. +class EditorTimelineSession extends EditorSession implements Listenable { + EditorTimelineSession({ + required super.document, + required super.persistence, + super.media, + super.exportService, + super.captionFiles, + super.diagnostics, + super.transcriptionBackend, + super.transcriptionModel, + super.translationBackend, + super.translationModel, + super.vocalSeparationBackend, + super.vocalSeparationModel, + super.layoutConfiguration, + super.assetUris, + }) { + _activeSequenceId = + document.defaultSequenceId ?? document.sequences.firstOrNull?.id; + } + bool _disposed = false; + AppFailure? get error => saveError == null + ? null + : AppFailure( + AppErrorCode.saveTimelineFailed, + diagnostic: saveError.toString(), + ); + final _views = {}; + final audioGainPreview = + ValueNotifier< + ({ + SequenceId sequence, + ElementId clip, + Object version, + ClipAudioGain gain, + })? + >(null); + + final _customSpeedClips = >{}; + + bool isCustomSpeedEnabled(SequenceId sequence, ElementId clip) => + _customSpeedClips[sequence]?.contains(clip) ?? false; + + void setCustomSpeedEnabled( + SequenceId sequence, + ElementId clip, + bool enabled, + ) { + final clips = _customSpeedClips.putIfAbsent(sequence, () => {}); + final changed = enabled ? clips.add(clip) : clips.remove(clip); + if (!changed) return; + _syncSpeedGeometry(sequence); + notifyListeners(); + } + + void previewAudioGain( + SequenceId sequence, + ElementId clip, + ClipAudioGain gain, + ) { + audioGainPreview.value = ( + sequence: sequence, + clip: clip, + version: view(sequence).version.kernelVersion, + gain: gain, + ); + } + + void clearAudioGainPreview(ElementId clip) { + if (_disposed) return; + if (audioGainPreview.value?.clip == clip) audioGainPreview.value = null; + } + + double waveformGain(ElementRecord clip) { + final timeline = audioGainPreview.value; + if (timeline != null && + timeline.clip == clip.id && + timeline.sequence == activeSequenceId && + identical( + timeline.version, + view(timeline.sequence).version.kernelVersion, + )) { + return timeline.gain.amplitudeScale; + } + return ClipAudioGain.fromRecord(clip).amplitudeScale; + } + + SequenceId? _activeSequenceId; + SequenceId? get activeSequenceId => _activeSequenceId; + void selectSequence(SequenceId id) { + if (_activeSequenceId == id) return; + if (!document.sequences.any((sequence) => sequence.id == id)) { + throw ArgumentError('Unknown sequence'); + } + _activeSequenceId = id; + notifyListeners(); + } + + TimelineViewController view( + SequenceId sequenceId, + ) => _views.putIfAbsent(sequenceId, () { + final owners = _resolveSpeedOwners(sequenceId); + _speedHeaderOwners[sequenceId] = owners; + _speedOnPrimary[sequenceId] = _hasPrimarySpeedOwner(sequenceId, owners); + final controller = TimelineViewController.editable( + engine: layout(sequenceId), + geometry: _viewportGeometry(sequenceId), + camera: TimelineCamera( + baseTick: 0, + pixelsPerTick: 60 / TimelineClock.ticksPerSecond, + ), + createConnectionId: () => ConnectionId(const Uuid().v4()), + createElementId: () => ElementId(const Uuid().v4()), + commitEdit: (T Function() action) => commit(sequenceId, action), + editOperation: ( + String operation, + Map context, + T Function() action, + ) => runEdit(operation, sequenceId, action, context: context), + onEditFailure: reportEditFailure, + onElementsSplit: (fragments) { + final clips = _customSpeedClips[sequenceId]; + if (clips == null) return; + final query = persistence.timeline(sequenceId).current.query(); + for (final fragment in fragments.entries) { + if (clips.contains(query.element(fragment.key).id)) { + clips.add(fragment.value); + } + } + }, + canUndo: () => canUndo(sequenceId), + canRedo: () => canRedo(sequenceId), + undo: () => undo(sequenceId), + redo: () => redo(sequenceId), + resolveComponent: (identity, _) => + resolveCaptionComponent(sequenceId, identity), + commitComponent: (identity, start, duration) => + setCaptionComponentInterval(sequenceId, identity, start, duration), + ); + _speedGeometryOwners[controller.version] = ( + owners: owners, + primary: _speedOnPrimary[sequenceId] ?? false, + ); + controller.contentChanges.addListener(() => _syncSpeedGeometry(sequenceId)); + return controller; + }); + + final _speedHeaderOwners = >{}; + final _speedOnPrimary = {}; + final _speedGeometryOwners = + Expando<({Set owners, bool primary})>(); + bool _syncingSpeedGeometry = false; + bool _movingHistory = false; + + @override + int primaryHeightFor(SequenceId sequence) { + final height = layoutConfiguration.primaryHeight; + if (_speedOnPrimary[sequence] != true) return height; + final topPadding = (height - layoutConfiguration.primaryClipHeight) ~/ 2; + return height + + (EditorLayoutConfiguration.speedHeaderHeight - topPadding).clamp( + 0, + EditorLayoutConfiguration.speedHeaderHeight, + ); + } + + @override + int clipHeightFor(SequenceId sequence, ElementRecord clip) => + super.clipHeightFor(sequence, clip) + + (isCustomSpeedEnabled(sequence, clip.id) + ? EditorLayoutConfiguration.speedHeaderHeight + : 0); + + TimelineViewportGeometry _viewportGeometry(SequenceId sequence) { + final height = primaryHeightFor(sequence); + final laneTop = + layoutConfiguration.primaryTop + + height - + layoutConfiguration.primaryHeight; + return TimelineViewportGeometry( + primaryTop: layoutConfiguration.primaryTop, + primaryHeight: height, + primaryLaneHeight: layoutConfiguration.primaryHeight, + primaryClipHeight: layoutConfiguration.primaryClipHeight, + clipHeaderOwners: _speedHeaderOwners[sequence] ?? const {}, + clipHeaderHeight: EditorLayoutConfiguration.speedHeaderHeight, + transitionTop: laneTop, + transitionHeight: layoutConfiguration.primaryHeight, + ); + } + + Set _resolveSpeedOwners(SequenceId sequence) { + final query = persistence.timeline(sequence).current.query(); + return Set.unmodifiable({ + for (final clip in _customSpeedClips[sequence] ?? const {}) + if (query.elementById(clip) case final handle?) + if (query.ownerOf(handle) != null && + clipSpeedSegments(query.element(handle)) != null) + handle, + }); + } + + bool _hasPrimarySpeedOwner(SequenceId sequence, Set owners) { + final query = persistence.timeline(sequence).current.query(); + return owners.any((owner) => query.connectionForTarget(owner) == null); + } + + void _syncSpeedGeometry(SequenceId sequence, {bool force = false}) { + if (_disposed || _syncingSpeedGeometry || _movingHistory) return; + final controller = _views[sequence]; + if (controller == null) return; + final owners = _resolveSpeedOwners(sequence); + final primary = _hasPrimarySpeedOwner(sequence, owners); + final dimensions = (owners: owners, primary: primary); + final retained = _speedGeometryOwners[controller.version]; + if (setEquals(_speedHeaderOwners[sequence] ?? const {}, owners) && + (_speedOnPrimary[sequence] ?? false) == primary && + (!force || + (retained != null && + retained.primary == primary && + setEquals(retained.owners, owners)))) { + _speedGeometryOwners[controller.version] = dimensions; + return; + } + _syncingSpeedGeometry = true; + try { + _speedHeaderOwners[sequence] = owners; + _speedOnPrimary[sequence] = primary; + final result = refreshLayoutGeometry(sequence); + _speedGeometryOwners[result.version] = dimensions; + controller.applyLayout(result, geometry: _viewportGeometry(sequence)); + } finally { + _syncingSpeedGeometry = false; + } + } + + @override + void undo(SequenceId sequence) { + _movingHistory = true; + try { + super.undo(sequence); + } finally { + _movingHistory = false; + } + _syncSpeedGeometry(sequence, force: true); + } + + @override + void redo(SequenceId sequence) { + _movingHistory = true; + try { + super.redo(sequence); + } finally { + _movingHistory = false; + } + _syncSpeedGeometry(sequence, force: true); + } + + @override + void didChangeProjectProperties() { + for (final view in _views.values) { + view.cancelDrag(); + view.notifyListeners(); + } + } + + @override + void didPublishLayout(SequenceId sequence, LayoutApplyResult result) { + _views[sequence]?.applyLayout(result); + } + + @override + void didInsertClip(SequenceId sequence, ElementId clip) { + _views[sequence]?.setSelection([ + persistence.timeline(sequence).current.query().elementById(clip)!, + ]); + } + + int _viewLeases = 0; + bool _closed = false; + + /// Keep presentation notifiers alive until their provider and widgets detach. + /// Closing still flushes edits and rejects further commands immediately. + VoidCallback retainViews() { + if (_disposed || _closed) { + throw AppException(AppErrorCode.timelineSessionClosed); + } + _viewLeases++; + var released = false; + return () { + if (released) return; + released = true; + _viewLeases--; + if (_closed && _viewLeases == 0) dispose(); + }; + } + + @override + void dispose() { + if (_disposed) return; + _closed = true; + // The old provider can remain mounted for a frame after a timeline switch. + // Its widgets must be able to detach from these notifiers before disposal. + if (_viewLeases > 0) return; + _disposed = true; + super.dispose(); + audioGainPreview.dispose(); + for (final controller in _views.values) { + controller.dispose(); + } + } +} diff --git a/lib/workspace/timeline_view_state.dart b/lib/workspace/timeline_view_state.dart new file mode 100644 index 0000000..43c52a4 --- /dev/null +++ b/lib/workspace/timeline_view_state.dart @@ -0,0 +1,183 @@ +import 'dart:async'; + +import 'package:cutdex_sdk/timeline/model.dart'; + +import '../persistence/app_settings_repositories.dart'; +import 'timeline_session.dart'; + +/// Keeps local timeline navigation out of the authored project document. +final class TimelineViewStateBinding { + static final _initialized = Expando(); + + TimelineViewStateBinding._( + this.projectId, + this.timelineId, + this.session, + this.repository, + ); + + static Future prepare({ + required String projectId, + required String timelineId, + required EditorTimelineSession session, + required TimelineViewSettingsRepository repository, + }) async { + if (_initialized[session] == true) return; + var saved = const TimelineViewState(); + try { + saved = await repository.load(projectId, timelineId); + } catch (_) { + // Corrupt or unavailable local UI state must not block the timeline. + } + _restore(session, saved); + _initialized[session] = true; + } + + static FutureOr attach({ + required String projectId, + required String timelineId, + required EditorTimelineSession session, + required TimelineViewSettingsRepository repository, + }) { + final shouldRestore = _initialized[session] != true; + if (!shouldRestore) { + return _bind( + projectId: projectId, + timelineId: timelineId, + session: session, + repository: repository, + saved: const TimelineViewState(), + shouldRestore: false, + ); + } + return () async { + var saved = const TimelineViewState(); + try { + saved = await repository.load(projectId, timelineId); + } catch (_) { + // Corrupt or unavailable local UI state must not block the timeline. + } + return _bind( + projectId: projectId, + timelineId: timelineId, + session: session, + repository: repository, + saved: saved, + shouldRestore: true, + ); + }(); + } + + static TimelineViewStateBinding _bind({ + required String projectId, + required String timelineId, + required EditorTimelineSession session, + required TimelineViewSettingsRepository repository, + required TimelineViewState saved, + required bool shouldRestore, + }) { + if (shouldRestore) _restore(session, saved); + final sequenceIds = session.document.sequences + .map((item) => item.id) + .toSet(); + final binding = TimelineViewStateBinding._( + projectId, + timelineId, + session, + repository, + ); + for (final sequenceId in sequenceIds) { + final controller = session.view(sequenceId); + void listener() => binding._schedule(sequenceId); + controller.addListener(listener); + binding._listeners[sequenceId] = listener; + } + _initialized[session] = true; + binding._activeSequenceId = session.activeSequenceId; + session.addListener(binding._sessionChanged); + return binding; + } + + static void _restore(EditorTimelineSession session, TimelineViewState saved) { + final sequenceIds = session.document.sequences + .map((item) => item.id) + .toSet(); + final active = saved.activeSequenceId; + if (active != null && sequenceIds.contains(active)) { + session.selectSequence(active); + } + for (final sequenceId in sequenceIds) { + final state = saved.sequences[sequenceId]; + if (state != null) { + session + .view(sequenceId) + .restoreViewState( + playheadTick: state.playheadTick, + camera: state.camera, + ); + } + } + } + + final String projectId; + final String timelineId; + final EditorTimelineSession session; + final TimelineViewSettingsRepository repository; + final Map _listeners = {}; + SequenceId? _activeSequenceId; + Timer? _timer; + Future _tail = Future.value(); + bool _closed = false; + + void _sessionChanged() { + final next = session.activeSequenceId; + if (next == _activeSequenceId) return; + final previous = _activeSequenceId; + _activeSequenceId = next; + _timer?.cancel(); + if (previous != null) _enqueue(previous); + if (next != null) _enqueue(next); + } + + void _schedule(SequenceId sequenceId) { + if (_closed || sequenceId != session.activeSequenceId) return; + _timer?.cancel(); + _timer = Timer(const Duration(milliseconds: 500), () { + _enqueue(sequenceId); + }); + } + + void _enqueue(SequenceId sequenceId) { + _tail = _tail.then((_) => _save(sequenceId)); + } + + Future _save(SequenceId sequenceId) async { + final controller = session.view(sequenceId); + try { + await repository.save( + projectId, + timelineId, + sequenceId, + TimelineSequenceViewState( + playheadTick: controller.playheadTick, + camera: controller.camera, + ), + ); + } catch (_) { + // View state must never block editing or project persistence. + } + } + + Future close() async { + if (_closed) return; + _closed = true; + _timer?.cancel(); + session.removeListener(_sessionChanged); + for (final entry in _listeners.entries) { + session.view(entry.key).removeListener(entry.value); + } + final active = session.activeSequenceId; + if (active != null) _enqueue(active); + await _tail; + } +} diff --git a/lib/workspace/view_settings.dart b/lib/workspace/view_settings.dart new file mode 100644 index 0000000..f1ba643 --- /dev/null +++ b/lib/workspace/view_settings.dart @@ -0,0 +1,78 @@ +import '../diagnostics/app_diagnostics.dart'; + +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import '../persistence/settings/view_settings_repositories.dart'; +import '../settings/settings_write_queue.dart'; +import 'workspace_mode.dart'; + +part 'view_settings.g.dart'; + +/// Persistent navigation preferences, shared by the application surface. +@Riverpod(keepAlive: true) +class WorkspaceViewSettings extends _$WorkspaceViewSettings { + final _writes = SettingsWriteQueue(); + + @override + Future build() async { + try { + return await ref.watch(workspaceViewSettingsRepositoryProvider).load(); + } catch (error, stackTrace) { + AppDiagnostics.failure( + 'settings', + 'loadWorkspaceView', + error, + stackTrace, + ); + return const WorkspaceViewSettingsData(); + } + } + + void setMode(WorkspaceMode mode) => + state = AsyncData(state.requireValue.copyWith(mode: mode)); + + void setSidebarCollapsed(bool collapsed) => state = AsyncData( + state.requireValue.copyWith(sidebarCollapsed: collapsed), + ); + + void setSidebarWidth(double? width) => + state = AsyncData(state.requireValue.copyWith(sidebarWidth: width)); + + /// Writes snapshots in order so a slower drag save cannot replace a newer one. + Future save({required String? activeProjectId}) { + final value = state.requireValue.copyWith(activeProjectId: activeProjectId); + state = AsyncData(value); + final repository = ref.read(workspaceViewSettingsRepositoryProvider); + return _writes.run(() => repository.save(value)); + } +} + +/// Project preferences survive timeline switches and widget reconstruction. +@Riverpod(keepAlive: true) +class ProjectViewSettings extends _$ProjectViewSettings { + final _writes = SettingsWriteQueue(); + + @override + Future build(String projectId) async { + try { + return await ref + .watch(projectViewSettingsRepositoryProvider) + .load(projectId); + } catch (error, stackTrace) { + AppDiagnostics.failure('settings', 'loadProjectView', error, stackTrace); + return const ProjectViewSettingsData(); + } + } + + void setPropertiesOpen(bool open) => + state = AsyncData(state.requireValue.copyWith(propertiesOpen: open)); + + void setTimelineHeight(double? height) => + state = AsyncData(state.requireValue.copyWith(timelineHeight: height)); + + Future save() { + final value = state.requireValue; + final repository = ref.read(projectViewSettingsRepositoryProvider); + return _writes.run(() => repository.save(projectId, value)); + } +} diff --git a/lib/workspace/view_settings.g.dart b/lib/workspace/view_settings.g.dart new file mode 100644 index 0000000..716cc3f --- /dev/null +++ b/lib/workspace/view_settings.g.dart @@ -0,0 +1,183 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'view_settings.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning +/// Persistent navigation preferences, shared by the application surface. + +@ProviderFor(WorkspaceViewSettings) +final workspaceViewSettingsProvider = WorkspaceViewSettingsProvider._(); + +/// Persistent navigation preferences, shared by the application surface. +final class WorkspaceViewSettingsProvider + extends + $AsyncNotifierProvider< + WorkspaceViewSettings, + WorkspaceViewSettingsData + > { + /// Persistent navigation preferences, shared by the application surface. + WorkspaceViewSettingsProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'workspaceViewSettingsProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$workspaceViewSettingsHash(); + + @$internal + @override + WorkspaceViewSettings create() => WorkspaceViewSettings(); +} + +String _$workspaceViewSettingsHash() => + r'35836b74a1bbd2718e9a381d5623255ff507c63a'; + +/// Persistent navigation preferences, shared by the application surface. + +abstract class _$WorkspaceViewSettings + extends $AsyncNotifier { + FutureOr build(); + @$mustCallSuper + @override + WhenComplete runBuild() { + final ref = + this.ref + as $Ref< + AsyncValue, + WorkspaceViewSettingsData + >; + final element = + ref.element + as $ClassProviderElement< + AnyNotifier< + AsyncValue, + WorkspaceViewSettingsData + >, + AsyncValue, + Object?, + Object? + >; + return element.handleCreate(ref, build); + } +} + +/// Project preferences survive timeline switches and widget reconstruction. + +@ProviderFor(ProjectViewSettings) +final projectViewSettingsProvider = ProjectViewSettingsFamily._(); + +/// Project preferences survive timeline switches and widget reconstruction. +final class ProjectViewSettingsProvider + extends + $AsyncNotifierProvider { + /// Project preferences survive timeline switches and widget reconstruction. + ProjectViewSettingsProvider._({ + required ProjectViewSettingsFamily super.from, + required String super.argument, + }) : super( + retry: null, + name: r'projectViewSettingsProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$projectViewSettingsHash(); + + @override + String toString() { + return r'projectViewSettingsProvider' + '' + '($argument)'; + } + + @$internal + @override + ProjectViewSettings create() => ProjectViewSettings(); + + @override + bool operator ==(Object other) { + return other is ProjectViewSettingsProvider && other.argument == argument; + } + + @override + int get hashCode { + return argument.hashCode; + } +} + +String _$projectViewSettingsHash() => + r'c036088de9f39789b8604c48000a63a52517c966'; + +/// Project preferences survive timeline switches and widget reconstruction. + +final class ProjectViewSettingsFamily extends $Family + with + $ClassFamilyOverride< + ProjectViewSettings, + AsyncValue, + ProjectViewSettingsData, + FutureOr, + String + > { + ProjectViewSettingsFamily._() + : super( + retry: null, + name: r'projectViewSettingsProvider', + dependencies: null, + $allTransitiveDependencies: null, + isAutoDispose: false, + ); + + /// Project preferences survive timeline switches and widget reconstruction. + + ProjectViewSettingsProvider call(String projectId) => + ProjectViewSettingsProvider._(argument: projectId, from: this); + + @override + String toString() => r'projectViewSettingsProvider'; +} + +/// Project preferences survive timeline switches and widget reconstruction. + +abstract class _$ProjectViewSettings + extends $AsyncNotifier { + late final _$args = ref.$arg as String; + String get projectId => _$args; + + FutureOr build(String projectId); + @$mustCallSuper + @override + WhenComplete runBuild() { + final ref = + this.ref + as $Ref< + AsyncValue, + ProjectViewSettingsData + >; + final element = + ref.element + as $ClassProviderElement< + AnyNotifier< + AsyncValue, + ProjectViewSettingsData + >, + AsyncValue, + Object?, + Object? + >; + return element.handleCreate(ref, () => build(_$args)); + } +} diff --git a/lib/workspace/workspace_mode.dart b/lib/workspace/workspace_mode.dart new file mode 100644 index 0000000..4c49db8 --- /dev/null +++ b/lib/workspace/workspace_mode.dart @@ -0,0 +1,2 @@ +/// The user's workflow; independent of available window space. +enum WorkspaceMode { agent, cut } diff --git a/lib/workspace/workspace_navigation.dart b/lib/workspace/workspace_navigation.dart new file mode 100644 index 0000000..dedef06 --- /dev/null +++ b/lib/workspace/workspace_navigation.dart @@ -0,0 +1,143 @@ +import 'dart:async'; + +import '../diagnostics/app_diagnostics.dart'; + +import 'package:flutter/foundation.dart'; + +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:riverpod_annotation/riverpod_annotation.dart'; + +import '../features/projects/conversation_sidebar.dart'; +import 'project_state.dart'; +import 'projects.dart'; +import 'view_settings.dart'; + +part 'workspace_navigation.g.dart'; +part 'workspace_navigation.freezed.dart'; + +@freezed +abstract class WorkspaceNavigationState with _$WorkspaceNavigationState { + const factory WorkspaceNavigationState({ + @Default(false) bool ready, + @Default(false) bool switchingProject, + String? selectedProjectId, + }) = _WorkspaceNavigationState; +} + +@Riverpod(keepAlive: true) +class WorkspaceNavigation extends _$WorkspaceNavigation { + int _revision = 0; + Completer _changed = Completer(); + Completer _quiet = Completer(); + Timer? _debounce; + RecentProject? _queued; + + @override + WorkspaceNavigationState build() { + ref.onDispose(() { + _debounce?.cancel(); + if (!_changed.isCompleted) _changed.complete(); + }); + ref.listen( + projectsProvider.select((value) => value.value?.activeProject?.id), + (before, after) { + if (before != after && state.ready) { + unawaited( + ref + .read(workspaceViewSettingsProvider.notifier) + .save(activeProjectId: after) + .catchError((Object error, StackTrace stack) { + AppDiagnostics.failure( + 'settings', + 'saveWorkspaceSelection', + error, + stack, + ); + }), + ); + } + }, + ); + unawaited(Future.microtask(_restore)); + return const WorkspaceNavigationState(); + } + + Future _restore() async { + try { + final settings = await ref.read(workspaceViewSettingsProvider.future); + if (!ref.mounted) return; + final workspace = await ref.read(projectsProvider.future); + if (!ref.mounted) return; + final project = workspace.recent + .where( + (item) => + item.id == settings.activeProjectId && + item.availability.canOpen, + ) + .firstOrNull; + if (workspace.activeProject == null && project != null) { + await openProject(project); + } + if (!ref.mounted) return; + await ref.read(conversationSidebarProvider.future); + } catch (error, stack) { + AppDiagnostics.failure('project', 'restoreWorkspace', error, stack); + } finally { + if (ref.mounted) state = state.copyWith(ready: true); + } + } + + Future openProject(RecentProject project) async { + final workspace = ref.read(projectsProvider).value; + if (state.selectedProjectId == project.id || + (!state.switchingProject && + (workspace?.projectBusy == true || + workspace?.activeProject?.id == project.id))) { + return; + } + _revision++; + _changed.complete(); + _changed = Completer(); + _debounce?.cancel(); + _quiet = Completer(); + _debounce = Timer(const Duration(milliseconds: 100), _quiet.complete); + _queued = project; + state = state.copyWith(selectedProjectId: project.id); + if (state.switchingProject) return; + state = state.copyWith(switchingProject: true); + try { + while (ref.mounted && _queued != null) { + final revision = _revision; + await Future.any([_quiet.future, _changed.future]); + if (!ref.mounted) return; + if (revision != _revision) continue; + final target = _queued!; + _queued = null; + if (ref.read(projectsProvider).value?.activeProject?.id == target.id) { + continue; + } + final opened = await ref + .read(projectsProvider.notifier) + .open( + target.path, + expectedId: target.id, + isCurrent: () => ref.mounted && revision == _revision, + ); + if (!ref.mounted) return; + if (opened && _queued == null) { + await ref + .read(workspaceViewSettingsProvider.notifier) + .save(activeProjectId: target.id); + } + } + } finally { + if (ref.mounted) { + state = state.copyWith( + switchingProject: false, + selectedProjectId: null, + ); + } + } + } +} diff --git a/lib/workspace/workspace_navigation.freezed.dart b/lib/workspace/workspace_navigation.freezed.dart new file mode 100644 index 0000000..2a910aa --- /dev/null +++ b/lib/workspace/workspace_navigation.freezed.dart @@ -0,0 +1,412 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'workspace_navigation.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +T _$identity(T value) => value; + +/// @nodoc +mixin _$WorkspaceNavigationState implements DiagnosticableTreeMixin { + bool get ready; + bool get switchingProject; + String? get selectedProjectId; + + /// Create a copy of WorkspaceNavigationState + /// with the given fields replaced by the non-null parameter values. + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + $WorkspaceNavigationStateCopyWith get copyWith => + _$WorkspaceNavigationStateCopyWithImpl( + this as WorkspaceNavigationState, + _$identity, + ); + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + final _this = this as WorkspaceNavigationState; + properties + ..add(DiagnosticsProperty('type', 'WorkspaceNavigationState')) + ..add(DiagnosticsProperty('ready', _this.ready)) + ..add(DiagnosticsProperty('switchingProject', _this.switchingProject)) + ..add(DiagnosticsProperty('selectedProjectId', _this.selectedProjectId)); + } + + @override + bool operator ==(Object other) { + final _this = this as WorkspaceNavigationState; + return identical(this, other) || + (other.runtimeType == runtimeType && + other is WorkspaceNavigationState && + (identical(other.ready, _this.ready) || + other.ready == _this.ready) && + (identical(other.switchingProject, _this.switchingProject) || + other.switchingProject == _this.switchingProject) && + (identical(other.selectedProjectId, _this.selectedProjectId) || + other.selectedProjectId == _this.selectedProjectId)); + } + + @override + int get hashCode { + final _this = this as WorkspaceNavigationState; + return Object.hash( + runtimeType, + _this.ready, + _this.switchingProject, + _this.selectedProjectId, + ); + } + + @override + String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { + final _this = this as WorkspaceNavigationState; + return 'WorkspaceNavigationState(ready: ${_this.ready}, switchingProject: ${_this.switchingProject}, selectedProjectId: ${_this.selectedProjectId})'; + } +} + +/// @nodoc +abstract mixin class $WorkspaceNavigationStateCopyWith<$Res> { + factory $WorkspaceNavigationStateCopyWith( + WorkspaceNavigationState value, + $Res Function(WorkspaceNavigationState) _then, + ) = _$WorkspaceNavigationStateCopyWithImpl; + @useResult + $Res call({bool ready, bool switchingProject, String? selectedProjectId}); +} + +/// @nodoc +class _$WorkspaceNavigationStateCopyWithImpl<$Res> + implements $WorkspaceNavigationStateCopyWith<$Res> { + _$WorkspaceNavigationStateCopyWithImpl(this._self, this._then); + + final WorkspaceNavigationState _self; + final $Res Function(WorkspaceNavigationState) _then; + + /// Create a copy of WorkspaceNavigationState + /// with the given fields replaced by the non-null parameter values. + @pragma('vm:prefer-inline') + @override + $Res call({ + Object? ready = null, + Object? switchingProject = null, + Object? selectedProjectId = freezed, + }) { + return _then( + WorkspaceNavigationState( + ready: null == ready + ? _self.ready + : ready // ignore: cast_nullable_to_non_nullable + as bool, + switchingProject: null == switchingProject + ? _self.switchingProject + : switchingProject // ignore: cast_nullable_to_non_nullable + as bool, + selectedProjectId: freezed == selectedProjectId + ? _self.selectedProjectId + : selectedProjectId // ignore: cast_nullable_to_non_nullable + as String?, + ), + ); + } +} + +/// Adds pattern-matching-related methods to [WorkspaceNavigationState]. +extension WorkspaceNavigationStatePatterns on WorkspaceNavigationState { + /// A variant of `map` that fallback to returning `orElse`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeMap( + TResult Function(_WorkspaceNavigationState value)? $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _WorkspaceNavigationState() when $default != null: + return $default(_that); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// Callbacks receives the raw object, upcasted. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case final Subclass2 value: + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult map( + TResult Function(_WorkspaceNavigationState value) $default, + ) { + final _that = this; + switch (_that) { + case _WorkspaceNavigationState(): + return $default(_that); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `map` that fallback to returning `null`. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case final Subclass value: + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? mapOrNull( + TResult? Function(_WorkspaceNavigationState value)? $default, + ) { + final _that = this; + switch (_that) { + case _WorkspaceNavigationState() when $default != null: + return $default(_that); + case _: + return null; + } + } + + /// A variant of `when` that fallback to an `orElse` callback. + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return orElse(); + /// } + /// ``` + + @optionalTypeArgs + TResult maybeWhen( + TResult Function( + bool ready, + bool switchingProject, + String? selectedProjectId, + )? + $default, { + required TResult orElse(), + }) { + final _that = this; + switch (_that) { + case _WorkspaceNavigationState() when $default != null: + return $default( + _that.ready, + _that.switchingProject, + _that.selectedProjectId, + ); + case _: + return orElse(); + } + } + + /// A `switch`-like method, using callbacks. + /// + /// As opposed to `map`, this offers destructuring. + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case Subclass2(:final field2): + /// return ...; + /// } + /// ``` + + @optionalTypeArgs + TResult when( + TResult Function( + bool ready, + bool switchingProject, + String? selectedProjectId, + ) + $default, + ) { + final _that = this; + switch (_that) { + case _WorkspaceNavigationState(): + return $default( + _that.ready, + _that.switchingProject, + _that.selectedProjectId, + ); + case _: + throw StateError('Unexpected subclass'); + } + } + + /// A variant of `when` that fallback to returning `null` + /// + /// It is equivalent to doing: + /// ```dart + /// switch (sealedClass) { + /// case Subclass(:final field): + /// return ...; + /// case _: + /// return null; + /// } + /// ``` + + @optionalTypeArgs + TResult? whenOrNull( + TResult? Function( + bool ready, + bool switchingProject, + String? selectedProjectId, + )? + $default, + ) { + final _that = this; + switch (_that) { + case _WorkspaceNavigationState() when $default != null: + return $default( + _that.ready, + _that.switchingProject, + _that.selectedProjectId, + ); + case _: + return null; + } + } +} + +/// @nodoc + +class _WorkspaceNavigationState + with DiagnosticableTreeMixin + implements WorkspaceNavigationState { + const _WorkspaceNavigationState({ + this.ready = false, + this.switchingProject = false, + this.selectedProjectId, + }); + + @override + @JsonKey() + final bool ready; + @override + @JsonKey() + final bool switchingProject; + @override + final String? selectedProjectId; + + /// Create a copy of WorkspaceNavigationState + /// with the given fields replaced by the non-null parameter values. + @override + @JsonKey(includeFromJson: false, includeToJson: false) + @pragma('vm:prefer-inline') + _$WorkspaceNavigationStateCopyWith<_WorkspaceNavigationState> get copyWith => + __$WorkspaceNavigationStateCopyWithImpl<_WorkspaceNavigationState>( + this, + _$identity, + ); + + @override + void debugFillProperties(DiagnosticPropertiesBuilder properties) { + properties + ..add(DiagnosticsProperty('type', 'WorkspaceNavigationState')) + ..add(DiagnosticsProperty('ready', ready)) + ..add(DiagnosticsProperty('switchingProject', switchingProject)) + ..add(DiagnosticsProperty('selectedProjectId', selectedProjectId)); + } + + @override + bool operator ==(Object other) { + return identical(this, other) || + (other.runtimeType == runtimeType && + other is _WorkspaceNavigationState && + (identical(other.ready, ready) || other.ready == ready) && + (identical(other.switchingProject, switchingProject) || + other.switchingProject == switchingProject) && + (identical(other.selectedProjectId, selectedProjectId) || + other.selectedProjectId == selectedProjectId)); + } + + @override + int get hashCode { + return Object.hash(runtimeType, ready, switchingProject, selectedProjectId); + } + + @override + String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) { + return 'WorkspaceNavigationState(ready: $ready, switchingProject: $switchingProject, selectedProjectId: $selectedProjectId)'; + } +} + +/// @nodoc +abstract mixin class _$WorkspaceNavigationStateCopyWith<$Res> + implements $WorkspaceNavigationStateCopyWith<$Res> { + factory _$WorkspaceNavigationStateCopyWith( + _WorkspaceNavigationState value, + $Res Function(_WorkspaceNavigationState) _then, + ) = __$WorkspaceNavigationStateCopyWithImpl; + @override + @useResult + $Res call({bool ready, bool switchingProject, String? selectedProjectId}); +} + +/// @nodoc +class __$WorkspaceNavigationStateCopyWithImpl<$Res> + implements _$WorkspaceNavigationStateCopyWith<$Res> { + __$WorkspaceNavigationStateCopyWithImpl(this._self, this._then); + + final _WorkspaceNavigationState _self; + final $Res Function(_WorkspaceNavigationState) _then; + + /// Create a copy of WorkspaceNavigationState + /// with the given fields replaced by the non-null parameter values. + @override + @pragma('vm:prefer-inline') + $Res call({ + Object? ready = null, + Object? switchingProject = null, + Object? selectedProjectId = freezed, + }) { + return _then( + _WorkspaceNavigationState( + ready: null == ready + ? _self.ready + : ready // ignore: cast_nullable_to_non_nullable + as bool, + switchingProject: null == switchingProject + ? _self.switchingProject + : switchingProject // ignore: cast_nullable_to_non_nullable + as bool, + selectedProjectId: freezed == selectedProjectId + ? _self.selectedProjectId + : selectedProjectId // ignore: cast_nullable_to_non_nullable + as String?, + ), + ); + } +} diff --git a/lib/workspace/workspace_navigation.g.dart b/lib/workspace/workspace_navigation.g.dart new file mode 100644 index 0000000..49a791a --- /dev/null +++ b/lib/workspace/workspace_navigation.g.dart @@ -0,0 +1,65 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'workspace_navigation.dart'; + +// ************************************************************************** +// RiverpodGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// ignore_for_file: type=lint, type=warning + +@ProviderFor(WorkspaceNavigation) +final workspaceNavigationProvider = WorkspaceNavigationProvider._(); + +final class WorkspaceNavigationProvider + extends $NotifierProvider { + WorkspaceNavigationProvider._() + : super( + from: null, + argument: null, + retry: null, + name: r'workspaceNavigationProvider', + isAutoDispose: false, + dependencies: null, + $allTransitiveDependencies: null, + ); + + @override + String debugGetCreateSourceHash() => _$workspaceNavigationHash(); + + @$internal + @override + WorkspaceNavigation create() => WorkspaceNavigation(); + + /// {@macro riverpod.override_with_value} + Override overrideWithValue(WorkspaceNavigationState value) { + return $ProviderOverride( + origin: this, + providerOverride: $SyncValueProvider(value), + ); + } +} + +String _$workspaceNavigationHash() => + r'00811d2f43d15a47499422a2623fee80cb37dd09'; + +abstract class _$WorkspaceNavigation + extends $Notifier { + WorkspaceNavigationState build(); + @$mustCallSuper + @override + WhenComplete runBuild() { + final ref = + this.ref as $Ref; + final element = + ref.element + as $ClassProviderElement< + AnyNotifier, + WorkspaceNavigationState, + Object?, + Object? + >; + return element.handleCreate(ref, build); + } +} diff --git a/lib/workspace/workspace_session_scope.dart b/lib/workspace/workspace_session_scope.dart new file mode 100644 index 0000000..77e8ccd --- /dev/null +++ b/lib/workspace/workspace_session_scope.dart @@ -0,0 +1,40 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../features/assistant/chat_controller.dart'; +import '../features/projects/conversation_sidebar.dart'; +import 'project_state.dart'; +import 'timeline_provider.dart'; + +/// Retains active editing and conversation bindings above replaceable shells. +/// ProjectWorkspace and AgentConversationRegistry remain the resource owners. +class WorkspaceSessionScope extends ConsumerWidget { + const WorkspaceSessionScope({ + super.key, + required this.state, + required this.child, + }); + + final ProjectState state; + final Widget child; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final projectId = state.activeProject?.id; + final timelineId = state.timeline?.id; + if (projectId != null && timelineId != null) { + ref.watch(editorTimelineProvider(projectId, timelineId)); + } + final selection = ref.watch(conversationSelectionProvider(projectId)); + if (projectId != null) { + ref.watch( + chatControllerProvider( + projectId, + conversationId: selection.selectedId, + draftKey: selection.selectedId == null ? selection.draftKey : null, + ), + ); + } + return child; + } +} diff --git a/linux/.gitignore b/linux/.gitignore new file mode 100644 index 0000000..d3896c9 --- /dev/null +++ b/linux/.gitignore @@ -0,0 +1 @@ +flutter/ephemeral diff --git a/linux/CMakeLists.txt b/linux/CMakeLists.txt new file mode 100644 index 0000000..317ebf0 --- /dev/null +++ b/linux/CMakeLists.txt @@ -0,0 +1,128 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "cutdex") +# The unique GTK application identifier for this application. See: +# https://wiki.gnome.org/HowDoI/ChooseApplicationID +set(APPLICATION_ID "com.example.cutdex") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Load bundled libraries from the lib/ directory relative to the binary. +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Root filesystem for cross-building. +if(FLUTTER_TARGET_PLATFORM_SYSROOT) + set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) + set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) + set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) + set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) +endif() + +# Define build configuration options. +if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") +endif() + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_14) + target_compile_options(${TARGET} PRIVATE -Wall -Werror) + target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") + target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) + +# Only the install-generated bundle's copy of the executable will launch +# correctly, since the resources must in the right relative locations. To avoid +# people trying to run the unbundled copy, put it in a subdirectory instead of +# the default top-level location. +set_target_properties(${BINARY_NAME} + PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" +) + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# By default, "installing" just makes a relocatable bundle in the build +# directory. +set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +# Start with a clean build bundle directory every time. +install(CODE " + file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") + " COMPONENT Runtime) + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) + install(FILES "${bundled_library}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endforeach(bundled_library) + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") + install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() diff --git a/linux/flutter/CMakeLists.txt b/linux/flutter/CMakeLists.txt new file mode 100644 index 0000000..d5bd016 --- /dev/null +++ b/linux/flutter/CMakeLists.txt @@ -0,0 +1,88 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.10) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. + +# Serves the same purpose as list(TRANSFORM ... PREPEND ...), +# which isn't available in 3.10. +function(list_prepend LIST_NAME PREFIX) + set(NEW_LIST "") + foreach(element ${${LIST_NAME}}) + list(APPEND NEW_LIST "${PREFIX}${element}") + endforeach(element) + set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) +endfunction() + +# === Flutter Library === +# System-level dependencies. +find_package(PkgConfig REQUIRED) +pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) +pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) +pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) + +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "fl_basic_message_channel.h" + "fl_binary_codec.h" + "fl_binary_messenger.h" + "fl_dart_project.h" + "fl_engine.h" + "fl_json_message_codec.h" + "fl_json_method_codec.h" + "fl_message_codec.h" + "fl_method_call.h" + "fl_method_channel.h" + "fl_method_codec.h" + "fl_method_response.h" + "fl_plugin_registrar.h" + "fl_plugin_registry.h" + "fl_standard_message_codec.h" + "fl_standard_method_codec.h" + "fl_string_codec.h" + "fl_value.h" + "fl_view.h" + "flutter_linux.h" +) +list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") +target_link_libraries(flutter INTERFACE + PkgConfig::GTK + PkgConfig::GLIB + PkgConfig::GIO +) +add_dependencies(flutter flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CMAKE_CURRENT_BINARY_DIR}/_phony_ + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" + ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} +) diff --git a/linux/flutter/generated_plugin_registrant.cc b/linux/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..7db12e1 --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.cc @@ -0,0 +1,19 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include + +void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) filegate_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "FilegatePlugin"); + filegate_plugin_register_with_registrar(filegate_registrar); + g_autoptr(FlPluginRegistrar) flutter_secure_storage_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "FlutterSecureStorageLinuxPlugin"); + flutter_secure_storage_linux_plugin_register_with_registrar(flutter_secure_storage_linux_registrar); +} diff --git a/linux/flutter/generated_plugin_registrant.h b/linux/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..e0f0a47 --- /dev/null +++ b/linux/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void fl_register_plugins(FlPluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/linux/flutter/generated_plugins.cmake b/linux/flutter/generated_plugins.cmake new file mode 100644 index 0000000..2308539 --- /dev/null +++ b/linux/flutter/generated_plugins.cmake @@ -0,0 +1,26 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + filegate + flutter_secure_storage_linux +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST + jni +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/linux/runner/CMakeLists.txt b/linux/runner/CMakeLists.txt new file mode 100644 index 0000000..e97dabc --- /dev/null +++ b/linux/runner/CMakeLists.txt @@ -0,0 +1,26 @@ +cmake_minimum_required(VERSION 3.13) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} + "main.cc" + "my_application.cc" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the application ID. +add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") + +# Add dependency libraries. Add any application-specific dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter) +target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) + +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") diff --git a/linux/runner/main.cc b/linux/runner/main.cc new file mode 100644 index 0000000..e7c5c54 --- /dev/null +++ b/linux/runner/main.cc @@ -0,0 +1,6 @@ +#include "my_application.h" + +int main(int argc, char** argv) { + g_autoptr(MyApplication) app = my_application_new(); + return g_application_run(G_APPLICATION(app), argc, argv); +} diff --git a/linux/runner/my_application.cc b/linux/runner/my_application.cc new file mode 100644 index 0000000..4eb3354 --- /dev/null +++ b/linux/runner/my_application.cc @@ -0,0 +1,148 @@ +#include "my_application.h" + +#include +#ifdef GDK_WINDOWING_X11 +#include +#endif + +#include "flutter/generated_plugin_registrant.h" + +struct _MyApplication { + GtkApplication parent_instance; + char** dart_entrypoint_arguments; +}; + +G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) + +// Called when first Flutter frame received. +static void first_frame_cb(MyApplication* self, FlView* view) { + gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view))); +} + +// Implements GApplication::activate. +static void my_application_activate(GApplication* application) { + MyApplication* self = MY_APPLICATION(application); + GtkWindow* window = + GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); + + // Use a header bar when running in GNOME as this is the common style used + // by applications and is the setup most users will be using (e.g. Ubuntu + // desktop). + // If running on X and not using GNOME then just use a traditional title bar + // in case the window manager does more exotic layout, e.g. tiling. + // If running on Wayland assume the header bar will work (may need changing + // if future cases occur). + gboolean use_header_bar = TRUE; +#ifdef GDK_WINDOWING_X11 + GdkScreen* screen = gtk_window_get_screen(window); + if (GDK_IS_X11_SCREEN(screen)) { + const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); + if (g_strcmp0(wm_name, "GNOME Shell") != 0) { + use_header_bar = FALSE; + } + } +#endif + if (use_header_bar) { + GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); + gtk_widget_show(GTK_WIDGET(header_bar)); + gtk_header_bar_set_title(header_bar, "cutdex"); + gtk_header_bar_set_show_close_button(header_bar, TRUE); + gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); + } else { + gtk_window_set_title(window, "cutdex"); + } + + gtk_window_set_default_size(window, 1280, 720); + + g_autoptr(FlDartProject) project = fl_dart_project_new(); + fl_dart_project_set_dart_entrypoint_arguments( + project, self->dart_entrypoint_arguments); + + FlView* view = fl_view_new(project); + GdkRGBA background_color; + // Background defaults to black, override it here if necessary, e.g. #00000000 + // for transparent. + gdk_rgba_parse(&background_color, "#000000"); + fl_view_set_background_color(view, &background_color); + gtk_widget_show(GTK_WIDGET(view)); + gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); + + // Show the window when Flutter renders. + // Requires the view to be realized so we can start rendering. + g_signal_connect_swapped(view, "first-frame", G_CALLBACK(first_frame_cb), + self); + gtk_widget_realize(GTK_WIDGET(view)); + + fl_register_plugins(FL_PLUGIN_REGISTRY(view)); + + gtk_widget_grab_focus(GTK_WIDGET(view)); +} + +// Implements GApplication::local_command_line. +static gboolean my_application_local_command_line(GApplication* application, + gchar*** arguments, + int* exit_status) { + MyApplication* self = MY_APPLICATION(application); + // Strip out the first argument as it is the binary name. + self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); + + g_autoptr(GError) error = nullptr; + if (!g_application_register(application, nullptr, &error)) { + g_warning("Failed to register: %s", error->message); + *exit_status = 1; + return TRUE; + } + + g_application_activate(application); + *exit_status = 0; + + return TRUE; +} + +// Implements GApplication::startup. +static void my_application_startup(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application startup. + + G_APPLICATION_CLASS(my_application_parent_class)->startup(application); +} + +// Implements GApplication::shutdown. +static void my_application_shutdown(GApplication* application) { + // MyApplication* self = MY_APPLICATION(object); + + // Perform any actions required at application shutdown. + + G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); +} + +// Implements GObject::dispose. +static void my_application_dispose(GObject* object) { + MyApplication* self = MY_APPLICATION(object); + g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); + G_OBJECT_CLASS(my_application_parent_class)->dispose(object); +} + +static void my_application_class_init(MyApplicationClass* klass) { + G_APPLICATION_CLASS(klass)->activate = my_application_activate; + G_APPLICATION_CLASS(klass)->local_command_line = + my_application_local_command_line; + G_APPLICATION_CLASS(klass)->startup = my_application_startup; + G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; + G_OBJECT_CLASS(klass)->dispose = my_application_dispose; +} + +static void my_application_init(MyApplication* self) {} + +MyApplication* my_application_new() { + // Set the program name to the application ID, which helps various systems + // like GTK and desktop environments map this running application to its + // corresponding .desktop file. This ensures better integration by allowing + // the application to be recognized beyond its binary name. + g_set_prgname(APPLICATION_ID); + + return MY_APPLICATION(g_object_new(my_application_get_type(), + "application-id", APPLICATION_ID, "flags", + G_APPLICATION_NON_UNIQUE, nullptr)); +} diff --git a/linux/runner/my_application.h b/linux/runner/my_application.h new file mode 100644 index 0000000..db16367 --- /dev/null +++ b/linux/runner/my_application.h @@ -0,0 +1,21 @@ +#ifndef FLUTTER_MY_APPLICATION_H_ +#define FLUTTER_MY_APPLICATION_H_ + +#include + +G_DECLARE_FINAL_TYPE(MyApplication, + my_application, + MY, + APPLICATION, + GtkApplication) + +/** + * my_application_new: + * + * Creates a new Flutter-based application. + * + * Returns: a new #MyApplication. + */ +MyApplication* my_application_new(); + +#endif // FLUTTER_MY_APPLICATION_H_ diff --git a/macos/.gitignore b/macos/.gitignore new file mode 100644 index 0000000..746adbb --- /dev/null +++ b/macos/.gitignore @@ -0,0 +1,7 @@ +# Flutter-related +**/Flutter/ephemeral/ +**/Pods/ + +# Xcode-related +**/dgph +**/xcuserdata/ diff --git a/macos/Flutter/Flutter-Debug.xcconfig b/macos/Flutter/Flutter-Debug.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/macos/Flutter/Flutter-Debug.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/Flutter-Release.xcconfig b/macos/Flutter/Flutter-Release.xcconfig new file mode 100644 index 0000000..c2efd0b --- /dev/null +++ b/macos/Flutter/Flutter-Release.xcconfig @@ -0,0 +1 @@ +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift new file mode 100644 index 0000000..fb0306d --- /dev/null +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -0,0 +1,20 @@ +// +// Generated file. Do not edit. +// + +import FlutterMacOS +import Foundation + +import cutdex_native +import cutdex_runtime +import deskup +import filegate +import flutter_secure_storage_darwin + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + CutdexNativePlugin.register(with: registry.registrar(forPlugin: "CutdexNativePlugin")) + CutdexRuntimePlugin.register(with: registry.registrar(forPlugin: "CutdexRuntimePlugin")) + DeskupPlugin.register(with: registry.registrar(forPlugin: "DeskupPlugin")) + FilegatePlugin.register(with: registry.registrar(forPlugin: "FilegatePlugin")) + FlutterSecureStorageDarwinPlugin.register(with: registry.registrar(forPlugin: "FlutterSecureStorageDarwinPlugin")) +} diff --git a/macos/Runner.xcodeproj/project.pbxproj b/macos/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..b6b1a79 --- /dev/null +++ b/macos/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,1309 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 60; + objects = { + +/* Begin PBXAggregateTarget section */ + 33CC111A2044C6BA0003C045 /* Flutter Assemble */ = { + isa = PBXAggregateTarget; + buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */; + buildPhases = ( + 33CC111E2044C6BF0003C045 /* ShellScript */, + ); + dependencies = ( + ); + name = "Flutter Assemble"; + productName = FLX; + }; +/* End PBXAggregateTarget section */ + +/* Begin PBXBuildFile section */ + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; }; + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */ = {isa = PBXBuildFile; productRef = 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC10EC2044A3C60003C045; + remoteInfo = Runner; + }; + 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC111A2044C6BA0003C045; + remoteInfo = FLX; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 33CC110E2044A8840003C045 /* Bundle Framework */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Bundle Framework"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = ""; }; + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; + 33CC10ED2044A3C60003C045 /* cutdex.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = cutdex.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; + 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; + 33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = ""; }; + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = ""; }; + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = ""; }; + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = ""; }; + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = ""; }; + 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; + 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; + 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */ = {isa = PBXFileReference; lastKnownFileType = wrapper; name = FlutterGeneratedPluginSwiftPackage; path = ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 331C80D2294CF70F00263BE5 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EA2044A3C60003C045 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 78A318202AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 331C80D6294CF71000263BE5 /* RunnerTests */ = { + isa = PBXGroup; + children = ( + 331C80D7294CF71000263BE5 /* RunnerTests.swift */, + ); + path = RunnerTests; + sourceTree = ""; + }; + 33BA886A226E78AF003329D5 /* Configs */ = { + isa = PBXGroup; + children = ( + 33E5194F232828860026EE4D /* AppInfo.xcconfig */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */, + ); + path = Configs; + sourceTree = ""; + }; + 33CC10E42044A3C60003C045 = { + isa = PBXGroup; + children = ( + 33FAB671232836740065AC1E /* Runner */, + 33CEB47122A05771004F2AC0 /* Flutter */, + 331C80D6294CF71000263BE5 /* RunnerTests */, + 33CC10EE2044A3C60003C045 /* Products */, + ); + sourceTree = ""; + }; + 33CC10EE2044A3C60003C045 /* Products */ = { + isa = PBXGroup; + children = ( + 33CC10ED2044A3C60003C045 /* cutdex.app */, + 331C80D5294CF71000263BE5 /* RunnerTests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 33CC11242044D66E0003C045 /* Resources */ = { + isa = PBXGroup; + children = ( + 33CC10F22044A3C60003C045 /* Assets.xcassets */, + 33CC10F42044A3C60003C045 /* MainMenu.xib */, + 33CC10F72044A3C60003C045 /* Info.plist */, + ); + name = Resources; + path = ..; + sourceTree = ""; + }; + 33CEB47122A05771004F2AC0 /* Flutter */ = { + isa = PBXGroup; + children = ( + 78E0A7A72DC9AD7400C4905E /* FlutterGeneratedPluginSwiftPackage */, + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */, + ); + path = Flutter; + sourceTree = ""; + }; + 33FAB671232836740065AC1E /* Runner */ = { + isa = PBXGroup; + children = ( + 33CC10F02044A3C60003C045 /* AppDelegate.swift */, + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */, + 33E51913231747F40026EE4D /* DebugProfile.entitlements */, + 33E51914231749380026EE4D /* Release.entitlements */, + 33CC11242044D66E0003C045 /* Resources */, + 33BA886A226E78AF003329D5 /* Configs */, + ); + path = Runner; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 331C80D4294CF70F00263BE5 /* RunnerTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */; + buildPhases = ( + 331C80D1294CF70F00263BE5 /* Sources */, + 331C80D2294CF70F00263BE5 /* Frameworks */, + 331C80D3294CF70F00263BE5 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 331C80DA294CF71000263BE5 /* PBXTargetDependency */, + ); + name = RunnerTests; + productName = RunnerTests; + productReference = 331C80D5294CF71000263BE5 /* RunnerTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 33CC10EC2044A3C60003C045 /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 33CC10E92044A3C60003C045 /* Sources */, + 33CC10EA2044A3C60003C045 /* Frameworks */, + 33CC10EB2044A3C60003C045 /* Resources */, + 33CC110E2044A8840003C045 /* Bundle Framework */, + 3399D490228B24CF009A79C7 /* ShellScript */, + ); + buildRules = ( + ); + dependencies = ( + 33CC11202044C79F0003C045 /* PBXTargetDependency */, + ); + name = Runner; + packageProductDependencies = ( + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */, + ); + productName = Runner; + productReference = 33CC10ED2044A3C60003C045 /* cutdex.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 33CC10E52044A3C60003C045 /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastSwiftUpdateCheck = 0920; + LastUpgradeCheck = 1510; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 331C80D4294CF70F00263BE5 = { + CreatedOnToolsVersion = 14.0; + TestTargetID = 33CC10EC2044A3C60003C045; + }; + 33CC10EC2044A3C60003C045 = { + CreatedOnToolsVersion = 9.2; + LastSwiftMigration = 1100; + ProvisioningStyle = Automatic; + SystemCapabilities = { + com.apple.Sandbox = { + enabled = 1; + }; + }; + }; + 33CC111A2044C6BA0003C045 = { + CreatedOnToolsVersion = 9.2; + ProvisioningStyle = Manual; + }; + }; + }; + buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + "zh-Hans", + "zh-Hant", + ja, + ko, + fr, + de, + es, + pt, + it, + ru, + Base, + ); + mainGroup = 33CC10E42044A3C60003C045; + packageReferences = ( + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "FlutterGeneratedPluginSwiftPackage" */, + ); + productRefGroup = 33CC10EE2044A3C60003C045 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 33CC10EC2044A3C60003C045 /* Runner */, + 331C80D4294CF70F00263BE5 /* RunnerTests */, + 33CC111A2044C6BA0003C045 /* Flutter Assemble */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 331C80D3294CF70F00263BE5 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10EB2044A3C60003C045 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */, + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 3399D490228B24CF009A79C7 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$PROJECT_DIR/../tool/macos/check_macos_build_target.sh\" \"$TARGET_BUILD_DIR/$EXECUTABLE_PATH\" || exit $?\necho \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n"; + }; + 33CC111E2044C6BF0003C045 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + alwaysOutOfDate = 1; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + Flutter/ephemeral/FlutterInputs.xcfilelist, + ); + inputPaths = ( + Flutter/ephemeral/tripwire, + ); + outputFileListPaths = ( + Flutter/ephemeral/FlutterOutputs.xcfilelist, + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$PROJECT_DIR/../tool/macos/check_macos_build_target.sh\" \"$BUILT_PRODUCTS_DIR/cutdex.app/Contents/MacOS/cutdex\" || exit $?\n\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 331C80D1294CF70F00263BE5 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 33CC10E92044A3C60003C045 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */, + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */, + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 331C80DA294CF71000263BE5 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC10EC2044A3C60003C045 /* Runner */; + targetProxy = 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */; + }; + 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; + targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 33CC10F42044A3C60003C045 /* MainMenu.xib */ = { + isa = PBXVariantGroup; + children = ( + 33CC10F52044A3C60003C045 /* Base */, + ); + name = MainMenu.xib; + path = Runner; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 066A0094D8FE5DEC889645FE /* Debug-production */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + APP_DISPLAY_NAME = Cutdex; + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = app.cutdex.desktop; + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + }; + name = "Debug-production"; + }; + 09E22859CB3AB98D9642EB62 /* Debug-production */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = "Debug-production"; + }; + 14744F29EF089362C6761E61 /* Release-development */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 14.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = "Release-development"; + }; + 1544E1422F50BB1DB307F5DE /* Profile-development */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + APP_DISPLAY_NAME = "Cutdex Dev"; + ASSETCATALOG_COMPILER_APPICON_NAME = AppIconDevelopment; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = app.cutdex.desktop.dev; + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = "Profile-development"; + }; + 17644D40BEBC800DF4AC74C4 /* Debug-development */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + APP_DISPLAY_NAME = "Cutdex Dev"; + ASSETCATALOG_COMPILER_APPICON_NAME = AppIconDevelopment; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = app.cutdex.desktop.dev; + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + }; + name = "Debug-development"; + }; + 28BBF4DFE9CBE3745161ACF5 /* Release-development */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = "Release-development"; + }; + 331C80DB294CF71000263BE5 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.cutdex.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/cutdex.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/cutdex"; + }; + name = Debug; + }; + 331C80DC294CF71000263BE5 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.cutdex.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/cutdex.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/cutdex"; + }; + name = Release; + }; + 331C80DD294CF71000263BE5 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.cutdex.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/cutdex.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/cutdex"; + }; + name = Profile; + }; + 338D0CE9231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 14.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Profile; + }; + 338D0CEA231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Profile; + }; + 338D0CEB231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Profile; + }; + 33CC10F92044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 14.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 33CC10FA2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 14.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; + 33CC10FC2044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 33CC10FD2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + 33CC111C2044C6BA0003C045 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 33CC111D2044C6BA0003C045 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; + 365B48B78600C3C64AD2963E /* Profile-production */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + APP_DISPLAY_NAME = Cutdex; + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = app.cutdex.desktop; + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = "Profile-production"; + }; + 36C7F10D652492533EFCC3AA /* Profile-development */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.cutdex.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/cutdex.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/cutdex"; + }; + name = "Profile-development"; + }; + 3E585069A996F2669CCFD4BB /* Release-production */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.cutdex.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/cutdex.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/cutdex"; + }; + name = "Release-production"; + }; + 4B5F232079989B2F52BAE08C /* Debug-production */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 14.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = "Debug-production"; + }; + 4DFE2C5FE0165DA114FBF896 /* Release-development */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.cutdex.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/cutdex.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/cutdex"; + }; + name = "Release-development"; + }; + 7BCD3F02084E8461052C4A2E /* Release-production */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + APP_DISPLAY_NAME = Cutdex; + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = app.cutdex.desktop; + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = "Release-production"; + }; + 7E6BCF4205056BF930E45BA2 /* Debug-production */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.cutdex.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/cutdex.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/cutdex"; + }; + name = "Debug-production"; + }; + 83BD0EDB0D337C752BA9A235 /* Profile-development */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = "Profile-development"; + }; + 84AA7A06936167DFFA394AE4 /* Profile-production */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 14.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = "Profile-production"; + }; + 9A5C75D1122497A87CE1EC7C /* Profile-development */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 14.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = "Profile-development"; + }; + B3D237F3EE921CEC2443B950 /* Profile-production */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.cutdex.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/cutdex.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/cutdex"; + }; + name = "Profile-production"; + }; + D76B826DA4FBCF130CD4748F /* Debug-development */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CURRENT_PROJECT_VERSION = 1; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0.0; + PRODUCT_BUNDLE_IDENTIFIER = com.example.cutdex.RunnerTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/cutdex.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/cutdex"; + }; + name = "Debug-development"; + }; + DBE26909696A73C840C32476 /* Release-production */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = "Release-production"; + }; + E25BB9F6D4FD674DA69E473A /* Debug-development */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 14.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = "Debug-development"; + }; + E40F21327842A177FAA25F34 /* Release-production */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + COPY_PHASE_STRIP = NO; + DEAD_CODE_STRIPPING = YES; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = NO; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 14.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = "Release-production"; + }; + EB1D929D30B55AFD301F404F /* Debug-development */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = "Debug-development"; + }; + ED99D7C26A3D36DFB0FA1713 /* Profile-production */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = "Profile-production"; + }; + FAE71E1D9CA9085D07284398 /* Release-development */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + APP_DISPLAY_NAME = "Cutdex Dev"; + ASSETCATALOG_COMPILER_APPICON_NAME = AppIconDevelopment; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = app.cutdex.desktop.dev; + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = "Release-development"; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 331C80DB294CF71000263BE5 /* Debug */, + 331C80DC294CF71000263BE5 /* Release */, + 331C80DD294CF71000263BE5 /* Profile */, + D76B826DA4FBCF130CD4748F /* Debug-development */, + 7E6BCF4205056BF930E45BA2 /* Debug-production */, + 36C7F10D652492533EFCC3AA /* Profile-development */, + B3D237F3EE921CEC2443B950 /* Profile-production */, + 4DFE2C5FE0165DA114FBF896 /* Release-development */, + 3E585069A996F2669CCFD4BB /* Release-production */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10F92044A3C60003C045 /* Debug */, + 33CC10FA2044A3C60003C045 /* Release */, + 338D0CE9231458BD00FA5F75 /* Profile */, + E25BB9F6D4FD674DA69E473A /* Debug-development */, + 4B5F232079989B2F52BAE08C /* Debug-production */, + 9A5C75D1122497A87CE1EC7C /* Profile-development */, + 84AA7A06936167DFFA394AE4 /* Profile-production */, + 14744F29EF089362C6761E61 /* Release-development */, + E40F21327842A177FAA25F34 /* Release-production */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10FC2044A3C60003C045 /* Debug */, + 33CC10FD2044A3C60003C045 /* Release */, + 338D0CEA231458BD00FA5F75 /* Profile */, + 17644D40BEBC800DF4AC74C4 /* Debug-development */, + 066A0094D8FE5DEC889645FE /* Debug-production */, + 1544E1422F50BB1DB307F5DE /* Profile-development */, + 365B48B78600C3C64AD2963E /* Profile-production */, + FAE71E1D9CA9085D07284398 /* Release-development */, + 7BCD3F02084E8461052C4A2E /* Release-production */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC111C2044C6BA0003C045 /* Debug */, + 33CC111D2044C6BA0003C045 /* Release */, + 338D0CEB231458BD00FA5F75 /* Profile */, + EB1D929D30B55AFD301F404F /* Debug-development */, + 09E22859CB3AB98D9642EB62 /* Debug-production */, + 83BD0EDB0D337C752BA9A235 /* Profile-development */, + ED99D7C26A3D36DFB0FA1713 /* Profile-production */, + 28BBF4DFE9CBE3745161ACF5 /* Release-development */, + DBE26909696A73C840C32476 /* Release-production */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCLocalSwiftPackageReference section */ + 781AD8BC2B33823900A9FFBB /* XCLocalSwiftPackageReference "FlutterGeneratedPluginSwiftPackage" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = Flutter/ephemeral/Packages/FlutterGeneratedPluginSwiftPackage; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCRemoteSwiftPackageReference section */ +/* End XCRemoteSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 78A3181F2AECB46A00862997 /* FlutterGeneratedPluginSwiftPackage */ = { + isa = XCSwiftPackageProductDependency; + productName = FlutterGeneratedPluginSwiftPackage; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = 33CC10E52044A3C60003C045 /* Project object */; +} diff --git a/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 0000000..89a223c --- /dev/null +++ b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,14 @@ +{ + "pins" : [ + { + "identity" : "sparkle", + "kind" : "remoteSourceControl", + "location" : "https://github.com/sparkle-project/Sparkle", + "state" : { + "revision" : "eef1a539a373c1f1a320624b1130fc5de7b2e100", + "version" : "2.10.0" + } + } + ], + "version" : 2 +} diff --git a/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100644 index 0000000..ea289fd --- /dev/null +++ b/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macos/Runner.xcodeproj/xcshareddata/xcschemes/development.xcscheme b/macos/Runner.xcodeproj/xcshareddata/xcschemes/development.xcscheme new file mode 100644 index 0000000..69dfb6f --- /dev/null +++ b/macos/Runner.xcodeproj/xcshareddata/xcschemes/development.xcscheme @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macos/Runner.xcodeproj/xcshareddata/xcschemes/production.xcscheme b/macos/Runner.xcodeproj/xcshareddata/xcschemes/production.xcscheme new file mode 100644 index 0000000..b9a9572 --- /dev/null +++ b/macos/Runner.xcodeproj/xcshareddata/xcschemes/production.xcscheme @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macos/Runner.xcworkspace/contents.xcworkspacedata b/macos/Runner.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..1d526a1 --- /dev/null +++ b/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/macos/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved b/macos/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved new file mode 100644 index 0000000..89a223c --- /dev/null +++ b/macos/Runner.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -0,0 +1,14 @@ +{ + "pins" : [ + { + "identity" : "sparkle", + "kind" : "remoteSourceControl", + "location" : "https://github.com/sparkle-project/Sparkle", + "state" : { + "revision" : "eef1a539a373c1f1a320624b1130fc5de7b2e100", + "version" : "2.10.0" + } + } + ], + "version" : 2 +} diff --git a/macos/Runner/AppDelegate.swift b/macos/Runner/AppDelegate.swift new file mode 100644 index 0000000..8de9088 --- /dev/null +++ b/macos/Runner/AppDelegate.swift @@ -0,0 +1,55 @@ +import Cocoa +import FlutterMacOS + +@main +class AppDelegate: FlutterAppDelegate { + private var lifecycleChannel: FlutterMethodChannel? + private var flutterReady = false + private var preparingToQuit = false + + func configureLifecycle(messenger: FlutterBinaryMessenger) { + let channel = FlutterMethodChannel(name: "cutdex/lifecycle", binaryMessenger: messenger) + lifecycleChannel = channel + channel.setMethodCallHandler { [weak self] call, result in + if call.method == "ready" { + self?.flutterReady = true + result(nil) + } else { + result(FlutterMethodNotImplemented) + } + } + } + + // Sparkle's install/relaunch and ordinary Quit both pass through this gate. + // Never terminate on a failed save or a missing Flutter response. + override func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply { + guard flutterReady, let channel = lifecycleChannel else { return .terminateCancel } + guard !preparingToQuit else { return .terminateLater } + preparingToQuit = true + channel.invokeMethod("prepareToQuit", arguments: nil) { [weak self] response in + guard let self else { return } + self.preparingToQuit = false + let ready = response as? Bool == true + if !ready { + let alert = NSAlert() + let busy = (response as? FlutterError)?.code == "workspaceBusy" + let chinese = Bundle.main.preferredLocalizations.first?.hasPrefix("zh") == true + alert.messageText = chinese ? "暂时无法退出 Cutdex" : "Cutdex cannot quit yet" + alert.informativeText = busy + ? (chinese ? "请等待后台任务完成后重试。" : "Wait for background tasks to finish, then try again.") + : (chinese ? "项目未能安全保存,请重试。" : "The project could not be saved safely. Please try again.") + alert.runModal() + } + sender.reply(toApplicationShouldTerminate: ready) + } + return .terminateLater + } + + override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + return true + } + + override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { + return true + } +} diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..a2ec33f --- /dev/null +++ b/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,68 @@ +{ + "images" : [ + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_16.png", + "scale" : "1x" + }, + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "2x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "1x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_64.png", + "scale" : "2x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_128.png", + "scale" : "1x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "2x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "1x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "2x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "1x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_1024.png", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png new file mode 100644 index 0000000..bf75562 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png new file mode 100644 index 0000000..49a511e Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png new file mode 100644 index 0000000..2f50c6d Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png new file mode 100644 index 0000000..445d555 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png new file mode 100644 index 0000000..44a2138 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png new file mode 100644 index 0000000..7c5f4ee Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png new file mode 100644 index 0000000..0d8e3ae Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ diff --git a/macos/Runner/Assets.xcassets/AppIconDevelopment.appiconset/Contents.json b/macos/Runner/Assets.xcassets/AppIconDevelopment.appiconset/Contents.json new file mode 100644 index 0000000..a2ec33f --- /dev/null +++ b/macos/Runner/Assets.xcassets/AppIconDevelopment.appiconset/Contents.json @@ -0,0 +1,68 @@ +{ + "images" : [ + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_16.png", + "scale" : "1x" + }, + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "2x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "1x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_64.png", + "scale" : "2x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_128.png", + "scale" : "1x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "2x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "1x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "2x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "1x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_1024.png", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/macos/Runner/Assets.xcassets/AppIconDevelopment.appiconset/app_icon_1024.png b/macos/Runner/Assets.xcassets/AppIconDevelopment.appiconset/app_icon_1024.png new file mode 100644 index 0000000..ac1b9bf Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIconDevelopment.appiconset/app_icon_1024.png differ diff --git a/macos/Runner/Assets.xcassets/AppIconDevelopment.appiconset/app_icon_128.png b/macos/Runner/Assets.xcassets/AppIconDevelopment.appiconset/app_icon_128.png new file mode 100644 index 0000000..d8c913a Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIconDevelopment.appiconset/app_icon_128.png differ diff --git a/macos/Runner/Assets.xcassets/AppIconDevelopment.appiconset/app_icon_16.png b/macos/Runner/Assets.xcassets/AppIconDevelopment.appiconset/app_icon_16.png new file mode 100644 index 0000000..c26a02d Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIconDevelopment.appiconset/app_icon_16.png differ diff --git a/macos/Runner/Assets.xcassets/AppIconDevelopment.appiconset/app_icon_256.png b/macos/Runner/Assets.xcassets/AppIconDevelopment.appiconset/app_icon_256.png new file mode 100644 index 0000000..3578f95 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIconDevelopment.appiconset/app_icon_256.png differ diff --git a/macos/Runner/Assets.xcassets/AppIconDevelopment.appiconset/app_icon_32.png b/macos/Runner/Assets.xcassets/AppIconDevelopment.appiconset/app_icon_32.png new file mode 100644 index 0000000..38db8b8 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIconDevelopment.appiconset/app_icon_32.png differ diff --git a/macos/Runner/Assets.xcassets/AppIconDevelopment.appiconset/app_icon_512.png b/macos/Runner/Assets.xcassets/AppIconDevelopment.appiconset/app_icon_512.png new file mode 100644 index 0000000..23c1e9d Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIconDevelopment.appiconset/app_icon_512.png differ diff --git a/macos/Runner/Assets.xcassets/AppIconDevelopment.appiconset/app_icon_64.png b/macos/Runner/Assets.xcassets/AppIconDevelopment.appiconset/app_icon_64.png new file mode 100644 index 0000000..8092e60 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIconDevelopment.appiconset/app_icon_64.png differ diff --git a/macos/Runner/Base.lproj/MainMenu.xib b/macos/Runner/Base.lproj/MainMenu.xib new file mode 100644 index 0000000..80e867a --- /dev/null +++ b/macos/Runner/Base.lproj/MainMenu.xib @@ -0,0 +1,343 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macos/Runner/Configs/AppInfo.xcconfig b/macos/Runner/Configs/AppInfo.xcconfig new file mode 100644 index 0000000..29c1817 --- /dev/null +++ b/macos/Runner/Configs/AppInfo.xcconfig @@ -0,0 +1,20 @@ +// Application-level settings for the Runner target. +// +// This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the +// future. If not, the values below would default to using the project name when this becomes a +// 'flutter create' template. + +// The application's name. By default this is also the title of the Flutter window. +PRODUCT_NAME = cutdex +APP_DISPLAY_NAME = Cutdex + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = app.cutdex.desktop + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2026 Cutdex. All rights reserved. + +// Public builds use ad-hoc signing; personal signing settings stay local. +CODE_SIGN_STYLE = Manual +CODE_SIGN_IDENTITY = - +#include? "Signing.local.xcconfig" diff --git a/macos/Runner/Configs/Debug.xcconfig b/macos/Runner/Configs/Debug.xcconfig new file mode 100644 index 0000000..36b0fd9 --- /dev/null +++ b/macos/Runner/Configs/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Debug.xcconfig" +#include "Warnings.xcconfig" diff --git a/macos/Runner/Configs/Release.xcconfig b/macos/Runner/Configs/Release.xcconfig new file mode 100644 index 0000000..0cfec87 --- /dev/null +++ b/macos/Runner/Configs/Release.xcconfig @@ -0,0 +1,5 @@ +#include "../../Flutter/Flutter-Release.xcconfig" +#include "Warnings.xcconfig" + +// The bundled processing runtime is built and verified for Apple Silicon. +ARCHS = arm64 diff --git a/macos/Runner/Configs/Warnings.xcconfig b/macos/Runner/Configs/Warnings.xcconfig new file mode 100644 index 0000000..42bcbf4 --- /dev/null +++ b/macos/Runner/Configs/Warnings.xcconfig @@ -0,0 +1,13 @@ +WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings +GCC_WARN_UNDECLARED_SELECTOR = YES +CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES +CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE +CLANG_WARN__DUPLICATE_METHOD_MATCH = YES +CLANG_WARN_PRAGMA_PACK = YES +CLANG_WARN_STRICT_PROTOTYPES = YES +CLANG_WARN_COMMA = YES +GCC_WARN_STRICT_SELECTOR_MATCH = YES +CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES +CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES +GCC_WARN_SHADOW = YES +CLANG_WARN_UNREACHABLE_CODE = YES diff --git a/macos/Runner/DebugProfile.entitlements b/macos/Runner/DebugProfile.entitlements new file mode 100644 index 0000000..520d25f --- /dev/null +++ b/macos/Runner/DebugProfile.entitlements @@ -0,0 +1,14 @@ + + + + + com.apple.security.network.client + + com.apple.security.app-sandbox + + com.apple.security.cs.allow-jit + + com.apple.security.network.server + + + diff --git a/macos/Runner/Info.plist b/macos/Runner/Info.plist new file mode 100644 index 0000000..a3fb836 --- /dev/null +++ b/macos/Runner/Info.plist @@ -0,0 +1,54 @@ + + + + + CFBundleLocalizations + + en + zh-Hans + zh-Hant + ja + ko + fr + de + es + pt + it + ru + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIconFile + + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundleDisplayName + $(APP_DISPLAY_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSMinimumSystemVersion + $(MACOSX_DEPLOYMENT_TARGET) + SUEnableAutomaticChecks + + SUAllowsAutomaticUpdates + + SUAutomaticallyUpdate + + NSHumanReadableCopyright + $(PRODUCT_COPYRIGHT) + NSMainNibFile + MainMenu + NSPrincipalClass + NSApplication + + diff --git a/macos/Runner/MainFlutterWindow.swift b/macos/Runner/MainFlutterWindow.swift new file mode 100644 index 0000000..2097d61 --- /dev/null +++ b/macos/Runner/MainFlutterWindow.swift @@ -0,0 +1,16 @@ +import Cocoa +import FlutterMacOS +import cutdex_native + +class MainFlutterWindow: CutdexNativeWindow { + override func awakeFromNib() { + let controller = FlutterViewController() + let windowFrame = frame + contentViewController = controller + setFrame(windowFrame, display: true) + RegisterGeneratedPlugins(registry: controller) + (NSApp.delegate as? AppDelegate)?.configureLifecycle( + messenger: controller.engine.binaryMessenger) + super.awakeFromNib() + } +} diff --git a/macos/Runner/Release.entitlements b/macos/Runner/Release.entitlements new file mode 100644 index 0000000..6e20ac7 --- /dev/null +++ b/macos/Runner/Release.entitlements @@ -0,0 +1,12 @@ + + + + + com.apple.security.network.client + + com.apple.security.network.server + + com.apple.security.app-sandbox + + + diff --git a/macos/RunnerTests/RunnerTests.swift b/macos/RunnerTests/RunnerTests.swift new file mode 100644 index 0000000..b42b97e --- /dev/null +++ b/macos/RunnerTests/RunnerTests.swift @@ -0,0 +1,206 @@ +import Cocoa +import FlutterMacOS +import XCTest +@testable import cutdex + +class RunnerTests: XCTestCase { + + func testFileDropPolicyUsesFlutterRulesForEveryDestination() throws { + let timeline = try XCTUnwrap(NativeFileDropPolicy(arguments: [ + "allowedExtensions": ["mp4", "wav"], "maximumFileCount": 1, + ])) + XCTAssertTrue(timeline.accepts([URL(fileURLWithPath: "/source.WAV")])) + XCTAssertTrue(timeline.accepts([URL(fileURLWithPath: "/source.mp4")])) + XCTAssertFalse(timeline.accepts([URL(fileURLWithPath: "/source.png")])) + XCTAssertFalse(timeline.accepts([ + URL(fileURLWithPath: "/a.wav"), URL(fileURLWithPath: "/b.mp4"), + ])) + XCTAssertFalse(timeline.accepts([])) + let library = try XCTUnwrap(NativeFileDropPolicy(arguments: [ + "allowedExtensions": ["mp4", "wav", "png"], "maximumFileCount": NSNull(), + ])) + XCTAssertTrue(library.accepts([ + URL(fileURLWithPath: "/a.png"), URL(fileURLWithPath: "/b.wav"), + ])) + XCTAssertFalse(library.accepts([ + URL(fileURLWithPath: "/a.png"), URL(fileURLWithPath: "/notes.pdf"), + ])) + let attachments = try XCTUnwrap(NativeFileDropPolicy(arguments: [ + "allowedExtensions": NSNull(), "maximumFileCount": NSNull(), + ])) + XCTAssertTrue(attachments.accepts([ + URL(fileURLWithPath: "/notes.pdf"), URL(fileURLWithPath: "/README"), + ])) + XCTAssertFalse(attachments.accepts([try XCTUnwrap(URL(string: "https://example.com/a.wav"))])) + } + + func testFileDropPolicyRejectsMissingAndMalformedRules() throws { + XCTAssertNil(NativeFileDropPolicy(arguments: [:])) + for extensions: Any in ["wav", [1], [""]] { + XCTAssertNil(NativeFileDropPolicy(arguments: [ + "allowedExtensions": extensions, "maximumFileCount": 1, + ])) + } + for count: Any in [0, -1, 1.5, true, "1"] { + XCTAssertNil(NativeFileDropPolicy(arguments: [ + "allowedExtensions": ["wav"], "maximumFileCount": count, + ])) + } + let empty = try XCTUnwrap(NativeFileDropPolicy(arguments: [ + "allowedExtensions": [String](), "maximumFileCount": NSNull(), + ])) + XCTAssertFalse(empty.accepts([URL(fileURLWithPath: "/source.wav")])) + } + + @MainActor + func testHeaderControlGestureBlocksNativeMovementUntilRelease() throws { + let window = MainFlutterWindow(contentRect: NSRect(x: 100, y: 100, width: 1200, height: 800), + styleMask: [.titled, .closable, .resizable], backing: .buffered, defer: false) + window.isReleasedWhenClosed = false + defer { window.close() } + let target = HeaderEventView() + let controller = NSViewController() + controller.view = target + window.contentViewController = controller + window.setEditorChrome(true) + func send(_ type: NSEvent.EventType, x: CGFloat, top: CGFloat, clicks: Int = 1) throws { + let content = try XCTUnwrap(window.contentView) + let point = NSPoint(x: x, y: content.isFlipped ? top : content.bounds.height - top) + window.sendEvent(try XCTUnwrap(NSEvent.mouseEvent(with: type, + location: content.convert(point, to: nil), modifierFlags: [], timestamp: 0, + windowNumber: window.windowNumber, context: nil, eventNumber: 0, + clickCount: clicks, pressure: 1))) + } + for x in [CGFloat(104), 140, 176, 1136, 1172] { + target.movableDuringEvents = [] + try send(.leftMouseDown, x: x, top: 20, clicks: 2) + try send(.leftMouseDragged, x: 600, top: 100) + try send(.leftMouseUp, x: 600, top: 100) + XCTAssertEqual(target.movableDuringEvents, [false, false, false]) + // Integrated chrome permits movement only during explicit header drags. + XCTAssertFalse(window.isMovable) + } + try send(.leftMouseDown, x: 104, top: 20) + window.resignKey() + XCTAssertFalse(window.isMovable) + window.isMovable = false + try send(.leftMouseDown, x: 104, top: 20) + try send(.leftMouseUp, x: 104, top: 20) + XCTAssertFalse(window.isMovable) + } + + @MainActor + func testHomeRetainsIntegratedChromeAndRestoresNativeCloseAction() throws { + let window = CloseTrackingWindow(contentRect: NSRect(x: 100, y: 100, width: 1200, height: 800), + styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: .buffered, defer: false) + window.isReleasedWhenClosed = false + defer { window.close() } + let button = try XCTUnwrap(window.standardWindowButton(.closeButton)) + let originalTarget = button.target + let originalAction = button.action + window.setEditorChrome(true, closeReturnsHome: false) + XCTAssertTrue(button.target === originalTarget) + XCTAssertEqual(button.action, originalAction) + window.setEditorChrome(true, closeReturnsHome: true) + button.performClick(nil) + XCTAssertEqual(window.homeRequestCount, 1) + window.setEditorChrome(true, closeReturnsHome: false) + XCTAssertTrue(button.target === originalTarget) + XCTAssertEqual(button.action, originalAction) + XCTAssertTrue(window.editorChromeEnabled) + XCTAssertEqual(window.titleVisibility, .hidden) + let content = try XCTUnwrap(window.contentView) + let rect = content.convert(button.bounds, from: button) + XCTAssertEqual(rect.midX, 19, accuracy: 0.5) + let top = content.isFlipped ? rect.midY : content.bounds.height - rect.midY + XCTAssertEqual(top, 20, accuracy: 0.5) + } + + @MainActor + func testClosingIntegratedEditorRequestsFlutterHome() throws { + let window = CloseTrackingWindow(contentRect: NSRect(x: 100, y: 100, width: 1200, height: 800), + styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: .buffered, defer: false) + window.isReleasedWhenClosed = false + defer { window.close() } + + window.setEditorChrome(true) + let closeButton = try XCTUnwrap(window.standardWindowButton(.closeButton)) + closeButton.performClick(nil) + XCTAssertEqual(window.homeRequestCount, 1) + + window.performClose(nil) + XCTAssertEqual(window.homeRequestCount, 2) + XCTAssertTrue(window.editorChromeEnabled) + } + + @MainActor + func testEditorChromePreservesNativeButtonsAndRestoresWindowStyle() throws { + let window = MainFlutterWindow(contentRect: NSRect(x: 100, y: 100, width: 1200, height: 800), + styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: .buffered, defer: false) + window.isReleasedWhenClosed = false + defer { window.close() } + let originalFrame = window.frame + let originalMask = window.styleMask + let buttons = try [NSWindow.ButtonType.closeButton, .miniaturizeButton, .zoomButton].map { + try XCTUnwrap(window.standardWindowButton($0)) + } + window.setEditorChrome(true) + XCTAssertEqual(window.frame, originalFrame) + XCTAssertEqual(window.titleVisibility, .hidden) + XCTAssertTrue(window.titlebarAppearsTransparent) + XCTAssertTrue(window.styleMask.contains(.fullSizeContentView)) + XCTAssertTrue(window.standardWindowButton(.closeButton) === buttons[0]) + XCTAssertTrue(window.standardWindowButton(.miniaturizeButton) === buttons[1]) + XCTAssertTrue(window.standardWindowButton(.zoomButton) === buttons[2]) + for width in [1200.0, 640.0, 1000.0] { + window.setFrame(NSRect(x: 100, y: 100, width: width, height: 800), display: true) + window.positionEditorWindowButtons() + let content = try XCTUnwrap(window.contentView) + for (index, button) in buttons.enumerated() { + let rect = content.convert(button.bounds, from: button) + XCTAssertEqual(rect.midX, 19 + Double(index) * 20, accuracy: 0.5) + let top = content.isFlipped ? rect.midY : content.bounds.height - rect.midY + XCTAssertEqual(top, 20, accuracy: 0.5) + XCTAssertFalse(button.isHidden) + XCTAssertNotNil(button.action) + } + } + let resizedFrame = window.frame + window.setEditorChrome(false) + XCTAssertEqual(window.frame, resizedFrame) + XCTAssertEqual(window.styleMask, originalMask) + XCTAssertEqual(window.titleVisibility, .visible) + XCTAssertFalse(window.titlebarAppearsTransparent) + window.setEditorChrome(true) + window.setEditorChrome(true) + XCTAssertTrue(window.editorChromeEnabled) + } + + @MainActor + func testDropsRegisterOnlyExistingFileReferences() { + let controller = FlutterViewController() + for region in ["project", "timeline", "composer"] { + let target = NativeFileDropView(controller: controller, + channelName: "cutdex/\(region)_file_drop", hidesSourceImage: region == "timeline") + XCTAssertEqual(Set(target.registeredDraggedTypes), Set([.fileURL])) + } + } + +} + +@MainActor +private final class HeaderEventView: NSView { + var movableDuringEvents: [Bool] = [] + override func mouseDown(with event: NSEvent) { movableDuringEvents.append(window!.isMovable) } + override func mouseDragged(with event: NSEvent) { movableDuringEvents.append(window!.isMovable) } + override func mouseUp(with event: NSEvent) { movableDuringEvents.append(window!.isMovable) } +} + +@MainActor +private final class CloseTrackingWindow: MainFlutterWindow { + private(set) var homeRequestCount = 0 + + override func requestEditorHome() { + homeRequestCount += 1 + } +} diff --git a/packages/cutdex_native/.gitignore b/packages/cutdex_native/.gitignore new file mode 100644 index 0000000..b9d7f25 --- /dev/null +++ b/packages/cutdex_native/.gitignore @@ -0,0 +1,33 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. +/pubspec.lock +**/doc/api/ +.dart_tool/ +.flutter-plugins-dependencies +/build/ +/coverage/ diff --git a/packages/cutdex_native/.metadata b/packages/cutdex_native/.metadata new file mode 100644 index 0000000..42e3ee4 --- /dev/null +++ b/packages/cutdex_native/.metadata @@ -0,0 +1,39 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "6a19cca56475dbfba1478ee68d7bd0c2ef891da1" + channel: "stable" + +project_type: plugin + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1 + base_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1 + - platform: android + create_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1 + base_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1 + - platform: ios + create_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1 + base_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1 + - platform: macos + create_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1 + base_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1 + - platform: windows + create_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1 + base_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/packages/cutdex_native/README.md b/packages/cutdex_native/README.md new file mode 100644 index 0000000..d9a9197 --- /dev/null +++ b/packages/cutdex_native/README.md @@ -0,0 +1,65 @@ +# cutdex_native + +Cutdex workspace 内部 Flutter 原生插件,暂不发布。 + +| 能力 | macOS | Windows | +| --- | --- | --- | +| 窗口标题栏、拖动区域与关闭请求拦截 | 支持 | 支持 | +| 本地文件拖放区域 | 支持 | 支持 | +| 原生上下文菜单 | 支持 | 由 UI 包回退为 Flutter 菜单 | +| 原生窗口全屏会话 | 支持 | 未提供 | + +Android、iOS 注册设备信息查询;窗口、拖放、菜单与全屏能力仍由对应桌面平台提供。 + +## 设备信息 + +`NativeDeviceInfo.read()` 在 Android 返回最大显示区域的最短边(逻辑像素),在 iOS 返回 `NativeInterfaceIdiom`。无法查询时返回 `null`。插件不使用当前应用窗口大小,也不决定手机、平板或桌面布局;分类阈值、回退规则与状态装配由应用维护。 + +## 窗口 + +Dart 使用 `WindowChromeSession`、`HeaderControlRegion` 与 `WindowHeaderLayout`。关闭请求通过回调交给应用处理,插件不决定项目保存、路由、退出行为或应用最小窗口尺寸。坐标上报统一使用 `NativeBoundsReporter`,按绘制变换计算窗口逻辑坐标中的外接矩形。 + +macOS 宿主窗口继承 `CutdexNativeWindow`,导入 `cutdex_native` 后按 Flutter 常规流程注册插件。该窗口类负责 AppKit 响应链与标题栏手势,宿主只负责创建 Flutter 控制器和应用生命周期接线。Windows 由插件注册自动接入。 + +## 文件拖放 + +`NativeFileDropRegion` 接收稳定的 `regionId`、`NativeDropConfiguration`、启用状态与回调,回调中的文件是原始路径列表。扩展名白名单与数量上限由调用方提供。 + +两端均拒绝目录和不存在的文件,并在落下时重新检查文件引用。 + +`NativeDropConfiguration` 拷贝并规范化白名单,按值比较;输入列表的后续修改不会改变规则。无约束配置使用 `NativeDropConfiguration.unrestricted`。标题栏命中区域与拖放区域随 `TickerMode` 停用和恢复;隐藏页面拒绝迟到的拖放事件。 + +需要拖动位置和自定义异步准备流程时,使用 `NativeFileDropConnection`。其事件包含阶段、会话编号、区域内坐标和路径;调用方在文件使用完成后调用 `release`。macOS 的安全作用域权限持续到释放,销毁区域不会提前释放正在处理的拖放会话。 + +同一 `regionId` 的替换连接取得事件所有权,旧连接不能清除新区域或修改其选项。连接销毁后不能再次绑定,但仍可释放未完成文件操作的权限。区域标识用于重复使用同一目的地,不应每帧生成新标识。macOS 拖动源图像是否隐藏由 `hidesSourceImage` 控制。 + +插件不导入媒体,不识别项目、时间线或聊天,也不创建临时素材副本。 + +## 菜单与全屏 + +`NativeContextMenu.show` 接收 `NativeMenuEntry` 和位置,返回选中的操作编号;应用或 UI 包负责执行操作。`NativeFullscreenSession` 接收退出回调,按顺序处理窗口全屏请求。使用 `dispose(exitFullscreen: true)` 在未被替换时恢复窗口;恢复会等待正在进行的转换完成。预览内容和布局由应用管理。 + +在应用根目录执行 `flutter pub get`;在本包目录执行 `flutter test`。真实窗口与系统拖放还需在对应桌面平台验证。 + +## 原生回归 + +以下命令在应用根目录执行,先退出占用同一构建目录的应用。 + +macOS 标题栏手势使用真实 AppKit 响应链,文件引用策略使用临时文件与目录: + +```sh +flutter build macos --debug --flavor development +bash packages/cutdex_native/tool/macos/test_header_control_gestures.sh +bash packages/cutdex_native/tool/macos/test_file_drop_policy.sh +``` + +Windows 标题栏回归验证真实 HWND、命中区域、最大化、DPI 与标题栏恢复;先准备 Flutter C++ wrapper: + +```sh +flutter build windows --debug --flavor development +cmake -S packages/cutdex_native/tool/windows/window_chrome_tests -B build/window_chrome_tests -A x64 +cmake --build build/window_chrome_tests --config Release +ctest --test-dir build/window_chrome_tests -C Release --output-on-failure +``` + +原生回归不替代 Finder/Explorer 的真实文件拖放验收。 diff --git a/packages/cutdex_native/analysis_options.yaml b/packages/cutdex_native/analysis_options.yaml new file mode 100644 index 0000000..930a325 --- /dev/null +++ b/packages/cutdex_native/analysis_options.yaml @@ -0,0 +1,12 @@ +include: package:flutter_lints/flutter.yaml +analyzer: + exclude: + - build/** + - windows/** + - macos/** + - android/** + - ios/** + language: + strict-casts: true + strict-inference: true + strict-raw-types: true diff --git a/packages/cutdex_native/android/.gitignore b/packages/cutdex_native/android/.gitignore new file mode 100644 index 0000000..161bdcd --- /dev/null +++ b/packages/cutdex_native/android/.gitignore @@ -0,0 +1,9 @@ +*.iml +.gradle +/local.properties +/.idea/workspace.xml +/.idea/libraries +.DS_Store +/build +/captures +.cxx diff --git a/packages/cutdex_native/android/build.gradle.kts b/packages/cutdex_native/android/build.gradle.kts new file mode 100644 index 0000000..d6a2fed --- /dev/null +++ b/packages/cutdex_native/android/build.gradle.kts @@ -0,0 +1,53 @@ +group = "dev.cutdex.cutdex_native" +version = "0.1.0" + +buildscript { + val kotlinVersion = "2.4.0" + repositories { + google() + mavenCentral() + } + + dependencies { + classpath("com.android.tools.build:gradle:9.1.0") + classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion") + } +} + +allprojects { + repositories { + google() + mavenCentral() + } +} + +plugins { + id("com.android.library") +} + +android { + namespace = "dev.cutdex.cutdex_native" + + compileSdk = 36 + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + sourceSets { + getByName("main") { + java.srcDirs("src/main/kotlin") + } + } + + defaultConfig { + minSdk = 24 + } +} + +kotlin { + compilerOptions { + jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17 + } +} diff --git a/packages/cutdex_native/android/settings.gradle.kts b/packages/cutdex_native/android/settings.gradle.kts new file mode 100644 index 0000000..12c500b --- /dev/null +++ b/packages/cutdex_native/android/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "cutdex_native" diff --git a/packages/cutdex_native/android/src/main/AndroidManifest.xml b/packages/cutdex_native/android/src/main/AndroidManifest.xml new file mode 100644 index 0000000..94cbbcf --- /dev/null +++ b/packages/cutdex_native/android/src/main/AndroidManifest.xml @@ -0,0 +1 @@ + diff --git a/packages/cutdex_native/android/src/main/kotlin/dev/cutdex/cutdex_native/CutdexNativePlugin.kt b/packages/cutdex_native/android/src/main/kotlin/dev/cutdex/cutdex_native/CutdexNativePlugin.kt new file mode 100644 index 0000000..3d795cf --- /dev/null +++ b/packages/cutdex_native/android/src/main/kotlin/dev/cutdex/cutdex_native/CutdexNativePlugin.kt @@ -0,0 +1,84 @@ +package dev.cutdex.cutdex_native + +import android.app.Activity +import android.content.Context +import android.os.Build +import android.util.DisplayMetrics +import io.flutter.embedding.engine.plugins.FlutterPlugin +import io.flutter.embedding.engine.plugins.activity.ActivityAware +import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding +import io.flutter.plugin.common.MethodCall +import io.flutter.plugin.common.MethodChannel + +class CutdexNativePlugin : FlutterPlugin, ActivityAware, MethodChannel.MethodCallHandler { + private var channel: MethodChannel? = null + private var activity: Activity? = null + private var context: Context? = null + + override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) { + context = binding.applicationContext + channel = MethodChannel(binding.binaryMessenger, "cutdex_native/device_info").also { + it.setMethodCallHandler(this) + } + } + + override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) { + if (call.method == "getApplicationInfo") { + val host = context ?: return result.error("unavailable", "No application context.", null) + try { + @Suppress("DEPRECATION") + val info = host.packageManager.getPackageInfo(host.packageName, 0) + @Suppress("DEPRECATION") + val build = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) info.longVersionCode else info.versionCode.toLong() + result.success(mapOf("appVersion" to (info.versionName ?: "unknown"), "appBuild" to build.toString())) + } catch (error: Exception) { + result.error("unavailable", "Application metadata unavailable.", null) + } + return + } + if (call.method != "getDeviceInfo") { + result.notImplemented() + return + } + val host = activity + if (host == null) { + result.error("unavailable", "No activity is attached.", null) + return + } + // Maximum bounds do not shrink with the app's split-screen window. + val shortestSideDp = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { + val bounds = host.windowManager.maximumWindowMetrics.bounds + minOf(bounds.width(), bounds.height()) / host.resources.displayMetrics.density + } else { + @Suppress("DEPRECATION") + val metrics = DisplayMetrics().also { + host.windowManager.defaultDisplay.getRealMetrics(it) + } + minOf(metrics.widthPixels, metrics.heightPixels) / metrics.density + } + result.success(mapOf("displayShortestSideDp" to shortestSideDp.toDouble())) + } + + override fun onAttachedToActivity(binding: ActivityPluginBinding) { + activity = binding.activity + } + + override fun onDetachedFromActivityForConfigChanges() { + activity = null + } + + override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) { + activity = binding.activity + } + + override fun onDetachedFromActivity() { + activity = null + } + + override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) { + channel?.setMethodCallHandler(null) + channel = null + activity = null + context = null + } +} diff --git a/packages/cutdex_native/ios/.gitignore b/packages/cutdex_native/ios/.gitignore new file mode 100644 index 0000000..034771f --- /dev/null +++ b/packages/cutdex_native/ios/.gitignore @@ -0,0 +1,38 @@ +.idea/ +.vagrant/ +.sconsign.dblite +.svn/ + +.DS_Store +*.swp +profile + +DerivedData/ +build/ +GeneratedPluginRegistrant.h +GeneratedPluginRegistrant.m + +.generated/ + +*.pbxuser +*.mode1v3 +*.mode2v3 +*.perspectivev3 + +!default.pbxuser +!default.mode1v3 +!default.mode2v3 +!default.perspectivev3 + +xcuserdata + +*.moved-aside + +*.pyc +*sync/ +Icon? +.tags* + +/Flutter/Generated.xcconfig +/Flutter/ephemeral/ +/Flutter/flutter_export_environment.sh diff --git a/packages/cutdex_native/ios/cutdex_native.podspec b/packages/cutdex_native/ios/cutdex_native.podspec new file mode 100644 index 0000000..ef0a73d --- /dev/null +++ b/packages/cutdex_native/ios/cutdex_native.podspec @@ -0,0 +1,15 @@ +Pod::Spec.new do |s| + s.name = 'cutdex_native' + s.version = '0.1.0' + s.summary = 'Cutdex native device information.' + s.description = 'Native device facts for application layout policy.' + s.homepage = 'https://github.com/lingjhf/cutdex' + s.license = { :type => 'MIT', :file => '../../../LICENSE' } + s.authors = 'Cutdex contributors' + s.source = { :path => '.' } + s.source_files = 'cutdex_native/Sources/cutdex_native/**/*.swift' + s.dependency 'Flutter' + s.platform = :ios, '15.0' + s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' } + s.swift_version = '5.0' +end diff --git a/packages/cutdex_native/ios/cutdex_native/Package.swift b/packages/cutdex_native/ios/cutdex_native/Package.swift new file mode 100644 index 0000000..f5ab76f --- /dev/null +++ b/packages/cutdex_native/ios/cutdex_native/Package.swift @@ -0,0 +1,15 @@ +// swift-tools-version: 5.9 +import PackageDescription + +let package = Package( + name: "cutdex_native", + platforms: [.iOS("15.0")], + products: [.library(name: "cutdex-native", targets: ["cutdex_native"])], + dependencies: [.package(name: "FlutterFramework", path: "../FlutterFramework")], + targets: [ + .target( + name: "cutdex_native", + dependencies: [.product(name: "FlutterFramework", package: "FlutterFramework")] + ) + ] +) diff --git a/packages/cutdex_native/ios/cutdex_native/Sources/cutdex_native/CutdexNativePlugin.swift b/packages/cutdex_native/ios/cutdex_native/Sources/cutdex_native/CutdexNativePlugin.swift new file mode 100644 index 0000000..d85b3cd --- /dev/null +++ b/packages/cutdex_native/ios/cutdex_native/Sources/cutdex_native/CutdexNativePlugin.swift @@ -0,0 +1,31 @@ +import Flutter +import UIKit + +public class CutdexNativePlugin: NSObject, FlutterPlugin { + public static func register(with registrar: FlutterPluginRegistrar) { + let channel = FlutterMethodChannel( + name: "cutdex_native/device_info", + binaryMessenger: registrar.messenger() + ) + registrar.addMethodCallDelegate(CutdexNativePlugin(), channel: channel) + } + + public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { + if call.method == "getApplicationInfo" { + result(["appVersion": Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "unknown", + "appBuild": Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "unknown"]) + return + } + guard call.method == "getDeviceInfo" else { + result(FlutterMethodNotImplemented) + return + } + let idiom: String + switch UIDevice.current.userInterfaceIdiom { + case .pad: idiom = "pad" + case .mac: idiom = "mac" + default: idiom = "phone" + } + result(["interfaceIdiom": idiom]) + } +} diff --git a/packages/cutdex_native/lib/cutdex_native.dart b/packages/cutdex_native/lib/cutdex_native.dart new file mode 100644 index 0000000..f0d0198 --- /dev/null +++ b/packages/cutdex_native/lib/cutdex_native.dart @@ -0,0 +1,9 @@ +export 'src/bounds_reporter.dart'; +export 'src/header_control_region.dart'; +export 'src/window_chrome_session.dart'; +export 'src/window_header_layout.dart'; +export 'src/fullscreen.dart'; +export 'src/file_drop.dart'; +export 'src/file_drop_region.dart'; +export 'src/context_menu.dart'; +export 'src/device_info.dart'; diff --git a/packages/cutdex_native/lib/src/bounds_reporter.dart b/packages/cutdex_native/lib/src/bounds_reporter.dart new file mode 100644 index 0000000..a10c81b --- /dev/null +++ b/packages/cutdex_native/lib/src/bounds_reporter.dart @@ -0,0 +1,63 @@ +import 'package:flutter/rendering.dart'; +import 'package:flutter/widgets.dart'; + +/// Reports laid-out window coordinates after layout and movement. +class NativeBoundsReporter extends SingleChildRenderObjectWidget { + const NativeBoundsReporter({ + super.key, + required this.onBounds, + required super.child, + }); + final ValueChanged onBounds; + @override + RenderObject createRenderObject(BuildContext context) => + _RenderBoundsReporter(onBounds); + @override + void updateRenderObject( + BuildContext context, + covariant RenderObject renderObject, + ) { + (renderObject as _RenderBoundsReporter).updateCallback(onBounds); + } +} + +class _RenderBoundsReporter extends RenderProxyBox { + _RenderBoundsReporter(this.onBounds); + ValueChanged onBounds; + void updateCallback(ValueChanged callback) { + onBounds = callback; + _lastBounds = null; + _scheduleReport(); + } + + bool _scheduled = false; + Rect? _lastBounds; + void _scheduleReport() { + if (_scheduled || !attached) return; + _scheduled = true; + WidgetsBinding.instance.addPostFrameCallback((_) { + _scheduled = false; + if (!attached) return; + if (hasSize) { + final bounds = MatrixUtils.transformRect( + getTransformTo(null), + Offset.zero & size, + ); + if (bounds != _lastBounds) { + _lastBounds = bounds; + onBounds(bounds); + } + } + // Ancestors can move retained layers without laying out or repainting + // this box. Observe the next frame without requesting an idle frame. + _scheduleReport(); + }); + } + + @override + void attach(PipelineOwner owner) { + super.attach(owner); + _lastBounds = null; + _scheduleReport(); + } +} diff --git a/packages/cutdex_native/lib/src/context_menu.dart b/packages/cutdex_native/lib/src/context_menu.dart new file mode 100644 index 0000000..4646e88 --- /dev/null +++ b/packages/cutdex_native/lib/src/context_menu.dart @@ -0,0 +1,58 @@ +import 'package:flutter/services.dart'; + +class NativeMenuEntry { + const NativeMenuEntry({ + required String this.label, + this.id, + this.enabled = true, + this.selected = false, + this.children, + }) : separator = false; + + const NativeMenuEntry.separator() + : separator = true, + label = null, + id = null, + enabled = false, + selected = false, + children = null; + + final String? label; + final int? id; + final bool separator; + final bool enabled; + final bool selected; + final List? children; + + Map _encode() => separator + ? {'separator': true} + : { + 'label': label, + if (id != null) 'id': id, + 'enabled': enabled, + 'selected': selected, + if (children != null) + 'children': [for (final child in children!) child._encode()], + }; +} + +class NativeMenuUnavailableException implements Exception { + const NativeMenuUnavailableException(); +} + +abstract final class NativeContextMenu { + static Future show(List items, Offset position) async { + try { + return await const MethodChannel('cutdex_native/context_menu') + .invokeMethod('show', { + 'x': position.dx, + 'y': position.dy, + 'items': [for (final item in items) item._encode()], + }); + } on MissingPluginException { + throw const NativeMenuUnavailableException(); + } on PlatformException { + throw const NativeMenuUnavailableException(); + } + } +} diff --git a/packages/cutdex_native/lib/src/device_info.dart b/packages/cutdex_native/lib/src/device_info.dart new file mode 100644 index 0000000..1928545 --- /dev/null +++ b/packages/cutdex_native/lib/src/device_info.dart @@ -0,0 +1,55 @@ +import 'package:flutter/services.dart'; + +/// The interface idiom reported by iOS. +enum NativeInterfaceIdiom { phone, pad, mac } + +/// Device facts used by the caller to select its layout policy. +final class NativeDeviceInfo { + const NativeDeviceInfo({this.interfaceIdiom, this.displayShortestSideDp}); + + /// The iOS interface idiom, independent of the current window size. + final NativeInterfaceIdiom? interfaceIdiom; + + /// The shortest side of Android's maximum display bounds in logical pixels. + final double? displayShortestSideDp; + + static const _channel = MethodChannel('cutdex_native/device_info'); + + /// The installed application's version and build, supplied by the host. + static Future> readApplicationInfo() async { + final result = await _channel.invokeMapMethod( + 'getApplicationInfo', + ); + return Map.unmodifiable(result ?? const {}); + } + + /// Reads device facts on Android and iOS. + /// + /// Returns `null` when the host cannot provide usable information. + /// The caller decides how to classify the device and how to fall back. + static Future read() async { + try { + final result = await _channel.invokeMethod('getDeviceInfo'); + if (result is! Map) return null; + final idiom = switch (result['interfaceIdiom']) { + 'phone' => NativeInterfaceIdiom.phone, + 'pad' => NativeInterfaceIdiom.pad, + 'mac' => NativeInterfaceIdiom.mac, + _ => null, + }; + final value = result['displayShortestSideDp']; + final shortestSide = value is num && value.isFinite && value > 0 + ? value.toDouble() + : null; + if (idiom == null && shortestSide == null) return null; + return NativeDeviceInfo( + interfaceIdiom: idiom, + displayShortestSideDp: shortestSide, + ); + } on MissingPluginException { + return null; + } on PlatformException { + return null; + } + } +} diff --git a/packages/cutdex_native/lib/src/file_drop.dart b/packages/cutdex_native/lib/src/file_drop.dart new file mode 100644 index 0000000..b1f5b0f --- /dev/null +++ b/packages/cutdex_native/lib/src/file_drop.dart @@ -0,0 +1,178 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:path/path.dart' as p; + +import 'native_channel_binding.dart'; + +class NativeDropConfiguration { + NativeDropConfiguration({ + Iterable? allowedExtensions, + this.maximumFileCount, + }) : allowedExtensions = allowedExtensions == null + ? null + : List.unmodifiable( + allowedExtensions + .map((extension) => extension.toLowerCase()) + .toSet() + .toList() + ..sort(), + ) { + if (maximumFileCount != null && maximumFileCount! <= 0) { + throw ArgumentError.value( + maximumFileCount, + 'maximumFileCount', + 'Must be positive', + ); + } + if (this.allowedExtensions?.any((extension) => extension.isEmpty) == true) { + throw ArgumentError.value( + allowedExtensions, + 'allowedExtensions', + 'Extensions must not be empty', + ); + } + } + + const NativeDropConfiguration._unrestricted() + : allowedExtensions = null, + maximumFileCount = null; + static const unrestricted = NativeDropConfiguration._unrestricted(); + + final List? allowedExtensions; + final int? maximumFileCount; + + @override + bool operator ==(Object other) => + other is NativeDropConfiguration && + maximumFileCount == other.maximumFileCount && + listEquals(allowedExtensions, other.allowedExtensions); + @override + int get hashCode => Object.hash( + maximumFileCount, + allowedExtensions == null ? null : Object.hashAll(allowedExtensions!), + ); + + bool accepts(List paths) => + paths.isNotEmpty && + (maximumFileCount == null || paths.length <= maximumFileCount!) && + paths.every((path) { + if (path.isEmpty) return false; + final extension = p.extension(path).toLowerCase().replaceFirst('.', ''); + return allowedExtensions == null || + allowedExtensions!.contains(extension); + }); + + Map regionArguments(Rect bounds) => { + 'x': bounds.left, + 'y': bounds.top, + 'width': bounds.width, + 'height': bounds.height, + 'allowedExtensions': allowedExtensions, + 'maximumFileCount': maximumFileCount, + }; +} + +enum NativeFileDropPhase { enter, move, exit, drop } + +class NativeFileDropEvent { + const NativeFileDropEvent({ + required this.phase, + required this.session, + required this.position, + required this.paths, + }); + + final NativeFileDropPhase phase; + final int session; + final Offset position; + final List paths; +} + +/// A named drop destination. Keep grants until asynchronous file use finishes. +class NativeFileDropConnection { + NativeFileDropConnection({ + required this.regionId, + required this.onEvent, + this.hidesSourceImage = false, + }) : assert(regionId != ''); + + static const _manager = MethodChannel('cutdex_native/file_drop'); + final String regionId; + final bool hidesSourceImage; + final Future Function(NativeFileDropEvent) onEvent; + late final _channel = MethodChannel('cutdex_native/file_drop/$regionId'); + late final _binding = NativeChannelBinding(_channel); + bool _disposed = false; + int _revision = 0; + bool get isOwner => !_disposed && _binding.isOwner; + + void bind() { + if (_disposed) throw StateError('Cannot bind a disposed drop connection'); + _binding.bind((call) async { + if (!isOwner || call.method != 'event') return; + final args = call.arguments as Map; + await onEvent( + NativeFileDropEvent( + phase: NativeFileDropPhase.values.byName(args['phase'] as String), + session: args['session'] as int, + position: Offset( + (args['x'] as num? ?? 0).toDouble(), + (args['y'] as num? ?? 0).toDouble(), + ), + paths: [ + for (final file in args['files'] as List? ?? const []) + (file as Map)['path'] as String, + ], + ), + ); + }); + } + + Future setRegion( + Rect? bounds, + NativeDropConfiguration configuration, + ) async { + if (!isOwner) return; + final revision = ++_revision; + try { + await _manager.invokeMethod('ensureRegion', { + 'id': regionId, + 'hidesSourceImage': hidesSourceImage, + }); + if (revision != _revision || !isOwner) return; + await _channel.invokeMethod( + 'setRegion', + bounds == null ? null : configuration.regionArguments(bounds), + ); + } on MissingPluginException { + // Native destinations are available only on registered desktop hosts. + } + } + + Future release(int session) => + _channel.invokeMethod('release', {'session': session}); + + void dispose() { + if (_disposed) return; + _disposed = true; + ++_revision; + if (_binding.unbind()) { + // Callers may still release security-scoped grants after disposal. + unawaited(_clearRegion()); + } + } + + Future _clearRegion() async { + // Let a replacement bind before clearing native state. Cleanup must not + // register a destination or change its options through the manager. + await Future.value(); + if (_binding.hasOwner) return; + try { + await _channel.invokeMethod('setRegion', null); + } on MissingPluginException { + // The native destination may never have been registered. + } + } +} diff --git a/packages/cutdex_native/lib/src/file_drop_region.dart b/packages/cutdex_native/lib/src/file_drop_region.dart new file mode 100644 index 0000000..19dad8f --- /dev/null +++ b/packages/cutdex_native/lib/src/file_drop_region.dart @@ -0,0 +1,148 @@ +import 'dart:async'; + +import 'package:flutter/widgets.dart'; + +import 'bounds_reporter.dart'; +import 'file_drop.dart'; + +/// Existing local file references from the macOS and Windows native hosts. +class NativeFileDropRegion extends StatefulWidget { + const NativeFileDropRegion({ + super.key, + required this.regionId, + this.configuration = NativeDropConfiguration.unrestricted, + this.hidesSourceImage = false, + required this.enabled, + required this.onEnter, + required this.onExit, + required this.onDrop, + required this.child, + }); + final String regionId; + final bool hidesSourceImage; + final NativeDropConfiguration configuration; + final bool enabled; + final ValueChanged> onEnter; + final VoidCallback onExit; + final Future Function(List) onDrop; + final Widget child; + @override + State createState() => _RegionState(); +} + +class _RegionState extends State { + late var connection = createConnection(); + NativeFileDropConnection createConnection() => NativeFileDropConnection( + regionId: widget.regionId, + hidesSourceImage: widget.hidesSourceImage, + onEvent: event, + ); + Rect? region; + NativeDropConfiguration? reportedPolicy; + int? session; + bool get active => widget.enabled && TickerMode.valuesOf(context).enabled; + @override + void initState() { + super.initState(); + connection.bind(); + } + + @override + void didUpdateWidget(covariant NativeFileDropRegion oldWidget) { + super.didUpdateWidget(oldWidget); + if (widget.regionId == oldWidget.regionId && + widget.hidesSourceImage == oldWidget.hidesSourceImage) { + return; + } + if (session != null) { + unawaited(connection.release(session!)); + oldWidget.onExit(); + } + connection.dispose(); + session = null; + region = null; + reportedPolicy = null; + connection = createConnection()..bind(); + } + + Future release(int id) => connection.release(id); + Future event(NativeFileDropEvent event) async { + if (!mounted || !connection.isOwner) return; + final owner = connection; + final id = event.session; + if (event.phase == NativeFileDropPhase.exit) { + if (session == id) { + session = null; + widget.onExit(); + await release(id); + } + } else if (event.phase == NativeFileDropPhase.enter) { + if (!active || !widget.configuration.accepts(event.paths)) { + await release(id); + return; + } + if (session case final previous? when previous != id) { + widget.onExit(); + unawaited(owner.release(previous)); + } + session = id; + widget.onEnter(event.paths); + } else if (event.phase == NativeFileDropPhase.drop && session == id) { + // A pending file operation owns its grant independently of the next drag. + session = null; + try { + if (active && widget.configuration.accepts(event.paths)) { + await widget.onDrop(event.paths); + } else { + widget.onExit(); + } + } finally { + await owner.release(id); + } + } + } + + Future send(Rect? bounds) => + connection.setRegion(bounds, widget.configuration); + + void report(Rect r) { + if (!mounted || !connection.isOwner) return; + final next = active ? r : null; + if (region == next && reportedPolicy == widget.configuration) return; + region = next; + reportedPolicy = widget.configuration; + if (next == null && session != null) { + final id = session!; + session = null; + widget.onExit(); + unawaited(release(id)); + } + unawaited(send(next)); + } + + @override + void dispose() { + connection.dispose(); + if (session case final id?) unawaited(release(id)); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + TickerMode.valuesOf(context); + WidgetsBinding.instance.addPostFrameCallback((_) { + if (!mounted || !connection.isOwner) return; + if (!active && session != null) { + final id = session!; + session = null; + widget.onExit(); + unawaited(release(id)); + region = null; + unawaited(send(null)); + } else if (region != null) { + report(region!); + } + }); + return NativeBoundsReporter(onBounds: report, child: widget.child); + } +} diff --git a/packages/cutdex_native/lib/src/fullscreen.dart b/packages/cutdex_native/lib/src/fullscreen.dart new file mode 100644 index 0000000..2c8193b --- /dev/null +++ b/packages/cutdex_native/lib/src/fullscreen.dart @@ -0,0 +1,71 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +import 'native_channel_binding.dart'; + +class NativeFullscreenSession { + NativeFullscreenSession({required this.onExit}); + + static const _channel = MethodChannel('cutdex_native/fullscreen'); + static Future? _request; + final void Function() onExit; + final _binding = NativeChannelBinding(_channel); + bool _disposed = false; + + void attach() { + if (_disposed) { + throw StateError('Cannot attach a disposed fullscreen session'); + } + _binding.bind((call) async { + if (_binding.isOwner && call.method == 'exited') onExit(); + }); + } + + Future setFullscreen(bool enabled) => _enqueue(enabled); + + Future _enqueue(bool enabled, {bool restoring = false}) { + // AppKit completes a request after its window transition. Serialize across + // owners so retiring and newly mounted routes cannot overlap transitions. + Future invoke() async { + if (restoring ? _binding.hasOwner : _disposed || !_binding.isOwner) { + return; + } + await _channel.invokeMethod('setFullscreen', enabled); + } + + final previous = _request; + final request = previous == null + ? invoke() + : previous.then( + (_) => invoke(), + onError: (Object _, StackTrace _) => invoke(), + ); + _request = request; + // A failed transition must not poison the next owner's request queue. + void clear() { + if (identical(_request, request)) _request = null; + } + + unawaited( + request.then( + (_) => clear(), + onError: (Object _, StackTrace _) => clear(), + ), + ); + return request; + } + + void dispose({bool exitFullscreen = false}) { + if (_disposed) return; + _disposed = true; + if (_binding.unbind() && exitFullscreen) { + unawaited( + _enqueue(false, restoring: true).catchError((Object error) { + debugPrint('Could not restore native fullscreen: $error'); + }), + ); + } + } +} diff --git a/packages/cutdex_native/lib/src/header_control_region.dart b/packages/cutdex_native/lib/src/header_control_region.dart new file mode 100644 index 0000000..413f692 --- /dev/null +++ b/packages/cutdex_native/lib/src/header_control_region.dart @@ -0,0 +1,57 @@ +import 'dart:async'; + +import 'package:flutter/widgets.dart'; + +import 'bounds_reporter.dart'; +import 'window_chrome_session.dart'; + +export 'window_chrome_session.dart' show HeaderControlRole; + +/// Reports actual Flutter control bounds so native windows drag empty header space. +class HeaderControlRegion extends StatefulWidget { + const HeaderControlRegion({ + super.key, + required this.child, + this.role = HeaderControlRole.control, + }); + final Widget child; + final HeaderControlRole role; + @override + State createState() => _HeaderControlRegionState(); +} + +class _HeaderControlRegionState extends State { + static int _nextId = 0; + late final _id = 'control-${_nextId++}'; + Rect? _lastRect; + Future _send(Rect? rect) => + WindowChromeSession.reportControl(_id, rect, widget.role); + + void _report(Rect rect) { + if (!mounted || !WindowChromeSession.supported) return; + final next = TickerMode.valuesOf(context).enabled ? rect : null; + if (next == _lastRect) return; + _lastRect = next; + unawaited(_send(next)); + } + + @override + void didUpdateWidget(covariant HeaderControlRegion oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.role != widget.role && _lastRect != null) { + unawaited(_send(_lastRect)); + } + } + + @override + void dispose() { + if (_lastRect != null) unawaited(_send(null)); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + TickerMode.valuesOf(context); + return NativeBoundsReporter(onBounds: _report, child: widget.child); + } +} diff --git a/packages/cutdex_native/lib/src/native_channel_binding.dart b/packages/cutdex_native/lib/src/native_channel_binding.dart new file mode 100644 index 0000000..e56cd7e --- /dev/null +++ b/packages/cutdex_native/lib/src/native_channel_binding.dart @@ -0,0 +1,26 @@ +import 'package:flutter/services.dart'; + +// A replacement widget can bind before Flutter disposes its predecessor. +// Only the current binding may clear the shared channel or native UI state. +class NativeChannelBinding { + NativeChannelBinding(this.channel); + + static final _owners = <(BinaryMessenger, String), Object>{}; + final MethodChannel channel; + final _token = Object(); + (BinaryMessenger, String) get _key => (channel.binaryMessenger, channel.name); + bool get isOwner => identical(_owners[_key], _token); + bool get hasOwner => _owners.containsKey(_key); + + void bind(Future Function(MethodCall) handler) { + _owners[_key] = _token; + channel.setMethodCallHandler(handler); + } + + bool unbind() { + if (!isOwner) return false; + _owners.remove(_key); + channel.setMethodCallHandler(null); + return true; + } +} diff --git a/packages/cutdex_native/lib/src/window_chrome_session.dart b/packages/cutdex_native/lib/src/window_chrome_session.dart new file mode 100644 index 0000000..40478ec --- /dev/null +++ b/packages/cutdex_native/lib/src/window_chrome_session.dart @@ -0,0 +1,167 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +enum WindowCaptionCommand { minimize, toggleMaximize, close } + +enum HeaderControlRole { control, maximize } + +/// Owns native window chrome while its Flutter owner is active. +class WindowChromeSession extends ChangeNotifier { + WindowChromeSession({required this._headerHeight, this._onCloseRequested}); + + static const _chrome = MethodChannel('cutdex_native/window'); + static const _controls = MethodChannel('cutdex_native/window_controls'); + static final _sessions = []; + static WindowChromeSession? _owner; + static bool get isWindows => + !kIsWeb && defaultTargetPlatform == TargetPlatform.windows; + static bool get supported => + !kIsWeb && (defaultTargetPlatform == TargetPlatform.macOS || isWindows); + + double _headerHeight; + VoidCallback? _onCloseRequested; + bool _interactive = true; + bool _disposed = false; + int _revision = 0; + bool _integrated = false; + bool _maximized = false; + bool _maximizeHovered = false; + bool get integrated => _integrated; + bool get maximized => _maximized; + bool get maximizeHovered => _maximizeHovered; + + void attach() { + if (!supported || _disposed || _sessions.contains(this)) return; + _sessions.add(this); + _activate(); + } + + void _activate() { + _owner = this; + _chrome.setMethodCallHandler(_handleMethodCall); + unawaited(_enable()); + } + + void configure({ + required double headerHeight, + VoidCallback? onCloseRequested, + }) { + final changed = + _headerHeight != headerHeight || + (_onCloseRequested == null) != (onCloseRequested == null); + _headerHeight = headerHeight; + _onCloseRequested = onCloseRequested; + if (changed && identical(_owner, this)) unawaited(_enable()); + } + + void setInteractive(bool interactive) { + if (_interactive == interactive) return; + _interactive = interactive; + if (isWindows && identical(_owner, this)) { + unawaited(_invoke('setHeaderInteractive', interactive)); + } + } + + Future perform(WindowCaptionCommand command) async { + if (!_disposed && identical(_owner, this)) { + await _invoke(command.name); + } + } + + Future _handleMethodCall(MethodCall call) async { + if (_disposed || !identical(_owner, this)) return false; + switch (call.method) { + case 'windowState': + final state = call.arguments as Map; + final maximized = state['maximized'] == true; + final hovered = state['maximizeHovered'] == true; + if (_maximized != maximized || _maximizeHovered != hovered) { + _maximized = maximized; + _maximizeHovered = hovered; + notifyListeners(); + } + return true; + case 'requestClose': + if (_onCloseRequested == null) return false; + _onCloseRequested!(); + return true; + default: + throw MissingPluginException('Unsupported window chrome method'); + } + } + + Future _enable() async { + final revision = ++_revision; + final enabled = await _invoke('configureChrome', { + 'enabled': true, + 'headerHeight': _headerHeight, + 'interceptClose': _onCloseRequested != null, + if (isWindows) 'headerInteractive': _interactive, + }); + if (!_disposed && + identical(_owner, this) && + revision == _revision && + _integrated != (enabled == true)) { + _integrated = enabled == true; + notifyListeners(); + } + } + + static Future _invoke(String method, [Object? arguments]) async { + try { + return await _chrome.invokeMethod(method, arguments); + } on MissingPluginException { + // Widget tests without native plugins keep the standard header. + } on PlatformException catch (error) { + debugPrint('Could not update window chrome: ${error.code}'); + } + return null; + } + + static Future reportControl( + String id, + Rect? rect, + HeaderControlRole role, + ) async { + try { + await _controls.invokeMethod('setHeaderControlRegion', { + 'id': id, + 'role': role.name, + 'rect': rect == null + ? null + : { + 'x': rect.left, + 'y': rect.top, + 'width': rect.width, + 'height': rect.height, + }, + }); + } on MissingPluginException { + // Widget tests do not register native plugins. + } on PlatformException catch (error) { + debugPrint('Could not update titlebar controls: ${error.code}'); + } + } + + @override + void dispose() { + _disposed = true; + _sessions.remove(this); + if (identical(_owner, this)) { + _owner = null; + _chrome.setMethodCallHandler(null); + if (_sessions.isNotEmpty) { + _sessions.last._activate(); + } else { + scheduleMicrotask(() { + if (_owner == null) { + unawaited(_invoke('configureChrome', {'enabled': false})); + } + }); + } + } + super.dispose(); + } +} diff --git a/packages/cutdex_native/lib/src/window_header_layout.dart b/packages/cutdex_native/lib/src/window_header_layout.dart new file mode 100644 index 0000000..57089c5 --- /dev/null +++ b/packages/cutdex_native/lib/src/window_header_layout.dart @@ -0,0 +1,68 @@ +import 'package:flutter/widgets.dart'; + +/// Shares caption bounds in each workspace pane's local layout coordinates. +class WindowHeaderLayout extends InheritedWidget { + const WindowHeaderLayout({ + super.key, + required this.captionBounds, + required super.child, + }); + final Rect captionBounds; + + static Rect? _boundsOf(BuildContext context) => context + .dependOnInheritedWidgetOfExactType() + ?.captionBounds; + + @override + bool updateShouldNotify(WindowHeaderLayout oldWidget) => + captionBounds != oldWidget.captionBounds; +} + +/// Translates the shared caption bounds at a workspace pane boundary. +class WindowHeaderPane extends StatelessWidget { + const WindowHeaderPane({ + super.key, + required this.offset, + required this.child, + }); + final Offset offset; + final Widget child; + + @override + Widget build(BuildContext context) { + final bounds = WindowHeaderLayout._boundsOf(context); + if (bounds == null) return child; + return WindowHeaderLayout( + captionBounds: bounds.shift(-offset), + child: child, + ); + } +} + +/// Reserves overlapping caption space directly from layout constraints. +class WindowHeaderPadding extends StatelessWidget { + const WindowHeaderPadding({super.key, required this.child}); + final Widget child; + + @override + Widget build(BuildContext context) { + final bounds = WindowHeaderLayout._boundsOf(context); + if (bounds == null) return child; + return LayoutBuilder( + builder: (context, constraints) { + final width = constraints.maxWidth; + final right = + bounds.top <= 0 && + bounds.bottom > 0 && + bounds.left < width && + bounds.right > 0 + ? (width - bounds.left).clamp(0.0, width) + : 0.0; + return Padding( + padding: EdgeInsets.only(right: right), + child: right >= width ? const SizedBox.shrink() : child, + ); + }, + ); + } +} diff --git a/packages/cutdex_native/macos/cutdex_native.podspec b/packages/cutdex_native/macos/cutdex_native.podspec new file mode 100644 index 0000000..7f964db --- /dev/null +++ b/packages/cutdex_native/macos/cutdex_native.podspec @@ -0,0 +1,15 @@ +Pod::Spec.new do |s| + s.name = 'cutdex_native' + s.version = '0.1.0' + s.summary = 'Cutdex desktop platform integration.' + s.description = 'Native window chrome, file drops, context menus and fullscreen.' + s.homepage = 'https://github.com/lingjhf/cutdex' + s.license = { :type => 'MIT', :file => '../../../LICENSE' } + s.authors = 'Cutdex contributors' + s.source = { :path => '.' } + s.source_files = 'cutdex_native/Sources/cutdex_native/**/*.swift' + s.dependency 'FlutterMacOS' + s.platform = :osx, '14.0' + s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' } + s.swift_version = '5.0' +end diff --git a/packages/cutdex_native/macos/cutdex_native/Package.swift b/packages/cutdex_native/macos/cutdex_native/Package.swift new file mode 100644 index 0000000..e2c2011 --- /dev/null +++ b/packages/cutdex_native/macos/cutdex_native/Package.swift @@ -0,0 +1,25 @@ +// swift-tools-version: 5.9 +// The swift-tools-version declares the minimum version of Swift required to build this package. + +import PackageDescription + +let package = Package( + name: "cutdex_native", + platforms: [ + .macOS("14.0") + ], + products: [ + .library(name: "cutdex-native", targets: ["cutdex_native"]) + ], + dependencies: [ + .package(name: "FlutterFramework", path: "../FlutterFramework") + ], + targets: [ + .target( + name: "cutdex_native", + dependencies: [ + .product(name: "FlutterFramework", package: "FlutterFramework") + ] + ) + ] +) diff --git a/packages/cutdex_native/macos/cutdex_native/Sources/cutdex_native/CutdexNativePlugin.swift b/packages/cutdex_native/macos/cutdex_native/Sources/cutdex_native/CutdexNativePlugin.swift new file mode 100644 index 0000000..67d91d4 --- /dev/null +++ b/packages/cutdex_native/macos/cutdex_native/Sources/cutdex_native/CutdexNativePlugin.swift @@ -0,0 +1,49 @@ +import Cocoa +import FlutterMacOS + +public final class CutdexNativePlugin: NSObject, FlutterPlugin { + private let view: NSView + private let messenger: FlutterBinaryMessenger + private let menu: NativeContextMenuBridge + private var drops: [String: NativeFileDropView] = [:] + + private init(view: NSView, messenger: FlutterBinaryMessenger) { + self.view = view + self.messenger = messenger + menu = NativeContextMenuBridge(view: view, messenger: messenger) + super.init() + (view.window as? CutdexNativeWindow)?.configureNative(messenger: messenger) + } + + public static func register(with registrar: FlutterPluginRegistrar) { + guard let view = registrar.view else { return } + let instance = CutdexNativePlugin(view: view, messenger: registrar.messenger) + let channel = FlutterMethodChannel(name: "cutdex_native/file_drop", + binaryMessenger: registrar.messenger) + registrar.addMethodCallDelegate(instance, channel: channel) + registrar.addMethodCallDelegate(instance, channel: FlutterMethodChannel( + name: "cutdex_native/device_info", binaryMessenger: registrar.messenger)) + } + + public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { + if call.method == "getApplicationInfo" { + result(["appVersion": Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "unknown", + "appBuild": Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "unknown"]) + return + } + guard call.method == "ensureRegion", + let args = call.arguments as? [String: Any], let id = args["id"] as? String, + !id.isEmpty, let hidesImage = args["hidesSourceImage"] as? Bool else { + return result(FlutterMethodNotImplemented) + } + if let drop = drops[id] { + drop.hidesSourceImage = hidesImage + } else { + let drop = NativeFileDropView(view: view, messenger: messenger, + channelName: "cutdex_native/file_drop/" + id, hidesSourceImage: hidesImage) + view.addSubview(drop) + drops[id] = drop + } + result(nil) + } +} diff --git a/packages/cutdex_native/macos/cutdex_native/Sources/cutdex_native/CutdexNativeWindow.swift b/packages/cutdex_native/macos/cutdex_native/Sources/cutdex_native/CutdexNativeWindow.swift new file mode 100644 index 0000000..0151caa --- /dev/null +++ b/packages/cutdex_native/macos/cutdex_native/Sources/cutdex_native/CutdexNativeWindow.swift @@ -0,0 +1,323 @@ +import Cocoa +import FlutterMacOS + +open class CutdexNativeWindow: NSWindow { + private var chromeChannel: FlutterMethodChannel? + private var controlsChannel: FlutterMethodChannel? + private var fullscreenChannel: FlutterMethodChannel? + private var ownsFullscreen = false + private var fullscreenReply: FlutterResult? + var headerControlRegions: [String: NSRect] = [:] + private var chromeObservers: [NSObjectProtocol] = [] + private(set) var chromeEnabled = false + private var interceptClose = true + private var headerHeight: CGFloat = 40 + private var originalButtonOrigins: [NSWindow.ButtonType: NSPoint] = [:] + private var originalTitleVisibility: NSWindow.TitleVisibility = .visible + private var originalTitlebarTransparency = false + private var originallyFullSize = false + private weak var originalCloseButtonTarget: AnyObject? + private var originalCloseButtonAction: Selector? + private weak var headerMouseTarget: NSView? + private var headerControlGestureActive = false + private var emptyHeaderDragActive = false + private var originalWindowMovable = true + private var originalBackgroundMovable = false + + func configureNative(messenger: FlutterBinaryMessenger) { + let channel = FlutterMethodChannel( + name: "cutdex_native/window", binaryMessenger: messenger) + chromeChannel = channel + channel.setMethodCallHandler { [weak self] call, result in + guard let self else { return result(nil) } + switch call.method { + case "minimize": self.miniaturize(nil); return result(nil) + case "toggleMaximize": self.performZoom(nil); return result(nil) + case "close": self.performClose(nil); return result(nil) + default: break + } + guard call.method == "configureChrome" else { + return result(FlutterMethodNotImplemented) + } + guard let args = call.arguments as? [String: Any], + let enabled = args["enabled"] as? Bool else { + return result(FlutterError(code: "invalidArgument", message: "Missing enabled flag", details: nil)) + } + let height = (args["headerHeight"] as? NSNumber)?.doubleValue ?? 40 + guard height.isFinite, height > 0 else { + return result(FlutterError(code: "invalidArgument", message: "Invalid header height", details: nil)) + } + self.configureChrome(enabled, headerHeight: height, + interceptClose: args["interceptClose"] as? Bool ?? true) + result(enabled) + } + let controls = FlutterMethodChannel( + name: "cutdex_native/window_controls", binaryMessenger: messenger) + controlsChannel = controls + controls.setMethodCallHandler { [weak self] call, result in + guard let self else { return result(nil) } + guard call.method == "setHeaderControlRegion", + let args = call.arguments as? [String: Any], let id = args["id"] as? String else { + return result(FlutterMethodNotImplemented) + } + if let rect = args["rect"] as? [String: NSNumber], + let x = rect["x"]?.doubleValue, let y = rect["y"]?.doubleValue, + let width = rect["width"]?.doubleValue, let height = rect["height"]?.doubleValue, + [x, y, width, height].allSatisfy({ $0.isFinite }), width >= 0, height >= 0 { + self.headerControlRegions[id] = NSRect(x: x, y: y, width: width, height: height) + } else { + self.headerControlRegions.removeValue(forKey: id) + } + result(nil) + } + for name in [NSWindow.didResizeNotification, NSWindow.didEndLiveResizeNotification, + NSWindow.didExitFullScreenNotification] { + chromeObservers.append(NotificationCenter.default.addObserver( + forName: name, object: self, queue: .main + ) { [weak self] _ in + self?.positionWindowButtons() + DispatchQueue.main.async { [weak self] in self?.positionWindowButtons() } + }) + } + + let fullscreen = FlutterMethodChannel( + name: "cutdex_native/fullscreen", binaryMessenger: messenger) + fullscreenChannel = fullscreen + fullscreen.setMethodCallHandler { [weak self] call, result in + guard let self else { return result(nil) } + guard call.method == "setFullscreen", let enabled = call.arguments as? Bool else { + return result(FlutterMethodNotImplemented) + } + guard self.fullscreenReply == nil else { + return result(FlutterError(code: "busy", message: "Fullscreen transition in progress", details: nil)) + } + if enabled { + guard !self.styleMask.contains(.fullScreen) else { return result(nil) } + self.ownsFullscreen = true + } else { + guard self.ownsFullscreen else { return result(nil) } + self.ownsFullscreen = false + guard self.styleMask.contains(.fullScreen) else { return result(nil) } + } + self.fullscreenReply = result + self.toggleFullScreen(nil) + } + for name in [NSWindow.didEnterFullScreenNotification, NSWindow.didExitFullScreenNotification] { + chromeObservers.append(NotificationCenter.default.addObserver( + forName: name, object: self, queue: .main + ) { [weak self] notification in + guard let self else { return } + let reply = self.fullscreenReply + self.fullscreenReply = nil + reply?(nil) + if notification.name == NSWindow.didExitFullScreenNotification { + self.ownsFullscreen = false + self.fullscreenChannel?.invokeMethod("exited", arguments: nil) + } + }) + } + + } + + deinit { + for observer in chromeObservers { NotificationCenter.default.removeObserver(observer) } + } + + /// Keep a titled, resizable AppKit window; only its content/titlebar layout changes. + public func configureChrome(_ enabled: Bool, headerHeight: CGFloat = 40, + interceptClose: Bool = true) { + self.headerHeight = headerHeight + self.interceptClose = interceptClose + guard enabled != chromeEnabled else { + if enabled, let button = standardWindowButton(.closeButton) { + configureCloseButton(button) + } + positionWindowButtons() + return + } + let preservedFrame = frame + if enabled { + originalTitleVisibility = titleVisibility + originalTitlebarTransparency = titlebarAppearsTransparent + originallyFullSize = styleMask.contains(.fullSizeContentView) + originalWindowMovable = isMovable + originalBackgroundMovable = isMovableByWindowBackground + originalButtonOrigins = [:] + for type in [NSWindow.ButtonType.closeButton, .miniaturizeButton, .zoomButton] { + originalButtonOrigins[type] = standardWindowButton(type)?.frame.origin + } + if let closeButton = standardWindowButton(.closeButton) { + originalCloseButtonTarget = closeButton.target as AnyObject? + originalCloseButtonAction = closeButton.action + configureCloseButton(closeButton) + } + chromeEnabled = true + // Disable server-side dragging before the mouse press reaches sendEvent. + // Only our explicit empty-titlebar drag path temporarily enables movement. + isMovable = false + isMovableByWindowBackground = false + titleVisibility = .hidden + titlebarAppearsTransparent = true + styleMask.insert(.fullSizeContentView) + } else { + chromeEnabled = false + isMovable = originalWindowMovable + isMovableByWindowBackground = originalBackgroundMovable + titleVisibility = originalTitleVisibility + titlebarAppearsTransparent = originalTitlebarTransparency + if !originallyFullSize { styleMask.remove(.fullSizeContentView) } + for (type, origin) in originalButtonOrigins { + standardWindowButton(type)?.setFrameOrigin(origin) + } + if let closeButton = standardWindowButton(.closeButton) { + closeButton.target = originalCloseButtonTarget + closeButton.action = originalCloseButtonAction + } + } + setFrame(preservedFrame, display: true) + positionWindowButtons() + DispatchQueue.main.async { [weak self] in self?.positionWindowButtons() } + } + + func positionWindowButtons() { + // AppKit owns the fullscreen titlebar and its reveal/hide animation. + guard chromeEnabled, !styleMask.contains(.fullScreen), let contentView else { return } + let types: [NSWindow.ButtonType] = [.closeButton, .miniaturizeButton, .zoomButton] + for (index, type) in types.enumerated() { + guard let button = standardWindowButton(type), let parent = button.superview else { continue } + if type == .closeButton { configureCloseButton(button) } + let center = NSPoint(x: 19 + CGFloat(index) * 20, + y: contentView.isFlipped ? headerHeight / 2 : contentView.bounds.height - headerHeight / 2) + let target = parent.convert(center, from: contentView) + button.setFrameOrigin(NSPoint(x: target.x - button.frame.width / 2, + y: target.y - button.frame.height / 2)) + } + } + + open override func performClose(_ sender: Any?) { + guard chromeEnabled, interceptClose else { + super.performClose(sender) + return + } + requestClose() + } + + /// The Flutter owner decides how to handle an intercepted close request. + func requestClose() { + chromeChannel?.invokeMethod("requestClose", arguments: nil) + } + + private func configureCloseButton(_ button: NSButton) { + guard interceptClose else { + button.target = originalCloseButtonTarget + button.action = originalCloseButtonAction + return + } + button.target = self + button.action = #selector(closeButtonPressed(_:)) + } + + @objc private func closeButtonPressed(_ sender: Any?) { + requestClose() + } + + private func endHeaderControlGesture() { + headerMouseTarget = nil + headerControlGestureActive = false + } + + private func dragEmptyHeader(with event: NSEvent) { + guard !headerControlGestureActive, originalWindowMovable else { return } + emptyHeaderDragActive = true + isMovable = true + defer { + emptyHeaderDragActive = false + isMovable = chromeEnabled ? false : originalWindowMovable + } + performDrag(with: event) + } + + open override func resignKey() { + endHeaderControlGesture() + super.resignKey() + } + + // Flutter can forward an unhandled event through NSResponder to this window. + // Keep that fallback from interpreting a control gesture as a titlebar action. + open override func mouseDown(with event: NSEvent) { + guard !headerControlGestureActive else { return } + super.mouseDown(with: event) + } + + open override func mouseDragged(with event: NSEvent) { + guard !headerControlGestureActive else { return } + super.mouseDragged(with: event) + } + + open override func mouseUp(with event: NSEvent) { + guard !headerControlGestureActive else { return } + super.mouseUp(with: event) + } + + open override func performDrag(with event: NSEvent) { + guard !headerControlGestureActive, !chromeEnabled || emptyHeaderDragActive else { return } + super.performDrag(with: event) + } + + open override func performZoom(_ sender: Any?) { + guard !headerControlGestureActive else { return } + super.performZoom(sender) + } + + open override func zoom(_ sender: Any?) { + guard !headerControlGestureActive else { return } + super.zoom(sender) + } + + open override func sendEvent(_ event: NSEvent) { + if event.type == .leftMouseDown { endHeaderControlGesture() } + if headerControlGestureActive { + if event.type == .leftMouseUp { + defer { endHeaderControlGesture() } + headerMouseTarget?.mouseUp(with: event) + return + } + if event.type == .leftMouseDragged { + headerMouseTarget?.mouseDragged(with: event) + return + } + } + if chromeEnabled, !styleMask.contains(.fullScreen), event.type == .leftMouseDown, + let contentView { + let point = contentView.convert(event.locationInWindow, from: nil) + let top = contentView.isFlipped ? point.y : contentView.bounds.height - point.y + let controlPoint = NSPoint(x: point.x, y: top) + let isHeaderControl = headerControlRegions.values.contains { $0.contains(controlPoint) } + if top >= 0, top < headerHeight, isHeaderControl, + let target = contentViewController?.view { + // Falling through to AppKit lets its transparent titlebar interpret + // a second click as window zoom before Flutter receives the gesture. + if !isKeyWindow { makeKeyAndOrderFront(nil) } + // Keep the control gesture in Flutter even after leaving its bounds. + headerControlGestureActive = true + headerMouseTarget = target + target.mouseDown(with: event) + return + } + if top >= 0, top < headerHeight, point.x >= 88 { + if event.clickCount == 2 { + switch UserDefaults.standard.string(forKey: "AppleActionOnDoubleClick") { + case "Minimize": miniaturize(nil) + case "None": break + default: performZoom(nil) + } + } else { + dragEmptyHeader(with: event) + } + return + } + } + super.sendEvent(event) + } + +} diff --git a/packages/cutdex_native/macos/cutdex_native/Sources/cutdex_native/NativeBridges.swift b/packages/cutdex_native/macos/cutdex_native/Sources/cutdex_native/NativeBridges.swift new file mode 100644 index 0000000..2eda89d --- /dev/null +++ b/packages/cutdex_native/macos/cutdex_native/Sources/cutdex_native/NativeBridges.swift @@ -0,0 +1,270 @@ +import Cocoa +import FlutterMacOS + +/// AppKit owns menu tracking; Dart receives an action only after tracking ends. +final class NativeContextMenuBridge: NSObject { + private let channel: FlutterMethodChannel + private weak var view: NSView? + private var selectedID: Int? + private var tracking = false + + init(view: NSView, messenger: FlutterBinaryMessenger) { + self.view = view + channel = FlutterMethodChannel(name: "cutdex_native/context_menu", + binaryMessenger: messenger) + super.init() + channel.setMethodCallHandler { [weak self] call, result in + guard let self else { return result(nil) } + guard call.method == "show" else { return result(FlutterMethodNotImplemented) } + guard let args = call.arguments as? [String: Any], + let x = args["x"] as? NSNumber, let y = args["y"] as? NSNumber, + x.doubleValue.isFinite, y.doubleValue.isFinite, + let entries = args["items"] as? [[String: Any]], + let view = self.view, view.window != nil, !self.tracking else { + return result(FlutterError(code: "unavailable", message: "Cannot open context menu", details: nil)) + } + self.tracking = true + self.selectedID = nil + let menu = self.makeMenu(entries) + let point = NSPoint(x: view.bounds.minX + CGFloat(x.doubleValue), + y: view.isFlipped ? view.bounds.minY + CGFloat(y.doubleValue) + : view.bounds.maxY - CGFloat(y.doubleValue)) + menu.popUp(positioning: nil, at: point, in: view) + self.tracking = false + result(self.selectedID) + } + } + + private func makeMenu(_ entries: [[String: Any]]) -> NSMenu { + let menu = NSMenu() + menu.autoenablesItems = false + for entry in entries { + if entry["separator"] as? Bool == true { + menu.addItem(.separator()) + continue + } + guard let label = entry["label"] as? String else { continue } + let item = NSMenuItem(title: label, action: nil, keyEquivalent: "") + item.isEnabled = entry["enabled"] as? Bool ?? true + item.state = entry["selected"] as? Bool == true ? .on : .off + if let children = entry["children"] as? [[String: Any]] { + item.submenu = makeMenu(children) + } else if let id = entry["id"] as? Int { + item.tag = id + item.target = self + item.action = #selector(selectItem(_:)) + } + menu.addItem(item) + } + return menu + } + + @objc private func selectItem(_ sender: NSMenuItem) { + selectedID = sender.tag + } +} + +/// Acceptance is configured by Flutter independently of drag image presentation. +struct NativeFileDropPolicy { + let allowedExtensions: Set? + let maximumFileCount: Int? + + init?(arguments: [String: Any]) { + guard let extensions = arguments["allowedExtensions"], + let count = arguments["maximumFileCount"] else { return nil } + if extensions is NSNull { + allowedExtensions = nil + } else if let values = extensions as? [String], values.allSatisfy({ !$0.isEmpty }) { + allowedExtensions = Set(values.map { $0.lowercased() }) + } else { return nil } + if count is NSNull { + maximumFileCount = nil + } else if let value = count as? NSNumber, + CFGetTypeID(value) != CFBooleanGetTypeID(), + value.doubleValue.isFinite, value.doubleValue > 0, + value.doubleValue < Double(Int.max), + value.doubleValue.rounded(.towardZero) == value.doubleValue { + maximumFileCount = value.intValue + } else { return nil } + } + + func accepts(_ urls: [URL]) -> Bool { + guard !urls.isEmpty, maximumFileCount.map({ urls.count <= $0 }) ?? true else { + return false + } + return urls.allSatisfy { + var isDirectory = ObjCBool(false) + return $0.isFileURL + && FileManager.default.fileExists(atPath: $0.path, isDirectory: &isDirectory) + && !isDirectory.boolValue + && (allowedExtensions?.contains($0.pathExtension.lowercased()) ?? true) + } + } +} + +/// A destination over a configured Flutter region; ordinary mouse events pass through. +final class NativeFileDropView: NSView { + private let channel: FlutterMethodChannel + var hidesSourceImage: Bool + private var policy: NativeFileDropPolicy? + private weak var root: NSView? + private var urls: [URL] = [] + private var grants: [Int: [URL]] = [:] + private var sequence: Int = 0 + private var didDrop = false + private var sourceDragImages: [Int: [NSDraggingImageComponent]] = [:] + private var sourceAnimatesToDestination: Bool? + private let transparentDragImage = NSImage(size: NSSize(width: 1, height: 1), + flipped: false) { rect in + NSColor.clear.setFill() + rect.fill(using: .copy) + return true + } + override var isFlipped: Bool { true } + + init(view: NSView, messenger: FlutterBinaryMessenger, channelName: String, hidesSourceImage: Bool) { + self.hidesSourceImage = hidesSourceImage + root = view + channel = FlutterMethodChannel(name: channelName, + binaryMessenger: messenger) + super.init(frame: .zero) + registerForDraggedTypes([.fileURL]) + channel.setMethodCallHandler { [weak self] call, result in + guard let self else { return result(nil) } + switch call.method { + case "setRegion": + if let a = call.arguments as? [String: Any], let root = self.root, + let policy = NativeFileDropPolicy(arguments: a), + let x = (a["x"] as? NSNumber)?.doubleValue, + let y = (a["y"] as? NSNumber)?.doubleValue, + let w = (a["width"] as? NSNumber)?.doubleValue, + let h = (a["height"] as? NSNumber)?.doubleValue, + [x, y, w, h].allSatisfy({ $0.isFinite }), w > 0, h > 0 { + self.policy = policy + self.frame = NSRect(x: x, y: root.isFlipped ? y : root.bounds.height - y - h, + width: w, height: h) + if !self.didDrop && !self.urls.isEmpty && !policy.accepts(self.urls) { + self.emit("exit", nil) + self.urls.removeAll() + } + } else { + self.emit("exit", nil) + self.policy = nil + self.urls.removeAll() + self.frame = .zero + } + result(nil) + case "release": + if let a = call.arguments as? [String: NSNumber], let id = a["session"]?.intValue { + self.releaseGrants(id) + } + result(nil) + default: result(FlutterMethodNotImplemented) + } + } + } + required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } + private func releaseGrants(_ id: Int) { + for url in grants.removeValue(forKey: id) ?? [] { url.stopAccessingSecurityScopedResource() } + } + private func emit(_ phase: String, _ sender: NSDraggingInfo?) { + let point = sender.map { convert($0.draggingLocation, from: nil) } ?? .zero + channel.invokeMethod("event", arguments: ["phase": phase, "session": sequence, + "x": point.x, "y": point.y, + "files": (phase == "enter" || phase == "drop" ? urls : []).map { ["path": $0.path] }]) + } + // Flutter renders the provisional clip, so suppress Finder's overlapping + // file icon and label. Keep components, never the transient NSDraggingItem. + private func hideSourceDragImages(_ sender: NSDraggingInfo) { + guard hidesSourceImage else { return } + if sourceAnimatesToDestination == nil { + sourceAnimatesToDestination = sender.animatesToDestination + } + sender.animatesToDestination = false + sender.enumerateDraggingItems(options: [], for: self, classes: [NSURL.self], + searchOptions: [.urlReadingFileURLsOnly: true]) { [self] item, index, _ in + if sourceDragImages[index] == nil { + sourceDragImages[index] = item.imageComponents ?? [] + } + // Keep a concrete destination-owned image instead of removing the + // provider. Finder can regenerate its source image during drag updates. + let component = NSDraggingImageComponent(key: .icon) + component.contents = transparentDragImage + component.frame = NSRect(origin: .zero, size: item.draggingFrame.size) + item.imageComponentsProvider = { [component] in [component] } + } + } + private func restoreSourceDragImages(_ sender: NSDraggingInfo?) { + guard let sender, !sourceDragImages.isEmpty else { return } + if let animates = sourceAnimatesToDestination { + sender.animatesToDestination = animates + } + sourceAnimatesToDestination = nil + let images = sourceDragImages + sender.enumerateDraggingItems(options: [], for: self, classes: [NSURL.self], + searchOptions: [.urlReadingFileURLsOnly: true]) { item, index, _ in + if let components = images[index] { + item.imageComponentsProvider = { components } + } + } + sourceDragImages.removeAll() + } + override func updateDraggingItemsForDrag(_ sender: NSDraggingInfo?) { + guard let sender, !urls.isEmpty, !didDrop else { return } + hideSourceDragImages(sender) + } + override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation { + sequence += 1 + didDrop = false + sourceDragImages.removeAll() + sourceAnimatesToDestination = nil + urls = (sender.draggingPasteboard.readObjects(forClasses: [NSURL.self], + options: [.urlReadingFileURLsOnly: true]) as? [URL]) ?? [] + guard sender.draggingSourceOperationMask.contains(.copy) else { + urls.removeAll(); return [] + } + if grants[sequence] == nil { + grants[sequence] = urls.filter { $0.startAccessingSecurityScopedResource() } + } + // Acquire sandbox access before checking file metadata. Rejected references + // never reach Dart, so their access can be released immediately. + guard policy?.accepts(urls) == true else { + releaseGrants(sequence) + urls.removeAll() + return [] + } + hideSourceDragImages(sender) + emit("enter", sender) + return .copy + } + override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation { + guard !urls.isEmpty else { return [] } + // Position updates only drive Flutter's ghost. AppKit requests image + // updates through updateDraggingItemsForDrag; do not restart them per move. + emit("move", sender) + return .copy + } + override func draggingExited(_ sender: NSDraggingInfo?) { + restoreSourceDragImages(sender) + emit("exit", sender) + // Dart releases access after its pending decoding finishes. + } + override func draggingEnded(_ sender: NSDraggingInfo) { + if !didDrop { + restoreSourceDragImages(sender) + emit("exit", sender) + } + sourceDragImages.removeAll() + } + override func wantsPeriodicDraggingUpdates() -> Bool { true } + override func prepareForDragOperation(_ sender: NSDraggingInfo) -> Bool { + policy?.accepts(urls) == true + } + override func performDragOperation(_ sender: NSDraggingInfo) -> Bool { + guard policy?.accepts(urls) == true else { return false } + didDrop = true + emit("drop", sender) + return true + } + deinit { for id in Array(grants.keys) { releaseGrants(id) } } +} diff --git a/packages/cutdex_native/pubspec.yaml b/packages/cutdex_native/pubspec.yaml new file mode 100644 index 0000000..8fcd948 --- /dev/null +++ b/packages/cutdex_native/pubspec.yaml @@ -0,0 +1,27 @@ +name: cutdex_native +description: Cutdex device information and desktop platform integration. +version: 0.1.0 +publish_to: none +resolution: workspace +environment: + sdk: ^3.13.2 +dependencies: + flutter: + sdk: flutter + path: ^1.9.1 +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^6.0.0 +flutter: + plugin: + platforms: + android: + package: dev.cutdex.cutdex_native + pluginClass: CutdexNativePlugin + ios: + pluginClass: CutdexNativePlugin + macos: + pluginClass: CutdexNativePlugin + windows: + pluginClass: CutdexNativePluginCApi diff --git a/packages/cutdex_native/test/bounds_reporter_test.dart b/packages/cutdex_native/test/bounds_reporter_test.dart new file mode 100644 index 0000000..8d05283 --- /dev/null +++ b/packages/cutdex_native/test/bounds_reporter_test.dart @@ -0,0 +1,86 @@ +import 'dart:math' as math; + +import 'package:cutdex_native/cutdex_native.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets('moving a cached layer updates native bounds', (tester) async { + final offset = ValueNotifier(Offset.zero); + addTearDown(offset.dispose); + final reports = []; + final content = RepaintBoundary( + child: NativeBoundsReporter( + onBounds: reports.add, + child: const SizedBox(width: 100, height: 40), + ), + ); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Align( + alignment: Alignment.topLeft, + child: ValueListenableBuilder( + valueListenable: offset, + child: content, + builder: (_, position, child) => + Transform.translate(offset: position, child: child), + ), + ), + ), + ); + expect(reports.last, const Rect.fromLTWH(0, 0, 100, 40)); + offset.value = const Offset(50, 25); + await tester.pump(); + expect(reports.last, const Rect.fromLTWH(50, 25, 100, 40)); + final count = reports.length; + await tester.pump(); + expect(reports, hasLength(count)); + expect(tester.binding.hasScheduledFrame, isFalse); + await tester.pumpWidget(const SizedBox()); + await tester.pump(); + expect(reports, hasLength(count)); + }); + + for (final rotated in [false, true]) { + testWidgets('native bounds include ${rotated ? 'rotation' : 'scaling'}', ( + tester, + ) async { + Rect? bounds; + final reporter = NativeBoundsReporter( + onBounds: (rect) => bounds = rect, + child: const SizedBox(width: 100, height: 40), + ); + await tester.pumpWidget( + Directionality( + textDirection: TextDirection.ltr, + child: Align( + alignment: Alignment.topLeft, + child: Padding( + padding: const EdgeInsets.only(left: 120, top: 100), + child: rotated + ? Transform.rotate( + angle: math.pi / 2, + alignment: Alignment.topLeft, + child: reporter, + ) + : Transform.scale( + scale: 2, + alignment: Alignment.topLeft, + child: reporter, + ), + ), + ), + ), + ); + expect(bounds, isNotNull); + final expected = rotated + ? const Rect.fromLTWH(80, 100, 40, 100) + : const Rect.fromLTWH(120, 100, 200, 80); + expect(bounds!.left, closeTo(expected.left, 1e-8)); + expect(bounds!.top, closeTo(expected.top, 1e-8)); + expect(bounds!.width, closeTo(expected.width, 1e-8)); + expect(bounds!.height, closeTo(expected.height, 1e-8)); + }); + } +} diff --git a/packages/cutdex_native/test/device_info_test.dart b/packages/cutdex_native/test/device_info_test.dart new file mode 100644 index 0000000..e31eb69 --- /dev/null +++ b/packages/cutdex_native/test/device_info_test.dart @@ -0,0 +1,63 @@ +import 'package:cutdex_native/cutdex_native.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + const channel = MethodChannel('cutdex_native/device_info'); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + tearDown(() => messenger.setMockMethodCallHandler(channel, null)); + + test( + 'Android display facts accept integer and floating point values', + () async { + for (final value in [600, 599.5]) { + messenger.setMockMethodCallHandler(channel, (call) async { + expect(call.method, 'getDeviceInfo'); + return {'displayShortestSideDp': value}; + }); + final info = await NativeDeviceInfo.read(); + expect(info?.displayShortestSideDp, value.toDouble()); + expect(info?.interfaceIdiom, isNull); + } + }, + ); + + test('iOS idioms remain raw device facts', () async { + for (final idiom in NativeInterfaceIdiom.values) { + messenger.setMockMethodCallHandler( + channel, + (call) async => {'interfaceIdiom': idiom.name}, + ); + final info = await NativeDeviceInfo.read(); + expect(info?.interfaceIdiom, idiom); + expect(info?.displayShortestSideDp, isNull); + } + }); + + test('invalid responses do not expose unusable device facts', () async { + for (final value in [ + null, + 'phone', + {}, + {'interfaceIdiom': 'unknown'}, + {'displayShortestSideDp': '600'}, + {'displayShortestSideDp': 0}, + {'displayShortestSideDp': -1}, + {'displayShortestSideDp': double.nan}, + {'displayShortestSideDp': double.infinity}, + ]) { + messenger.setMockMethodCallHandler(channel, (call) async => value); + expect(await NativeDeviceInfo.read(), isNull, reason: '$value'); + } + }); + + test('unregistered and unavailable native hosts return no facts', () async { + expect(await NativeDeviceInfo.read(), isNull); + messenger.setMockMethodCallHandler(channel, (call) async { + throw PlatformException(code: 'unavailable'); + }); + expect(await NativeDeviceInfo.read(), isNull); + }); +} diff --git a/packages/cutdex_native/test/drop_configuration_test.dart b/packages/cutdex_native/test/drop_configuration_test.dart new file mode 100644 index 0000000..4f319df --- /dev/null +++ b/packages/cutdex_native/test/drop_configuration_test.dart @@ -0,0 +1,41 @@ +import 'package:cutdex_native/cutdex_native.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + test('invalid policies fail before reaching native registration', () { + expect( + () => NativeDropConfiguration(maximumFileCount: 0), + throwsArgumentError, + ); + expect( + () => NativeDropConfiguration(allowedExtensions: ['']), + throwsArgumentError, + ); + }); + test('configuration owns an immutable extension whitelist', () { + final extensions = ['wav']; + final configuration = NativeDropConfiguration( + allowedExtensions: extensions, + ); + extensions[0] = 'mp4'; + expect(configuration.accepts(['/sample.wav']), true); + expect(configuration.accepts(['/sample.mp4']), false); + expect( + () => configuration.allowedExtensions!.add('mp4'), + throwsUnsupportedError, + ); + }); + + test('equivalent whitelist sets share equality and hashing', () { + final first = NativeDropConfiguration( + allowedExtensions: ['WAV', 'mp4', 'wav'], + maximumFileCount: 2, + ); + final second = NativeDropConfiguration( + allowedExtensions: ['mp4', 'wav'], + maximumFileCount: 2, + ); + expect(first, second); + expect(first.hashCode, second.hashCode); + }); +} diff --git a/packages/cutdex_native/test/file_drop_test.dart b/packages/cutdex_native/test/file_drop_test.dart new file mode 100644 index 0000000..cc12e27 --- /dev/null +++ b/packages/cutdex_native/test/file_drop_test.dart @@ -0,0 +1,340 @@ +import 'dart:async'; + +import 'package:cutdex_native/cutdex_native.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + const manager = MethodChannel('cutdex_native/file_drop'); + const destination = MethodChannel('cutdex_native/file_drop/test'); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + final calls = []; + setUp(() { + calls.clear(); + messenger.setMockMethodCallHandler(manager, (_) async => null); + messenger.setMockMethodCallHandler(destination, (call) async { + calls.add(call); + return null; + }); + }); + tearDown(() { + messenger.setMockMethodCallHandler(manager, null); + messenger.setMockMethodCallHandler(destination, null); + }); + + Future event( + String phase, + int session, { + String channelName = 'cutdex_native/file_drop/test', + }) async { + await messenger.handlePlatformMessage( + channelName, + const StandardMethodCodec().encodeMethodCall( + MethodCall('event', { + 'phase': phase, + 'session': session, + 'x': 12.0, + 'y': 8.0, + 'files': [ + {'path': '/example/input.wav'}, + ], + }), + ), + (_) {}, + ); + } + + testWidgets( + 'inactive routes reject late drag events and release their grants', + (tester) async { + var entered = 0; + var dropped = 0; + await tester.pumpWidget( + MaterialApp( + home: TickerMode( + enabled: false, + child: NativeFileDropRegion( + regionId: 'test', + enabled: true, + onEnter: (_) => entered++, + onExit: () {}, + onDrop: (_) async => dropped++, + child: const SizedBox.expand(), + ), + ), + ), + ); + await tester.pumpAndSettle(); + await event('enter', 7); + await event('drop', 7); + await tester.pump(); + expect(entered, 0); + expect(dropped, 0); + expect(calls.where((c) => c.method == 'release'), hasLength(1)); + await tester.pumpWidget(const SizedBox()); + await tester.pumpAndSettle(); + }, + ); + + testWidgets( + 'equivalent policies at fixed bounds do not rewrite native state', + (tester) async { + Widget target() => MaterialApp( + home: NativeFileDropRegion( + regionId: 'test', + enabled: true, + configuration: NativeDropConfiguration( + allowedExtensions: ['wav'], + maximumFileCount: 1, + ), + onEnter: (_) {}, + onExit: () {}, + onDrop: (_) async {}, + child: const SizedBox.expand(), + ), + ); + await tester.pumpWidget(target()); + await tester.pumpAndSettle(); + final reports = calls.where((c) => c.method == 'setRegion').length; + await tester.pumpWidget(target()); + await tester.pumpAndSettle(); + expect(calls.where((c) => c.method == 'setRegion'), hasLength(reports)); + await tester.pumpWidget(const SizedBox()); + await tester.pumpAndSettle(); + }, + ); + + testWidgets('a completed drop cannot erase the next drag session', ( + tester, + ) async { + final pending = Completer(); + var dropped = 0; + await tester.pumpWidget( + MaterialApp( + home: NativeFileDropRegion( + regionId: 'test', + enabled: true, + onEnter: (_) {}, + onExit: () {}, + onDrop: (_) async { + if (++dropped == 1) await pending.future; + }, + child: const SizedBox.expand(), + ), + ), + ); + await tester.pumpAndSettle(); + await event('enter', 7); + unawaited(event('drop', 7)); + await tester.pump(); + await event('enter', 8); + pending.complete(); + await tester.pump(); + await event('drop', 8); + await tester.pump(); + expect(dropped, 2); + expect( + calls + .where((c) => c.method == 'release') + .map((c) => (c.arguments as Map)['session']), + [7, 8], + ); + await tester.pumpWidget(const SizedBox()); + await tester.pumpAndSettle(); + }); + + testWidgets('a disposed connection cannot steal a replacement binding', ( + tester, + ) async { + final first = NativeFileDropConnection( + regionId: 'test', + onEvent: (_) async {}, + ); + final events = []; + final second = NativeFileDropConnection( + regionId: 'test', + onEvent: (e) async => events.add(e), + ); + first.bind(); + first.dispose(); + await tester.pump(); + second.bind(); + expect(first.bind, throwsStateError); + await event('move', 8); + expect(events, hasLength(1)); + second.dispose(); + await tester.pump(); + }); + + testWidgets('a stale connection cannot change native destination options', ( + tester, + ) async { + final registrations = []; + messenger.setMockMethodCallHandler(manager, (call) async { + registrations.add(call); + return null; + }); + final first = NativeFileDropConnection( + regionId: 'test', + hidesSourceImage: true, + onEvent: (_) async {}, + ); + final second = NativeFileDropConnection( + regionId: 'test', + onEvent: (_) async {}, + ); + first.bind(); + second.bind(); + await second.setRegion( + const Rect.fromLTWH(0, 0, 200, 100), + NativeDropConfiguration.unrestricted, + ); + await first.setRegion( + const Rect.fromLTWH(0, 0, 100, 100), + NativeDropConfiguration.unrestricted, + ); + first.dispose(); + expect(registrations, hasLength(1)); + expect((registrations.single.arguments as Map)['hidesSourceImage'], false); + second.dispose(); + await tester.pump(); + }); + + testWidgets( + 'security grant survives disposal until the drop callback finishes', + (tester) async { + final pending = Completer(); + var dropped = 0; + await tester.pumpWidget( + MaterialApp( + home: NativeFileDropRegion( + regionId: 'test', + enabled: true, + onEnter: (_) {}, + onExit: () {}, + onDrop: (paths) async { + expect(paths, ['/example/input.wav']); + dropped++; + await pending.future; + }, + child: const SizedBox.expand(), + ), + ), + ); + await tester.pumpAndSettle(); + await event('enter', 7); + unawaited(event('drop', 7)); + await tester.pump(); + expect(dropped, 1); + expect(calls.where((call) => call.method == 'release'), isEmpty); + await tester.pumpWidget(const SizedBox()); + await tester.pumpAndSettle(); + expect(calls.where((call) => call.method == 'release'), isEmpty); + pending.complete(); + await tester.pump(); + expect(calls.where((call) => call.method == 'release'), hasLength(1)); + expect((calls.last.arguments as Map)['session'], 7); + }, + ); + + testWidgets('late registration cannot clear a replacement destination', ( + tester, + ) async { + final registrations = >[]; + messenger.setMockMethodCallHandler(manager, (call) async { + expect((call.arguments as Map)['id'], 'test'); + final pending = Completer(); + registrations.add(pending); + await pending.future; + return null; + }); + final first = NativeFileDropConnection( + regionId: 'test', + onEvent: (_) async {}, + ); + final events = []; + final second = NativeFileDropConnection( + regionId: 'test', + onEvent: (event) async => events.add(event), + ); + first.bind(); + final oldReport = first.setRegion( + const Rect.fromLTWH(0, 0, 100, 100), + NativeDropConfiguration.unrestricted, + ); + await tester.pump(); + second.bind(); + first.dispose(); + final newReport = second.setRegion( + const Rect.fromLTWH(0, 0, 200, 100), + NativeDropConfiguration.unrestricted, + ); + await tester.pump(); + for (final pending in registrations) { + pending.complete(); + } + await tester.pump(); + await Future.wait([oldReport, newReport]); + expect(calls.where((call) => call.method == 'setRegion'), hasLength(1)); + expect((calls.single.arguments as Map)['width'], 200.0); + await event('move', 8); + expect(events.single.position, const Offset(12, 8)); + expect(events.single.phase, NativeFileDropPhase.move); + messenger.setMockMethodCallHandler(manager, (_) async => null); + second.dispose(); + await tester.pump(); + }); + + testWidgets( + 'changing destinations preserves a pending drop on its original channel', + (tester) async { + const other = MethodChannel('cutdex_native/file_drop/other'); + final otherCalls = []; + messenger.setMockMethodCallHandler(other, (call) async { + otherCalls.add(call); + return null; + }); + addTearDown(() => messenger.setMockMethodCallHandler(other, null)); + final pending = Completer(); + Widget target(String id) => MaterialApp( + home: NativeFileDropRegion( + regionId: id, + enabled: true, + onEnter: (_) {}, + onExit: () {}, + onDrop: (_) async { + if (id == 'test') await pending.future; + }, + child: const SizedBox.expand(), + ), + ); + await tester.pumpWidget(target('test')); + await tester.pumpAndSettle(); + await event('enter', 7); + unawaited(event('drop', 7)); + await tester.pump(); + await tester.pumpWidget(target('other')); + await tester.pumpAndSettle(); + expect(calls.where((call) => call.method == 'release'), isEmpty); + await event('enter', 8, channelName: other.name); + await event('drop', 8, channelName: other.name); + await tester.pump(); + expect( + otherCalls.where((call) => call.method == 'release'), + hasLength(1), + ); + pending.complete(); + await tester.pump(); + expect((calls.last.arguments as Map)['session'], 7); + expect( + otherCalls.where((call) => call.method == 'release'), + hasLength(1), + ); + await tester.pumpWidget(const SizedBox()); + await tester.pumpAndSettle(); + }, + ); +} diff --git a/packages/cutdex_native/test/fullscreen_test.dart b/packages/cutdex_native/test/fullscreen_test.dart new file mode 100644 index 0000000..1d1a96e --- /dev/null +++ b/packages/cutdex_native/test/fullscreen_test.dart @@ -0,0 +1,87 @@ +import 'dart:async'; + +import 'package:cutdex_native/cutdex_native.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + const channel = MethodChannel('cutdex_native/fullscreen'); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + final requests = []; + setUp(() { + requests.clear(); + messenger.setMockMethodCallHandler(channel, (call) async { + requests.add(call.arguments as bool); + return null; + }); + }); + tearDown(() => messenger.setMockMethodCallHandler(channel, null)); + + testWidgets('a disposed session cannot reclaim the window', (tester) async { + final first = NativeFullscreenSession(onExit: () {}); + var exits = 0; + final second = NativeFullscreenSession(onExit: () => exits++); + first.attach(); + first.dispose(); + second.attach(); + expect(first.attach, throwsStateError); + await first.setFullscreen(false); + await messenger.handlePlatformMessage( + channel.name, + const StandardMethodCodec().encodeMethodCall(const MethodCall('exited')), + (_) {}, + ); + expect(exits, 1); + expect(requests, isEmpty); + second.dispose(); + }); + + testWidgets('a replacement takes ownership while an entry is pending', ( + tester, + ) async { + final entered = Completer(); + messenger.setMockMethodCallHandler(channel, (call) async { + requests.add(call.arguments as bool); + if (requests.length == 1) await entered.future; + return null; + }); + final first = NativeFullscreenSession(onExit: () {}); + final second = NativeFullscreenSession(onExit: () {}); + first.attach(); + final entering = first.setFullscreen(true); + await tester.pump(); + second.attach(); + final replacement = second.setFullscreen(true); + first.dispose(exitFullscreen: true); + await tester.pump(); + expect(requests, [true]); + entered.complete(); + await tester.pump(); + await Future.wait([entering, replacement]); + expect(requests, [true, true]); + second.dispose(exitFullscreen: true); + await tester.pump(); + expect(requests, [true, true, false]); + }); + + testWidgets('a failed transition does not block the next request', ( + tester, + ) async { + messenger.setMockMethodCallHandler(channel, (call) async { + requests.add(call.arguments as bool); + if (call.arguments == true) throw PlatformException(code: 'failed'); + return null; + }); + final session = NativeFullscreenSession(onExit: () {}); + session.attach(); + await expectLater( + session.setFullscreen(true), + throwsA(isA()), + ); + await session.setFullscreen(false); + expect(requests, [true, false]); + session.dispose(); + }); +} diff --git a/packages/cutdex_native/test/header_control_region_test.dart b/packages/cutdex_native/test/header_control_region_test.dart new file mode 100644 index 0000000..341d205 --- /dev/null +++ b/packages/cutdex_native/test/header_control_region_test.dart @@ -0,0 +1,43 @@ +import 'package:cutdex_native/cutdex_native.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets( + 'inactive routes unregister header hit regions and restore them on return', + (tester) async { + const channel = MethodChannel('cutdex_native/window_controls'); + final calls = []; + final messenger = tester.binding.defaultBinaryMessenger; + messenger.setMockMethodCallHandler(channel, (call) async { + calls.add(call); + return null; + }); + addTearDown(() => messenger.setMockMethodCallHandler(channel, null)); + Widget target(bool enabled) => MaterialApp( + home: TickerMode( + enabled: enabled, + child: const HeaderControlRegion( + child: SizedBox(width: 100, height: 40), + ), + ), + ); + await tester.pumpWidget(target(true)); + await tester.pumpAndSettle(); + expect((calls.last.arguments as Map)['rect'], isNotNull); + final id = (calls.last.arguments as Map)['id']; + await tester.pumpWidget(target(false)); + await tester.pumpAndSettle(); + expect((calls.last.arguments as Map)['id'], id); + expect((calls.last.arguments as Map)['rect'], isNull); + await tester.pumpWidget(target(true)); + await tester.pumpAndSettle(); + expect((calls.last.arguments as Map)['rect'], isNotNull); + await tester.pumpWidget(const SizedBox()); + await tester.pumpAndSettle(); + expect((calls.last.arguments as Map)['rect'], isNull); + }, + variant: TargetPlatformVariant.only(TargetPlatform.macOS), + ); +} diff --git a/packages/cutdex_native/tool/macos/file_drop_policy_test.swift b/packages/cutdex_native/tool/macos/file_drop_policy_test.swift new file mode 100644 index 0000000..9bba36f --- /dev/null +++ b/packages/cutdex_native/tool/macos/file_drop_policy_test.swift @@ -0,0 +1,43 @@ +import Cocoa +import FlutterMacOS + +@main +struct FileDropPolicyTests { + static func main() throws { + let files = FileManager.default + let root = files.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try files.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? files.removeItem(at: root) } + let file = root.appendingPathComponent("input.WAV") + try Data([0]).write(to: file) + let directory = root.appendingPathComponent("directory.wav") + try files.createDirectory(at: directory, withIntermediateDirectories: true) + let missing = root.appendingPathComponent("missing.wav") + let unrestricted = NativeFileDropPolicy(arguments: [ + "allowedExtensions": NSNull(), "maximumFileCount": NSNull() + ])! + let audio = NativeFileDropPolicy(arguments: [ + "allowedExtensions": ["wav"], "maximumFileCount": 1 + ])! + var failures = 0 + func check(_ condition: Bool, _ label: String) { + if !condition { + failures += 1 + fputs("FAIL: \(label)\n", stderr) + } + } + check(audio.accepts([file]), "existing file with uppercase extension") + check(unrestricted.accepts([file]), "existing file without extension restrictions") + check(!audio.accepts([directory]), "directory with a permitted extension") + check(!unrestricted.accepts([directory]), "directory without extension restrictions") + check(!audio.accepts([missing]), "missing file with a permitted extension") + check(!unrestricted.accepts([missing]), "missing file without extension restrictions") + check(!audio.accepts([file, file]), "file count limit") + check(!audio.accepts([]), "empty input") + check(!unrestricted.accepts([URL(string: "https://example.com/input.wav")!]), "non-file URL") + try files.removeItem(at: file) + check(!audio.accepts([file]), "file deleted after entering the drop destination") + if failures > 0 { exit(1) } + print("Native file drop policy passed") + } +} diff --git a/packages/cutdex_native/tool/macos/header_control_gestures_test.swift b/packages/cutdex_native/tool/macos/header_control_gestures_test.swift new file mode 100644 index 0000000..b687b75 --- /dev/null +++ b/packages/cutdex_native/tool/macos/header_control_gestures_test.swift @@ -0,0 +1,88 @@ +import Cocoa +import FlutterMacOS + +// The harness exercises a window without initializing plugins or showing it. +final class HiddenTestWindow: CutdexNativeWindow { + var emptyDrags = 0 + override var isKeyWindow: Bool { true } + override func performDrag(with event: NSEvent) { + if isMovable { + emptyDrags += 1 + return // Observe the explicit native drag entry without a blocking tracking loop. + } + super.performDrag(with: event) + } + override func makeKeyAndOrderFront(_ sender: Any?) {} +} + +final class BubblingControlView: NSView { + var downs = 0 + var drags = 0 + var ups = 0 + override func mouseDown(with event: NSEvent) { + downs += 1 + precondition(window?.isMovable == false) + // Exercise responder fallback and direct native actions during the gesture. + window?.mouseDown(with: event) + window?.performZoom(nil) + window?.zoom(nil) + window?.performDrag(with: event) + } + override func mouseDragged(with event: NSEvent) { + drags += 1 + precondition(window?.isMovable == false) + window?.mouseDragged(with: event) + window?.performDrag(with: event) + } + override func mouseUp(with event: NSEvent) { + ups += 1 + precondition(window?.isMovable == false) + window?.mouseUp(with: event) + } +} + +@main +struct HeaderGestureTest { + static func main() { + _ = NSApplication.shared + let window = HiddenTestWindow(contentRect: NSRect(x: 100, y: 100, width: 640, height: 480), + styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: .buffered, defer: false) + let control = BubblingControlView(frame: NSRect(x: 0, y: 0, width: 640, height: 480)) + let controller = NSViewController() + controller.view = control + window.contentViewController = controller + window.isMovable = true + window.isMovableByWindowBackground = true + window.configureChrome(true) + window.headerControlRegions["control"] = NSRect(x: 88, y: 0, width: 140, height: 40) + precondition(!window.isMovable && !window.isMovableByWindowBackground) + let original = window.frame + func event(_ type: NSEvent.EventType, x: CGFloat, top: CGFloat, clicks: Int = 1) -> NSEvent { + let view = window.contentView! + let p = NSPoint(x: x, y: view.isFlipped ? top : view.bounds.height - top) + return NSEvent.mouseEvent(with: type, location: view.convert(p, to: nil), + modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime, + windowNumber: window.windowNumber, context: nil, eventNumber: 0, + clickCount: clicks, pressure: 1)! + } + window.sendEvent(event(.leftMouseDown, x: 110, top: 20)) + // A route change caused by the press must not release native protection. + window.configureChrome(true) + window.sendEvent(event(.leftMouseDragged, x: 400, top: 150)) + window.sendEvent(event(.leftMouseUp, x: 400, top: 150)) + precondition(!window.isMovable) + precondition(window.frame == original) + window.sendEvent(event(.leftMouseDown, x: 110, top: 20, clicks: 2)) + window.sendEvent(event(.leftMouseUp, x: 110, top: 20, clicks: 2)) + precondition(!window.isMovable) + precondition(window.frame == original) + precondition(control.downs == 2 && control.drags == 1 && control.ups == 2) + precondition(window.emptyDrags == 0) + window.sendEvent(event(.leftMouseDown, x: 400, top: 20)) + precondition(window.emptyDrags == 1) + precondition(!window.isMovable) + window.configureChrome(false) + precondition(window.isMovable && window.isMovableByWindowBackground) + print("Native header control gestures passed") + } +} diff --git a/packages/cutdex_native/tool/macos/test_file_drop_policy.sh b/packages/cutdex_native/tool/macos/test_file_drop_policy.sh new file mode 100644 index 0000000..8023c21 --- /dev/null +++ b/packages/cutdex_native/tool/macos/test_file_drop_policy.sh @@ -0,0 +1,25 @@ +#!/bin/sh +set -eu + +if [ "$#" -eq 1 ] && { [ "$1" = "--help" ] || [ "$1" = "-h" ]; }; then + echo "Usage: $0 [flutter-framework-directory]" + exit 0 +fi + +if [ "$#" -gt 1 ]; then + echo "Usage: $0 [flutter-framework-directory]" >&2 + exit 2 +fi + +task_root=$(cd "$(dirname "$0")/../.." && pwd) +task_workspace_root=$(cd "$task_root/../.." && pwd) +task_framework_dir=${1:-"$task_workspace_root/build/macos/Build/Products/Debug-development"} +task_test_dir=$(mktemp -d) +trap 'rm -rf "$task_test_dir"' EXIT HUP INT TERM + +xcrun swiftc -F "$task_framework_dir" -framework FlutterMacOS -framework Cocoa \ + -Xlinker -rpath -Xlinker "$task_framework_dir" \ + "$task_root/macos/cutdex_native/Sources/cutdex_native/NativeBridges.swift" \ + "$task_root/tool/macos/file_drop_policy_test.swift" \ + -o "$task_test_dir/file-drop-policy" +"$task_test_dir/file-drop-policy" diff --git a/packages/cutdex_native/tool/macos/test_header_control_gestures.sh b/packages/cutdex_native/tool/macos/test_header_control_gestures.sh new file mode 100644 index 0000000..d735269 --- /dev/null +++ b/packages/cutdex_native/tool/macos/test_header_control_gestures.sh @@ -0,0 +1,25 @@ +#!/bin/sh +set -eu + +if [ "$#" -eq 1 ] && { [ "$1" = "--help" ] || [ "$1" = "-h" ]; }; then + echo "Usage: $0 [flutter-framework-directory]" + exit 0 +fi + +if [ "$#" -gt 1 ]; then + echo "Usage: $0 [flutter-framework-directory]" >&2 + exit 2 +fi + +task_root=$(cd "$(dirname "$0")/../.." && pwd) +task_workspace_root=$(cd "$task_root/../.." && pwd) +task_framework_dir=${1:-"$task_workspace_root/build/macos/Build/Products/Debug-development"} +task_test_dir=$(mktemp -d) +trap 'rm -rf "$task_test_dir"' EXIT HUP INT TERM + +xcrun swiftc -F "$task_framework_dir" -framework FlutterMacOS -framework Cocoa \ + -Xlinker -rpath -Xlinker "$task_framework_dir" \ + "$task_root/macos/cutdex_native/Sources/cutdex_native/CutdexNativeWindow.swift" \ + "$task_root/tool/macos/header_control_gestures_test.swift" \ + -o "$task_test_dir/header-gestures" +"$task_test_dir/header-gestures" diff --git a/packages/cutdex_native/tool/windows/window_chrome_tests/CMakeLists.txt b/packages/cutdex_native/tool/windows/window_chrome_tests/CMakeLists.txt new file mode 100644 index 0000000..fb18fe2 --- /dev/null +++ b/packages/cutdex_native/tool/windows/window_chrome_tests/CMakeLists.txt @@ -0,0 +1,20 @@ +cmake_minimum_required(VERSION 3.14) +project(window_chrome_tests LANGUAGES CXX) +set(PACKAGE_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../../..") +set(NATIVE_SOURCES "${PACKAGE_ROOT}/windows") +set(WRAPPER "${PACKAGE_ROOT}/../../windows/flutter/ephemeral/cpp_client_wrapper") +if(NOT EXISTS "${WRAPPER}/standard_codec.cc") + message(FATAL_ERROR "Run flutter build windows once to prepare the Flutter wrapper") +endif() +add_executable(window_chrome_tests + "window_chrome_tests.cpp" "${NATIVE_SOURCES}/window_chrome.cpp" "${WRAPPER}/standard_codec.cc" + "${WRAPPER}/core_implementations.cc") +target_include_directories(window_chrome_tests PRIVATE "${NATIVE_SOURCES}" "${WRAPPER}/include" "${WRAPPER}/..") +target_compile_features(window_chrome_tests PRIVATE cxx_std_17) +target_compile_definitions(window_chrome_tests PRIVATE UNICODE _UNICODE NOMINMAX) +target_compile_options(window_chrome_tests PRIVATE /W4 /WX /wd4100 /EHsc) +target_link_libraries(window_chrome_tests PRIVATE dwmapi comctl32 "${WRAPPER}/../flutter_windows.dll.lib") +add_custom_command(TARGET window_chrome_tests POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_if_different "${WRAPPER}/../flutter_windows.dll" "$") +enable_testing() +add_test(NAME window_chrome COMMAND window_chrome_tests) diff --git a/packages/cutdex_native/tool/windows/window_chrome_tests/window_chrome_tests.cpp b/packages/cutdex_native/tool/windows/window_chrome_tests/window_chrome_tests.cpp new file mode 100644 index 0000000..1ba4627 --- /dev/null +++ b/packages/cutdex_native/tool/windows/window_chrome_tests/window_chrome_tests.cpp @@ -0,0 +1,227 @@ +#include "window_chrome.h" +#include +#include + +#include +#include +#include + +namespace { +using Value = flutter::EncodableValue; +using Map = flutter::EncodableMap; +int checks = 0; +void Check(bool condition, const char* message) { + ++checks; + if (!condition) { std::cerr << "FAIL: " << message << '\n'; std::exit(1); } +} +class Messenger : public flutter::BinaryMessenger { + public: + std::map handlers; + mutable std::vector notifications; + void Send(const std::string&, const uint8_t* bytes, size_t size, + flutter::BinaryReply reply) const override { + auto call = flutter::StandardMethodCodec::GetInstance().DecodeMethodCall(bytes, size); + notifications.push_back(call->method_name()); + } + void SetMessageHandler(const std::string& channel, + flutter::BinaryMessageHandler handler) override { + handlers[channel] = std::move(handler); + } + void Call(const char* channel, const char* method, Value args) { + const auto bytes = flutter::StandardMethodCodec::GetInstance().EncodeMethodCall( + flutter::MethodCall(method, std::make_unique(std::move(args)))); + bool success = false; + handlers.at(channel)(bytes->data(), bytes->size(), + [&](const uint8_t* data, size_t size) { success = size > 0 && data[0] == 0; }); + Check(success, method); + } +}; +WindowChrome* chrome = nullptr; +HWND view = nullptr; +LRESULT CALLBACK WindowProc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { + if (chrome) { + auto result = chrome->HandleMessage(message, wparam, lparam); + if (result) return *result; + } + if (message == WM_GETMINMAXINFO) { + DefWindowProc(window, message, wparam, lparam); + const auto dpi = static_cast(GetDpiForWindow(window)); + auto limits = reinterpret_cast(lparam); + limits->ptMinTrackSize.x = MulDiv(520, dpi, 96); + limits->ptMinTrackSize.y = MulDiv(360, dpi, 96); + return 0; + } + if (message == WM_SIZE && view) { + RECT rect{}; + GetClientRect(window, &rect); + MoveWindow(view, 0, 0, rect.right, rect.bottom, FALSE); + return 0; + } + return DefWindowProc(window, message, wparam, lparam); +} +LPARAM Position(HWND window, double x, double y) { + const double scale = GetDpiForWindow(window) / 96.0; + POINT point{static_cast(x * scale), static_cast(y * scale)}; + ClientToScreen(window, &point); + return MAKELPARAM(point.x, point.y); +} +void Configure(Messenger& messenger, bool enabled = true, bool intercept_close = false) { + messenger.Call("cutdex_native/window", "configureChrome", Value(Map{ + {Value("enabled"), Value(enabled)}, {Value("headerHeight"), Value(46.0)}, + {Value("interceptClose"), Value(intercept_close)}})); +} + +void ReportControl(Messenger& messenger, const char* id, double x, double width, + const char* role = "control") { + messenger.Call("cutdex_native/window_controls", "setHeaderControlRegion", Value(Map{ + {Value("id"), Value(id)}, {Value("role"), Value(role)}, + {Value("rect"), Value(Map{ + {Value("x"), Value(x)}, {Value("y"), Value(0.0)}, + {Value("width"), Value(width)}, {Value("height"), Value(46.0)}})}})); +} +} // namespace + +int main() { + SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); + WNDCLASS window_class{}; + window_class.lpfnWndProc = WindowProc; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.lpszClassName = L"CutdexChromeTest"; + RegisterClass(&window_class); + const HWND window = CreateWindow(window_class.lpszClassName, L"Chrome test", + WS_OVERLAPPEDWINDOW, -350, -100, 900, 600, nullptr, nullptr, + window_class.hInstance, nullptr); + Check(window != nullptr, "create window at negative screen coordinates"); + WNDCLASS view_class{}; + view_class.lpfnWndProc = DefWindowProc; + view_class.hInstance = window_class.hInstance; + view_class.lpszClassName = L"CutdexChromeTestView"; + RegisterClass(&view_class); + view = CreateWindow(view_class.lpszClassName, L"", WS_CHILD | WS_VISIBLE, 0, 0, 800, 500, window, + nullptr, window_class.hInstance, nullptr); + Messenger messenger; + auto owner = std::make_unique(window, view, &messenger); + chrome = owner.get(); + Configure(messenger); + const LONG_PTR style = GetWindowLongPtr(window, GWL_STYLE); + Check((style & WS_THICKFRAME) != 0 && (style & WS_SYSMENU) != 0 && + (style & WS_MAXIMIZEBOX) != 0, "retain Windows frame and commands"); + Check(SendMessage(window, WM_NCHITTEST, 0, Position(view, 300, 22)) == HTCAPTION, + "empty header drags"); + Check(SendMessage(view, WM_NCHITTEST, 0, Position(view, 300, 22)) == HTTRANSPARENT, + "Flutter child passes native header hits to parent"); + Check(SendMessage(window, WM_NCHITTEST, 0, Position(view, 300, 100)) == HTCLIENT, + "body stays in Flutter"); + messenger.Call("cutdex_native/window_controls", "setHeaderControlRegion", Value(Map{ + {Value("id"), Value("button")}, {Value("rect"), Value(Map{ + {Value("x"), Value(270.0)}, {Value("y"), Value(0.0)}, + {Value("width"), Value(60.0)}, {Value("height"), Value(46.0)}})}})); + Check(SendMessage(window, WM_NCHITTEST, 0, Position(view, 300, 22)) == HTCLIENT, + "buttons and inputs do not drag"); + Check(SendMessage(view, WM_NCHITTEST, 0, Position(view, 300, 22)) != HTTRANSPARENT, + "Flutter child keeps control hits"); + messenger.Call("cutdex_native/window_controls", "setHeaderControlRegion", Value(Map{ + {Value("id"), Value("button")}, {Value("rect"), Value()}})); + Check(SendMessage(window, WM_NCHITTEST, 0, Position(view, 300, 22)) == HTCAPTION, + "disposed control removes its exclusion"); + RECT client{}; + GetClientRect(view, &client); + const double width = client.right * 96.0 / GetDpiForWindow(window); + Check(SendMessage(window, WM_NCHITTEST, 0, Position(view, width - 69, 22)) == HTCAPTION, + "no guessed caption hit targets before Flutter reports bounds"); + // Deliberately differ from the current UI's 46-pixel buttons. Win32 must use + // the reported geometry, even if button widths or their positions change. + ReportControl(messenger, "minimize", width - 218, 68); + ReportControl(messenger, "maximize", width - 150, 74, "maximize"); + ReportControl(messenger, "close", width - 76, 76); + LPARAM max_position = Position(view, width - 113, 22); + Check(SendMessage(window, WM_NCHITTEST, 0, max_position) == HTMAXBUTTON, + "maximize advertises Snap Layouts hit target"); + Check(SendMessage(view, WM_NCHITTEST, 0, max_position) == HTTRANSPARENT, + "maximize hit reaches native parent"); + ReportControl(messenger, "a-clipped-control", width - 150, 74); + Check(SendMessage(window, WM_NCHITTEST, 0, max_position) == HTMAXBUTTON, + "maximize takes precedence over overlapping workspace control bounds"); + messenger.Call("cutdex_native/window_controls", "setHeaderControlRegion", Value(Map{ + {Value("id"), Value("a-clipped-control")}, {Value("rect"), Value()}})); + Check(SendMessage(window, WM_NCHITTEST, 0, Position(view, width - 23, 22)) == HTCLIENT, + "close button stays in Flutter"); + Check(SendMessage(window, WM_NCHITTEST, 0, Position(view, width - 184, 22)) == HTCLIENT, + "minimize button stays in Flutter"); + Check(SendMessage(window, WM_NCHITTEST, 0, Position(view, width - 69, 22)) == HTCLIENT, + "old hardcoded maximize slot is a reported close control"); + ReportControl(messenger, "maximize", width - 310, 74, "maximize"); + Check(SendMessage(window, WM_NCHITTEST, 0, max_position) == HTCAPTION, + "moving the maximize button removes its old hit target"); + max_position = Position(view, width - 273, 22); + Check(SendMessage(window, WM_NCHITTEST, 0, max_position) == HTMAXBUTTON, + "moving the maximize button updates its native hit target"); + ReportControl(messenger, "maximize", width - 310, 74); + Check(SendMessage(window, WM_NCHITTEST, 0, max_position) == HTCLIENT, + "a changed role updates hit behavior without moving the control"); + ReportControl(messenger, "maximize", width - 310, 74, "maximize"); + RECT bounds{}; + GetWindowRect(window, &bounds); + Check(SendMessage(window, WM_NCHITTEST, 0, MAKELPARAM(bounds.left + 1, bounds.top + 1)) == HTTOPLEFT, + "top-left edge resizes"); + Check(SendMessage(window, WM_NCHITTEST, 0, MAKELPARAM(bounds.right - 1, bounds.bottom - 1)) == HTBOTTOMRIGHT, + "bottom-right edge resizes"); + Check(SendMessage(window, WM_NCHITTEST, 0, MAKELPARAM(bounds.left + 100, bounds.top + 1)) == HTTOP, + "top edge resizes"); + messenger.Call("cutdex_native/window", "setHeaderInteractive", Value(false)); + Check(SendMessage(window, WM_NCHITTEST, 0, Position(view, 300, 22)) == HTCLIENT, + "modal route blocks native header drag"); + Check(SendMessage(window, WM_NCHITTEST, 0, max_position) == HTCLIENT, + "modal route blocks maximize hit target"); + messenger.Call("cutdex_native/window", "setHeaderInteractive", Value(true)); + SendMessage(window, WM_NCLBUTTONDOWN, HTMAXBUTTON, max_position); + Check(GetCapture() == window, "maximize captures the press"); + SendMessage(window, WM_CANCELMODE, 0, 0); + ReleaseCapture(); + Check(!IsZoomed(window), "cancelled maximize press leaves state unchanged"); + POINT max_point{GET_X_LPARAM(max_position), GET_Y_LPARAM(max_position)}; + ScreenToClient(window, &max_point); + SendMessage(window, WM_NCLBUTTONDOWN, HTMAXBUTTON, max_position); + SendMessage(window, WM_LBUTTONUP, 0, MAKELPARAM(max_point.x, max_point.y)); + ShowWindow(window, SW_HIDE); + Check(IsZoomed(window) != FALSE, "native maximize mouse press and release"); + SendMessage(window, WM_NCLBUTTONDBLCLK, HTCAPTION, Position(view, 300, 22)); + ShowWindow(window, SW_HIDE); + Check(!IsZoomed(window), "double-click empty caption restores"); + messenger.Call("cutdex_native/window", "toggleMaximize", Value()); + ShowWindow(window, SW_HIDE); + Check(IsZoomed(window) != FALSE, "maximize command"); + RECT max_bounds{}, max_client{}; + GetWindowRect(window, &max_bounds); + GetClientRect(window, &max_client); + POINT origin{}; + ClientToScreen(window, &origin); + Check(origin.y > max_bounds.top, "maximized client avoids invisible top frame"); + Check(SendMessage(window, WM_NCHITTEST, 0, Position(view, 300, 1)) == HTCAPTION, + "maximized top is caption instead of resize"); + messenger.Call("cutdex_native/window", "toggleMaximize", Value()); + ShowWindow(window, SW_HIDE); + Check(!IsZoomed(window), "restore command"); + MINMAXINFO limits{}; + SendMessage(window, WM_GETMINMAXINFO, 0, reinterpret_cast(&limits)); + Check(limits.ptMinTrackSize.x == MulDiv(520, static_cast(GetDpiForWindow(window)), 96) && + limits.ptMinTrackSize.y == MulDiv(360, static_cast(GetDpiForWindow(window)), 96), + "host minimum size survives native chrome and follows monitor DPI"); + Configure(messenger, true, true); + const auto before = messenger.notifications.size(); + SendMessage(window, WM_CLOSE, 0, 0); + Check(IsWindow(window) && messenger.notifications.size() == before + 1 && + messenger.notifications.back() == "requestClose", "close callback is intercepted"); + Configure(messenger, false); + POINT standard_origin{}; + ClientToScreen(window, &standard_origin); + GetWindowRect(window, &bounds); + Check(standard_origin.y > bounds.top, "disable restores system titlebar"); + chrome = nullptr; + owner.reset(); + Check(!messenger.handlers["cutdex_native/window"] && + !messenger.handlers["cutdex_native/window_controls"], "channel handlers unregister"); + view = nullptr; + DestroyWindow(window); + std::cout << checks << " native window checks passed at " << GetDpiForSystem() << " DPI\n"; +} diff --git a/packages/cutdex_native/windows/.gitignore b/packages/cutdex_native/windows/.gitignore new file mode 100644 index 0000000..b3eb2be --- /dev/null +++ b/packages/cutdex_native/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/packages/cutdex_native/windows/CMakeLists.txt b/packages/cutdex_native/windows/CMakeLists.txt new file mode 100644 index 0000000..f0259e7 --- /dev/null +++ b/packages/cutdex_native/windows/CMakeLists.txt @@ -0,0 +1,64 @@ +# The Flutter tooling requires that developers have a version of Visual Studio +# installed that includes CMake 3.14 or later. You should not increase this +# version, as doing so will cause the plugin to fail to compile for some +# customers of the plugin. +cmake_minimum_required(VERSION 3.14) + +# Project-level configuration. +set(PROJECT_NAME "cutdex_native") +project(${PROJECT_NAME} LANGUAGES CXX) + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(VERSION 3.14...3.25) + +# This value is used when generating builds using this plugin, so it must +# not be changed +set(PLUGIN_NAME "cutdex_native_plugin") + +# Any new source files that you add to the plugin should be added here. +list(APPEND PLUGIN_SOURCES + "cutdex_native_plugin.cpp" + "cutdex_native_plugin.h" + "window_chrome.cpp" + "native_file_drop.cpp" +) + +# Define the plugin library target. Its name must not be changed (see comment +# on PLUGIN_NAME above). +add_library(${PLUGIN_NAME} SHARED + "include/cutdex_native/cutdex_native_plugin_c_api.h" + "cutdex_native_plugin_c_api.cpp" + ${PLUGIN_SOURCES} +) + +# Apply a standard set of build settings that are configured in the +# application-level CMakeLists.txt. This can be removed for plugins that want +# full control over build settings. +apply_standard_settings(${PLUGIN_NAME}) + +# Symbols are hidden by default to reduce the chance of accidental conflicts +# between plugins. This should not be removed; any symbols that should be +# exported should be explicitly exported with the FLUTTER_PLUGIN_EXPORT macro. +set_target_properties(${PLUGIN_NAME} PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL) + +# Source include directories and library dependencies. Add any plugin-specific +# dependencies here. +target_include_directories(${PLUGIN_NAME} INTERFACE + "${CMAKE_CURRENT_SOURCE_DIR}/include") +target_link_libraries(${PLUGIN_NAME} PRIVATE flutter flutter_wrapper_plugin dwmapi comctl32 ole32 shell32 uuid) + +# List of absolute paths to libraries that should be bundled with the plugin. +# This list could contain prebuilt libraries, or libraries created by an +# external build triggered from this build file. +set(cutdex_native_bundled_libraries + "" + PARENT_SCOPE +) + +target_compile_definitions(${PLUGIN_NAME} PRIVATE NOMINMAX) +target_compile_definitions(${PLUGIN_NAME} PRIVATE + "CUTDEX_APP_VERSION=\"${FLUTTER_VERSION}\"" + "CUTDEX_APP_BUILD=\"${FLUTTER_VERSION_BUILD}\"") diff --git a/packages/cutdex_native/windows/cutdex_native_plugin.cpp b/packages/cutdex_native/windows/cutdex_native_plugin.cpp new file mode 100644 index 0000000..8197c53 --- /dev/null +++ b/packages/cutdex_native/windows/cutdex_native_plugin.cpp @@ -0,0 +1,40 @@ +#include "cutdex_native_plugin.h" +#include + +namespace cutdex_native { +void CutdexNativePlugin::RegisterWithRegistrar( + flutter::PluginRegistrarWindows* registrar) { + registrar->AddPlugin(std::make_unique(registrar)); +} + +CutdexNativePlugin::CutdexNativePlugin(flutter::PluginRegistrarWindows* registrar) + : registrar_(registrar) { + device_info_ = std::make_unique>( + registrar->messenger(), "cutdex_native/device_info", + &flutter::StandardMethodCodec::GetInstance()); + device_info_->SetMethodCallHandler([](const auto& call, auto result) { + if (call.method_name() != "getApplicationInfo") { + result->NotImplemented(); + return; + } + result->Success(flutter::EncodableValue(flutter::EncodableMap{ + {flutter::EncodableValue("appVersion"), flutter::EncodableValue(CUTDEX_APP_VERSION)}, + {flutter::EncodableValue("appBuild"), flutter::EncodableValue(CUTDEX_APP_BUILD)}})); + }); + const HWND view = registrar->GetView()->GetNativeWindow(); + chrome_ = std::make_unique( + GetAncestor(view, GA_ROOT), view, registrar->messenger()); + drop_ = std::make_unique(view, registrar->messenger()); + delegate_id_ = registrar->RegisterTopLevelWindowProcDelegate( + [this](HWND, UINT message, WPARAM wparam, LPARAM lparam) + -> std::optional { + return chrome_->HandleMessage(message, wparam, lparam); + }); +} + +CutdexNativePlugin::~CutdexNativePlugin() { + registrar_->UnregisterTopLevelWindowProcDelegate(delegate_id_); + drop_.reset(); + chrome_.reset(); +} +} diff --git a/packages/cutdex_native/windows/cutdex_native_plugin.h b/packages/cutdex_native/windows/cutdex_native_plugin.h new file mode 100644 index 0000000..1bbcc74 --- /dev/null +++ b/packages/cutdex_native/windows/cutdex_native_plugin.h @@ -0,0 +1,25 @@ +#ifndef FLUTTER_PLUGIN_CUTDEX_NATIVE_PLUGIN_H_ +#define FLUTTER_PLUGIN_CUTDEX_NATIVE_PLUGIN_H_ +#include +#include +#include "window_chrome.h" +#include "native_file_drop.h" +#include + +namespace cutdex_native { +class CutdexNativePlugin : public flutter::Plugin { + public: + static void RegisterWithRegistrar(flutter::PluginRegistrarWindows* registrar); + explicit CutdexNativePlugin(flutter::PluginRegistrarWindows* registrar); + ~CutdexNativePlugin() override; + CutdexNativePlugin(const CutdexNativePlugin&) = delete; + CutdexNativePlugin& operator=(const CutdexNativePlugin&) = delete; + private: + flutter::PluginRegistrarWindows* registrar_; + int delegate_id_; + std::unique_ptr chrome_; + std::unique_ptr drop_; + std::unique_ptr> device_info_; +}; +} +#endif diff --git a/packages/cutdex_native/windows/cutdex_native_plugin_c_api.cpp b/packages/cutdex_native/windows/cutdex_native_plugin_c_api.cpp new file mode 100644 index 0000000..de3a45f --- /dev/null +++ b/packages/cutdex_native/windows/cutdex_native_plugin_c_api.cpp @@ -0,0 +1,12 @@ +#include "include/cutdex_native/cutdex_native_plugin_c_api.h" + +#include + +#include "cutdex_native_plugin.h" + +void CutdexNativePluginCApiRegisterWithRegistrar( + FlutterDesktopPluginRegistrarRef registrar) { + cutdex_native::CutdexNativePlugin::RegisterWithRegistrar( + flutter::PluginRegistrarManager::GetInstance() + ->GetRegistrar(registrar)); +} diff --git a/packages/cutdex_native/windows/include/cutdex_native/cutdex_native_plugin_c_api.h b/packages/cutdex_native/windows/include/cutdex_native/cutdex_native_plugin_c_api.h new file mode 100644 index 0000000..c69bc0f --- /dev/null +++ b/packages/cutdex_native/windows/include/cutdex_native/cutdex_native_plugin_c_api.h @@ -0,0 +1,23 @@ +#ifndef FLUTTER_PLUGIN_CUTDEX_NATIVE_PLUGIN_C_API_H_ +#define FLUTTER_PLUGIN_CUTDEX_NATIVE_PLUGIN_C_API_H_ + +#include + +#ifdef FLUTTER_PLUGIN_IMPL +#define FLUTTER_PLUGIN_EXPORT __declspec(dllexport) +#else +#define FLUTTER_PLUGIN_EXPORT __declspec(dllimport) +#endif + +#if defined(__cplusplus) +extern "C" { +#endif + +FLUTTER_PLUGIN_EXPORT void CutdexNativePluginCApiRegisterWithRegistrar( + FlutterDesktopPluginRegistrarRef registrar); + +#if defined(__cplusplus) +} // extern "C" +#endif + +#endif // FLUTTER_PLUGIN_CUTDEX_NATIVE_PLUGIN_C_API_H_ diff --git a/packages/cutdex_native/windows/native_file_drop.cpp b/packages/cutdex_native/windows/native_file_drop.cpp new file mode 100644 index 0000000..66b605b --- /dev/null +++ b/packages/cutdex_native/windows/native_file_drop.cpp @@ -0,0 +1,367 @@ +#include "native_file_drop.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +using Value = flutter::EncodableValue; +using Map = flutter::EncodableMap; +using List = flutter::EncodableList; +using Channel = flutter::MethodChannel; + +struct Region { + double x; + double y; + double width; + double height; + std::optional> allowed_extensions; + std::optional maximum_file_count; + + bool Contains(double px, double py) const { + return px >= x && py >= y && px < x + width && py < y + height; + } +}; + +std::optional Number(const Map& map, const char* key) { + const auto entry = map.find(Value(key)); + if (entry == map.end()) return std::nullopt; + const auto& value = entry->second; + if (const auto* n = std::get_if(&value)) return *n; + if (const auto* n = std::get_if(&value)) return *n; + if (const auto* n = std::get_if(&value)) { + return static_cast(*n); + } + return std::nullopt; +} + +std::optional ReadRegion(const Value* value) { + const auto* map = value ? std::get_if(value) : nullptr; + if (!map) return std::nullopt; + const auto x = Number(*map, "x"); + const auto y = Number(*map, "y"); + const auto w = Number(*map, "width"); + const auto h = Number(*map, "height"); + if (!x || !y || !w || !h || !std::isfinite(*x) || !std::isfinite(*y) || + !std::isfinite(*w) || !std::isfinite(*h) || *w <= 0 || *h <= 0) { + return std::nullopt; + } + const auto extensions = map->find(Value("allowedExtensions")); + const auto count = map->find(Value("maximumFileCount")); + if (extensions == map->end() || count == map->end()) return std::nullopt; + Region region{*x, *y, *w, *h, std::nullopt, std::nullopt}; + if (!std::holds_alternative(extensions->second)) { + const auto* values = std::get_if(&extensions->second); + if (!values) return std::nullopt; + region.allowed_extensions.emplace(); + for (const auto& entry : *values) { + const auto* extension = std::get_if(&entry); + if (!extension || extension->empty()) return std::nullopt; + region.allowed_extensions->push_back(*extension); + } + } + if (!std::holds_alternative(count->second)) { + if (const auto* count32 = std::get_if(&count->second)) { + region.maximum_file_count = *count32; + } else if (const auto* count64 = std::get_if(&count->second)) { + region.maximum_file_count = *count64; + } else { + return std::nullopt; + } + if (*region.maximum_file_count <= 0) return std::nullopt; + } + return region; +} + +std::string Utf8(const std::wstring& text) { + const int count = static_cast(text.size()); + const int size = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, text.data(), + count, nullptr, 0, nullptr, nullptr); + if (size <= 0) return {}; + std::string result(static_cast(size), '\0'); + if (WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, text.data(), count, + result.data(), size, nullptr, nullptr) != size) { + return {}; + } + return result; +} + +List ReadFiles(IDataObject* data) { + List files; + if (!data) return files; + // Only existing file references are accepted. Virtual file descriptors and + // promised contents are not existing local file references. + FORMATETC format{CF_HDROP, nullptr, DVASPECT_CONTENT, -1, TYMED_HGLOBAL}; + STGMEDIUM medium{}; + if (FAILED(data->GetData(&format, &medium))) return files; + if (medium.tymed == TYMED_HGLOBAL && medium.hGlobal) { + const auto drop = static_cast(medium.hGlobal); + const UINT count = DragQueryFileW(drop, 0xFFFFFFFF, nullptr, 0); + for (UINT i = 0; i < count; ++i) { + const UINT size = DragQueryFileW(drop, i, nullptr, 0); + std::vector buffer(static_cast(size) + 1); + if (size == 0 || DragQueryFileW(drop, i, buffer.data(), size + 1) != size) { + files.clear(); + break; + } + const DWORD attributes = GetFileAttributesW(buffer.data()); + const auto path = Utf8(std::wstring(buffer.data(), size)); + if (path.empty() || attributes == INVALID_FILE_ATTRIBUTES || + (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0) { + files.clear(); + break; + } + files.emplace_back(Map{{Value("path"), Value(path)}}); + } + } + ReleaseStgMedium(&medium); + return files; +} + +bool Accepts(const Region& region, const List& files) { + if (files.empty() || + (region.maximum_file_count && + files.size() > static_cast(*region.maximum_file_count))) { + return false; + } + if (!region.allowed_extensions) return true; + for (const auto& entry : files) { + const auto& file = std::get(entry); + const auto& path = std::get(file.at(Value("path"))); + const auto separator = path.find_last_of("/\\"); + const auto dot = path.find_last_of('.'); + if (dot == std::string::npos || + (separator != std::string::npos && dot <= separator)) return false; + auto extension = path.substr(dot + 1); + for (char& c : extension) { + if (c >= 'A' && c <= 'Z') c = static_cast(c + ('a' - 'A')); + } + const auto& allowed = *region.allowed_extensions; + if (std::find(allowed.begin(), allowed.end(), extension) == allowed.end()) { + return false; + } + } + return true; +} +} // namespace + +class NativeFileDrop::Target : public IDropTarget { + public: + Target(HWND view, flutter::BinaryMessenger* messenger) + : view_(view), messenger_(messenger) { + manager_ = std::make_unique(messenger, "cutdex_native/file_drop", + &flutter::StandardMethodCodec::GetInstance()); + manager_->SetMethodCallHandler([this](const auto& call, auto result) { + const auto* args = call.arguments(); + const auto* map = args ? std::get_if(args) : nullptr; + if (call.method_name() != "ensureRegion" || !map) { + result->NotImplemented(); return; + } + const auto entry = map->find(Value("id")); + const auto* id = entry == map->end() ? nullptr + : std::get_if(&entry->second); + if (!id || id->empty()) { + result->Error("invalid_arguments", "Expected a region id"); return; + } + if (ids_.find(*id) == ids_.end()) { + const size_t i = channels_.size(); + ids_[*id] = i; + regions_.emplace_back(); + channels_.push_back(std::make_unique(messenger_, + "cutdex_native/file_drop/" + *id, + &flutter::StandardMethodCodec::GetInstance())); + channels_[i]->SetMethodCallHandler([this, i](const auto& call, auto result) { + if (call.method_name() == "setRegion") { + regions_[i] = ReadRegion(call.arguments()); + if (active_ == static_cast(i) && + (!regions_[i] || !Accepts(*regions_[i], files_))) LeaveRegion(); + result->Success(); + } else if (call.method_name() == "release") { + result->Success(); + } else { + result->NotImplemented(); + } + }); + } + result->Success(); + }); + } + + virtual ~Target() = default; + + void Detach() { + LeaveRegion(); + manager_->SetMethodCallHandler(nullptr); + for (auto& channel : channels_) channel->SetMethodCallHandler(nullptr); + } + + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void** object) override { + if (!object) return E_POINTER; + *object = nullptr; + if (IsEqualIID(iid, IID_IUnknown) || IsEqualIID(iid, IID_IDropTarget)) { + *object = static_cast(this); + AddRef(); + return S_OK; + } + return E_NOINTERFACE; + } + + ULONG STDMETHODCALLTYPE AddRef() override { return ++references_; } + ULONG STDMETHODCALLTYPE Release() override { + const ULONG remaining = --references_; + if (remaining == 0) delete this; + return remaining; + } + + HRESULT STDMETHODCALLTYPE DragEnter(IDataObject* data, DWORD, POINTL point, + DWORD* effect) override { + if (!effect) return E_POINTER; + Reset(); + files_ = ReadFiles(data); + Update(point, (*effect & DROPEFFECT_COPY) != 0); + *effect = active_ >= 0 ? DROPEFFECT_COPY : DROPEFFECT_NONE; + return S_OK; + } + + HRESULT STDMETHODCALLTYPE DragOver(DWORD, POINTL point, + DWORD* effect) override { + if (!effect) return E_POINTER; + Update(point, (*effect & DROPEFFECT_COPY) != 0); + *effect = active_ >= 0 ? DROPEFFECT_COPY : DROPEFFECT_NONE; + return S_OK; + } + + HRESULT STDMETHODCALLTYPE DragLeave() override { + Reset(); + return S_OK; + } + + HRESULT STDMETHODCALLTYPE Drop(IDataObject* data, DWORD, POINTL point, + DWORD* effect) override { + if (!effect) return E_POINTER; + // Confirm the same paths still exist when the user releases the mouse. + const auto current = ReadFiles(data); + Update(point, (*effect & DROPEFFECT_COPY) != 0 && current == files_); + if (active_ >= 0) { + Emit("drop"); + *effect = DROPEFFECT_COPY; + // Dart keeps this session until its asynchronous import has completed. + // Do not send exit here: asynchronous file preparation can still be pending. + active_ = -1; + files_.clear(); + } else { + *effect = DROPEFFECT_NONE; + Reset(); + } + return S_OK; + } + + private: + void Update(POINTL point, bool copy_allowed) { + POINT client{point.x, point.y}; + if (!ScreenToClient(view_, &client)) { + LeaveRegion(); + return; + } + const UINT dpi = FlutterDesktopGetDpiForMonitor( + MonitorFromWindow(view_, MONITOR_DEFAULTTONEAREST)); + const double scale = dpi > 0 ? dpi / 96.0 : 1.0; + x_ = client.x / scale; + y_ = client.y / scale; + int next = -1; + if (copy_allowed && !files_.empty()) { + for (int i = static_cast(regions_.size()) - 1; i >= 0; --i) { + if (regions_[i] && regions_[i]->Contains(x_, y_) && + Accepts(*regions_[i], files_)) { + next = i; + break; + } + } + } + if (next != active_) { + LeaveRegion(); + active_ = next; + if (active_ >= 0) { + ++session_; + Emit("enter"); + } + } else if (active_ >= 0) { + Emit("move"); + } + } + + void Emit(const char* phase) { + if (active_ < 0) return; + const auto i = static_cast(active_); + const auto& region = regions_[i]; + const bool include_files = std::string(phase) == "enter" || + std::string(phase) == "drop"; + channels_[i]->InvokeMethod("event", std::make_unique(Map{ + {Value("phase"), Value(phase)}, + {Value("session"), Value(session_)}, + {Value("x"), Value(x_ - (region ? region->x : 0))}, + {Value("y"), Value(y_ - (region ? region->y : 0))}, + {Value("files"), Value(include_files ? files_ : List{})}, + })); + } + + void LeaveRegion() { + Emit("exit"); + active_ = -1; + } + + void Reset() { + LeaveRegion(); + files_.clear(); + } + + std::atomic references_{1}; + HWND view_; + flutter::BinaryMessenger* messenger_; + std::unique_ptr manager_; + std::map ids_; + std::vector> channels_; + std::vector> regions_; + List files_; + int active_ = -1; + int64_t session_ = 0; + double x_ = 0; + double y_ = 0; +}; + +NativeFileDrop::NativeFileDrop(HWND view, flutter::BinaryMessenger* messenger) + : view_(view) { + // CoInitializeEx alone does not initialize OLE drag-and-drop support. + ole_initialized_ = SUCCEEDED(OleInitialize(nullptr)); + if (!ole_initialized_) { + OutputDebugStringW(L"Cutdex: OLE file drop initialization failed.\n"); + return; + } + target_ = new Target(view, messenger); + registered_ = SUCCEEDED(RegisterDragDrop(view, target_)); + if (!registered_) { + OutputDebugStringW(L"Cutdex: native file drop registration failed.\n"); + } +} + +NativeFileDrop::~NativeFileDrop() { + if (registered_) RevokeDragDrop(view_); + if (target_) { + target_->Detach(); + target_->Release(); + } + if (ole_initialized_) OleUninitialize(); +} diff --git a/packages/cutdex_native/windows/native_file_drop.h b/packages/cutdex_native/windows/native_file_drop.h new file mode 100644 index 0000000..8104f56 --- /dev/null +++ b/packages/cutdex_native/windows/native_file_drop.h @@ -0,0 +1,25 @@ +#ifndef FLUTTER_PLUGIN_CUTDEX_NATIVE_FILE_DROP_H_ +#define FLUTTER_PLUGIN_CUTDEX_NATIVE_FILE_DROP_H_ + +#include +#include + +// Receives Explorer file references and routes them to configured Flutter +// destinations. Must live on the window's STA thread. +class NativeFileDrop { + public: + NativeFileDrop(HWND view, flutter::BinaryMessenger* messenger); + ~NativeFileDrop(); + + NativeFileDrop(const NativeFileDrop&) = delete; + NativeFileDrop& operator=(const NativeFileDrop&) = delete; + + private: + class Target; + Target* target_ = nullptr; + HWND view_; + bool ole_initialized_ = false; + bool registered_ = false; +}; + +#endif // FLUTTER_PLUGIN_CUTDEX_NATIVE_FILE_DROP_H_ diff --git a/packages/cutdex_native/windows/window_chrome.cpp b/packages/cutdex_native/windows/window_chrome.cpp new file mode 100644 index 0000000..232ec15 --- /dev/null +++ b/packages/cutdex_native/windows/window_chrome.cpp @@ -0,0 +1,265 @@ +#include "window_chrome.h" + +#include +#include +#include + +#include + +namespace { +using Value = flutter::EncodableValue; +using Map = flutter::EncodableMap; +const Value* Find(const Map* map, const char* name) { + if (!map) return nullptr; + const auto it = map->find(Value(name)); + return it == map->end() ? nullptr : &it->second; +} +bool Boolean(const Map* map, const char* name, bool fallback = false) { + const auto value = Find(map, name); + const auto boolean = value ? std::get_if(value) : nullptr; + return boolean ? *boolean : fallback; +} +double Number(const Map* map, const char* name, double fallback = 0) { + const auto value = Find(map, name); + if (value) { + if (const auto number = std::get_if(value)) return *number; + if (const auto number = std::get_if(value)) return *number; + } + return fallback; +} +} // namespace + +WindowChrome::WindowChrome(HWND window, HWND view, + flutter::BinaryMessenger* messenger) + : window_(window), view_(view) { + SetWindowSubclass(view_, ViewProc, reinterpret_cast(this), + reinterpret_cast(this)); + chrome_ = std::make_unique>( + messenger, "cutdex_native/window", &flutter::StandardMethodCodec::GetInstance()); + controls_channel_ = std::make_unique>( + messenger, "cutdex_native/window_controls", &flutter::StandardMethodCodec::GetInstance()); + chrome_->SetMethodCallHandler([this](const auto& call, auto result) { + const auto args = call.arguments(); + const auto map = args ? std::get_if(args) : nullptr; + if (call.method_name() == "configureChrome") { + const double height = Number(map, "headerHeight", 46); + if (!map || !std::isfinite(height) || height <= 0) { + result->Error("invalid_arguments", "Expected a positive header height"); + return; + } + Configure(Boolean(map, "enabled"), height, + Boolean(map, "interceptClose"), Boolean(map, "headerInteractive", true)); + result->Success(Value(enabled_)); + NotifyState(); + } else if (call.method_name() == "setHeaderInteractive") { + const auto active = args ? std::get_if(args) : nullptr; + if (!active) { result->Error("invalid_arguments", "Expected a boolean"); return; } + interactive_ = *active; + SetMaximizeHovered(false); + result->Success(); + } else if (call.method_name() == "minimize") { + ShowWindow(window_, SW_MINIMIZE); + result->Success(); + } else if (call.method_name() == "toggleMaximize") { + ShowWindow(window_, IsZoomed(window_) ? SW_RESTORE : SW_MAXIMIZE); + result->Success(); + } else if (call.method_name() == "close") { + // Defer destruction until the method reply has reached Flutter. + PostMessage(window_, WM_CLOSE, 0, 0); + result->Success(); + } else { + result->NotImplemented(); + } + }); + controls_channel_->SetMethodCallHandler([this](const auto& call, auto result) { + if (call.method_name() != "setHeaderControlRegion") { result->NotImplemented(); return; } + const auto args = call.arguments(); + const auto map = args ? std::get_if(args) : nullptr; + const auto id_value = Find(map, "id"); + const auto id = id_value ? std::get_if(id_value) : nullptr; + const auto rect_value = Find(map, "rect"); + if (!id || !rect_value) { result->Error("invalid_arguments", "Expected id and rect"); return; } + if (std::holds_alternative(*rect_value)) { + controls_.erase(*id); + } else if (const auto rect = std::get_if(rect_value)) { + Region region{Number(rect, "x"), Number(rect, "y"), + Number(rect, "width"), Number(rect, "height"), false}; + const auto role_value = Find(map, "role"); + const auto role = role_value ? std::get_if(role_value) : nullptr; + region.maximize = role && *role == "maximize"; + if (!std::isfinite(region.x) || !std::isfinite(region.y) || + !std::isfinite(region.width) || !std::isfinite(region.height) || + region.width < 0 || region.height < 0) { + result->Error("invalid_arguments", "Invalid control bounds"); return; + } + controls_[*id] = region; + } else { result->Error("invalid_arguments", "Invalid rect"); return; } + result->Success(); + }); +} + +WindowChrome::~WindowChrome() { + chrome_->SetMethodCallHandler(nullptr); + controls_channel_->SetMethodCallHandler(nullptr); + if (IsWindow(view_)) RemoveWindowSubclass(view_, ViewProc, reinterpret_cast(this)); +} + +void WindowChrome::Configure(bool enabled, double height, bool intercept_close, + bool interactive) { + // Plugin registration precedes the runner parenting the Flutter view. + window_ = GetAncestor(view_, GA_ROOT); + const bool changed = enabled_ != enabled; + enabled_ = enabled; + header_height_ = height; + intercept_close_ = intercept_close; + interactive_ = interactive; + if (!changed) return; + if (!enabled) { + maximize_pressed_ = false; + if (GetCapture() == window_) ReleaseCapture(); + SetMaximizeHovered(false); + } + // Retain WS_THICKFRAME, WS_SYSMENU and the caption command styles so Windows + // still owns resizing, Alt+Space, double-click zoom and drag-to-snap. + const MARGINS margins{0, 0, enabled ? 1 : 0, 0}; + DwmExtendFrameIntoClientArea(window_, &margins); + SetWindowPos(window_, nullptr, 0, 0, 0, 0, + SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED); +} + +LRESULT WindowChrome::HitTest(LPARAM position) const { + POINT point{GET_X_LPARAM(position), GET_Y_LPARAM(position)}; + RECT window_rect{}; + GetWindowRect(window_, &window_rect); + const UINT dpi = GetDpiForWindow(window_); + const int frame = GetSystemMetricsForDpi(SM_CXSIZEFRAME, dpi) + + GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi); + if (!IsZoomed(window_)) { + const bool left = point.x < window_rect.left + frame; + const bool right = point.x >= window_rect.right - frame; + const bool top = point.y < window_rect.top + frame; + const bool bottom = point.y >= window_rect.bottom - frame; + if (top) return left ? HTTOPLEFT : right ? HTTOPRIGHT : HTTOP; + if (bottom) return left ? HTBOTTOMLEFT : right ? HTBOTTOMRIGHT : HTBOTTOM; + if (left) return HTLEFT; + if (right) return HTRIGHT; + } + if (!interactive_) return HTCLIENT; + ScreenToClient(view_, &point); + const double scale = dpi / 96.0; + const double x = point.x / scale; + const double y = point.y / scale; + if (y < 0 || y >= header_height_) return HTCLIENT; + // Flutter owns button sizes and positions. Only the reported maximize region + // becomes a native hit target for Windows 11 Snap Layouts. + LRESULT hit = HTCAPTION; + for (const auto& entry : controls_) { + const auto& region = entry.second; + if (x >= region.x && x < region.x + region.width && + y >= region.y && y < region.y + region.height) { + // The caption strip is above workspace controls, including controls + // whose layout bounds extend beyond a clipped scroll viewport. + if (region.maximize) return HTMAXBUTTON; + hit = HTCLIENT; + } + } + return hit; +} + +void WindowChrome::NotifyState() { + chrome_->InvokeMethod("windowState", std::make_unique(Map{ + {Value("maximized"), Value(IsZoomed(window_) != FALSE)}, + {Value("maximizeHovered"), Value(maximize_hovered_)}})); +} + +void WindowChrome::SetMaximizeHovered(bool hovered) { + if (maximize_hovered_ == hovered) return; + maximize_hovered_ = hovered; + NotifyState(); +} + +std::optional WindowChrome::HandleMessage(UINT message, WPARAM wparam, + LPARAM lparam) { + if (!enabled_) return std::nullopt; + switch (message) { + case WM_NCCALCSIZE: { + // Let Windows keep the side/bottom resize borders, replacing only the top. + auto rect = wparam ? &reinterpret_cast(lparam)->rgrc[0] + : reinterpret_cast(lparam); + const LONG top = rect->top; + DefWindowProc(window_, message, wparam, lparam); + const UINT dpi = GetDpiForWindow(window_); + rect->top = top + (IsZoomed(window_) ? + GetSystemMetricsForDpi(SM_CYSIZEFRAME, dpi) + + GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi) : 0); + return 0; + } + case WM_NCHITTEST: + return HitTest(lparam); + case WM_NCMOUSEMOVE: { + SetMaximizeHovered(wparam == HTMAXBUTTON); + TRACKMOUSEEVENT tracking{sizeof(TRACKMOUSEEVENT), TME_LEAVE | TME_NONCLIENT, + window_, 0}; + TrackMouseEvent(&tracking); + // Continue through DWM/DefWindowProc so Snap Layouts can appear. + break; + } + case WM_NCMOUSELEAVE: + SetMaximizeHovered(false); + break; + case WM_NCLBUTTONDOWN: + case WM_NCLBUTTONDBLCLK: + if (wparam == HTMAXBUTTON) { + maximize_pressed_ = true; + SetCapture(window_); + return 0; + } + break; + case WM_LBUTTONUP: + if (maximize_pressed_) { + POINT point{GET_X_LPARAM(lparam), GET_Y_LPARAM(lparam)}; + ClientToScreen(window_, &point); + const bool activate = HitTest(MAKELPARAM(point.x, point.y)) == HTMAXBUTTON; + maximize_pressed_ = false; + ReleaseCapture(); + SetMaximizeHovered(false); + if (activate) ShowWindow(window_, IsZoomed(window_) ? SW_RESTORE : SW_MAXIMIZE); + return 0; + } + break; + case WM_CAPTURECHANGED: + case WM_CANCELMODE: + maximize_pressed_ = false; + break; + case WM_SIZE: + NotifyState(); + break; + case WM_CLOSE: + if (intercept_close_) { + chrome_->InvokeMethod("requestClose", nullptr); + return 0; + } + break; + case WM_DWMCOMPOSITIONCHANGED: { + const MARGINS margins{0, 0, 1, 0}; + DwmExtendFrameIntoClientArea(window_, &margins); + break; + } + } + LRESULT result = 0; + if (DwmDefWindowProc(window_, message, wparam, lparam, &result)) return result; + return std::nullopt; +} + +LRESULT CALLBACK WindowChrome::ViewProc(HWND window, UINT message, WPARAM wparam, + LPARAM lparam, UINT_PTR id, DWORD_PTR data) { + const auto chrome = reinterpret_cast(data); + if (message == WM_NCHITTEST && chrome->enabled_ && + chrome->HitTest(lparam) != HTCLIENT) { + // Flutter is a child HWND covering the client area. Let native caption and + // resize hits pass through to its parent while keeping controls in Flutter. + return HTTRANSPARENT; + } + if (message == WM_NCDESTROY) RemoveWindowSubclass(window, ViewProc, id); + return DefSubclassProc(window, message, wparam, lparam); +} diff --git a/packages/cutdex_native/windows/window_chrome.h b/packages/cutdex_native/windows/window_chrome.h new file mode 100644 index 0000000..db5ec92 --- /dev/null +++ b/packages/cutdex_native/windows/window_chrome.h @@ -0,0 +1,45 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +// Keeps the system resize frame and window commands around a Flutter header. +class WindowChrome { + public: + WindowChrome(HWND window, HWND view, flutter::BinaryMessenger* messenger); + ~WindowChrome(); + std::optional HandleMessage(UINT message, WPARAM wparam, LPARAM lparam); + + private: + struct Region { + double x, y, width, height; + bool maximize; + }; + void Configure(bool enabled, double height, bool intercept_close, + bool interactive); + LRESULT HitTest(LPARAM position) const; + void NotifyState(); + void SetMaximizeHovered(bool hovered); + static LRESULT CALLBACK ViewProc(HWND window, UINT message, WPARAM wparam, + LPARAM lparam, UINT_PTR id, DWORD_PTR data); + + HWND window_; + HWND view_; + bool enabled_ = false; + bool intercept_close_ = false; + bool interactive_ = true; + bool maximize_hovered_ = false; + bool maximize_pressed_ = false; + double header_height_ = 46; + std::map controls_; + std::unique_ptr> chrome_; + std::unique_ptr> controls_channel_; +}; diff --git a/packages/cutdex_ui/.gitignore b/packages/cutdex_ui/.gitignore new file mode 100644 index 0000000..dd5eb98 --- /dev/null +++ b/packages/cutdex_ui/.gitignore @@ -0,0 +1,31 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. +/pubspec.lock +**/doc/api/ +.dart_tool/ +.flutter-plugins-dependencies +/build/ +/coverage/ diff --git a/packages/cutdex_ui/.metadata b/packages/cutdex_ui/.metadata new file mode 100644 index 0000000..139ecd2 --- /dev/null +++ b/packages/cutdex_ui/.metadata @@ -0,0 +1,10 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "6a19cca56475dbfba1478ee68d7bd0c2ef891da1" + channel: "stable" + +project_type: package diff --git a/packages/cutdex_ui/README.md b/packages/cutdex_ui/README.md new file mode 100644 index 0000000..25ec606 --- /dev/null +++ b/packages/cutdex_ui/README.md @@ -0,0 +1,22 @@ +# cutdex_ui + +Cutdex workspace 内部 Flutter 包,维护通用组件与基础视觉主题,暂不发布。 + +- `theme.dart`:主题、语义颜色、间距与控件尺寸。 +- `widgets.dart`:菜单、选择框、对话框、输入控件、标签页、面板、下载进度、滚动渐隐等。 +- `cutdex_ui.dart`:上述两个入口。 + +组件通过参数接收文本、数据与回调;应用本地化与项目状态由调用方提供。选择框的空列表文案使用 `emptyLabel`,可搜索选择框同时传入 `searchHint`。对话框默认关闭提示由 Flutter 的 Material 本地化提供,也可传入 `closeLabel`。 + +`WorkspacePanel` 通过参数接收标题、控件与内容;`ResourceDownloadProgress` 接收字节数、速度与调用方提供的状态文案,`formatResourceBytes` 使用十进制字节单位。资源目录、下载任务与业务对话框由应用维护。 + +原生菜单通过 `cutdex_native` 展示,无法展示时回退到 Flutter 菜单。时间线与编辑器的业务样式由应用维护。 + +在应用根目录执行 `flutter pub get`;在本包目录执行: + +```sh +dart run build_runner build +flutter test +``` + +生成的 Freezed 文件随源码提交。测试维护在本包 `test/`,应用接线测试保留在应用中。 diff --git a/packages/cutdex_ui/analysis_options.yaml b/packages/cutdex_ui/analysis_options.yaml new file mode 100644 index 0000000..0add8e2 --- /dev/null +++ b/packages/cutdex_ui/analysis_options.yaml @@ -0,0 +1,8 @@ +include: package:flutter_lints/flutter.yaml +analyzer: + exclude: + - build/** + language: + strict-casts: true + strict-inference: true + strict-raw-types: true diff --git a/packages/cutdex_ui/lib/cutdex_ui.dart b/packages/cutdex_ui/lib/cutdex_ui.dart new file mode 100644 index 0000000..82711d5 --- /dev/null +++ b/packages/cutdex_ui/lib/cutdex_ui.dart @@ -0,0 +1,2 @@ +export 'theme.dart'; +export 'widgets.dart'; diff --git a/packages/cutdex_ui/lib/src/theme/app_theme.dart b/packages/cutdex_ui/lib/src/theme/app_theme.dart new file mode 100644 index 0000000..6d994de --- /dev/null +++ b/packages/cutdex_ui/lib/src/theme/app_theme.dart @@ -0,0 +1,1310 @@ +import 'package:flutter/foundation.dart'; + +import 'menu_metrics.dart'; + +import 'package:flutter/material.dart'; + +/// Workspace semantic colors and Codex desktop typography. +abstract final class AppTheme { + static ThemeData get penLight => _build(AppColors.penLight); + static ThemeData get penDark => _build(AppColors.penDark); + + /// Media canvas controls keep a dark palette in either workspace appearance. + static ThemeData get previewCanvasTheme => penDark; + + /// Fullscreen also places Material children on the black preview surface. + static ThemeData get previewFullscreenTheme { + final theme = previewCanvasTheme; + return theme.copyWith( + colorScheme: theme.colorScheme.copyWith( + surface: theme.extension()!.previewBackground, + ), + ); + } + + static Color itemHoverColor(BuildContext context, {required bool selected}) { + final theme = Theme.of(context); + return theme.colorScheme.onSurface.withValues( + alpha: selected + ? .05 + : theme.brightness == Brightness.dark + ? .078 + : .058, + ); + } + + static Color comboboxBackground(BuildContext context) { + final theme = Theme.of(context); + return theme.brightness == Brightness.dark + ? theme.colorScheme.surfaceContainerHighest.withValues(alpha: .3) + : Colors.transparent; + } + + static Color tabBorderColor( + BuildContext context, { + required bool selected, + required bool headerStyle, + }) { + final theme = Theme.of(context); + return selected && (headerStyle || theme.brightness == Brightness.dark) + ? theme.colorScheme.outlineVariant + : Colors.transparent; + } + + static Color dropOverlayBackground(BuildContext context) { + final theme = Theme.of(context); + return theme.colorScheme.scrim.withValues( + alpha: theme.brightness == Brightness.dark ? .62 : .38, + ); + } + + static TextStyle resourceProgressTextStyle(BuildContext context) { + final theme = Theme.of(context); + return theme.textTheme.bodyMedium!.copyWith( + color: theme.brightness == Brightness.dark + ? theme.colorScheme.onSurface.withValues(alpha: .55) + : theme.colorScheme.onSurfaceVariant, + ); + } + + static Color settingsSidebarBackground(BuildContext context) { + final theme = Theme.of(context); + return theme.brightness == Brightness.dark + ? AppColors.penDark.settingsSidebar + : theme.colorScheme.surfaceContainer; + } + + static Color switchTrackColor(BuildContext context, Set states) { + final theme = Theme.of(context); + final configured = theme.switchTheme.trackColor?.resolve(states); + if (configured != null) return configured; + if (states.contains(WidgetState.selected)) return theme.colorScheme.primary; + final input = theme.inputDecorationTheme.enabledBorder!.borderSide.color; + return input.withValues( + alpha: input.a * (theme.brightness == Brightness.dark ? .8 : 1), + ); + } + + static Color switchThumbColor(BuildContext context, Set states) { + final theme = Theme.of(context); + final configured = theme.switchTheme.thumbColor?.resolve(states); + if (configured != null) return configured; + if (theme.brightness == Brightness.dark) { + return states.contains(WidgetState.selected) + ? theme.colorScheme.onPrimary + : theme.colorScheme.onSurface; + } + return theme.colorScheme.surface; + } + + static String systemFontFamily(TargetPlatform platform) => switch (platform) { + TargetPlatform.macOS || TargetPlatform.iOS => '.AppleSystemUIFont', + TargetPlatform.windows => 'Segoe UI', + _ => 'sans-serif', + }; + + static Color popoverBackground(BuildContext context) { + final theme = Theme.of(context); + return theme.extension()?.popoverBackground ?? + theme.colorScheme.surfaceContainerHigh; + } + + /// The visible sidebar/content boundary in the opaque Codex window. + static Color sidebarDividerColor(BuildContext context) => + Theme.of(context).dividerColor; + + /// Side panels keep their Material children on the same surface. + static ThemeData panelTheme(ThemeData theme) { + final background = theme.colorScheme.surfaceContainerLow; + return theme.copyWith( + canvasColor: background, + colorScheme: theme.colorScheme.copyWith(surface: background), + ); + } + + static ThemeData timelinePanelTheme(ThemeData theme) { + final divider = theme.dividerColor; + return theme.copyWith( + dividerColor: divider, + dividerTheme: DividerThemeData(color: divider, thickness: 1, space: 1), + ); + } + + /// Inspector controls share the desktop UI type scale. + static ThemeData propertiesPanelTheme(ThemeData theme) { + final colors = theme.colorScheme; + final panelText = theme.textTheme; + final panelColors = colors.copyWith(surface: colors.surfaceContainerLow); + final composerBackground = theme + .extension()! + .composerBackground; + final hintColor = theme.brightness == Brightness.dark + ? colors.onSurface.withValues(alpha: .249) + : colors.onSurfaceVariant.withValues(alpha: .5); + const inputShape = OutlineInputBorder( + borderRadius: BorderRadius.all(Radius.circular(AppRadius.large)), + borderSide: BorderSide.none, + ); + return theme.copyWith( + canvasColor: colors.surfaceContainerLow, + colorScheme: panelColors, + textTheme: panelText, + primaryTextTheme: panelText, + inputDecorationTheme: theme.inputDecorationTheme.copyWith( + constraints: const BoxConstraints( + minHeight: AppControlSize.propertyControl, + ), + contentPadding: const EdgeInsets.symmetric( + horizontal: AppSpacing.controlHorizontal, + vertical: AppSpacing.tiny, + ), + fillColor: composerBackground, + hintStyle: panelText.bodyMedium?.copyWith(color: hintColor), + border: inputShape, + enabledBorder: inputShape, + disabledBorder: inputShape, + focusedBorder: inputShape, + errorBorder: inputShape, + focusedErrorBorder: inputShape, + ), + iconButtonTheme: IconButtonThemeData( + style: theme.iconButtonTheme.style?.copyWith( + minimumSize: const WidgetStatePropertyAll( + Size.square(AppControlSize.propertyControl), + ), + maximumSize: const WidgetStatePropertyAll( + Size.square(AppControlSize.propertyControl), + ), + fixedSize: const WidgetStatePropertyAll( + Size.square(AppControlSize.propertyControl), + ), + ), + ), + textButtonTheme: TextButtonThemeData( + style: theme.textButtonTheme.style?.copyWith( + textStyle: WidgetStatePropertyAll(panelText.labelLarge), + ), + ), + filledButtonTheme: FilledButtonThemeData( + style: theme.filledButtonTheme.style?.copyWith( + textStyle: WidgetStatePropertyAll(panelText.labelLarge), + ), + ), + outlinedButtonTheme: OutlinedButtonThemeData( + style: theme.outlinedButtonTheme.style?.copyWith( + textStyle: WidgetStatePropertyAll(panelText.labelLarge), + ), + ), + ); + } + + static TextStyle toolbarTextStyle(BuildContext context) => + Theme.of(context).textTheme.bodyMedium! + .copyWith(fontSize: 13, height: 18 / 13); + + /// Codex desktop's compact heading-sm: 13px, 1.4 line height, medium ink. + static TextStyle propertySectionTitleStyle(BuildContext context) => + Theme.of(context).textTheme.labelLarge!.copyWith( + height: 1.4, + color: Theme.of(context).colorScheme.onSurface, + ); + + static ButtonStyle toolbarButtonStyle(BuildContext context) => ButtonStyle( + textStyle: WidgetStatePropertyAll(toolbarTextStyle(context)), + minimumSize: const WidgetStatePropertyAll( + Size(0, AppControlSize.headerButton), + ), + padding: const WidgetStatePropertyAll( + EdgeInsets.symmetric(horizontal: AppSpacing.small), + ), + ); + + static ThemeData dialogContentTheme(ThemeData theme) { + const buttonSize = WidgetStatePropertyAll(Size(0, 32)); + const buttonPadding = WidgetStatePropertyAll( + EdgeInsets.symmetric(horizontal: 16, vertical: AppSpacing.gap), + ); + final buttonText = WidgetStatePropertyAll( + theme.textTheme.labelLarge?.copyWith(fontSize: 14, height: 20 / 14), + ); + final dark = theme.brightness == Brightness.dark; + final inputBorder = OutlineInputBorder( + borderRadius: BorderRadius.circular(AppRadius.large), + borderSide: BorderSide( + color: dark + ? AppColors.penDark.dialogBorder + : theme.colorScheme.outlineVariant, + ), + ); + return theme.copyWith( + textTheme: theme.textTheme.copyWith( + bodyMedium: theme.textTheme.bodyMedium?.copyWith( + fontSize: 14, + height: 20 / 14, + ), + ), + inputDecorationTheme: theme.inputDecorationTheme.copyWith( + constraints: const BoxConstraints(minHeight: 36), + fillColor: dark + ? AppColors.penDark.dialogInputBackground + : theme.colorScheme.surface, + contentPadding: const EdgeInsets.symmetric( + horizontal: 10, + vertical: AppSpacing.small, + ), + border: inputBorder, + enabledBorder: inputBorder, + focusedBorder: inputBorder.copyWith( + borderSide: BorderSide( + color: dark + ? AppColors.penDark.dialogFocusBorder + : theme.colorScheme.outline, + ), + ), + ), + textButtonTheme: TextButtonThemeData( + style: theme.textButtonTheme.style?.copyWith( + minimumSize: buttonSize, + padding: buttonPadding, + textStyle: buttonText, + ), + ), + filledButtonTheme: FilledButtonThemeData( + style: theme.filledButtonTheme.style?.copyWith( + minimumSize: buttonSize, + padding: buttonPadding, + textStyle: buttonText, + ), + ), + outlinedButtonTheme: OutlinedButtonThemeData( + style: theme.outlinedButtonTheme.style?.copyWith( + minimumSize: buttonSize, + padding: buttonPadding, + textStyle: buttonText, + ), + ), + ); + } + + static ThemeData settingsContentTheme(ThemeData theme) { + final base = dialogContentTheme(theme); + final dark = base.brightness == Brightness.dark; + final colors = base.colorScheme; + final text = base.textTheme; + final border = dark + ? AppColors.penDark.settingsBorder + : colors.outlineVariant; + final body = text.bodyMedium!.copyWith( + fontSize: 13, + height: 18 / 13, + letterSpacing: 0, + fontWeight: FontWeight.w400, + fontVariations: const [FontVariation('wght', 400)], + ); + ButtonStyle? control(ButtonStyle? style) => style?.copyWith( + minimumSize: const WidgetStatePropertyAll( + Size(0, AppSettingsMetrics.controlHeight), + ), + padding: const WidgetStatePropertyAll( + EdgeInsets.symmetric(horizontal: 10, vertical: 5), + ), + textStyle: WidgetStatePropertyAll(body), + iconSize: const WidgetStatePropertyAll(16), + shape: const WidgetStatePropertyAll( + RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(10)), + ), + ), + ); + return base.copyWith( + colorScheme: colors.copyWith( + surface: dark ? AppColors.penDark.background : colors.surface, + surfaceContainer: dark + ? AppColors.penDark.settingsContainer + : colors.surfaceContainer, + outlineVariant: border, + ), + dividerTheme: base.dividerTheme.copyWith(color: border, thickness: 1), + textTheme: text.copyWith( + bodyMedium: body, + labelLarge: body, + labelMedium: body, + bodySmall: text.bodySmall?.copyWith(fontSize: 12, height: 16 / 12), + titleLarge: text.headlineSmall?.copyWith( + fontSize: 28, + height: 36 / 28, + fontWeight: FontWeight.w600, + fontVariations: const [FontVariation('wght', 600)], + ), + ), + textButtonTheme: TextButtonThemeData( + style: control(base.textButtonTheme.style), + ), + filledButtonTheme: FilledButtonThemeData( + style: control(base.filledButtonTheme.style)?.copyWith( + backgroundColor: WidgetStateProperty.resolveWith( + (states) => colors.onSurface.withValues( + alpha: states.contains(WidgetState.disabled) ? .3 : 1, + ), + ), + foregroundColor: WidgetStatePropertyAll(colors.surface), + side: const WidgetStatePropertyAll(BorderSide.none), + ), + ), + outlinedButtonTheme: OutlinedButtonThemeData( + style: control(base.outlinedButtonTheme.style)?.copyWith( + backgroundColor: WidgetStatePropertyAll( + dark ? AppColors.penDark.settingsControlBackground : colors.surface, + ), + side: WidgetStatePropertyAll(BorderSide(color: border)), + ), + ), + switchTheme: base.switchTheme.copyWith( + trackColor: WidgetStateProperty.resolveWith( + (states) => states.contains(WidgetState.selected) + ? AppColors.settingsSwitchAccent + : (dark ? AppColors.penDark : AppColors.penLight) + .settingsSwitchTrack, + ), + thumbColor: const WidgetStatePropertyAll(Colors.white), + ), + ); + } + + static ThemeData dialogActionTheme(ThemeData theme) { + final colors = theme.colorScheme; + final dark = theme.brightness == Brightness.dark; + return theme.copyWith( + textButtonTheme: TextButtonThemeData( + style: theme.textButtonTheme.style?.copyWith( + backgroundColor: WidgetStatePropertyAll( + (dark ? AppColors.penDark : AppColors.penLight) + .dialogActionBackground, + ), + side: WidgetStatePropertyAll( + BorderSide( + color: dark + ? AppColors.penDark.dialogBorder + : colors.outlineVariant, + ), + ), + foregroundColor: WidgetStatePropertyAll(colors.onSurface), + ), + ), + filledButtonTheme: FilledButtonThemeData( + style: theme.filledButtonTheme.style?.copyWith( + backgroundColor: WidgetStatePropertyAll(colors.onSurface), + foregroundColor: WidgetStatePropertyAll(colors.surface), + side: const WidgetStatePropertyAll(BorderSide.none), + ), + ), + ); + } + + static ButtonStyle panelTabStyle( + BuildContext context, { + required bool selected, + }) { + final colors = Theme.of(context).colorScheme; + final ink = colors.onSurface; + return ButtonStyle( + minimumSize: const WidgetStatePropertyAll( + Size(0, AppControlSize.headerButton), + ), + maximumSize: const WidgetStatePropertyAll( + Size(double.infinity, AppControlSize.headerButton), + ), + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + textStyle: WidgetStatePropertyAll(toolbarTextStyle(context)), + padding: const WidgetStatePropertyAll( + EdgeInsets.symmetric(horizontal: AppSpacing.small), + ), + shape: WidgetStatePropertyAll( + RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)), + ), + foregroundColor: WidgetStatePropertyAll( + selected + ? ink + : Theme.of(context).brightness == Brightness.dark + ? ink.withValues(alpha: .498) + : colors.onSurfaceVariant, + ), + backgroundColor: WidgetStatePropertyAll( + selected ? ink.withValues(alpha: .05) : Colors.transparent, + ), + overlayColor: WidgetStateProperty.resolveWith((states) { + if (states.contains(WidgetState.hovered) || + states.contains(WidgetState.focused) || + states.contains(WidgetState.pressed)) { + return selected + ? ink.withValues(alpha: .05) + : ink.withValues(alpha: .078); + } + return Colors.transparent; + }), + ); + } + + static ButtonStyle iconButtonStyle(BuildContext context) { + final theme = Theme.of(context); + return _iconButtonStyle(theme.colorScheme.onSurface, theme.brightness); + } + + static ButtonStyle _iconButtonStyle(Color ink, Brightness brightness) { + final dark = brightness == Brightness.dark; + final inactive = ink.withValues(alpha: dark ? .498 : .51); + final hover = ink.withValues(alpha: dark ? .078 : .058); + return ButtonStyle( + foregroundColor: WidgetStateProperty.resolveWith((states) { + final color = states.contains(WidgetState.selected) ? ink : inactive; + return states.contains(WidgetState.disabled) + ? color.withValues(alpha: color.a * .5) + : color; + }), + backgroundColor: WidgetStateProperty.resolveWith((states) { + if (!states.contains(WidgetState.selected)) return Colors.transparent; + final interacting = + !states.contains(WidgetState.disabled) && + (states.contains(WidgetState.hovered) || + states.contains(WidgetState.focused) || + states.contains(WidgetState.pressed)); + return ink.withValues(alpha: interacting ? .10 : .05); + }), + overlayColor: WidgetStateProperty.resolveWith((states) { + // Selected buttons resolve their entire background above, without an + // extra overlay: Codex secondary uses bg-text/5 and hover:bg-text/10. + if (states.contains(WidgetState.disabled) || + states.contains(WidgetState.selected)) { + return Colors.transparent; + } + if (states.contains(WidgetState.hovered) || + states.contains(WidgetState.focused) || + states.contains(WidgetState.pressed)) { + return hover; + } + return Colors.transparent; + }), + ); + } + + static ButtonStyle primaryIconButtonStyle(BuildContext context) { + final colors = Theme.of(context).colorScheme; + return ButtonStyle( + backgroundColor: WidgetStateProperty.resolveWith( + (states) => states.contains(WidgetState.disabled) + ? colors.onSurface.withValues(alpha: 0.12) + : colors.primary, + ), + foregroundColor: WidgetStateProperty.resolveWith( + (states) => states.contains(WidgetState.disabled) + ? colors.onSurface.withValues(alpha: 0.38) + : colors.onPrimary, + ), + ); + } + + static BoxDecoration userMessageDecoration(BuildContext context) => + BoxDecoration( + color: Theme.of(context).colorScheme.onSurface.withValues(alpha: .08), + borderRadius: const BorderRadius.all(Radius.circular(20)), + ); + + static TextStyle chatMessageTextStyle(BuildContext context) => + Theme.of(context).textTheme.bodyMedium!.copyWith( + fontSize: 14, + height: 1.5, + color: Theme.of(context).colorScheme.onSurface, + ); + + static TextStyle chatMetaTextStyle(BuildContext context) => + Theme.of(context).textTheme.bodySmall!.copyWith( + fontSize: 13, + height: 18 / 13, + color: Theme.of(context).colorScheme.onSurface.withValues(alpha: .5), + ); + + static TextStyle inputTextStyle(BuildContext context) => + Theme.of(context).textTheme.bodyMedium!; + + static TextStyle composerTextStyle(BuildContext context) => + AppSidebarTypography.style( + context, + fontSize: 13, + height: 20 / 13, + color: Theme.of(context).colorScheme.onSurface, + ).copyWith(leadingDistribution: TextLeadingDistribution.even); + + static Color composerReferenceColor(BuildContext context) { + final theme = Theme.of(context); + return Color.lerp( + theme.colorScheme.outline, + theme.colorScheme.onSurface, + theme.brightness == Brightness.dark ? .35 : .15, + )!; + } + + /// Composer action bar composites the dark elevated-secondary alpha surface. + static Color composerUtilityBackground(BuildContext context) { + final theme = Theme.of(context); + return theme.brightness == Brightness.dark + ? Color.alphaBlend( + AppColors.penDark.composerUtilityOverlay, + theme.colorScheme.surface, + ) + : theme.colorScheme.surfaceContainerLow; + } + + static TextStyle composerHintStyle(BuildContext context) { + final tertiary = AppSidebarColors.of(context).tertiary; + return composerTextStyle(context) + .copyWith(color: tertiary.withValues(alpha: tertiary.a * 0.5)); + } + + /// Match the glyph size, rather than the editable line's leading. + static double inputCursorHeight(BuildContext context) => + MediaQuery.textScalerOf(context).scale(inputTextStyle(context).fontSize!); + + static double composerCursorHeight(BuildContext context) => + MediaQuery.textScalerOf(context) + .scale(composerTextStyle(context).fontSize!); + + static const composerInputDecoration = InputDecoration( + border: InputBorder.none, + enabledBorder: InputBorder.none, + focusedBorder: InputBorder.none, + disabledBorder: InputBorder.none, + filled: false, + contentPadding: EdgeInsets.only(left: 12, top: 12, right: 8), + ); + + static ThemeData _build(AppColors palette) { + final brightness = palette.brightness; + final colors = ColorScheme( + brightness: brightness, + primary: palette.primary, + onPrimary: palette.primaryForeground, + primaryContainer: palette.accent, + onPrimaryContainer: palette.foreground, + primaryFixed: palette.primary, + primaryFixedDim: palette.mutedForeground, + onPrimaryFixed: palette.card, + onPrimaryFixedVariant: palette.accent, + secondary: palette.foreground, + onSecondary: palette.primaryForeground, + secondaryContainer: palette.accent, + onSecondaryContainer: palette.foreground, + secondaryFixed: palette.primary, + secondaryFixedDim: palette.mutedForeground, + onSecondaryFixed: palette.card, + onSecondaryFixedVariant: palette.accent, + tertiary: palette.foreground, + onTertiary: palette.primaryForeground, + tertiaryContainer: palette.accent, + onTertiaryContainer: palette.foreground, + tertiaryFixed: palette.primary, + tertiaryFixedDim: palette.mutedForeground, + onTertiaryFixed: palette.card, + onTertiaryFixedVariant: palette.accent, + surface: palette.background, + onSurface: palette.foreground, + onSurfaceVariant: palette.mutedForeground, + surfaceDim: palette.background, + surfaceBright: palette.accent, + surfaceContainerLowest: palette.background, + surfaceContainerLow: palette.sidebar, + surfaceContainer: palette.card, + surfaceContainerHigh: palette.accent, + surfaceContainerHighest: palette.accent, + surfaceTint: Colors.transparent, + outline: palette.ring, + outlineVariant: palette.border, + inverseSurface: palette.foreground, + onInverseSurface: palette.card, + inversePrimary: palette.accent, + error: palette.destructive, + onError: palette.background, + errorContainer: palette.destructiveBackground, + onErrorContainer: palette.destructive, + shadow: Colors.black, + scrim: Colors.black, + ); + final text = _typography(palette); + final controlShape = const RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(AppRadius.menuItem)), + ); + final cardShape = RoundedRectangleBorder( + borderRadius: const BorderRadius.all(Radius.circular(20)), + side: BorderSide(color: palette.border), + ); + const dialogShape = RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(AppRadius.dialog)), + ); + final inputBorder = OutlineInputBorder( + borderRadius: const BorderRadius.all(Radius.circular(AppRadius.large)), + borderSide: BorderSide(color: palette.input), + ); + final buttonStyle = ButtonStyle( + shape: WidgetStatePropertyAll(controlShape), + minimumSize: const WidgetStatePropertyAll( + Size(0, AppControlSize.standard), + ), + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + textStyle: WidgetStatePropertyAll(text.labelLarge), + iconSize: const WidgetStatePropertyAll(AppIconSize.standard), + padding: const WidgetStatePropertyAll( + EdgeInsets.symmetric( + horizontal: AppSpacing.controlHorizontal, + vertical: AppSpacing.tiny, + ), + ), + overlayColor: WidgetStateProperty.resolveWith((states) { + if (states.contains(WidgetState.focused)) { + return palette.ring.withValues(alpha: 0.3); + } + if (states.contains(WidgetState.hovered) || + states.contains(WidgetState.pressed)) { + return palette.foreground.withValues(alpha: 0.05); + } + return null; + }), + ); + final foreground = WidgetStateProperty.resolveWith( + (states) => states.contains(WidgetState.disabled) + ? palette.foreground.withValues(alpha: 0.5) + : palette.foreground, + ); + return ThemeData( + brightness: brightness, + useMaterial3: true, + colorScheme: colors, + fontFamily: systemFontFamily(defaultTargetPlatform), + fontFamilyFallback: const [ + 'PingFang SC', + 'Noto Sans CJK SC', + 'sans-serif', + ], + textTheme: text, + primaryTextTheme: text, + scaffoldBackgroundColor: palette.background, + canvasColor: palette.background, + disabledColor: palette.foreground.withValues(alpha: 0.5), + hoverColor: palette.accent, + focusColor: palette.ring.withValues(alpha: 0.3), + splashFactory: NoSplash.splashFactory, + dividerColor: palette.divider, + visualDensity: VisualDensity.standard, + materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, + appBarTheme: AppBarThemeData( + backgroundColor: palette.background, + foregroundColor: palette.foreground, + surfaceTintColor: Colors.transparent, + elevation: 0, + titleTextStyle: text.titleLarge, + toolbarHeight: AppControlSize.panelHeader, + ), + dividerTheme: DividerThemeData( + color: palette.divider, + thickness: brightness == Brightness.dark ? 0.5 : 1, + space: 1, + ), + iconTheme: IconThemeData( + color: palette.mutedForeground, + size: AppIconSize.standard, + ), + iconButtonTheme: IconButtonThemeData( + style: _iconButtonStyle(palette.foreground, brightness) + .merge(buttonStyle) + .copyWith( + minimumSize: const WidgetStatePropertyAll( + Size.square(AppControlSize.compact), + ), + padding: const WidgetStatePropertyAll( + EdgeInsets.all(AppSpacing.tiny), + ), + ), + ), + cardTheme: CardThemeData( + color: palette.card, + surfaceTintColor: Colors.transparent, + elevation: 0, + margin: EdgeInsets.zero, + shape: cardShape, + clipBehavior: Clip.antiAlias, + ), + dialogTheme: DialogThemeData( + backgroundColor: palette.popover, + surfaceTintColor: Colors.transparent, + shape: dialogShape, + titleTextStyle: text.headlineSmall?.copyWith( + fontWeight: FontWeight.w600, + fontVariations: const [FontVariation('wght', 600)], + ), + contentTextStyle: text.bodyMedium?.copyWith( + fontSize: 14, + height: 20 / 14, + ), + actionsPadding: const EdgeInsets.all(AppSpacing.large), + barrierColor: Colors.black.withValues(alpha: 0.5), + ), + inputDecorationTheme: InputDecorationThemeData( + constraints: const BoxConstraints(minHeight: AppControlSize.input), + isDense: true, + filled: true, + fillColor: palette.inputFill, + border: inputBorder, + enabledBorder: inputBorder, + disabledBorder: inputBorder, + focusedBorder: inputBorder.copyWith( + borderSide: BorderSide(color: palette.ring, width: 2), + ), + errorBorder: inputBorder.copyWith( + borderSide: BorderSide(color: palette.destructive), + ), + focusedErrorBorder: inputBorder.copyWith( + borderSide: BorderSide(color: palette.destructive, width: 2), + ), + contentPadding: const EdgeInsets.symmetric( + horizontal: AppSpacing.controlHorizontal, + vertical: AppSpacing.inputVertical, + ), + hintStyle: text.bodyMedium?.copyWith(color: palette.mutedForeground), + labelStyle: text.bodyMedium?.copyWith(color: palette.mutedForeground), + errorStyle: text.bodySmall?.copyWith(color: palette.destructive), + ), + textSelectionTheme: TextSelectionThemeData( + cursorColor: palette.foreground, + selectionColor: palette.ring.withValues(alpha: 0.5), + selectionHandleColor: palette.foreground, + ), + filledButtonTheme: FilledButtonThemeData( + style: buttonStyle.copyWith( + backgroundColor: WidgetStateProperty.resolveWith( + (states) => states.contains(WidgetState.disabled) + ? palette.buttonBackground.withValues(alpha: 0.5) + : palette.buttonBackground, + ), + foregroundColor: WidgetStatePropertyAll(palette.foreground), + side: WidgetStatePropertyAll(BorderSide(color: palette.buttonBorder)), + ), + ), + outlinedButtonTheme: OutlinedButtonThemeData( + style: buttonStyle.copyWith( + side: WidgetStatePropertyAll(BorderSide(color: palette.buttonBorder)), + foregroundColor: foreground, + ), + ), + textButtonTheme: TextButtonThemeData( + style: buttonStyle.copyWith(foregroundColor: foreground), + ), + popupMenuTheme: PopupMenuThemeData( + textStyle: text.bodyMedium, + color: palette.popover, + surfaceTintColor: Colors.transparent, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(AppMenuMetrics.radius), + side: BorderSide( + color: palette.border, + width: AppMenuMetrics.borderWidth, + ), + ), + menuPadding: const EdgeInsets.all(AppMenuMetrics.gutter), + ), + menuTheme: MenuThemeData( + style: MenuStyle( + backgroundColor: WidgetStatePropertyAll(palette.popover), + surfaceTintColor: const WidgetStatePropertyAll(Colors.transparent), + side: WidgetStatePropertyAll( + BorderSide( + color: palette.border, + width: AppMenuMetrics.borderWidth, + ), + ), + padding: const WidgetStatePropertyAll( + EdgeInsets.all(AppMenuMetrics.gutter), + ), + shape: const WidgetStatePropertyAll( + RoundedRectangleBorder( + borderRadius: BorderRadius.all( + Radius.circular(AppMenuMetrics.radius), + ), + ), + ), + ), + ), + menuButtonTheme: MenuButtonThemeData( + style: buttonStyle.copyWith( + textStyle: WidgetStatePropertyAll( + text.bodyMedium?.copyWith( + height: AppMenuMetrics.lineHeight / AppMenuMetrics.fontSize, + ), + ), + minimumSize: const WidgetStatePropertyAll( + Size(0, AppMenuMetrics.rowHeight), + ), + iconSize: const WidgetStatePropertyAll(AppMenuMetrics.iconSize), + padding: const WidgetStatePropertyAll( + EdgeInsets.symmetric( + horizontal: AppMenuMetrics.iconGap, + vertical: 5, + ), + ), + shape: const WidgetStatePropertyAll( + RoundedRectangleBorder( + borderRadius: BorderRadius.all( + Radius.circular(AppMenuMetrics.itemRadius), + ), + ), + ), + ), + ), + listTileTheme: ListTileThemeData( + minTileHeight: AppControlSize.standard, + minVerticalPadding: AppSpacing.tiny, + horizontalTitleGap: AppSpacing.small, + minLeadingWidth: AppIconSize.standard, + iconColor: palette.mutedForeground, + textColor: palette.foreground, + selectedColor: palette.foreground, + selectedTileColor: palette.accent, + titleTextStyle: text.bodyMedium, + subtitleTextStyle: text.bodySmall, + contentPadding: const EdgeInsets.symmetric( + horizontal: AppSpacing.compact, + ), + ), + snackBarTheme: SnackBarThemeData( + backgroundColor: palette.card, + contentTextStyle: text.bodyMedium, + behavior: SnackBarBehavior.floating, + shape: cardShape, + ), + tooltipTheme: TooltipThemeData( + textStyle: text.bodySmall?.copyWith(color: palette.card), + decoration: ShapeDecoration( + color: palette.foreground, + shape: controlShape, + ), + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.small, + vertical: AppSpacing.tiny, + ), + ), + progressIndicatorTheme: ProgressIndicatorThemeData( + color: palette.primary, + linearMinHeight: 2, + ), + checkboxTheme: CheckboxThemeData( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(AppRadius.small), + ), + side: BorderSide(color: palette.input), + fillColor: WidgetStateProperty.resolveWith( + (states) => states.contains(WidgetState.selected) + ? palette.primary + : palette.inputFill, + ), + checkColor: WidgetStatePropertyAll(palette.primaryForeground), + materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + switchTheme: SwitchThemeData( + trackOutlineColor: const WidgetStatePropertyAll(Colors.transparent), + trackColor: WidgetStateProperty.resolveWith( + (states) => states.contains(WidgetState.selected) + ? palette.primary + : palette.input, + ), + thumbColor: WidgetStateProperty.resolveWith( + (states) => states.contains(WidgetState.selected) + ? palette.primaryForeground + : palette.foreground, + ), + ), + scrollbarTheme: ScrollbarThemeData( + thickness: const WidgetStatePropertyAll(6), + radius: const Radius.circular(3), + thumbColor: WidgetStateProperty.resolveWith((states) { + final interacting = + states.contains(WidgetState.hovered) || + states.contains(WidgetState.dragged) || + states.contains(WidgetState.pressed); + return palette.foreground.withValues( + alpha: brightness == Brightness.dark + ? (interacting ? .156 : .084) + : (interacting ? .126 : .084), + ); + }), + trackColor: const WidgetStatePropertyAll(Colors.transparent), + trackBorderColor: const WidgetStatePropertyAll(Colors.transparent), + ), + extensions: [ + AppSurfaces( + previewBackground: Colors.black, + composerBackground: palette.composer, + popoverBackground: palette.popover, + errorText: text.bodyMedium!.copyWith(color: palette.destructive), + ), + ], + ); + } + + static TextTheme _typography(AppColors palette) { + TextStyle style( + double size, + double lineHeight, { + FontWeight weight = FontWeight.w400, + Color? color, + }) => TextStyle( + inherit: false, + fontFamily: systemFontFamily(defaultTargetPlatform), + fontFamilyFallback: const [ + 'PingFang SC', + 'Noto Sans CJK SC', + 'sans-serif', + ], + textBaseline: TextBaseline.alphabetic, + fontSize: size, + height: lineHeight / size, + fontWeight: weight, + fontVariations: [ + FontVariation( + 'wght', + weight == FontWeight.w400 ? 430 : weight.value.toDouble(), + ), + ], + letterSpacing: 0, + color: color ?? palette.foreground, + ); + return TextTheme( + displayLarge: style(48, 56, weight: FontWeight.w600), + displayMedium: style(36, 44, weight: FontWeight.w600), + displaySmall: style(30, 38, weight: FontWeight.w600), + headlineLarge: style(28, 36, weight: FontWeight.w600), + headlineMedium: style(24, 32, weight: FontWeight.w600), + headlineSmall: style(20, 28, weight: FontWeight.w600), + titleLarge: style(18, 24, weight: FontWeight.w600), + titleMedium: style(14, 21, weight: FontWeight.w500), + titleSmall: style(14, 20, weight: FontWeight.w500), + bodyLarge: style(16, 24), + bodyMedium: style(13, 20), + bodySmall: style(12, 18, color: palette.mutedForeground), + labelLarge: style(13, 20, weight: FontWeight.w500), + labelMedium: style(12, 18, weight: FontWeight.w500), + labelSmall: style(12, 18, color: palette.mutedForeground), + ); + } +} + +/// Pen colors with editor-specific workspace and side-panel surfaces. +enum AppColors { + penLight, + penDark; + + bool get _dark => this == penDark; + Brightness get brightness => _dark ? Brightness.dark : Brightness.light; + + Color get background => switch (this) { + penLight => const Color(0xFFF6F6F6), + penDark => const Color(0xFF111111), + }; + Color get foreground => switch (this) { + penDark => const Color(0xFFFCFCFC), + penLight => const Color(0xFF020202), + }; + Color get card => switch (this) { + penLight => const Color(0xFFFAFAFA), + penDark => const Color(0xFF27272A), + }; + Color get popover => _dark ? const Color(0xFF242424) : card; + Color get sidebar => switch (this) { + penLight => const Color(0xFFFAFAFA), + // Project sidebar sampled from Codex's opaque-window screenshot (2026-09-28). + penDark => const Color(0xFF151515), + }; + Color get primary => switch (this) { + penLight => const Color(0xFF18181B), + penDark => const Color(0xFFF4F4F5), + }; + Color get primaryForeground => switch (this) { + penLight => const Color(0xFFFAFAFA), + penDark => const Color(0xFF18181B), + }; + Color get accent => switch (this) { + penDark => const Color(0xFF3F3F46), + penLight => const Color(0xFFECECEE), + }; + Color get mutedForeground => switch (this) { + penLight => const Color(0xFF71717A), + penDark => const Color(0xFFFCFCFC).withValues(alpha: 0.71), + }; + Color get ring => const Color(0xFF3B82F6); + Color get border => switch (this) { + penLight => const Color(0xFFE4E4E7), + penDark => const Color(0xFFFCFCFC).withValues(alpha: 0.084), + }; + Color get divider => _dark ? const Color(0xFF303030) : border; + Color get input => switch (this) { + penLight => const Color(0x0A020202), + penDark => const Color(0x1AC8C8C8), + }; + Color get inputFill => switch (this) { + penLight => const Color(0x0A020202), + penDark => const Color(0x1AC8C8C8), + }; + Color get buttonBackground => switch (this) { + penLight => const Color(0xFFFAFAFA), + penDark => const Color(0xFF18181B), + }; + Color get buttonBorder => switch (this) { + penLight => const Color(0xFFE4E4E7), + penDark => const Color(0xFF38383C), + }; + Color get destructive => + _dark ? const Color(0xFFFF6467) : const Color(0xFFE7000B); + Color get destructiveBackground => + destructive.withValues(alpha: _dark ? 0.2 : 0.1); + + Color get visualClip => _dark ? const Color(0xFF2F2F2F) : accent; + Color get composer => _dark ? const Color(0xFF2F2F2F) : background; + Color get composerUtilityOverlay => + _dark ? foreground.withValues(alpha: .032) : Colors.transparent; + Color get dialogBorder => _dark ? const Color(0xFF3C3C3C) : border; + Color get dialogInputBackground => + _dark ? const Color(0xFF262626) : background; + Color get dialogFocusBorder => _dark ? const Color(0xFF6084AF) : ring; + Color get dialogActionBackground => + _dark ? const Color(0xFF2B2B2B) : const Color(0xFFF0F0F0); + Color get settingsSidebar => _dark ? const Color(0xFF141414) : card; + Color get settingsContainer => _dark ? const Color(0xFF1C1C1C) : card; + Color get settingsBorder => _dark ? const Color(0xFF2E2E2E) : border; + Color get settingsControlBackground => + _dark ? const Color(0xFF262626) : background; + Color get settingsSwitchTrack => + _dark ? const Color(0xFF333333) : const Color(0xFFD0D0D0); + static const settingsSwitchAccent = Color(0xFF007AFF); + + AppSidebarColors resolveSidebarColors( + ColorScheme colors, { + required Color disabledColor, + }) { + if (_dark) { + final ink = foreground; + return AppSidebarColors( + primary: ink.withValues(alpha: .85), + secondary: ink.withValues(alpha: .71), + tertiary: ink.withValues(alpha: .498), + disabled: ink.withValues(alpha: .85 * .6), + hover: ink.withValues(alpha: .078), + section: ink.withValues(alpha: .498 * .75), + ); + } + return AppSidebarColors( + primary: colors.onSurface, + secondary: colors.onSurfaceVariant, + tertiary: colors.onSurfaceVariant, + disabled: disabledColor, + hover: colors.onSurface.withValues(alpha: .0535), + section: colors.onSurfaceVariant.withValues(alpha: .75), + ); + } +} + +/// Styles with product semantics that Material's built-in themes do not expose. +@immutable +class AppSurfaces extends ThemeExtension { + const AppSurfaces({ + required this.previewBackground, + required this.composerBackground, + required this.popoverBackground, + required this.errorText, + }); + final Color previewBackground; + final Color composerBackground; + final Color popoverBackground; + final TextStyle errorText; + + static AppSurfaces of(BuildContext context) => + Theme.of(context).extension()!; + + @override + AppSurfaces copyWith({ + Color? previewBackground, + Color? composerBackground, + Color? popoverBackground, + TextStyle? errorText, + }) => AppSurfaces( + previewBackground: previewBackground ?? this.previewBackground, + composerBackground: composerBackground ?? this.composerBackground, + popoverBackground: popoverBackground ?? this.popoverBackground, + errorText: errorText ?? this.errorText, + ); + + @override + AppSurfaces lerp(covariant AppSurfaces? other, double t) { + if (other == null) return this; + return AppSurfaces( + previewBackground: Color.lerp( + previewBackground, + other.previewBackground, + t, + )!, + composerBackground: Color.lerp( + composerBackground, + other.composerBackground, + t, + )!, + popoverBackground: Color.lerp( + popoverBackground, + other.popoverBackground, + t, + )!, + errorText: TextStyle.lerp(errorText, other.errorText, t)!, + ); + } +} + +abstract final class AppSidebarMetrics { + static const rowHeight = 30.0; + static const modeHeight = 32.0; + static const outerPadding = 8.0; + static const cellPadding = 8.0; + static const iconSize = 16.0; + static const iconGap = 0.0; + // hZ: row-sized icon slot, -3px margins, and 4px padding on each side. + static const iconSlotWidth = rowHeight + 2; + static const actionSize = 24.0; + static const radius = 10.0; + static const fontSize = 14.0; + static const conversationFontSize = 14.0; + static const conversationLineHeight = 20 / conversationFontSize; + static const lineHeight = 1.5; + static const sectionFontSize = 14.0; + static const sectionHeight = 25.0; + static const sectionGap = 4.0; + static const rowGap = 1.0; + static const projectGap = 1.0; + static const hintFontSize = 12.0; + static const titleFontSize = 18.0; + static const titleLineHeight = 24 / titleFontSize; + static const textInset = iconSlotWidth; + static const rowPadding = EdgeInsets.symmetric(horizontal: outerPadding); +} + +/// Sidebar typography retains its own size and foreground hierarchy. +abstract final class AppSidebarTypography { + static TextStyle style( + BuildContext context, { + double fontSize = AppSidebarMetrics.fontSize, + double height = AppSidebarMetrics.lineHeight, + FontWeight weight = FontWeight.w400, + Color? color, + }) => TextStyle( + fontFamily: AppTheme.systemFontFamily(Theme.of(context).platform), + fontFamilyFallback: const ['PingFang SC', 'Noto Sans CJK SC', 'sans-serif'], + fontSize: fontSize, + height: height, + fontWeight: weight, + fontVariations: [ + FontVariation( + 'wght', + weight == FontWeight.w400 ? 430 : weight.value.toDouble(), + ), + ], + color: color ?? AppSidebarColors.of(context).primary, + ); +} + +/// Text hierarchy for project navigation, independent of editor text colors. +@immutable +class AppSidebarColors { + const AppSidebarColors({ + required this.primary, + required this.secondary, + required this.tertiary, + required this.disabled, + required this.hover, + required this.section, + }); + + final Color primary; + final Color secondary; + final Color tertiary; + final Color disabled; + final Color hover; + final Color section; + + static AppSidebarColors of(BuildContext context) { + final theme = Theme.of(context); + final palette = theme.brightness == Brightness.dark + ? AppColors.penDark + : AppColors.penLight; + return palette.resolveSidebarColors( + theme.colorScheme, + disabledColor: theme.disabledColor, + ); + } +} + +/// Shared spacing for compact controls and unframed editor panels. +abstract final class AppSpacing { + static const hairline = 2.0; + static const tiny = 4.0; + static const gap = 6.0; + static const small = 8.0; + static const itemVertical = 10.0; + static const controlHorizontal = 8.0; + static const panelContentHorizontal = gap + controlHorizontal; + static const inputVertical = 3.0; + static const compact = 12.0; + static const medium = 16.0; + static const large = 20.0; + static const extraLarge = 24.0; + static const dialogHorizontal = 32.0; + static const page = 16.0; + static const emptyState = 64.0; + static const panelSection = EdgeInsets.symmetric( + horizontal: panelContentHorizontal, + vertical: small, + ); +} + +/// Compact desktop controls with slightly softer dialog and card corners. +abstract final class AppRadius { + static const extraSmall = 3.0; + static const large = 6.0; + static const small = 4.0; + static const medium = 5.0; + static const menuItem = 8.0; + static const extraLarge = 10.0; + static const dialog = 20.0; + static const pill = 999.0; +} + +abstract final class AppSettingsMetrics { + static const contentPadding = EdgeInsets.all(AppSpacing.large); + static const rowVerticalPadding = AppSpacing.compact; + static const controlHeight = 28.0; + static const inputHeight = 36.0; + static const controlWidth = 144.0; + static const contentWidth = 728.0; + static const cardRadius = 16.0; +} + +abstract final class AppControlSize { + static const compact = 24.0; + static const small = 24.0; + static const standard = 24.0; + static const input = 24.0; + static const propertyControl = 28.0; + static const propertyItem = 32.0; + static const headerButton = 28.0; + static const panelHeader = 46.0; + static const panelToolbar = 40.0; +} + +abstract final class AppIconSize { + static const header = 16.0; + static const small = 16.0; + static const standard = 16.0; + static const emptyState = 24.0; + static const project = 40.0; +} diff --git a/packages/cutdex_ui/lib/src/theme/menu_metrics.dart b/packages/cutdex_ui/lib/src/theme/menu_metrics.dart new file mode 100644 index 0000000..37f42e7 --- /dev/null +++ b/packages/cutdex_ui/lib/src/theme/menu_metrics.dart @@ -0,0 +1,20 @@ +/// Shared compact popover/menu scale, based on the Codex project picker. +abstract final class AppMenuMetrics { + static const modeMenuWidth = 240.0; + static const descriptionRowHeight = 56.0; + static const descriptionVerticalPadding = 10.0; + static const titleFontSize = 14.0; + static const titleLineHeight = 20.0; + static const descriptionFontSize = 12.0; + static const descriptionLineHeight = 16.0; + static const radius = 20.0; + static const itemRadius = 12.0; + static const gutter = 6.0; + static const separatorVerticalPadding = 4.0; + static const rowHeight = 28.0; + static const iconSize = 14.0; + static const iconGap = 8.0; + static const fontSize = 13.0; + static const lineHeight = 18.0; + static const borderWidth = 0.5; +} diff --git a/packages/cutdex_ui/lib/src/widgets/app_button_group.dart b/packages/cutdex_ui/lib/src/widgets/app_button_group.dart new file mode 100644 index 0000000..63d0b41 --- /dev/null +++ b/packages/cutdex_ui/lib/src/widgets/app_button_group.dart @@ -0,0 +1,88 @@ +import 'package:flutter/material.dart'; + +import '../theme/app_theme.dart'; + +/// Connected action buttons with a shared outline and internal separators. +class AppButtonGroup extends StatelessWidget { + const AppButtonGroup({ + super.key, + required this.label, + required this.children, + this.expanded = false, + }); + + final String label; + final List children; + final bool expanded; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final colors = theme.colorScheme; + final inputBorder = theme.inputDecorationTheme.enabledBorder; + final borderRadius = inputBorder is OutlineInputBorder + ? inputBorder.borderRadius + : BorderRadius.circular(AppRadius.large); + final height = + theme.inputDecorationTheme.constraints?.minHeight ?? + AppControlSize.input; + final fill = theme.inputDecorationTheme.fillColor ?? Colors.transparent; + return Semantics( + container: true, + label: label, + child: SizedBox( + height: height, + child: Container( + clipBehavior: Clip.antiAlias, + decoration: BoxDecoration( + color: Colors.transparent, + borderRadius: borderRadius, + ), + child: IconButtonTheme( + data: IconButtonThemeData( + style: + IconButton.styleFrom( + minimumSize: Size(28, height), + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.gap, + ), + shape: const RoundedRectangleBorder(), + side: BorderSide.none, + foregroundColor: colors.onSurface, + hoverColor: colors.onSurface.withValues(alpha: .06), + ).copyWith( + backgroundColor: WidgetStateProperty.resolveWith((states) { + if (!states.contains(WidgetState.selected)) return fill; + final interacting = + states.contains(WidgetState.hovered) || + states.contains(WidgetState.focused) || + states.contains(WidgetState.pressed); + return Color.alphaBlend( + colors.onSurface.withValues( + alpha: interacting ? .10 : .05, + ), + fill, + ); + }), + ), + ), + child: Row( + mainAxisSize: expanded ? MainAxisSize.max : MainAxisSize.min, + children: [ + for (var i = 0; i < children.length; i++) ...[ + if (i > 0) + const VerticalDivider( + width: 1, + thickness: 1, + color: Colors.transparent, + ), + if (expanded) Expanded(child: children[i]) else children[i], + ], + ], + ), + ), + ), + ), + ); + } +} diff --git a/packages/cutdex_ui/lib/src/widgets/app_combobox.dart b/packages/cutdex_ui/lib/src/widgets/app_combobox.dart new file mode 100644 index 0000000..0c7a431 --- /dev/null +++ b/packages/cutdex_ui/lib/src/widgets/app_combobox.dart @@ -0,0 +1,249 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import 'app_menu.dart'; +import '../theme/app_theme.dart'; + +/// Editable select: typed text filters options, but only a selection changes value. +class AppCombobox extends StatefulWidget { + const AppCombobox({ + super.key, + required this.value, + required this.options, + required this.onChanged, + required this.label, + required this.emptyLabel, + required this.searchHint, + }); + final T value; + final List> options; + final ValueChanged? onChanged; + final String label; + final String emptyLabel; + final String searchHint; + + @override + State> createState() => _AppComboboxState(); +} + +class _AppComboboxState extends State> { + final _menu = MenuController(); + final _focus = FocusNode(); + final _input = TextEditingController(); + final _firstOption = GlobalKey(); + String _query = ''; + + String get _selectedLabel => + widget.options + .where((option) => option.value == widget.value) + .firstOrNull + ?.label ?? + ''; + List> get _filtered => widget.options + .where( + (option) => [ + option.label, + ...option.searchTerms, + ].any((term) => term.toLowerCase().contains(_query.toLowerCase())), + ) + .toList(); + + @override + void initState() { + super.initState(); + _input.text = _selectedLabel; + } + + @override + void didUpdateWidget(covariant AppCombobox oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.value != widget.value || !_menu.isOpen) { + _input.text = _selectedLabel; + } + } + + @override + void dispose() { + _focus.dispose(); + _input.dispose(); + super.dispose(); + } + + void _open() { + if (widget.onChanged == null || _menu.isOpen) return; + setState(() => _query = ''); + _focus.requestFocus(); + _input.selection = TextSelection( + baseOffset: 0, + extentOffset: _input.text.length, + ); + _menu.open(); + } + + void _restore() { + _input.text = _selectedLabel; + if (mounted) setState(() => _query = ''); + } + + KeyEventResult _handleKey(FocusNode node, KeyEvent event) { + if (event is! KeyDownEvent || widget.onChanged == null) { + return KeyEventResult.ignored; + } + if (event.logicalKey == LogicalKeyboardKey.escape && _menu.isOpen) { + _menu.close(); + return KeyEventResult.handled; + } + if (event.logicalKey == LogicalKeyboardKey.arrowDown) { + if (!_menu.isOpen) { + _open(); + } else { + final entry = _firstOption.currentContext; + if (entry != null) { + FocusTraversalGroup.of(entry) + .findFirstFocus(FocusScope.of(entry), ignoreCurrentFocus: true) + ?.requestFocus(); + } + } + return KeyEventResult.handled; + } + if (event.logicalKey == LogicalKeyboardKey.enter && _menu.isOpen) { + final first = _filtered.where((option) => option.enabled).firstOrNull; + if (first != null) { + _menu.close(); + widget.onChanged!(first.value); + } + return KeyEventResult.handled; + } + return KeyEventResult.ignored; + } + + @override + Widget build(BuildContext context) => LayoutBuilder( + builder: (context, constraints) { + final theme = Theme.of(context); + final colors = theme.colorScheme; + final width = constraints.hasBoundedWidth ? constraints.maxWidth : 240.0; + final filtered = _filtered; + return MenuAnchor( + controller: _menu, + childFocusNode: _focus, + consumeOutsideTap: false, + crossAxisUnconstrained: false, + alignmentOffset: const Offset(0, 4), + style: AppMenuStyle.selectPanel(context, minWidth: width).copyWith( + maximumSize: const WidgetStatePropertyAll(Size(double.infinity, 320)), + ), + onClose: _restore, + menuChildren: [ + if (filtered.isEmpty) AppMenuLabel(widget.emptyLabel), + for (var i = 0; i < filtered.length; i++) + Builder( + key: i == 0 ? _firstOption : null, + builder: (_) { + final option = filtered[i]; + return AppMenuItem( + label: option.label, + selected: option.value == widget.value, + selectOption: true, + requestFocusOnHover: false, + onPressed: widget.onChanged == null || !option.enabled + ? null + : () => widget.onChanged!(option.value), + ); + }, + ), + ], + child: Semantics( + label: widget.label, + child: SizedBox( + width: width, + child: Focus( + canRequestFocus: false, + onKeyEvent: _handleKey, + child: Opacity( + opacity: widget.onChanged == null ? .5 : 1, + child: Container( + constraints: const BoxConstraints( + minHeight: AppControlSize.input, + ), + padding: const EdgeInsetsDirectional.only( + start: AppSpacing.compact, + end: AppSpacing.tiny, + ), + decoration: BoxDecoration( + color: AppTheme.comboboxBackground(context), + borderRadius: BorderRadius.circular(AppRadius.large), + border: Border.all(color: colors.outlineVariant), + boxShadow: [ + BoxShadow( + color: colors.shadow.withValues(alpha: .05), + offset: const Offset(0, 1), + blurRadius: 2, + ), + ], + ), + child: Row( + children: [ + Expanded( + child: TextField( + controller: _input, + focusNode: _focus, + enabled: widget.onChanged != null, + onTap: _open, + onTapAlwaysCalled: true, + onChanged: (text) { + setState(() => _query = text); + if (!_menu.isOpen) _menu.open(); + }, + style: theme.textTheme.bodyLarge, + decoration: InputDecoration( + constraints: const BoxConstraints( + minHeight: AppControlSize.input - 2, + ), + hintText: widget.searchHint, + isDense: true, + filled: false, + contentPadding: const EdgeInsets.symmetric( + vertical: AppSpacing.inputVertical - 2, + ), + border: InputBorder.none, + enabledBorder: InputBorder.none, + focusedBorder: InputBorder.none, + disabledBorder: InputBorder.none, + errorBorder: InputBorder.none, + focusedErrorBorder: InputBorder.none, + ), + ), + ), + IconButton( + tooltip: null, + onPressed: widget.onChanged == null + ? null + : () => _menu.isOpen ? _menu.close() : _open(), + style: IconButton.styleFrom( + overlayColor: Colors.transparent, + minimumSize: const Size.square( + AppControlSize.input - 2, + ), + padding: const EdgeInsets.all( + AppSpacing.inputVertical, + ), + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + icon: Icon( + Icons.expand_more, + size: 16, + color: colors.onSurfaceVariant.withValues(alpha: .5), + ), + ), + ], + ), + ), + ), + ), + ), + ), + ); + }, + ); +} diff --git a/packages/cutdex_ui/lib/src/widgets/app_dialog.dart b/packages/cutdex_ui/lib/src/widgets/app_dialog.dart new file mode 100644 index 0000000..8fd67d3 --- /dev/null +++ b/packages/cutdex_ui/lib/src/widgets/app_dialog.dart @@ -0,0 +1,322 @@ +import 'package:flutter/material.dart'; + +import '../theme/app_theme.dart'; + +Future showAppDialog({ + required BuildContext context, + required WidgetBuilder builder, +}) => showDialog( + context: context, + barrierColor: Theme.of(context).dialogTheme.barrierColor, + animationStyle: const AnimationStyle(duration: Duration(milliseconds: 200)), + builder: builder, +); + +/// A compact selectable row for dialogs that ask the user to choose an item. +class AppDialogOption extends StatelessWidget { + const AppDialogOption({ + super.key, + required this.label, + required this.onPressed, + }); + + final String label; + final VoidCallback onPressed; + + @override + Widget build(BuildContext context) => InkWell( + onTap: onPressed, + borderRadius: BorderRadius.circular(AppRadius.large), + child: SizedBox( + height: 32, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: AppSpacing.small), + child: Align( + alignment: AlignmentDirectional.centerStart, + child: Text(label, overflow: TextOverflow.ellipsis), + ), + ), + ), + ); +} + +/// Shared desktop dialog with Codex content, header and footer spacing. +class AppDialog extends StatelessWidget { + const AppDialog({ + super.key, + required this.title, + required this.child, + this.description, + this.header, + this.navigation, + this.actions = const [], + this.width = 420, + this.height, + this.closeLabel, + this.withShadow = true, + this.editorHeader = false, + this.contentOnly = false, + this.showEditorTitle = true, + this.editorHeaderHeight = AppControlSize.panelHeader, + this.editorHeaderHorizontalPadding = AppSpacing.compact, + this.editorContentPadding, + this.scrollContent = true, + }); + + final String title; + final String? description; + final Widget? header; + final Widget? navigation; + final Widget child; + final List actions; + final double width; + final double? height; + final String? closeLabel; + final bool withShadow; + final bool editorHeader; + final bool contentOnly; + final bool showEditorTitle; + final double editorHeaderHeight; + final double editorHeaderHorizontalPadding; + final EdgeInsets? editorContentPadding; + final bool scrollContent; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final colors = theme.colorScheme; + final dialogTheme = theme.dialogTheme; + final shape = + dialogTheme.shape ?? + const RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(AppRadius.dialog)), + ); + final radius = shape is RoundedRectangleBorder + ? shape.borderRadius + : const BorderRadius.all(Radius.circular(AppRadius.dialog)); + return Theme( + data: editorHeader || contentOnly + ? theme + : AppTheme.dialogContentTheme(theme), + child: Dialog( + insetPadding: const EdgeInsets.all(AppSpacing.medium), + backgroundColor: Colors.transparent, + surfaceTintColor: Colors.transparent, + elevation: 0, + constraints: const BoxConstraints(), + clipBehavior: Clip.none, + child: DecoratedBox( + decoration: BoxDecoration( + borderRadius: radius, + // Approximate Tailwind shadow-lg using two Flutter shadows. + boxShadow: withShadow + ? [ + BoxShadow( + color: colors.shadow.withValues(alpha: .1), + offset: const Offset(0, 10), + blurRadius: 15, + spreadRadius: -3, + ), + BoxShadow( + color: colors.shadow.withValues(alpha: .1), + offset: const Offset(0, 4), + blurRadius: 6, + spreadRadius: -4, + ), + ] + : null, + ), + child: Material( + color: dialogTheme.backgroundColor ?? colors.surfaceContainer, + shape: shape, + clipBehavior: Clip.antiAlias, + child: SizedBox( + key: const Key('app-dialog-frame'), + width: width, + height: height, + child: Stack( + children: [ + Padding( + padding: contentOnly + ? EdgeInsets.zero + : editorHeader + ? editorContentPadding ?? + EdgeInsets.fromLTRB( + AppSpacing.medium, + editorHeaderHeight + AppSpacing.medium, + AppSpacing.medium, + AppSpacing.medium, + ) + : const EdgeInsets.all(AppSpacing.large), + child: DefaultTextStyle( + style: + dialogTheme.contentTextStyle ?? + theme.textTheme.bodyMedium!, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (!editorHeader && !contentOnly) + Padding( + padding: const EdgeInsetsDirectional.only( + end: + AppControlSize.headerButton + + AppSpacing.gap, + ), + child: Semantics( + namesRoute: true, + header: true, + label: header != null ? title : null, + child: + header ?? + Text( + title, + style: dialogTheme.titleTextStyle, + ), + ), + ), + if (description != null) ...[ + const SizedBox(height: AppSpacing.tiny), + Text( + description!, + style: dialogTheme.contentTextStyle?.copyWith( + color: colors.onSurfaceVariant, + ), + ), + ], + if (navigation != null) ...[ + const SizedBox(height: AppSpacing.medium), + Align( + alignment: AlignmentDirectional.centerStart, + child: navigation, + ), + ], + if (!editorHeader && !contentOnly) + const SizedBox(height: AppSpacing.compact), + Flexible( + fit: height == null ? FlexFit.loose : FlexFit.tight, + child: scrollContent + ? SingleChildScrollView(child: child) + : child, + ), + if (actions.isNotEmpty) ...[ + const SizedBox(height: AppSpacing.compact), + Builder( + builder: (context) => Theme( + data: AppTheme.dialogActionTheme( + Theme.of(context), + ), + child: Wrap( + alignment: WrapAlignment.end, + spacing: AppSpacing.compact, + runSpacing: AppSpacing.small, + children: actions, + ), + ), + ), + ], + ], + ), + ), + ), + if (editorHeader && !contentOnly) ...[ + PositionedDirectional( + top: 0, + start: 0, + end: 0, + height: editorHeaderHeight, + child: Padding( + padding: EdgeInsetsDirectional.only( + start: editorHeaderHorizontalPadding, + end: + editorHeaderHorizontalPadding + + AppControlSize.headerButton + + AppSpacing.tiny, + ), + child: Row( + children: [ + if (showEditorTitle) + Semantics( + namesRoute: true, + header: true, + child: Text( + title, + key: const Key('app-dialog-header-title'), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: theme.textTheme.titleSmall, + ), + ), + if (header != null) ...[ + if (showEditorTitle) + const SizedBox(width: AppSpacing.compact), + Flexible( + child: Align( + alignment: AlignmentDirectional.centerStart, + child: KeyedSubtree( + key: const Key('app-dialog-header-content'), + child: header!, + ), + ), + ), + ], + ], + ), + ), + ), + PositionedDirectional( + top: editorHeaderHeight - 1, + start: 0, + end: 0, + child: const Divider( + key: Key('app-dialog-header-divider'), + height: 1, + ), + ), + ], + PositionedDirectional( + top: editorHeader + ? (editorHeaderHeight - AppControlSize.headerButton) / 2 + : AppSpacing.medium, + end: editorHeader + ? editorHeaderHorizontalPadding + : AppSpacing.medium, + child: SizedBox.square( + dimension: editorHeader + ? AppControlSize.headerButton + : 24, + child: IconButton( + key: const Key('app-dialog-close-button'), + tooltip: + closeLabel ?? + MaterialLocalizations.of(context) + .closeButtonTooltip, + onPressed: () => Navigator.of(context).pop(), + style: IconButton.styleFrom( + foregroundColor: colors.onSurface.withValues( + alpha: .7, + ), + minimumSize: Size.square( + editorHeader ? AppControlSize.headerButton : 24, + ), + padding: const EdgeInsets.all(AppSpacing.tiny), + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular( + AppRadius.large, + ), + ), + ), + icon: const Icon(Icons.close, size: AppIconSize.header), + ), + ), + ), + ], + ), + ), + ), + ), + ), + ); + } +} diff --git a/packages/cutdex_ui/lib/src/widgets/app_field.dart b/packages/cutdex_ui/lib/src/widgets/app_field.dart new file mode 100644 index 0000000..a45e6fb --- /dev/null +++ b/packages/cutdex_ui/lib/src/widgets/app_field.dart @@ -0,0 +1,102 @@ +import 'package:flutter/material.dart'; + +import '../theme/app_theme.dart'; + +/// Consistent spacing between related settings fields. +class AppFieldGroup extends StatelessWidget { + const AppFieldGroup({super.key, required this.children}); + final List children; + + @override + Widget build(BuildContext context) => Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + spacing: AppSpacing.extraLarge, + children: children, + ); +} + +enum AppFieldOrientation { vertical, horizontal } + +class AppField extends StatelessWidget { + const AppField({ + super.key, + required this.label, + required this.child, + this.description, + this.error, + this.orientation = AppFieldOrientation.vertical, + this.enabled = true, + }); + final String label; + final Widget child; + final String? description; + final String? error; + final AppFieldOrientation orientation; + final bool enabled; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final heading = Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(label, style: theme.textTheme.labelLarge), + if (description != null) ...[ + const SizedBox(height: AppSpacing.hairline), + Text( + description!, + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ], + ); + return Opacity( + opacity: enabled ? 1 : .5, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + LayoutBuilder( + builder: (context, constraints) => + orientation == AppFieldOrientation.horizontal && + constraints.maxWidth >= 440 + ? Row( + children: [ + Expanded(child: heading), + const SizedBox(width: AppSpacing.medium), + Flexible( + child: Align( + alignment: AlignmentDirectional.centerEnd, + child: child, + ), + ), + ], + ) + : Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + heading, + const SizedBox(height: AppSpacing.small), + child, + ], + ), + ), + if (error != null) ...[ + const SizedBox(height: AppSpacing.small), + Semantics( + liveRegion: true, + child: Text( + error!, + style: theme.textTheme.bodyMedium?.copyWith( + color: theme.colorScheme.error, + ), + ), + ), + ], + ], + ), + ); + } +} diff --git a/packages/cutdex_ui/lib/src/widgets/app_item.dart b/packages/cutdex_ui/lib/src/widgets/app_item.dart new file mode 100644 index 0000000..9062cd0 --- /dev/null +++ b/packages/cutdex_ui/lib/src/widgets/app_item.dart @@ -0,0 +1,85 @@ +import 'package:flutter/material.dart'; + +import '../theme/app_theme.dart'; + +/// Compact content row with independent actions and optional selection. +class AppItem extends StatelessWidget { + const AppItem({ + super.key, + required this.child, + this.leading, + this.actions = const [], + this.selected = false, + this.onPressed, + }); + + final Widget child; + final Widget? leading; + final List actions; + final bool selected; + final VoidCallback? onPressed; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final ink = theme.colorScheme.onSurface; + final hover = AppTheme.itemHoverColor(context, selected: selected); + return Semantics( + container: true, + selected: selected, + child: Material( + color: selected ? ink.withValues(alpha: .05) : Colors.transparent, + borderRadius: BorderRadius.circular(AppRadius.large), + clipBehavior: Clip.antiAlias, + child: InkWell( + onTap: onPressed, + borderRadius: BorderRadius.circular(AppRadius.large), + hoverColor: hover, + child: SizedBox( + height: AppControlSize.propertyItem, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: AppSpacing.small), + child: Row( + children: [ + if (leading != null) ...[ + leading!, + const SizedBox(width: AppSpacing.small), + ], + Expanded( + child: DefaultTextStyle( + style: theme.textTheme.labelLarge!, + maxLines: 1, + overflow: TextOverflow.ellipsis, + child: child, + ), + ), + if (actions.isNotEmpty) ...[ + const SizedBox(width: AppSpacing.small), + ...actions, + ], + ], + ), + ), + ), + ), + ), + ); + } +} + +class AppItemGroup extends StatelessWidget { + const AppItemGroup({super.key, required this.children}); + + final List children; + + @override + Widget build(BuildContext context) => Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + for (var i = 0; i < children.length; i++) ...[ + if (i > 0) const SizedBox(height: AppSidebarMetrics.projectGap), + children[i], + ], + ], + ); +} diff --git a/packages/cutdex_ui/lib/src/widgets/app_menu.dart b/packages/cutdex_ui/lib/src/widgets/app_menu.dart new file mode 100644 index 0000000..e3b1792 --- /dev/null +++ b/packages/cutdex_ui/lib/src/widgets/app_menu.dart @@ -0,0 +1,670 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../theme/app_theme.dart'; +import '../theme/menu_metrics.dart'; +import 'native_context_menu.dart'; +import 'app_combobox.dart'; + +part 'app_menu.freezed.dart'; + +void _focusMenu(GlobalKey entryKey) { + WidgetsBinding.instance.addPostFrameCallback((_) { + final context = entryKey.currentContext; + if (context == null) return; + final scope = FocusScope.of(context); + final policy = FocusTraversalGroup.of(context); + policy.findFirstFocus(scope, ignoreCurrentFocus: true)?.requestFocus(); + }); +} + +abstract final class AppMenuStyle { + static MenuStyle panel(BuildContext context, {double minWidth = 160}) { + final colors = Theme.of(context).colorScheme; + return MenuStyle( + backgroundColor: WidgetStatePropertyAll( + AppTheme.popoverBackground(context), + ), + surfaceTintColor: const WidgetStatePropertyAll(Colors.transparent), + elevation: const WidgetStatePropertyAll(4), + shadowColor: WidgetStatePropertyAll(colors.shadow.withValues(alpha: .2)), + minimumSize: WidgetStatePropertyAll(Size(minWidth, 0)), + padding: const WidgetStatePropertyAll( + EdgeInsets.all(AppMenuMetrics.gutter), + ), + side: WidgetStatePropertyAll( + BorderSide( + color: colors.outlineVariant, + width: AppMenuMetrics.borderWidth, + ), + ), + shape: const WidgetStatePropertyAll( + RoundedRectangleBorder( + borderRadius: BorderRadius.all( + Radius.circular(AppMenuMetrics.radius), + ), + ), + ), + ); + } + + static MenuStyle selectPanel( + BuildContext context, { + required double minWidth, + }) => panel(context, minWidth: minWidth); + + static ButtonStyle selectItem(BuildContext context) => item(context); + + static ButtonStyle descriptionItem( + BuildContext context, { + bool destructive = false, + }) => item(context, destructive: destructive).copyWith( + minimumSize: const WidgetStatePropertyAll( + Size(0, AppMenuMetrics.descriptionRowHeight), + ), + padding: const WidgetStatePropertyAll( + EdgeInsets.symmetric( + horizontal: AppMenuMetrics.iconGap, + vertical: AppMenuMetrics.descriptionVerticalPadding, + ), + ), + textStyle: WidgetStatePropertyAll( + Theme.of(context).textTheme.bodyMedium?.copyWith( + fontSize: AppMenuMetrics.titleFontSize, + height: AppMenuMetrics.titleLineHeight / AppMenuMetrics.titleFontSize, + ), + ), + ); + + static ButtonStyle item(BuildContext context, {bool destructive = false}) { + final theme = Theme.of(context); + final colors = theme.colorScheme; + final foreground = destructive ? colors.error : colors.onSurface; + return ButtonStyle( + textStyle: WidgetStatePropertyAll( + theme.textTheme.bodyMedium?.copyWith( + fontSize: AppMenuMetrics.fontSize, + height: AppMenuMetrics.lineHeight / AppMenuMetrics.fontSize, + ), + ), + iconSize: const WidgetStatePropertyAll(AppMenuMetrics.iconSize), + minimumSize: const WidgetStatePropertyAll( + Size(0, AppMenuMetrics.rowHeight), + ), + padding: const WidgetStatePropertyAll( + EdgeInsets.symmetric(horizontal: AppMenuMetrics.iconGap, vertical: 5), + ), + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + visualDensity: VisualDensity.standard, + shape: const WidgetStatePropertyAll( + RoundedRectangleBorder( + borderRadius: BorderRadius.all( + Radius.circular(AppMenuMetrics.itemRadius), + ), + ), + ), + foregroundColor: WidgetStateProperty.resolveWith( + (states) => states.contains(WidgetState.disabled) + ? foreground.withValues(alpha: .5) + : foreground, + ), + iconColor: WidgetStateProperty.resolveWith( + (states) => states.contains(WidgetState.disabled) + ? foreground.withValues(alpha: .5) + : foreground, + ), + backgroundColor: WidgetStateProperty.resolveWith( + (states) => + states.any( + { + WidgetState.hovered, + WidgetState.focused, + WidgetState.pressed, + }.contains, + ) + ? (destructive + ? colors.errorContainer + : AppSidebarColors.of(context).hover) + : Colors.transparent, + ), + overlayColor: const WidgetStatePropertyAll(Colors.transparent), + ); + } +} + +class AppMenuItem extends StatefulWidget { + const AppMenuItem({ + super.key, + required this.label, + this.description, + this.onPressed, + this.icon, + this.selected, + this.destructive = false, + this.selectOption = false, + this.requestFocusOnHover = true, + }); + final String label; + final String? description; + final VoidCallback? onPressed; + final IconData? icon; + final bool? selected; + final bool destructive; + final bool selectOption; + final bool requestFocusOnHover; + + @override + State createState() => _AppMenuItemState(); +} + +class _AppMenuItemState extends State { + final _focus = FocusNode(); + bool _focusFromHover = false; + + @override + void dispose() { + _focus.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => Semantics( + selected: widget.selected, + child: Focus( + canRequestFocus: false, + onKeyEvent: (_, event) { + if (event is KeyDownEvent) _focusFromHover = false; + return KeyEventResult.ignored; + }, + child: MenuItemButton( + focusNode: _focus, + requestFocusOnHover: widget.requestFocusOnHover, + onHover: (hovered) { + // Material moves focus on pointer hover, but retains it on exit. + // Release only mouse-acquired focus when scrolling moves this item + // away; keep keyboard focus and the normal highlight transition. + if (!hovered && _focusFromHover && _focus.hasFocus) { + _focus.unfocus(); + } + _focusFromHover = hovered; + }, + onPressed: widget.onPressed, + style: widget.description != null + ? AppMenuStyle.descriptionItem( + context, + destructive: widget.destructive, + ) + : widget.selectOption + ? AppMenuStyle.selectItem(context) + : AppMenuStyle.item(context, destructive: widget.destructive), + leadingIcon: widget.icon == null ? null : Icon(widget.icon), + trailingIcon: widget.selectOption || widget.selected == null + ? null + : SizedBox.square( + dimension: AppMenuMetrics.iconSize, + child: widget.selected! ? const Icon(Icons.check) : null, + ), + child: widget.selectOption + ? Row( + children: [ + Expanded( + child: Text( + widget.label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + const SizedBox(width: AppSpacing.small), + SizedBox.square( + dimension: 16, + child: widget.selected == true + ? const Icon(Icons.check, size: 16) + : null, + ), + ], + ) + : widget.description == null + ? Text(widget.label, maxLines: 1, overflow: TextOverflow.ellipsis) + : Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + widget.label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + Text( + widget.description!, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: Theme.of(context).textTheme.bodySmall?.copyWith( + fontSize: AppMenuMetrics.descriptionFontSize, + height: + AppMenuMetrics.descriptionLineHeight / + AppMenuMetrics.descriptionFontSize, + ), + ), + ], + ), + ), + ), + ); +} + +class AppMenuSeparator extends StatelessWidget { + const AppMenuSeparator({super.key}); + @override + Widget build(BuildContext context) => const Padding( + padding: EdgeInsets.symmetric( + horizontal: AppMenuMetrics.iconGap, + vertical: AppMenuMetrics.separatorVerticalPadding, + ), + child: Divider(height: 1, thickness: 1), + ); +} + +class AppMenuLabel extends StatelessWidget { + const AppMenuLabel(this.label, {super.key}); + final String label; + @override + Widget build(BuildContext context) => Padding( + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.gap, + vertical: AppSpacing.tiny, + ), + child: Text( + label, + style: Theme.of(context).textTheme.labelMedium + ?.copyWith(color: Theme.of(context).colorScheme.onSurfaceVariant), + ), + ); +} + +class AppSubmenu extends StatelessWidget { + const AppSubmenu({ + super.key, + required this.label, + required this.items, + this.icon, + }); + final String label; + final List items; + final IconData? icon; + @override + Widget build(BuildContext context) => SubmenuButton( + style: AppMenuStyle.item(context), + menuStyle: AppMenuStyle.panel(context), + leadingIcon: icon == null ? null : Icon(icon), + menuChildren: items, + child: Text(label), + ); +} + +typedef AppMenuTriggerBuilder = Widget Function( + BuildContext context, + VoidCallback? toggle, + FocusNode focusNode, +); + +class AppDropdownMenu extends StatefulWidget { + const AppDropdownMenu({ + super.key, + required this.items, + required this.builder, + this.enabled = true, + this.minWidth = 160, + this.maxHeight, + this.onClose, + this.menuStyle, + this.crossAxisUnconstrained = false, + this.alignmentOffset = const Offset(0, 4), + }); + final List items; + final AppMenuTriggerBuilder builder; + final bool enabled; + final double minWidth; + final double? maxHeight; + final VoidCallback? onClose; + final MenuStyle? menuStyle; + final bool crossAxisUnconstrained; + final Offset alignmentOffset; + @override + State createState() => _AppDropdownMenuState(); +} + +class _AppDropdownMenuState extends State { + final _focus = FocusNode(); + final _controller = MenuController(); + final _entryKey = GlobalKey(); + @override + void dispose() { + _focus.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => MenuAnchor( + controller: _controller, + childFocusNode: _focus, + consumeOutsideTap: true, + crossAxisUnconstrained: widget.crossAxisUnconstrained, + alignmentOffset: widget.alignmentOffset, + style: + (widget.menuStyle ?? + AppMenuStyle.panel(context, minWidth: widget.minWidth)) + .copyWith( + maximumSize: widget.maxHeight == null + ? null + : WidgetStatePropertyAll( + Size(double.infinity, widget.maxHeight!), + ), + ), + onClose: widget.onClose, + onOpen: () => _focusMenu(_entryKey), + menuChildren: [ + for (var i = 0; i < widget.items.length; i++) + if (i == 0) + Builder(key: _entryKey, builder: (_) => widget.items[i]) + else + widget.items[i], + ], + builder: (context, controller, _) => Shortcuts( + shortcuts: const { + SingleActivator(LogicalKeyboardKey.arrowDown): ActivateIntent(), + }, + child: widget.builder( + context, + !widget.enabled + ? null + : () { + controller.isOpen ? controller.close() : controller.open(); + }, + _focus, + ), + ), + ); +} + +@freezed +abstract class AppSelectOption with _$AppSelectOption { + const factory AppSelectOption( + T value, + String label, { + @Default(true) bool enabled, + @Default([]) List searchTerms, + }) = _AppSelectOption; +} + +/// Shared shadcn-style select; searchable for long option lists. +class AppSelect extends StatelessWidget { + const AppSelect({ + super.key, + required this.value, + required this.options, + required this.onChanged, + required this.label, + required this.emptyLabel, + this.searchHint, + this.outlined = true, + this.searchable = false, + this.controlHeight, + this.textStyle, + }) : assert(!searchable || searchHint != null); + final T value; + final List> options; + final ValueChanged? onChanged; + final String label; + final String emptyLabel; + final String? searchHint; + final bool outlined; + final bool searchable; + final double? controlHeight; + final TextStyle? textStyle; + + @override + Widget build(BuildContext context) => searchable + ? AppCombobox( + value: value, + options: options, + onChanged: onChanged, + label: label, + emptyLabel: emptyLabel, + searchHint: searchHint!, + ) + : LayoutBuilder( + builder: (context, constraints) { + final theme = Theme.of(context); + final colors = theme.colorScheme; + final current = options + .where((option) => option.value == value) + .firstOrNull; + final bounded = constraints.hasBoundedWidth; + return AppDropdownMenu( + enabled: onChanged != null, + minWidth: outlined && bounded ? constraints.maxWidth : 160, + maxHeight: 320, + menuStyle: AppMenuStyle.selectPanel( + context, + minWidth: outlined && bounded ? constraints.maxWidth : 128, + ), + items: [ + if (options.isEmpty) AppMenuLabel(emptyLabel), + for (final option in options) + AppMenuItem( + label: option.label, + selected: option.value == value, + selectOption: true, + onPressed: onChanged == null || !option.enabled + ? null + : () => onChanged!(option.value), + ), + ], + builder: (context, toggle, focus) => Semantics( + label: label, + child: Opacity( + opacity: onChanged == null ? .5 : 1, + child: AnimatedContainer( + duration: const Duration(milliseconds: 100), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(AppRadius.large), + boxShadow: outlined + ? [ + BoxShadow( + color: colors.shadow.withValues(alpha: .05), + offset: const Offset(0, 1), + blurRadius: 2, + ), + ] + : null, + ), + child: TextButton( + focusNode: focus, + onPressed: toggle, + style: TextButton.styleFrom( + textStyle: textStyle ?? theme.textTheme.bodyMedium, + foregroundColor: colors.onSurface, + disabledForegroundColor: colors.onSurface, + overlayColor: Colors.transparent, + backgroundColor: outlined + ? theme.inputDecorationTheme.fillColor + : Colors.transparent, + fixedSize: controlHeight == null + ? null + : Size.fromHeight(controlHeight!), + minimumSize: Size( + 0, + outlined + ? AppControlSize.input + : AppControlSize.small, + ), + tapTargetSize: MaterialTapTargetSize.shrinkWrap, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(AppRadius.large), + ), + side: outlined + ? theme + .inputDecorationTheme + .enabledBorder + ?.borderSide ?? + BorderSide(color: colors.outlineVariant) + : null, + padding: EdgeInsets.symmetric( + horizontal: outlined ? 12 : AppSpacing.tiny, + vertical: outlined ? AppSpacing.inputVertical : 0, + ), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Flexible( + fit: outlined && bounded + ? FlexFit.tight + : FlexFit.loose, + child: Text( + current?.label ?? label, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + const SizedBox(width: AppSpacing.small), + Icon( + Icons.expand_more, + size: 16, + color: colors.onSurfaceVariant.withValues( + alpha: .5, + ), + ), + ], + ), + ), + ), + ), + ), + ); + }, + ); +} + +class AppContextMenu extends StatefulWidget { + const AppContextMenu({ + super.key, + required this.itemsBuilder, + required this.child, + }); + final List Function(BuildContext) itemsBuilder; + final Widget child; + @override + State createState() => _AppContextMenuState(); +} + +class _AppContextMenuState extends State { + final _controller = MenuController(); + final _focus = FocusNode(); + final _entryKey = GlobalKey(); + Offset _anchorPosition = Offset.zero; + bool _focusFirstItem = false; + bool _opening = false; + @override + void dispose() { + _focus.dispose(); + super.dispose(); + } + + Future _open(Offset position, {required bool focusFirstItem}) async { + if (_opening) return; + _opening = true; + try { + _focus.requestFocus(); + final box = context.findRenderObject() as RenderBox; + if (await showNativeContextMenu( + widget.itemsBuilder(context), + box.localToGlobal(position), + () => mounted, + )) { + return; + } + if (!mounted) return; + _openFlutter(position, focusFirstItem: focusFirstItem); + } finally { + _opening = false; + } + } + + void _openFlutter(Offset position, {required bool focusFirstItem}) { + _focus.requestFocus(); + if (_controller.isOpen) _controller.close(); + setState(() { + _anchorPosition = position; + _focusFirstItem = focusFirstItem; + }); + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) _controller.open(); + }); + } + + @override + Widget build(BuildContext context) => Focus( + focusNode: _focus, + onKeyEvent: (node, event) { + if (event is! KeyDownEvent) return KeyEventResult.ignored; + if (event.logicalKey == LogicalKeyboardKey.contextMenu || + (event.logicalKey == LogicalKeyboardKey.f10 && + HardwareKeyboard.instance.isShiftPressed)) { + _open(Offset.zero, focusFirstItem: true); + return KeyEventResult.handled; + } + if (_controller.isOpen && + !_focusFirstItem && + event.logicalKey == LogicalKeyboardKey.arrowDown) { + _focusFirstItem = true; + _focusMenu(_entryKey); + return KeyEventResult.handled; + } + return KeyEventResult.ignored; + }, + child: Stack( + fit: StackFit.passthrough, + children: [ + GestureDetector( + behavior: HitTestBehavior.translucent, + // Let Flutter finish the pointer sequence before AppKit takes over + // event tracking, otherwise NSMenu can consume the right-button up. + onSecondaryTapUp: (details) => + _open(details.localPosition, focusFirstItem: false), + onLongPressStart: (details) => + _open(details.localPosition, focusFirstItem: false), + child: widget.child, + ), + Positioned( + left: _anchorPosition.dx, + top: _anchorPosition.dy, + child: MenuAnchor( + controller: _controller, + childFocusNode: _focus, + consumeOutsideTap: true, + crossAxisUnconstrained: false, + style: AppMenuStyle.panel(context), + onOpen: () { + if (_focusFirstItem) _focusMenu(_entryKey); + }, + menuChildren: _items(context), + child: const IgnorePointer(child: SizedBox.square(dimension: 1)), + ), + ), + ], + ), + ); + + List _items(BuildContext context) { + final items = widget.itemsBuilder(context); + return [ + for (var i = 0; i < items.length; i++) + if (i == 0) + Builder(key: _entryKey, builder: (_) => items[i]) + else + items[i], + ]; + } +} diff --git a/packages/cutdex_ui/lib/src/widgets/app_menu.freezed.dart b/packages/cutdex_ui/lib/src/widgets/app_menu.freezed.dart new file mode 100644 index 0000000..47fea31 --- /dev/null +++ b/packages/cutdex_ui/lib/src/widgets/app_menu.freezed.dart @@ -0,0 +1,294 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'app_menu.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// dart format off +T _$identity(T value) => value; +/// @nodoc +mixin _$AppSelectOption { + + T get value; String get label; bool get enabled; List get searchTerms; +/// Create a copy of AppSelectOption +/// with the given fields replaced by the non-null parameter values. +@JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +$AppSelectOptionCopyWith> get copyWith => _$AppSelectOptionCopyWithImpl>(this as AppSelectOption, _$identity); + + + +@override +bool operator ==(Object other) { + final _this = this as AppSelectOption; + return identical(this, other) || (other.runtimeType == runtimeType&&other is AppSelectOption&&const DeepCollectionEquality().equals(other.value, _this.value)&&(identical(other.label, _this.label) || other.label == _this.label)&&(identical(other.enabled, _this.enabled) || other.enabled == _this.enabled)&&const DeepCollectionEquality().equals(other.searchTerms, _this.searchTerms)); +} + + +@override +int get hashCode { + final _this = this as AppSelectOption; + return Object.hash(runtimeType,const DeepCollectionEquality().hash(_this.value),_this.label,_this.enabled,const DeepCollectionEquality().hash(_this.searchTerms)); +} + +@override +String toString() { + final _this = this as AppSelectOption; + return 'AppSelectOption<$T>(value: ${_this.value}, label: ${_this.label}, enabled: ${_this.enabled}, searchTerms: ${_this.searchTerms})'; +} + + +} + +/// @nodoc +abstract mixin class $AppSelectOptionCopyWith { + factory $AppSelectOptionCopyWith(AppSelectOption value, $Res Function(AppSelectOption) _then) = _$AppSelectOptionCopyWithImpl; +@useResult +$Res call({ + T value, String label, bool enabled, List searchTerms +}); + + + + +} +/// @nodoc +class _$AppSelectOptionCopyWithImpl + implements $AppSelectOptionCopyWith { + _$AppSelectOptionCopyWithImpl(this._self, this._then); + + final AppSelectOption _self; + final $Res Function(AppSelectOption) _then; + +/// Create a copy of AppSelectOption +/// with the given fields replaced by the non-null parameter values. +@pragma('vm:prefer-inline') @override $Res call({Object? value = freezed,Object? label = null,Object? enabled = null,Object? searchTerms = null,}) { + return _then(AppSelectOption( +freezed == value ? _self.value : value // ignore: cast_nullable_to_non_nullable +as T,null == label ? _self.label : label // ignore: cast_nullable_to_non_nullable +as String,enabled: null == enabled ? _self.enabled : enabled // ignore: cast_nullable_to_non_nullable +as bool,searchTerms: null == searchTerms ? _self.searchTerms : searchTerms // ignore: cast_nullable_to_non_nullable +as List, + )); +} + +} + + +/// Adds pattern-matching-related methods to [AppSelectOption]. +extension AppSelectOptionPatterns on AppSelectOption { +/// A variant of `map` that fallback to returning `orElse`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeMap(TResult Function( _AppSelectOption value)? $default,{required TResult orElse(),}){ +final _that = this; +switch (_that) { +case _AppSelectOption() when $default != null: +return $default(_that);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// Callbacks receives the raw object, upcasted. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case final Subclass2 value: +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult map(TResult Function( _AppSelectOption value) $default,){ +final _that = this; +switch (_that) { +case _AppSelectOption(): +return $default(_that);case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `map` that fallback to returning `null`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? mapOrNull(TResult? Function( _AppSelectOption value)? $default,){ +final _that = this; +switch (_that) { +case _AppSelectOption() when $default != null: +return $default(_that);case _: + return null; + +} +} +/// A variant of `when` that fallback to an `orElse` callback. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeWhen(TResult Function( T value, String label, bool enabled, List searchTerms)? $default,{required TResult orElse(),}) {final _that = this; +switch (_that) { +case _AppSelectOption() when $default != null: +return $default(_that.value,_that.label,_that.enabled,_that.searchTerms);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// As opposed to `map`, this offers destructuring. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case Subclass2(:final field2): +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult when(TResult Function( T value, String label, bool enabled, List searchTerms) $default,) {final _that = this; +switch (_that) { +case _AppSelectOption(): +return $default(_that.value,_that.label,_that.enabled,_that.searchTerms);case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `when` that fallback to returning `null` +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? whenOrNull(TResult? Function( T value, String label, bool enabled, List searchTerms)? $default,) {final _that = this; +switch (_that) { +case _AppSelectOption() when $default != null: +return $default(_that.value,_that.label,_that.enabled,_that.searchTerms);case _: + return null; + +} +} + +} + +/// @nodoc + + +class _AppSelectOption implements AppSelectOption { + const _AppSelectOption(this.value, this.label, {this.enabled = true, List searchTerms = const []}): _searchTerms = searchTerms; + + +@override final T value; +@override final String label; +@override@JsonKey() final bool enabled; + final List _searchTerms; +@override@JsonKey() List get searchTerms { + if (_searchTerms is EqualUnmodifiableListView) return _searchTerms; + // ignore: implicit_dynamic_type + return EqualUnmodifiableListView(_searchTerms); +} + + +/// Create a copy of AppSelectOption +/// with the given fields replaced by the non-null parameter values. +@override @JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +_$AppSelectOptionCopyWith> get copyWith => __$AppSelectOptionCopyWithImpl>(this, _$identity); + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is _AppSelectOption&&const DeepCollectionEquality().equals(other.value, value)&&(identical(other.label, label) || other.label == label)&&(identical(other.enabled, enabled) || other.enabled == enabled)&&const DeepCollectionEquality().equals(other.searchTerms, _searchTerms)); +} + + +@override +int get hashCode { + return Object.hash(runtimeType,const DeepCollectionEquality().hash(value),label,enabled,const DeepCollectionEquality().hash(_searchTerms)); +} + +@override +String toString() { + return 'AppSelectOption<$T>(value: $value, label: $label, enabled: $enabled, searchTerms: $searchTerms)'; +} + + +} + +/// @nodoc +abstract mixin class _$AppSelectOptionCopyWith implements $AppSelectOptionCopyWith { + factory _$AppSelectOptionCopyWith(_AppSelectOption value, $Res Function(_AppSelectOption) _then) = __$AppSelectOptionCopyWithImpl; +@override @useResult +$Res call({ + T value, String label, bool enabled, List searchTerms +}); + + + + +} +/// @nodoc +class __$AppSelectOptionCopyWithImpl + implements _$AppSelectOptionCopyWith { + __$AppSelectOptionCopyWithImpl(this._self, this._then); + + final _AppSelectOption _self; + final $Res Function(_AppSelectOption) _then; + +/// Create a copy of AppSelectOption +/// with the given fields replaced by the non-null parameter values. +@override @pragma('vm:prefer-inline') $Res call({Object? value = freezed,Object? label = null,Object? enabled = null,Object? searchTerms = null,}) { + return _then(_AppSelectOption( +freezed == value ? _self.value : value // ignore: cast_nullable_to_non_nullable +as T,null == label ? _self.label : label // ignore: cast_nullable_to_non_nullable +as String,enabled: null == enabled ? _self.enabled : enabled // ignore: cast_nullable_to_non_nullable +as bool,searchTerms: null == searchTerms ? _self._searchTerms : searchTerms // ignore: cast_nullable_to_non_nullable +as List, + )); +} + + +} + +// dart format on diff --git a/packages/cutdex_ui/lib/src/widgets/app_popover.dart b/packages/cutdex_ui/lib/src/widgets/app_popover.dart new file mode 100644 index 0000000..0efeead --- /dev/null +++ b/packages/cutdex_ui/lib/src/widgets/app_popover.dart @@ -0,0 +1,154 @@ +import 'dart:math' as math; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../theme/app_theme.dart'; +import '../theme/menu_metrics.dart'; + +/// Anchored shadcn-style surface, dismissed outside or with Escape. +class AppPopover extends StatefulWidget { + const AppPopover({ + super.key, + required this.builder, + required this.child, + this.width = 288, + this.maxHeight = 480, + this.enabled = true, + this.alignment = AlignmentDirectional.bottomStart, + this.surfaceKey, + this.backgroundColor, + this.borderRadius = AppMenuMetrics.radius, + this.padding = const EdgeInsets.all(AppMenuMetrics.gutter), + }); + + final Widget Function(BuildContext, VoidCallback toggle) builder; + final Widget child; + final double width; + final double maxHeight; + final bool enabled; + final AlignmentGeometry alignment; + final Key? surfaceKey; + final Color? backgroundColor; + final double borderRadius; + final EdgeInsetsGeometry padding; + + @override + State createState() => _AppPopoverState(); +} + +class _AppPopoverState extends State { + final _menu = MenuController(); + + void _toggle() { + if (!widget.enabled) return; + if (_menu.isOpen) { + _menu.close(); + } else { + _menu.open(); + } + } + + @override + void didUpdateWidget(AppPopover oldWidget) { + super.didUpdateWidget(oldWidget); + if (!widget.enabled && _menu.isOpen) _menu.close(); + } + + @override + Widget build(BuildContext context) { + final colors = Theme.of(context).colorScheme; + final viewport = MediaQuery.sizeOf(context); + final surfaceWidth = math.min( + widget.width, + math.max(0.0, viewport.width - 32), + ); + final endAligned = widget.alignment == AlignmentDirectional.bottomEnd; + final direction = Directionality.of(context); + return MenuAnchor( + controller: _menu, + alignmentOffset: Offset( + endAligned + ? (direction == TextDirection.ltr ? -surfaceWidth : surfaceWidth) + : 0, + 4, + ), + consumeOutsideTap: false, + crossAxisUnconstrained: false, + clipBehavior: Clip.none, + style: MenuStyle( + alignment: widget.alignment, + padding: const WidgetStatePropertyAll(EdgeInsets.zero), + backgroundColor: const WidgetStatePropertyAll(Colors.transparent), + surfaceTintColor: const WidgetStatePropertyAll(Colors.transparent), + elevation: const WidgetStatePropertyAll(0), + shadowColor: const WidgetStatePropertyAll(Colors.transparent), + // The inner surface owns the border; do not inherit MenuTheme's stroke. + side: const WidgetStatePropertyAll(BorderSide.none), + shape: WidgetStatePropertyAll( + RoundedRectangleBorder( + borderRadius: BorderRadius.circular(widget.borderRadius), + ), + ), + ), + menuChildren: [ + SizedBox( + key: widget.surfaceKey, + width: surfaceWidth, + child: DecoratedBox( + decoration: BoxDecoration( + color: + widget.backgroundColor ?? AppTheme.popoverBackground(context), + borderRadius: BorderRadius.circular(widget.borderRadius), + border: Border.all( + color: colors.outlineVariant, + width: AppMenuMetrics.borderWidth, + ), + boxShadow: [ + BoxShadow( + color: colors.shadow.withValues(alpha: .1), + offset: const Offset(0, 4), + blurRadius: 6, + spreadRadius: -1, + ), + BoxShadow( + color: colors.shadow.withValues(alpha: .1), + offset: const Offset(0, 2), + blurRadius: 4, + spreadRadius: -2, + ), + ], + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(widget.borderRadius), + child: Padding( + padding: widget.padding, + child: ConstrainedBox( + constraints: BoxConstraints( + maxHeight: math.max( + 0, + math.min(widget.maxHeight, viewport.height - 96), + ), + ), + child: Focus( + autofocus: true, + onKeyEvent: (_, event) { + if (event is KeyDownEvent && + event.logicalKey == LogicalKeyboardKey.escape) { + _menu.close(); + return KeyEventResult.handled; + } + return KeyEventResult.ignored; + }, + child: widget.child, + ), + ), + ), + ), + ), + ), + ], + builder: (context, _, _) => widget.builder(context, _toggle), + ); + } +} diff --git a/packages/cutdex_ui/lib/src/widgets/app_scrub_label.dart b/packages/cutdex_ui/lib/src/widgets/app_scrub_label.dart new file mode 100644 index 0000000..b031e3d --- /dev/null +++ b/packages/cutdex_ui/lib/src/widgets/app_scrub_label.dart @@ -0,0 +1,123 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../theme/app_theme.dart'; + +/// A numeric field's drag handle; the owner controls values and history. +class AppScrubLabel extends StatefulWidget { + const AppScrubLabel({ + super.key, + required this.label, + required this.enabled, + required this.onStart, + required this.onUpdate, + required this.onEnd, + required this.onCancel, + }); + + final String label; + final bool enabled; + final bool Function() onStart; + final ValueChanged onUpdate; + final VoidCallback onEnd; + final VoidCallback onCancel; + + @override + State createState() => _AppScrubLabelState(); +} + +class _AppScrubLabelState extends State { + final _focus = FocusNode(skipTraversal: true); + bool _active = false; + Offset? _down; + + void _update(Offset position) { + final down = _down; + if (!_active || down == null) return; + widget.onUpdate(position.dx - down.dx); + } + + void _cancel() { + _down = null; + if (!_active) return; + _active = false; + widget.onCancel(); + } + + @override + void didUpdateWidget(covariant AppScrubLabel oldWidget) { + super.didUpdateWidget(oldWidget); + if (!widget.enabled && _active) { + _active = false; + _down = null; + scheduleMicrotask(widget.onCancel); + } + } + + @override + void dispose() { + if (_active) scheduleMicrotask(widget.onCancel); + _focus.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => Focus( + focusNode: _focus, + onFocusChange: (focused) { + if (!focused) _cancel(); + }, + onKeyEvent: (_, event) { + if (_active && + event is KeyDownEvent && + event.logicalKey == LogicalKeyboardKey.escape) { + _cancel(); + return KeyEventResult.handled; + } + return KeyEventResult.ignored; + }, + child: MouseRegion( + cursor: widget.enabled + ? SystemMouseCursors.resizeLeftRight + : SystemMouseCursors.basic, + child: Listener( + onPointerCancel: (_) => _cancel(), + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onHorizontalDragDown: (details) => _down = details.globalPosition, + onHorizontalDragStart: (details) { + if (!widget.enabled || !widget.onStart()) return; + _active = true; + _focus.requestFocus(); + _update(details.globalPosition); + }, + onHorizontalDragUpdate: (event) { + _update(event.globalPosition); + }, + onHorizontalDragEnd: (_) { + if (!_active) return; + _active = false; + _down = null; + widget.onEnd(); + }, + onHorizontalDragCancel: _cancel, + child: Align( + widthFactor: 1, + heightFactor: 1, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: AppSpacing.small), + child: Text( + widget.label, + style: Theme.of(context).textTheme.bodyMedium?.copyWith( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + ), + ), + ), + ), + ), + ); +} diff --git a/packages/cutdex_ui/lib/src/widgets/app_slider.dart b/packages/cutdex_ui/lib/src/widgets/app_slider.dart new file mode 100644 index 0000000..1be0e7a --- /dev/null +++ b/packages/cutdex_ui/lib/src/widgets/app_slider.dart @@ -0,0 +1,75 @@ +import 'package:flutter/material.dart'; + +import '../theme/app_theme.dart'; + +class AppSlider extends StatelessWidget { + const AppSlider({ + super.key, + required this.value, + required this.onChanged, + this.min = 0, + this.max = 1, + this.divisions, + this.label, + this.focusNode, + this.semanticFormatterCallback, + this.onChangeStart, + this.onChangeEnd, + }); + + final double value; + final double min; + final double max; + final int? divisions; + final String? label; + final FocusNode? focusNode; + final SemanticFormatterCallback? semanticFormatterCallback; + final ValueChanged? onChanged; + final ValueChanged? onChangeStart; + final ValueChanged? onChangeEnd; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final colors = theme.colorScheme; + final accent = colors.primary; + return SizedBox( + height: AppControlSize.standard, + child: SliderTheme( + data: SliderTheme.of(context).copyWith( + trackHeight: 4, + trackGap: 0, + padding: const EdgeInsets.symmetric(horizontal: AppSpacing.compact), + activeTrackColor: accent, + inactiveTrackColor: colors.secondaryContainer, + disabledActiveTrackColor: colors.onSurface.withValues(alpha: 0.24), + disabledInactiveTrackColor: colors.outlineVariant, + thumbColor: colors.onPrimary, + disabledThumbColor: colors.onSurface.withValues(alpha: 0.38), + overlayColor: accent.withValues(alpha: 0.14), + thumbShape: const RoundSliderThumbShape( + enabledThumbRadius: 6, + disabledThumbRadius: 6, + elevation: 1, + pressedElevation: 1, + ), + overlayShape: const RoundSliderOverlayShape(overlayRadius: 12), + trackShape: const RoundedRectSliderTrackShape(), + showValueIndicator: ShowValueIndicator.never, + ), + child: Slider( + value: value, + min: min, + max: max, + divisions: divisions, + label: label, + focusNode: focusNode, + semanticFormatterCallback: semanticFormatterCallback, + onChanged: onChanged, + onChangeStart: onChangeStart, + onChangeEnd: onChangeEnd, + ), + ), + ); + } +} diff --git a/packages/cutdex_ui/lib/src/widgets/app_switch.dart b/packages/cutdex_ui/lib/src/widgets/app_switch.dart new file mode 100644 index 0000000..f84f67b --- /dev/null +++ b/packages/cutdex_ui/lib/src/widgets/app_switch.dart @@ -0,0 +1,102 @@ +import 'package:flutter/material.dart'; + +import '../theme/app_theme.dart'; + +/// Keeps Flutter switch semantics and keyboard handling under a Nova visual. +class AppSwitch extends StatefulWidget { + const AppSwitch({ + super.key, + required this.value, + required this.onChanged, + this.semanticLabel, + this.focusNode, + this.small = false, + }); + final bool value; + final ValueChanged? onChanged; + final String? semanticLabel; + final FocusNode? focusNode; + final bool small; + @override + State createState() => _AppSwitchState(); +} + +class _AppSwitchState extends State { + bool _focused = false; + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final colors = theme.colorScheme; + final width = widget.small ? 24.0 : 32.0; + final height = widget.small ? 14.0 : 20.0; + final states = { + if (widget.value) WidgetState.selected, + if (widget.onChanged == null) WidgetState.disabled, + }; + final thumb = widget.small ? 12.0 : 16.0; + return Semantics( + label: widget.semanticLabel, + child: Focus( + onFocusChange: (value) => setState(() => _focused = value), + child: SizedBox( + width: width, + height: 36, + child: Stack( + alignment: Alignment.center, + children: [ + Opacity( + opacity: widget.onChanged == null ? .5 : 1, + child: AnimatedContainer( + duration: const Duration(milliseconds: 100), + width: width, + height: height, + padding: const EdgeInsets.all(1), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(AppRadius.pill), + color: AppTheme.switchTrackColor(context, states), + boxShadow: _focused + ? [ + BoxShadow( + color: colors.outline.withValues(alpha: .5), + spreadRadius: 3, + ), + ] + : [], + ), + child: AnimatedAlign( + duration: const Duration(milliseconds: 100), + alignment: widget.value + ? AlignmentDirectional.centerEnd + : AlignmentDirectional.centerStart, + child: SizedBox.square( + dimension: thumb, + child: DecoratedBox( + decoration: BoxDecoration( + shape: BoxShape.circle, + color: AppTheme.switchThumbColor(context, states), + ), + ), + ), + ), + ), + ), + Positioned.fill( + child: Opacity( + opacity: 0, + alwaysIncludeSemantics: true, + child: Switch( + value: widget.value, + onChanged: widget.onChanged, + focusNode: widget.focusNode, + padding: EdgeInsets.zero, + materialTapTargetSize: MaterialTapTargetSize.shrinkWrap, + ), + ), + ), + ], + ), + ), + ), + ); + } +} diff --git a/packages/cutdex_ui/lib/src/widgets/app_tabs.dart b/packages/cutdex_ui/lib/src/widgets/app_tabs.dart new file mode 100644 index 0000000..43a2185 --- /dev/null +++ b/packages/cutdex_ui/lib/src/widgets/app_tabs.dart @@ -0,0 +1,158 @@ +import 'package:freezed_annotation/freezed_annotation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../theme/app_theme.dart'; + +part 'app_tabs.freezed.dart'; + +@freezed +abstract class AppTab with _$AppTab { + const factory AppTab( + T value, + String label, { + IconData? icon, + @Default(true) bool enabled, + }) = _AppTab; +} + +class AppTabs extends StatefulWidget { + const AppTabs({ + super.key, + required this.tabs, + required this.value, + required this.onChanged, + this.textStyle, + this.iconSize = 16, + this.headerStyle = false, + }); + final List> tabs; + final T value; + final ValueChanged onChanged; + final TextStyle? textStyle; + final double iconSize; + final bool headerStyle; + @override + State> createState() => _AppTabsState(); +} + +class _AppTabsState extends State> { + final _focus = {}; + @override + void dispose() { + for (final node in _focus.values) { + node.dispose(); + } + super.dispose(); + } + + @override + void didUpdateWidget(covariant AppTabs oldWidget) { + super.didUpdateWidget(oldWidget); + for (final value in _focus.keys.toList()) { + if (!widget.tabs.any((tab) => tab.value == value)) { + _focus.remove(value)!.dispose(); + } + } + } + + void _navigate(T value, LogicalKeyboardKey key) { + final tabs = widget.tabs.where((tab) => tab.enabled).toList(); + if (tabs.isEmpty) return; + final index = tabs.indexWhere((tab) => tab.value == value); + final rtl = Directionality.of(context) == TextDirection.rtl; + final step = (key == LogicalKeyboardKey.arrowRight) != rtl ? 1 : -1; + final next = key == LogicalKeyboardKey.home + ? 0 + : key == LogicalKeyboardKey.end + ? tabs.length - 1 + : (index + step) % tabs.length; + _focus[tabs[next].value]?.requestFocus(); + widget.onChanged(tabs[next].value); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final colors = theme.colorScheme; + return SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Container( + height: widget.headerStyle ? 38 : 32, + padding: const EdgeInsets.all(AppSpacing.inputVertical), + decoration: BoxDecoration( + color: colors.secondaryContainer, + borderRadius: BorderRadius.circular(widget.headerStyle ? 10 : 8), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + for (final tab in widget.tabs) + Focus( + onKeyEvent: (_, event) { + if (event is KeyDownEvent && + [ + LogicalKeyboardKey.arrowLeft, + LogicalKeyboardKey.arrowRight, + LogicalKeyboardKey.home, + LogicalKeyboardKey.end, + ].contains(event.logicalKey)) { + _navigate(tab.value, event.logicalKey); + return KeyEventResult.handled; + } + return KeyEventResult.ignored; + }, + child: Semantics( + selected: widget.value == tab.value, + child: TextButton( + focusNode: _focus.putIfAbsent(tab.value, FocusNode.new), + onPressed: tab.enabled + ? () { + _focus[tab.value]?.requestFocus(); + widget.onChanged(tab.value); + } + : null, + style: TextButton.styleFrom( + textStyle: widget.textStyle, + minimumSize: Size(0, widget.headerStyle ? 32 : 26), + padding: EdgeInsets.symmetric( + horizontal: widget.headerStyle ? 10 : 6, + ), + foregroundColor: widget.value == tab.value + ? colors.onSurface + : colors.onSurfaceVariant, + backgroundColor: widget.value == tab.value + ? colors.surface + : Colors.transparent, + side: BorderSide( + color: AppTheme.tabBorderColor( + context, + selected: widget.value == tab.value, + headerStyle: widget.headerStyle, + ), + ), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular( + widget.headerStyle ? 8 : 6, + ), + ), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (tab.icon != null) ...[ + Icon(tab.icon, size: widget.iconSize), + SizedBox(width: widget.headerStyle ? 8 : 6), + ], + Text(tab.label), + ], + ), + ), + ), + ), + ], + ), + ), + ); + } +} diff --git a/packages/cutdex_ui/lib/src/widgets/app_tabs.freezed.dart b/packages/cutdex_ui/lib/src/widgets/app_tabs.freezed.dart new file mode 100644 index 0000000..438ae0b --- /dev/null +++ b/packages/cutdex_ui/lib/src/widgets/app_tabs.freezed.dart @@ -0,0 +1,288 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND +// coverage:ignore-file +// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package +// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark + +part of 'app_tabs.dart'; + +// ************************************************************************** +// FreezedGenerator +// ************************************************************************** + +// GENERATED CODE - DO NOT MODIFY BY HAND +// dart format off +T _$identity(T value) => value; +/// @nodoc +mixin _$AppTab { + + T get value; String get label; IconData? get icon; bool get enabled; +/// Create a copy of AppTab +/// with the given fields replaced by the non-null parameter values. +@JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +$AppTabCopyWith> get copyWith => _$AppTabCopyWithImpl>(this as AppTab, _$identity); + + + +@override +bool operator ==(Object other) { + final _this = this as AppTab; + return identical(this, other) || (other.runtimeType == runtimeType&&other is AppTab&&const DeepCollectionEquality().equals(other.value, _this.value)&&(identical(other.label, _this.label) || other.label == _this.label)&&(identical(other.icon, _this.icon) || other.icon == _this.icon)&&(identical(other.enabled, _this.enabled) || other.enabled == _this.enabled)); +} + + +@override +int get hashCode { + final _this = this as AppTab; + return Object.hash(runtimeType,const DeepCollectionEquality().hash(_this.value),_this.label,_this.icon,_this.enabled); +} + +@override +String toString() { + final _this = this as AppTab; + return 'AppTab<$T>(value: ${_this.value}, label: ${_this.label}, icon: ${_this.icon}, enabled: ${_this.enabled})'; +} + + +} + +/// @nodoc +abstract mixin class $AppTabCopyWith { + factory $AppTabCopyWith(AppTab value, $Res Function(AppTab) _then) = _$AppTabCopyWithImpl; +@useResult +$Res call({ + T value, String label, IconData? icon, bool enabled +}); + + + + +} +/// @nodoc +class _$AppTabCopyWithImpl + implements $AppTabCopyWith { + _$AppTabCopyWithImpl(this._self, this._then); + + final AppTab _self; + final $Res Function(AppTab) _then; + +/// Create a copy of AppTab +/// with the given fields replaced by the non-null parameter values. +@pragma('vm:prefer-inline') @override $Res call({Object? value = freezed,Object? label = null,Object? icon = freezed,Object? enabled = null,}) { + return _then(AppTab( +freezed == value ? _self.value : value // ignore: cast_nullable_to_non_nullable +as T,null == label ? _self.label : label // ignore: cast_nullable_to_non_nullable +as String,icon: freezed == icon ? _self.icon : icon // ignore: cast_nullable_to_non_nullable +as IconData?,enabled: null == enabled ? _self.enabled : enabled // ignore: cast_nullable_to_non_nullable +as bool, + )); +} + +} + + +/// Adds pattern-matching-related methods to [AppTab]. +extension AppTabPatterns on AppTab { +/// A variant of `map` that fallback to returning `orElse`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeMap(TResult Function( _AppTab value)? $default,{required TResult orElse(),}){ +final _that = this; +switch (_that) { +case _AppTab() when $default != null: +return $default(_that);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// Callbacks receives the raw object, upcasted. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case final Subclass2 value: +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult map(TResult Function( _AppTab value) $default,){ +final _that = this; +switch (_that) { +case _AppTab(): +return $default(_that);case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `map` that fallback to returning `null`. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case final Subclass value: +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? mapOrNull(TResult? Function( _AppTab value)? $default,){ +final _that = this; +switch (_that) { +case _AppTab() when $default != null: +return $default(_that);case _: + return null; + +} +} +/// A variant of `when` that fallback to an `orElse` callback. +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return orElse(); +/// } +/// ``` + +@optionalTypeArgs TResult maybeWhen(TResult Function( T value, String label, IconData? icon, bool enabled)? $default,{required TResult orElse(),}) {final _that = this; +switch (_that) { +case _AppTab() when $default != null: +return $default(_that.value,_that.label,_that.icon,_that.enabled);case _: + return orElse(); + +} +} +/// A `switch`-like method, using callbacks. +/// +/// As opposed to `map`, this offers destructuring. +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case Subclass2(:final field2): +/// return ...; +/// } +/// ``` + +@optionalTypeArgs TResult when(TResult Function( T value, String label, IconData? icon, bool enabled) $default,) {final _that = this; +switch (_that) { +case _AppTab(): +return $default(_that.value,_that.label,_that.icon,_that.enabled);case _: + throw StateError('Unexpected subclass'); + +} +} +/// A variant of `when` that fallback to returning `null` +/// +/// It is equivalent to doing: +/// ```dart +/// switch (sealedClass) { +/// case Subclass(:final field): +/// return ...; +/// case _: +/// return null; +/// } +/// ``` + +@optionalTypeArgs TResult? whenOrNull(TResult? Function( T value, String label, IconData? icon, bool enabled)? $default,) {final _that = this; +switch (_that) { +case _AppTab() when $default != null: +return $default(_that.value,_that.label,_that.icon,_that.enabled);case _: + return null; + +} +} + +} + +/// @nodoc + + +class _AppTab implements AppTab { + const _AppTab(this.value, this.label, {this.icon, this.enabled = true}); + + +@override final T value; +@override final String label; +@override final IconData? icon; +@override@JsonKey() final bool enabled; + +/// Create a copy of AppTab +/// with the given fields replaced by the non-null parameter values. +@override @JsonKey(includeFromJson: false, includeToJson: false) +@pragma('vm:prefer-inline') +_$AppTabCopyWith> get copyWith => __$AppTabCopyWithImpl>(this, _$identity); + + + +@override +bool operator ==(Object other) { + return identical(this, other) || (other.runtimeType == runtimeType&&other is _AppTab&&const DeepCollectionEquality().equals(other.value, value)&&(identical(other.label, label) || other.label == label)&&(identical(other.icon, icon) || other.icon == icon)&&(identical(other.enabled, enabled) || other.enabled == enabled)); +} + + +@override +int get hashCode { + return Object.hash(runtimeType,const DeepCollectionEquality().hash(value),label,icon,enabled); +} + +@override +String toString() { + return 'AppTab<$T>(value: $value, label: $label, icon: $icon, enabled: $enabled)'; +} + + +} + +/// @nodoc +abstract mixin class _$AppTabCopyWith implements $AppTabCopyWith { + factory _$AppTabCopyWith(_AppTab value, $Res Function(_AppTab) _then) = __$AppTabCopyWithImpl; +@override @useResult +$Res call({ + T value, String label, IconData? icon, bool enabled +}); + + + + +} +/// @nodoc +class __$AppTabCopyWithImpl + implements _$AppTabCopyWith { + __$AppTabCopyWithImpl(this._self, this._then); + + final _AppTab _self; + final $Res Function(_AppTab) _then; + +/// Create a copy of AppTab +/// with the given fields replaced by the non-null parameter values. +@override @pragma('vm:prefer-inline') $Res call({Object? value = freezed,Object? label = null,Object? icon = freezed,Object? enabled = null,}) { + return _then(_AppTab( +freezed == value ? _self.value : value // ignore: cast_nullable_to_non_nullable +as T,null == label ? _self.label : label // ignore: cast_nullable_to_non_nullable +as String,icon: freezed == icon ? _self.icon : icon // ignore: cast_nullable_to_non_nullable +as IconData?,enabled: null == enabled ? _self.enabled : enabled // ignore: cast_nullable_to_non_nullable +as bool, + )); +} + + +} + +// dart format on diff --git a/packages/cutdex_ui/lib/src/widgets/app_text_field.dart b/packages/cutdex_ui/lib/src/widgets/app_text_field.dart new file mode 100644 index 0000000..09a671a --- /dev/null +++ b/packages/cutdex_ui/lib/src/widgets/app_text_field.dart @@ -0,0 +1,198 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../theme/app_theme.dart'; + +/// Shared inline-labelled input built on Flutter's native text editing. +class AppTextField extends StatefulWidget { + const AppTextField({ + super.key, + this.controller, + this.focusNode, + this.label, + this.leading, + this.unit, + this.hintText, + this.errorText, + this.enabled = true, + this.readOnly = false, + this.canRequestFocus = true, + this.keyboardType, + this.inputFormatters, + this.minLines, + this.maxLines = 1, + this.textInputAction, + this.onChanged, + this.onEditingComplete, + this.onSubmitted, + this.onTapOutside, + }); + + final TextEditingController? controller; + final FocusNode? focusNode; + final String? label; + final Widget? leading; + final String? unit; + final String? hintText; + final String? errorText; + final bool enabled; + + final bool readOnly; + final bool canRequestFocus; + final TextInputType? keyboardType; + final List? inputFormatters; + final int? minLines; + final int? maxLines; + final TextInputAction? textInputAction; + final ValueChanged? onChanged; + final VoidCallback? onEditingComplete; + final ValueChanged? onSubmitted; + final TapRegionCallback? onTapOutside; + + @override + State createState() => _AppTextFieldState(); +} + +class _AppTextFieldState extends State { + bool _hovered = false; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final colors = theme.colorScheme; + final foreground = widget.enabled + ? colors.onSurface + : colors.onSurface.withValues(alpha: 0.38); + final focusColor = colors.primary; + final borderless = + theme.inputDecorationTheme.enabledBorder?.borderSide == BorderSide.none; + final style = theme.textTheme.bodyMedium!.copyWith( + color: foreground, + letterSpacing: 0, + ); + OutlineInputBorder border(Color color) => OutlineInputBorder( + borderRadius: BorderRadius.circular(AppRadius.large), + borderSide: BorderSide(color: color), + ); + + return MouseRegion( + onEnter: (_) => setState(() => _hovered = true), + onExit: (_) => setState(() => _hovered = false), + child: Semantics( + label: [widget.label, widget.unit].whereType().join(' '), + child: TextField( + controller: widget.controller, + focusNode: widget.focusNode, + enabled: widget.enabled, + readOnly: widget.readOnly, + canRequestFocus: widget.canRequestFocus, + keyboardType: widget.keyboardType, + inputFormatters: widget.inputFormatters, + minLines: widget.minLines, + maxLines: widget.maxLines, + textInputAction: widget.textInputAction, + style: style, + cursorColor: focusColor, + cursorHeight: AppTheme.inputCursorHeight(context), + cursorWidth: 1, + textAlignVertical: TextAlignVertical.center, + decoration: InputDecoration( + isDense: true, + filled: true, + fillColor: theme.inputDecorationTheme.fillColor, + hoverColor: Colors.transparent, + hintText: widget.hintText, + hintStyle: + theme.inputDecorationTheme.hintStyle ?? + style.copyWith(color: colors.onSurfaceVariant), + errorText: widget.errorText, + errorMaxLines: 2, + contentPadding: + theme.inputDecorationTheme.contentPadding ?? + const EdgeInsets.symmetric( + horizontal: AppSpacing.controlHorizontal, + vertical: AppSpacing.inputVertical, + ), + prefixIcon: + widget.leading ?? + (widget.label == null + ? null + : Align( + widthFactor: 1, + heightFactor: 1, + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.small, + ), + child: ExcludeSemantics( + child: Text( + widget.label!, + style: style.copyWith( + color: widget.enabled + ? colors.onSurfaceVariant + : foreground, + ), + ), + ), + ), + )), + prefixIconConstraints: const BoxConstraints( + minWidth: AppControlSize.standard, + minHeight: AppControlSize.input, + ), + suffixIcon: widget.unit == null + ? null + : Align( + widthFactor: 1, + heightFactor: 1, + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.small, + ), + child: ExcludeSemantics( + child: Text( + widget.unit!, + style: style.copyWith( + color: widget.enabled + ? colors.onSurfaceVariant + : foreground, + ), + ), + ), + ), + ), + suffixIconConstraints: const BoxConstraints( + minWidth: AppControlSize.compact, + minHeight: AppControlSize.input, + ), + border: theme.inputDecorationTheme.border, + enabledBorder: borderless + ? theme.inputDecorationTheme.enabledBorder + : border( + _hovered + ? colors.outline + : theme + .inputDecorationTheme + .enabledBorder + ?.borderSide + .color ?? + colors.outlineVariant, + ), + disabledBorder: theme.inputDecorationTheme.disabledBorder, + focusedBorder: theme.inputDecorationTheme.focusedBorder, + errorBorder: borderless + ? theme.inputDecorationTheme.errorBorder + : border(colors.error), + focusedErrorBorder: borderless + ? theme.inputDecorationTheme.focusedErrorBorder + : border(colors.error), + ), + onChanged: widget.onChanged, + onEditingComplete: widget.onEditingComplete, + onSubmitted: widget.onSubmitted, + onTapOutside: widget.onTapOutside, + ), + ), + ); + } +} diff --git a/packages/cutdex_ui/lib/src/widgets/compact_panel_tabs.dart b/packages/cutdex_ui/lib/src/widgets/compact_panel_tabs.dart new file mode 100644 index 0000000..9e0c6c5 --- /dev/null +++ b/packages/cutdex_ui/lib/src/widgets/compact_panel_tabs.dart @@ -0,0 +1,61 @@ +import 'package:flutter/material.dart'; + +import '../theme/app_theme.dart'; + +class CompactPanelTabs extends StatelessWidget { + const CompactPanelTabs({ + super.key, + required this.values, + required this.selected, + required this.labelBuilder, + required this.onSelected, + this.tabKeyBuilder, + this.padding = const EdgeInsets.all(AppSpacing.gap), + }); + + static const height = AppControlSize.panelToolbar; + + final List values; + final T selected; + final String Function(T) labelBuilder; + final ValueChanged onSelected; + final Key Function(T)? tabKeyBuilder; + final EdgeInsetsGeometry padding; + + @override + Widget build(BuildContext context) => SizedBox( + height: height, + child: Padding( + padding: padding, + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + children: [ + for (final value in values) + Padding( + padding: EdgeInsetsDirectional.only( + end: value == values.last ? 0 : AppSpacing.tiny, + ), + child: Semantics( + selected: selected == value, + child: TextButton( + key: tabKeyBuilder?.call(value), + onPressed: () => onSelected(value), + style: AppTheme.panelTabStyle( + context, + selected: selected == value, + ), + child: Text( + labelBuilder(value), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + ), + ), + ], + ), + ), + ), + ); +} diff --git a/packages/cutdex_ui/lib/src/widgets/delayed_loading_indicator.dart b/packages/cutdex_ui/lib/src/widgets/delayed_loading_indicator.dart new file mode 100644 index 0000000..78543a7 --- /dev/null +++ b/packages/cutdex_ui/lib/src/widgets/delayed_loading_indicator.dart @@ -0,0 +1,39 @@ +import 'dart:async'; + +import 'package:flutter/widgets.dart'; + +/// Keeps brief operations from flashing a loading indicator. +class DelayedLoadingIndicator extends StatefulWidget { + const DelayedLoadingIndicator({super.key, required this.child}); + + static const delay = Duration(milliseconds: 200); + + final Widget child; + + @override + State createState() => + _DelayedLoadingIndicatorState(); +} + +class _DelayedLoadingIndicatorState extends State { + Timer? _timer; + bool _visible = false; + + @override + void initState() { + super.initState(); + _timer = Timer(DelayedLoadingIndicator.delay, () { + if (mounted) setState(() => _visible = true); + }); + } + + @override + void dispose() { + _timer?.cancel(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => + _visible ? widget.child : const SizedBox.shrink(); +} diff --git a/packages/cutdex_ui/lib/src/widgets/native_context_menu.dart b/packages/cutdex_ui/lib/src/widgets/native_context_menu.dart new file mode 100644 index 0000000..f160bf4 --- /dev/null +++ b/packages/cutdex_ui/lib/src/widgets/native_context_menu.dart @@ -0,0 +1,59 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:cutdex_native/cutdex_native.dart'; + +import 'app_menu.dart'; + +/// Returns false when native menus are unavailable or an entry is unsupported. +Future showNativeContextMenu( + List items, + Offset position, + bool Function() isMounted, +) async { + if (kIsWeb || defaultTargetPlatform != TargetPlatform.macOS) return false; + final actions = []; + List? encode(List entries) { + final encoded = []; + for (final entry in entries) { + switch (entry) { + case AppMenuItem(): + final id = actions.length; + actions.add(entry.onPressed); + encoded.add( + NativeMenuEntry( + id: id, + label: entry.label, + enabled: entry.onPressed != null, + selected: entry.selected == true, + ), + ); + case AppMenuSeparator(): + encoded.add(const NativeMenuEntry.separator()); + case AppMenuLabel(): + encoded.add(NativeMenuEntry(label: entry.label, enabled: false)); + case AppSubmenu(): + final children = encode(entry.items); + if (children == null) return null; + encoded.add(NativeMenuEntry(label: entry.label, children: children)); + default: + return null; + } + } + return encoded; + } + + final entries = encode(items); + if (entries == null) return false; + try { + final selected = await NativeContextMenu.show(entries, position); + if (isMounted() && + selected != null && + selected >= 0 && + selected < actions.length) { + actions[selected]?.call(); + } + return true; + } on NativeMenuUnavailableException { + return false; + } +} diff --git a/packages/cutdex_ui/lib/src/widgets/resource_download_progress.dart b/packages/cutdex_ui/lib/src/widgets/resource_download_progress.dart new file mode 100644 index 0000000..cb48a42 --- /dev/null +++ b/packages/cutdex_ui/lib/src/widgets/resource_download_progress.dart @@ -0,0 +1,65 @@ +import 'package:flutter/material.dart'; + +import 'package:cutdex_ui/theme.dart'; + +/// Byte-based download progress shared by resource dialogs and task details. +class ResourceDownloadProgress extends StatelessWidget { + const ResourceDownloadProgress({ + super.key, + required this.downloadedBytes, + required this.totalBytes, + required this.status, + this.paused = false, + this.bytesPerSecond = 0, + }); + + final int downloadedBytes; + final int totalBytes; + final String status; + final bool paused; + final int bytesPerSecond; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final total = totalBytes; + final downloaded = downloadedBytes.clamp(0, total); + final progress = total <= 0 ? 0.0 : downloaded / total; + final speedPrefix = paused + ? '' + : '${formatResourceBytes(bytesPerSecond)}/s - '; + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + '$speedPrefix' + '${formatResourceBytes(downloaded)}/${formatResourceBytes(total)}' + '${status.isEmpty ? '' : ', $status'}', + style: AppTheme.resourceProgressTextStyle(context), + ), + const SizedBox(height: AppSpacing.tiny), + LinearProgressIndicator( + value: progress, + minHeight: 3, + borderRadius: const BorderRadius.all(Radius.circular(2)), + color: theme.colorScheme.primary, + backgroundColor: theme.dividerColor, + ), + ], + ); + } +} + +String formatResourceBytes(int bytes) { + if (bytes < 1000) return '$bytes B'; + final units = ['KB', 'MB', 'GB', 'TB']; + var amount = bytes.toDouble(); + var unit = -1; + do { + amount /= 1000; + unit++; + } while (amount >= 1000 && unit < units.length - 1); + final precision = amount >= 100 ? 0 : 1; + return '${amount.toStringAsFixed(precision)} ${units[unit]}'; +} diff --git a/packages/cutdex_ui/lib/src/widgets/scroll_edge_fade.dart b/packages/cutdex_ui/lib/src/widgets/scroll_edge_fade.dart new file mode 100644 index 0000000..6f8425c --- /dev/null +++ b/packages/cutdex_ui/lib/src/widgets/scroll_edge_fade.dart @@ -0,0 +1,175 @@ +import 'package:flutter/material.dart'; + +/// Owns the controller shared by a scroll view and its edge fade. +class ScrollEdgeFadeBuilder extends StatefulWidget { + const ScrollEdgeFadeBuilder({ + super.key, + required this.builder, + this.axis = Axis.vertical, + this.fadeExtent = 24, + }); + + final Widget Function(ScrollController controller) builder; + final Axis axis; + final double fadeExtent; + + @override + State createState() => _ScrollEdgeFadeBuilderState(); +} + +class _ScrollEdgeFadeBuilderState extends State { + final ScrollController _controller = ScrollController(); + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => ScrollEdgeFade( + controller: _controller, + axis: widget.axis, + fadeExtent: widget.fadeExtent, + child: widget.builder(_controller), + ); +} + +/// Fades overflowing scroll content at the viewport edges. +/// +/// [controller] must also be attached to the child scroll view and remains +/// owned by the caller. [axis] must match the child scroll view's axis. +class ScrollEdgeFade extends StatefulWidget { + const ScrollEdgeFade({ + super.key, + required this.controller, + required this.child, + this.axis = Axis.vertical, + this.fadeExtent = 24, + this.bottomInset = 0, + }) : assert(fadeExtent > 0 && fadeExtent < double.infinity); + + final ScrollController controller; + final Widget child; + final Axis axis; + final double fadeExtent; + + /// Keeps the bottom fade above an overlay while the scroll view fills it. + final double bottomInset; + + @override + State createState() => _ScrollEdgeFadeState(); +} + +class _ScrollEdgeFadeState extends State { + double _fadeStart = 0; + double _fadeEnd = 0; + bool _updateScheduled = false; + + @override + void initState() { + super.initState(); + widget.controller.addListener(_updateFade); + _scheduleFadeUpdate(); + } + + @override + void didUpdateWidget(covariant ScrollEdgeFade oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.controller != widget.controller) { + oldWidget.controller.removeListener(_updateFade); + widget.controller.addListener(_updateFade); + } + _scheduleFadeUpdate(); + } + + void _scheduleFadeUpdate() { + if (_updateScheduled) return; + _updateScheduled = true; + WidgetsBinding.instance.addPostFrameCallback((_) { + _updateScheduled = false; + if (mounted) _updateFade(); + }); + } + + void _updateFade() { + final controller = widget.controller; + if (!controller.hasClients || !controller.position.hasContentDimensions) { + return; + } + final position = controller.position; + final reversed = + position.axisDirection == AxisDirection.up || + position.axisDirection == AxisDirection.left; + final before = (position.extentBefore / widget.fadeExtent).clamp(0.0, 1.0); + final after = (position.extentAfter / widget.fadeExtent).clamp(0.0, 1.0); + final start = reversed ? after : before; + final end = reversed ? before : after; + if ((start - _fadeStart).abs() > 0.005 || (end - _fadeEnd).abs() > 0.005) { + setState(() { + _fadeStart = start; + _fadeEnd = end; + }); + } + } + + @override + void dispose() { + widget.controller.removeListener(_updateFade); + super.dispose(); + } + + @override + Widget build(BuildContext context) => + NotificationListener( + onNotification: (notification) { + if (notification.depth == 0) _scheduleFadeUpdate(); + return false; + }, + child: ShaderMask( + blendMode: BlendMode.dstIn, + shaderCallback: (bounds) { + final vertical = widget.axis == Axis.vertical; + final extent = vertical ? bounds.height : bounds.width; + final fadeSize = extent <= widget.fadeExtent * 2 + ? 0.5 + : widget.fadeExtent / extent; + final inset = vertical ? widget.bottomInset : 0.0; + final visibleEnd = extent <= 0 + ? 0.0 + : ((extent - inset) / extent).clamp(0.0, 1.0); + final insetFadeSize = fadeSize.clamp(0.0, visibleEnd / 2); + return LinearGradient( + begin: vertical ? Alignment.topCenter : Alignment.centerLeft, + end: vertical ? Alignment.bottomCenter : Alignment.centerRight, + stops: inset <= 0 + ? [0, fadeSize, 1 - fadeSize, 1] + : [ + 0, + insetFadeSize, + visibleEnd - insetFadeSize, + visibleEnd, + visibleEnd, + 1, + ], + colors: inset <= 0 + ? [ + Colors.white.withValues(alpha: 1 - _fadeStart), + Colors.white, + Colors.white, + Colors.white.withValues(alpha: 1 - _fadeEnd), + ] + : [ + Colors.white.withValues(alpha: 1 - _fadeStart), + Colors.white, + Colors.white, + Colors.white.withValues(alpha: 1 - _fadeEnd), + Colors.transparent, + Colors.transparent, + ], + ).createShader(bounds); + }, + child: widget.child, + ), + ); +} diff --git a/packages/cutdex_ui/lib/src/widgets/workspace_panel.dart b/packages/cutdex_ui/lib/src/widgets/workspace_panel.dart new file mode 100644 index 0000000..38e5b7b --- /dev/null +++ b/packages/cutdex_ui/lib/src/widgets/workspace_panel.dart @@ -0,0 +1,77 @@ +import 'package:flutter/material.dart'; + +import 'package:cutdex_ui/theme.dart'; + +class WorkspacePanel extends StatelessWidget { + const WorkspacePanel({ + super.key, + this.title, + this.icon, + required this.child, + this.trailing, + this.controls, + this.headerHeight = AppControlSize.panelHeader, + this.headerPadding = const EdgeInsets.symmetric( + horizontal: AppSpacing.compact, + ), + this.showHeaderDivider = true, + this.paintBackground = true, + }); + + final String? title; + final IconData? icon; + final Widget child; + final Widget? trailing; + final Widget? controls; + final double headerHeight; + final EdgeInsetsGeometry headerPadding; + final bool showHeaderDivider; + final bool paintBackground; + + @override + Widget build(BuildContext context) { + final content = Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + SizedBox( + height: headerHeight, + child: Padding( + padding: headerPadding, + child: Row( + children: [ + if (icon case final icon?) ...[ + Icon(icon, size: AppIconSize.small), + const SizedBox(width: AppSpacing.small), + ], + if (title case final title?) + Expanded( + child: Text( + title, + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: Theme.of(context).textTheme.labelLarge, + ), + ), + if (controls case final controls?) ...[ + if (title != null) const SizedBox(width: AppSpacing.small), + Expanded(child: controls), + ], + if (trailing case final trailing?) ...[ + if (title == null && controls == null) const Spacer(), + trailing, + ], + ], + ), + ), + ), + if (showHeaderDivider) const Divider(), + Expanded(child: child), + ], + ); + if (!paintBackground) return content; + return ColoredBox( + color: Theme.of(context).colorScheme.surface, + child: content, + ); + } +} diff --git a/packages/cutdex_ui/lib/theme.dart b/packages/cutdex_ui/lib/theme.dart new file mode 100644 index 0000000..163de14 --- /dev/null +++ b/packages/cutdex_ui/lib/theme.dart @@ -0,0 +1,2 @@ +export 'src/theme/app_theme.dart'; +export 'src/theme/menu_metrics.dart'; diff --git a/packages/cutdex_ui/lib/widgets.dart b/packages/cutdex_ui/lib/widgets.dart new file mode 100644 index 0000000..2b19c61 --- /dev/null +++ b/packages/cutdex_ui/lib/widgets.dart @@ -0,0 +1,18 @@ +export 'src/widgets/app_button_group.dart'; +export 'src/widgets/app_combobox.dart'; +export 'src/widgets/app_dialog.dart'; +export 'src/widgets/app_field.dart'; +export 'src/widgets/app_item.dart'; +export 'src/widgets/app_menu.dart'; +export 'src/widgets/app_popover.dart'; +export 'src/widgets/app_scrub_label.dart'; +export 'src/widgets/app_slider.dart'; +export 'src/widgets/app_switch.dart'; +export 'src/widgets/app_tabs.dart'; +export 'src/widgets/app_text_field.dart'; +export 'src/widgets/compact_panel_tabs.dart'; +export 'src/widgets/delayed_loading_indicator.dart'; +export 'src/widgets/native_context_menu.dart'; +export 'src/widgets/scroll_edge_fade.dart'; +export 'src/widgets/workspace_panel.dart'; +export 'src/widgets/resource_download_progress.dart'; diff --git a/packages/cutdex_ui/pubspec.yaml b/packages/cutdex_ui/pubspec.yaml new file mode 100644 index 0000000..1d2d6fb --- /dev/null +++ b/packages/cutdex_ui/pubspec.yaml @@ -0,0 +1,18 @@ +name: cutdex_ui +description: Shared Cutdex widgets and visual theme. +version: 0.1.0 +publish_to: none +resolution: workspace +environment: + sdk: ^3.13.2 +dependencies: + flutter: + sdk: flutter + cutdex_native: ^0.1.0 + freezed_annotation: ^3.1.0 +dev_dependencies: + flutter_test: + sdk: flutter + flutter_lints: ^6.0.0 + build_runner: ^2.16.1 + freezed: ^4.0.2 diff --git a/packages/cutdex_ui/test/app_dialog_style_test.dart b/packages/cutdex_ui/test/app_dialog_style_test.dart new file mode 100644 index 0000000..2e15d10 --- /dev/null +++ b/packages/cutdex_ui/test/app_dialog_style_test.dart @@ -0,0 +1,129 @@ +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex_ui/widgets.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets('standard dialog uses Codex spacing, type and button size', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + theme: AppTheme.penDark, + home: Scaffold( + body: Builder( + builder: (context) => TextButton( + onPressed: () => showAppDialog( + context: context, + builder: (_) => AppDialog( + title: '下载资源', + description: '下载所需模型', + actions: [ + TextButton(onPressed: () {}, child: const Text('取消')), + FilledButton(onPressed: () {}, child: const Text('下载')), + ], + child: const Text('正在准备资源'), + ), + ), + child: const Text('Open'), + ), + ), + ), + ), + ); + await tester.tap(find.text('Open')); + await tester.pumpAndSettle(); + + final frame = tester.getRect(find.byKey(const Key('app-dialog-frame'))); + final title = tester.getRect(find.text('下载资源')); + final description = tester.getRect(find.text('下载所需模型')); + final body = tester.getRect(find.text('正在准备资源')); + final close = tester.getRect( + find.byKey(const Key('app-dialog-close-button')), + ); + final action = tester.getRect(find.widgetWithText(FilledButton, '下载')); + final cancel = tester.getRect(find.widgetWithText(TextButton, '取消')); + expect(title.left - frame.left, AppSpacing.large); + expect(frame.width, 420); + expect(title.top - frame.top, AppSpacing.large); + expect(body.left - frame.left, AppSpacing.large); + expect(description.top - title.bottom, AppSpacing.tiny); + expect(body.top - description.bottom, AppSpacing.compact); + expect(frame.right - close.right, AppSpacing.medium); + expect(close.top - frame.top, AppSpacing.medium); + expect(close.size, const Size.square(24)); + expect( + Theme.of(tester.element(find.text('下载'))) + .filledButtonTheme + .style! + .minimumSize! + .resolve({}), + const Size(0, 32), + ); + expect(action.height, 32); + expect(cancel.height, 32); + expect(action.left - cancel.right, AppSpacing.compact); + expect(frame.right - action.right, AppSpacing.large); + expect(action.top - body.bottom, AppSpacing.compact); + expect(frame.bottom - action.bottom, AppSpacing.large); + expect(tester.widget(find.text('下载资源')).style?.fontSize, 20); + expect( + tester.widget(find.text('下载资源')).style?.fontWeight, + FontWeight.w600, + ); + expect( + DefaultTextStyle.of(tester.element(find.text('正在准备资源'))).style.fontSize, + 14, + ); + expect( + Theme.of(tester.element(find.text('正在准备资源'))).dialogTheme.backgroundColor, + const Color(0xFF242424), + ); + final shape = AppTheme.penDark.dialogTheme.shape! as RoundedRectangleBorder; + expect(shape.borderRadius, BorderRadius.circular(AppRadius.dialog)); + expect(shape.side, BorderSide.none); + expect( + Theme.of(tester.element(find.text('取消'))) + .textButtonTheme + .style! + .textStyle! + .resolve({})! + .fontSize, + 14, + ); + }); + + testWidgets('selection dialog returns the chosen option', (tester) async { + String? selected; + await tester.pumpWidget( + MaterialApp( + theme: AppTheme.penDark, + home: Scaffold( + body: Builder( + builder: (context) => TextButton( + onPressed: () async { + selected = await showAppDialog( + context: context, + builder: (dialogContext) => AppDialog( + title: '选择目标片段', + child: AppDialogOption( + label: '片段 A', + onPressed: () => Navigator.pop(dialogContext, 'a'), + ), + ), + ); + }, + child: const Text('Open'), + ), + ), + ), + ), + ); + await tester.tap(find.text('Open')); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('app-dialog-frame')), findsOneWidget); + await tester.tap(find.text('片段 A')); + await tester.pumpAndSettle(); + expect(selected, 'a'); + }); +} diff --git a/packages/cutdex_ui/test/app_item_test.dart b/packages/cutdex_ui/test/app_item_test.dart new file mode 100644 index 0000000..1759443 --- /dev/null +++ b/packages/cutdex_ui/test/app_item_test.dart @@ -0,0 +1,107 @@ +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex_ui/widgets.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets('property list rows use the project item gap without a line', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + theme: AppTheme.penDark, + home: Theme( + data: AppTheme.propertiesPanelTheme(AppTheme.penDark), + child: Scaffold( + body: AppItemGroup( + children: [ + AppItem( + key: const Key('first-mask'), + leading: IconButton( + key: const Key('mask-visibility'), + icon: const Icon(Icons.visibility_outlined), + onPressed: () {}, + ), + actions: [ + IconButton( + key: const Key('mask-delete'), + icon: const Icon(Icons.delete_outline), + onPressed: () {}, + ), + ], + child: const Text('蒙版 1'), + ), + const AppItem(key: Key('second-mask'), child: Text('蒙版 2')), + ], + ), + ), + ), + ), + ); + expect( + tester.getSize(find.byKey(const Key('first-mask'))).height, + AppControlSize.propertyItem, + ); + expect( + tester.getSize(find.byKey(const Key('second-mask'))).height, + AppControlSize.propertyItem, + ); + expect( + tester.getSize(find.byKey(const Key('mask-visibility'))).height, + AppControlSize.propertyControl, + ); + expect( + tester.getRect(find.byKey(const Key('second-mask'))).top - + tester.getRect(find.byKey(const Key('first-mask'))).bottom, + AppSidebarMetrics.projectGap, + ); + expect(find.byType(Divider), findsNothing); + }); + + testWidgets('property list hover and selection use translucent ink', ( + tester, + ) async { + for (final theme in [AppTheme.penLight, AppTheme.penDark]) { + Future mount({required bool selected}) => tester.pumpWidget( + MaterialApp( + theme: theme, + home: Theme( + data: AppTheme.propertiesPanelTheme(theme), + child: Scaffold( + body: AppItem( + selected: selected, + onPressed: () {}, + child: const Text('蒙版 1'), + ), + ), + ), + ), + ); + + Finder row() => + find.descendant(of: find.byType(AppItem), matching: find.byType(T)); + final ink = theme.colorScheme.onSurface; + await mount(selected: false); + expect( + tester.widget(row()).color, + Colors.transparent, + ); + expect( + tester.widget(row()).hoverColor, + ink.withValues( + alpha: theme.brightness == Brightness.dark ? .078 : .058, + ), + ); + + await mount(selected: true); + expect( + tester.widget(row()).color, + ink.withValues(alpha: .05), + ); + expect( + tester.widget(row()).hoverColor, + ink.withValues(alpha: .05), + ); + } + }); +} diff --git a/packages/cutdex_ui/test/app_menu_test.dart b/packages/cutdex_ui/test/app_menu_test.dart new file mode 100644 index 0000000..9a31139 --- /dev/null +++ b/packages/cutdex_ui/test/app_menu_test.dart @@ -0,0 +1,428 @@ +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex_ui/widgets.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets( + 'native menu waits for right-button release and dismissal keeps left clicks working', + (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.macOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + const channel = MethodChannel('cutdex_native/context_menu'); + var opened = 0; + var clicked = 0; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, ( + _, + ) async { + opened++; + return null; + }); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + channel, + null, + ), + ); + await tester.pumpWidget( + MaterialApp( + theme: AppTheme.penLight, + + home: Scaffold( + body: Column( + children: [ + AppContextMenu( + itemsBuilder: (_) => [ + AppMenuItem(label: 'Action', onPressed: () {}), + ], + child: const SizedBox(width: 200, height: 200), + ), + TextButton( + onPressed: () => clicked++, + child: const Text('Other control'), + ), + ], + ), + ), + ), + ); + for (var i = 0; i < 2; i++) { + final pointer = await tester.startGesture( + tester.getCenter(find.byType(AppContextMenu)), + kind: PointerDeviceKind.mouse, + buttons: kSecondaryMouseButton, + ); + // Hold past the tap-down deadline: native tracking must not start yet. + await tester.pump(const Duration(milliseconds: 200)); + expect(opened, i); + await pointer.up(); + await tester.pumpAndSettle(); + expect(opened, i + 1); + expect(find.text('Action'), findsNothing); + await tester.tap(find.text('Other control')); + await tester.pumpAndSettle(); + expect(clicked, i + 1); + } + expect(tester.takeException(), isNull); + debugDefaultTargetPlatformOverride = null; + }, + ); + + testWidgets( + 'searchable shared select filters languages and resets after selection', + (tester) async { + var value = 'ja'; + await tester.pumpWidget( + MaterialApp( + theme: AppTheme.penLight, + + home: Scaffold( + body: SizedBox( + width: 280, + child: StatefulBuilder( + builder: (context, setState) => AppSelect( + emptyLabel: '没有匹配的选项', + label: '源语言', + value: value, + searchable: true, + searchHint: '搜索选项', + onChanged: (next) => setState(() => value = next), + options: const [ + AppSelectOption('ja', '日语 (ja)'), + AppSelectOption('zh', '中文 (zh)'), + AppSelectOption('en', '英语 (en)', enabled: false), + ], + ), + ), + ), + ), + ), + ); + await tester.tap(find.byType(TextField)); + await tester.pumpAndSettle(); + await tester.enterText(find.byType(TextField), 'zh'); + await tester.pumpAndSettle(); + expect(find.widgetWithText(MenuItemButton, '日语 (ja)'), findsNothing); + await tester.tap(find.widgetWithText(MenuItemButton, '中文 (zh)')); + await tester.pumpAndSettle(); + expect(value, 'zh'); + await tester.tap(find.byType(TextField)); + await tester.pumpAndSettle(); + expect(find.widgetWithText(MenuItemButton, '日语 (ja)'), findsOneWidget); + expect( + tester + .widget( + find.widgetWithText(MenuItemButton, '英语 (en)'), + ) + .onPressed, + isNull, + ); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pumpAndSettle(); + expect(find.byType(MenuItemButton), findsNothing); + expect( + tester.widget(find.byType(TextField)).controller!.text, + '中文 (zh)', + ); + await tester.tap(find.byType(TextField)); + await tester.enterText(find.byType(TextField), 'unknown'); + await tester.pumpAndSettle(); + expect(find.text('没有匹配的选项'), findsOneWidget); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pumpAndSettle(); + expect(value, 'zh'); + expect( + tester.widget(find.byType(TextField)).controller!.text, + '中文 (zh)', + ); + await tester.tap(find.byType(TextField)); + await tester.enterText(find.byType(TextField), 'ja'); + await tester.pumpAndSettle(); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + expect(value, 'ja'); + expect( + tester.widget(find.byType(TextField)).controller!.text, + '日语 (ja)', + ); + expect(tester.takeException(), isNull); + }, + ); + + testWidgets( + 'stationary mouse scroll releases old hover focus without shifting the menu', + (tester) async { + await tester.pumpWidget( + MaterialApp( + theme: AppTheme.penDark, + home: Scaffold( + body: SizedBox( + width: 280, + child: AppSelect( + emptyLabel: 'No matching options', + label: 'Language', + value: 0, + searchable: true, + searchHint: '搜索选项', + onChanged: (_) {}, + options: [ + for (var i = 0; i < 40; i++) + AppSelectOption(i, 'Language $i'), + ], + ), + ), + ), + ), + ); + await tester.tap(find.byType(TextField)); + await tester.pumpAndSettle(); + final previous = find.widgetWithText(MenuItemButton, 'Language 3'); + final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse); + await mouse.addPointer(location: Offset.zero); + await mouse.moveTo(tester.getCenter(previous)); + await tester.pumpAndSettle(); + expect( + tester.widget(previous).focusNode!.hasFocus, + isFalse, + ); + final scrollable = tester + .stateList(find.byType(Scrollable)) + .firstWhere((state) => state.axisDirection == AxisDirection.down); + scrollable.position.jumpTo(24); + // Do not move the pointer: allow the normal transition to finish. + await tester.pumpAndSettle(); + expect( + tester.widget(previous).focusNode!.hasFocus, + isFalse, + ); + expect(scrollable.position.pixels, 24); + final highlight = const Color(0xFFFCFCFC).withValues(alpha: 0.078); + final backgrounds = tester.widgetList( + find.descendant( + of: find.byType(MenuItemButton), + matching: find.byType(Material), + ), + ); + expect( + backgrounds.where((material) => material.color == highlight), + hasLength(1), + ); + await mouse.removePointer(); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + }, + ); + + testWidgets('select works inside a dialog in both themes', (tester) async { + for (final theme in [AppTheme.penLight, AppTheme.penDark]) { + var value = 1; + await tester.pumpWidget( + MaterialApp( + theme: theme, + home: StatefulBuilder( + builder: (context, setState) => Scaffold( + body: AlertDialog( + content: SizedBox( + width: 360, + child: AppSelect( + emptyLabel: 'No matching options', + value: value, + label: 'Theme', + options: const [ + AppSelectOption(1, 'System'), + AppSelectOption(2, 'Dark'), + AppSelectOption(3, 'Disabled', enabled: false), + ], + onChanged: (next) => setState(() => value = next), + ), + ), + ), + ), + ), + ), + ); + await tester.tap(find.byType(TextButton)); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + expect(find.byIcon(Icons.check), findsOneWidget); + expect( + tester.getSize(find.widgetWithText(MenuItemButton, 'Dark')).height, + 28, + ); + expect( + tester + .widget( + find.widgetWithText(MenuItemButton, 'Disabled'), + ) + .onPressed, + isNull, + ); + await tester.tap(find.widgetWithText(MenuItemButton, 'Dark')); + await tester.pumpAndSettle(); + expect(value, 2); + expect(find.byType(MenuItemButton), findsNothing); + } + }); + + testWidgets('dropdown supports keyboard selection and escape', ( + tester, + ) async { + var selected = false; + late FocusNode triggerFocus; + await tester.pumpWidget( + MaterialApp( + theme: AppTheme.penLight, + home: Scaffold( + body: AppDropdownMenu( + items: [ + AppMenuItem(label: 'Action', onPressed: () => selected = true), + ], + builder: (context, toggle, focus) { + triggerFocus = focus; + return TextButton( + focusNode: focus, + onPressed: toggle, + child: const Text('Open'), + ); + }, + ), + ), + ), + ); + triggerFocus.requestFocus(); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pumpAndSettle(); + expect(find.text('Action'), findsOneWidget); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + expect(selected, isTrue); + expect(triggerFocus.hasFocus, isTrue); + await tester.tap(find.text('Open')); + await tester.pumpAndSettle(); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pumpAndSettle(); + expect(find.text('Action'), findsNothing); + expect(triggerFocus.hasFocus, isTrue); + }); + + testWidgets('context menu clamps at edges and opens submenu', (tester) async { + var selected = false; + await tester.pumpWidget( + MaterialApp( + theme: AppTheme.penDark, + home: Scaffold( + body: AppContextMenu( + itemsBuilder: (_) => [ + AppSubmenu( + label: 'More', + items: [ + AppMenuItem( + label: 'Action', + onPressed: () => selected = true, + ), + ], + ), + ], + child: const SizedBox.expand(), + ), + ), + ), + ); + await tester.tapAt(const Offset(795, 595), buttons: kSecondaryMouseButton); + await tester.pumpAndSettle(); + final rect = tester.getRect(find.byType(SubmenuButton)); + expect(rect.right, lessThanOrEqualTo(800)); + expect(rect.bottom, lessThanOrEqualTo(600)); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); + await tester.pumpAndSettle(); + await tester.tap(find.text('Action')); + await tester.pumpAndSettle(); + expect(selected, isTrue); + expect(find.text('More'), findsNothing); + expect(tester.takeException(), isNull); + }); + + testWidgets( + 'context menu stays beside a bottom pointer in an offset region', + (tester) async { + await tester.pumpWidget( + MaterialApp( + theme: AppTheme.penDark, + home: Scaffold( + body: Padding( + padding: const EdgeInsets.only(left: 180, top: 120), + child: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 400, + height: 460, + child: AppContextMenu( + itemsBuilder: (_) => const [ + AppMenuItem(label: 'Action 1'), + AppMenuItem(label: 'Action 2'), + AppMenuItem(label: 'Action 3'), + AppMenuItem(label: 'Action 4'), + AppMenuItem(label: 'Action 5'), + ], + child: const ColoredBox(color: Colors.black), + ), + ), + ), + ), + ), + ), + ); + const pointer = Offset(340, 560); + await tester.tapAt(pointer, buttons: kSecondaryMouseButton); + await tester.pumpAndSettle(); + + final items = find.byType(MenuItemButton); + expect(items, findsNWidgets(5)); + final first = tester.getRect(items.first); + final last = tester.getRect(items.last); + expect(first.left, closeTo(pointer.dx + 6, 1)); + expect(first.top, greaterThan(380)); + expect(last.bottom, lessThanOrEqualTo(pointer.dy)); + }, + ); + + testWidgets( + 'context menu only focuses its first item when opened by keyboard', + (tester) async { + await tester.pumpWidget( + MaterialApp( + theme: AppTheme.penDark, + home: Scaffold( + body: AppContextMenu( + itemsBuilder: (_) => const [AppMenuItem(label: 'Action')], + child: const SizedBox.expand(), + ), + ), + ), + ); + await tester.tapAt( + const Offset(300, 300), + buttons: kSecondaryMouseButton, + ); + await tester.pumpAndSettle(); + expect(find.text('Action'), findsOneWidget); + expect(FocusManager.instance.primaryFocus, isA()); + expect(FocusManager.instance.primaryFocus, isNot(isA())); + + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pumpAndSettle(); + await tester.sendKeyEvent(LogicalKeyboardKey.contextMenu); + await tester.pumpAndSettle(); + expect(find.text('Action'), findsOneWidget); + expect(FocusManager.instance.primaryFocus, isA()); + }, + ); +} diff --git a/packages/cutdex_ui/test/app_popover_test.dart b/packages/cutdex_ui/test/app_popover_test.dart new file mode 100644 index 0000000..58e3612 --- /dev/null +++ b/packages/cutdex_ui/test/app_popover_test.dart @@ -0,0 +1,101 @@ +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex_ui/widgets.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets( + 'popover anchors below its trigger and dismisses outside and with Escape', + (tester) async { + var outsideClicks = 0; + await tester.pumpWidget( + MaterialApp( + theme: AppTheme.penLight, + home: Scaffold( + body: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + AppPopover( + builder: (_, toggle) => IconButton( + key: const Key('trigger'), + onPressed: toggle, + icon: const Icon(Icons.task_alt), + ), + child: const Text('Tasks'), + ), + const SizedBox(height: 200), + TextButton( + onPressed: () => outsideClicks++, + child: const Text('Outside'), + ), + ], + ), + ), + ), + ); + await tester.tap(find.byKey(const Key('trigger'))); + await tester.pumpAndSettle(); + expect(find.text('Tasks'), findsOneWidget); + // The menu host must not add a second outline around the inner surface. + final menuSurface = tester + .widgetList( + find.ancestor( + of: find.text('Tasks'), + matching: find.byType(Material), + ), + ) + .firstWhere((material) => material.shape is OutlinedBorder); + expect( + (menuSurface.shape! as OutlinedBorder).side.style, + BorderStyle.none, + ); + + expect( + tester.getTopLeft(find.text('Tasks')).dy, + greaterThan(tester.getBottomLeft(find.byKey(const Key('trigger'))).dy), + ); + await tester.tap(find.text('Outside')); + await tester.pumpAndSettle(); + expect(find.text('Tasks'), findsNothing); + expect(outsideClicks, 1); + await tester.tap(find.byKey(const Key('trigger'))); + await tester.pumpAndSettle(); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pumpAndSettle(); + expect(find.text('Tasks'), findsNothing); + expect(tester.takeException(), isNull); + }, + ); + + testWidgets('end-aligned popover stays inside the viewport', (tester) async { + await tester.pumpWidget( + MaterialApp( + theme: AppTheme.penLight, + home: Scaffold( + body: Align( + alignment: Alignment.topLeft, + child: AppPopover( + width: 288, + alignment: AlignmentDirectional.bottomEnd, + surfaceKey: const Key('surface'), + builder: (_, toggle) => TextButton( + key: const Key('trigger'), + onPressed: toggle, + child: const Text('Open'), + ), + child: const Text('Content'), + ), + ), + ), + ), + ); + await tester.tap(find.byKey(const Key('trigger'))); + await tester.pumpAndSettle(); + expect( + tester.getRect(find.byKey(const Key('surface'))).left, + greaterThanOrEqualTo(0), + ); + expect(tester.takeException(), isNull); + }); +} diff --git a/packages/cutdex_ui/test/app_settings_components_test.dart b/packages/cutdex_ui/test/app_settings_components_test.dart new file mode 100644 index 0000000..7d70974 --- /dev/null +++ b/packages/cutdex_ui/test/app_settings_components_test.dart @@ -0,0 +1,120 @@ +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex_ui/widgets.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets( + 'dialog fits small screens and restores trigger focus on escape', + (tester) async { + tester.view.physicalSize = const Size(320, 400); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final focus = FocusNode(); + addTearDown(focus.dispose); + for (final theme in [AppTheme.penLight, AppTheme.penDark]) { + await tester.pumpWidget( + MaterialApp( + theme: theme, + home: Scaffold( + body: Builder( + builder: (context) => TextButton( + focusNode: focus, + onPressed: () => showAppDialog( + context: context, + builder: (_) => AppDialog( + title: 'Settings', + width: 1040, + height: 680, + actions: [ + TextButton(onPressed: () {}, child: const Text('Save')), + ], + child: Column( + children: List.generate( + 12, + (index) => AppField( + label: 'Field $index', + error: index == 0 ? 'Invalid' : null, + orientation: AppFieldOrientation.horizontal, + child: const TextField(), + ), + ), + ), + ), + ), + child: const Text('Open'), + ), + ), + ), + ), + ); + focus.requestFocus(); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + expect(find.text('Settings'), findsOneWidget); + expect( + tester.getRect(find.byType(Dialog)).right, + lessThanOrEqualTo(320), + ); + expect(tester.takeException(), isNull); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pumpAndSettle(); + expect(find.text('Settings'), findsNothing); + expect(focus.hasFocus, isTrue); + } + }, + ); + + testWidgets('tabs navigate enabled options and switch supports keyboard', ( + tester, + ) async { + var tab = 0; + var enabled = false; + final focus = FocusNode(); + addTearDown(focus.dispose); + await tester.pumpWidget( + MaterialApp( + theme: AppTheme.penDark, + home: Scaffold( + body: StatefulBuilder( + builder: (context, update) => Column( + children: [ + AppTabs( + tabs: const [ + AppTab(0, 'General'), + AppTab(1, 'Disabled', enabled: false), + AppTab(2, 'MCP'), + ], + value: tab, + onChanged: (value) => update(() => tab = value), + ), + AppSwitch( + value: enabled, + focusNode: focus, + semanticLabel: 'Service', + onChanged: (value) => update(() => enabled = value), + ), + ], + ), + ), + ), + ), + ); + await tester.tap(find.text('General')); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); + await tester.pump(); + expect(tab, 2); + await tester.sendKeyEvent(LogicalKeyboardKey.home); + await tester.pump(); + expect(tab, 0); + focus.requestFocus(); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.space); + await tester.pumpAndSettle(); + expect(enabled, isTrue); + expect(tester.takeException(), isNull); + }); +} diff --git a/packages/cutdex_ui/test/app_theme_test.dart b/packages/cutdex_ui/test/app_theme_test.dart new file mode 100644 index 0000000..ac947d8 --- /dev/null +++ b/packages/cutdex_ui/test/app_theme_test.dart @@ -0,0 +1,216 @@ +import 'dart:ui' as ui; + +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex_ui/widgets.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + test('Icon button states use translucent ink without stacking selection', () { + final style = AppTheme.penDark.iconButtonTheme.style!; + const ink = Color(0xFFFCFCFC); + expect(style.foregroundColor!.resolve({}), ink.withValues(alpha: .498)); + expect(style.backgroundColor!.resolve({}), Colors.transparent); + expect( + style.overlayColor!.resolve({WidgetState.hovered}), + ink.withValues(alpha: .078), + ); + expect( + style.overlayColor!.resolve({WidgetState.pressed}), + ink.withValues(alpha: .078), + ); + expect( + style.backgroundColor!.resolve({WidgetState.selected}), + ink.withValues(alpha: .05), + ); + expect(style.foregroundColor!.resolve({WidgetState.selected}), ink); + expect( + style.foregroundColor!.resolve({WidgetState.hovered}), + ink.withValues(alpha: .498), + ); + expect( + style.backgroundColor!.resolve({ + WidgetState.selected, + WidgetState.hovered, + }), + ink.withValues(alpha: .10), + ); + expect( + style.overlayColor!.resolve({WidgetState.selected, WidgetState.hovered}), + Colors.transparent, + ); + expect( + style.overlayColor!.resolve({WidgetState.disabled, WidgetState.hovered}), + Colors.transparent, + ); + }); + + test('Scrollbar uses neutral translucent states and a transparent track', () { + final theme = AppTheme.penDark.scrollbarTheme; + const ink = Color(0xFFFCFCFC); + expect(theme.thumbColor!.resolve({}), ink.withValues(alpha: .084)); + expect( + theme.thumbColor!.resolve({WidgetState.hovered}), + ink.withValues(alpha: .156), + ); + expect( + theme.thumbColor!.resolve({WidgetState.dragged}), + ink.withValues(alpha: .156), + ); + expect( + theme.trackColor!.resolve({WidgetState.hovered}), + Colors.transparent, + ); + expect( + theme.trackBorderColor!.resolve({WidgetState.hovered}), + Colors.transparent, + ); + }); + + testWidgets('property inputs use the composer surface and text colors', ( + tester, + ) async { + for (final theme in [AppTheme.penLight, AppTheme.penDark]) { + final inspector = AppTheme.propertiesPanelTheme(theme); + await tester.pumpWidget( + MaterialApp( + theme: theme, + home: Theme( + data: inspector, + child: const Scaffold( + body: AppTextField(label: 'X', hintText: 'Value'), + ), + ), + ), + ); + final input = tester.widget(find.byType(TextField)); + final decoration = input.decoration!; + expect( + decoration.fillColor, + theme.extension()!.composerBackground, + ); + expect(input.style!.color, theme.colorScheme.onSurface); + expect(input.cursorHeight, input.style!.fontSize); + expect( + decoration.hintStyle!.color, + inspector.inputDecorationTheme.hintStyle!.color, + ); + for (final border in [ + decoration.border, + decoration.enabledBorder, + decoration.disabledBorder, + decoration.focusedBorder, + decoration.errorBorder, + decoration.focusedErrorBorder, + ]) { + expect(border, isA()); + expect(border!.borderSide, BorderSide.none); + expect( + (border as OutlineInputBorder).borderRadius, + BorderRadius.circular(AppRadius.large), + ); + } + await tester.tap(find.byType(TextField)); + await tester.pump(); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + } + }); + + testWidgets('property input fill paints the full 28px control height', ( + tester, + ) async { + const boundaryKey = ValueKey('property-input-pixels'); + await tester.pumpWidget( + MaterialApp( + theme: AppTheme.penDark, + home: Theme( + data: AppTheme.propertiesPanelTheme(AppTheme.penDark), + child: const Scaffold( + body: Center( + child: RepaintBoundary( + key: boundaryKey, + child: SizedBox( + width: 120, + height: AppControlSize.propertyControl, + child: AppTextField(label: 'X'), + ), + ), + ), + ), + ), + ), + ); + await tester.pump(); + expect( + tester.getSize(find.byType(TextField)).height, + AppControlSize.propertyControl, + ); + final boundary = tester.renderObject( + find.byKey(boundaryKey), + ); + await tester.runAsync(() async { + final image = await boundary.toImage(pixelRatio: 1); + final pixels = (await image.toByteData( + format: ui.ImageByteFormat.rawRgba, + ))!; + List pixel(int x, int y) { + final offset = (y * image.width + x) * 4; + return List.generate(4, (channel) => pixels.getUint8(offset + channel)); + } + + expect(pixel(60, 14), [47, 47, 47, 255]); + expect(pixel(60, 0), pixel(60, 14)); + expect(pixel(60, 27), pixel(60, 14)); + image.dispose(); + }); + }); + + testWidgets('system typography and themed controls work in light and dark', ( + tester, + ) async { + for (final theme in [AppTheme.penLight, AppTheme.penDark]) { + var enabled = false; + await tester.pumpWidget( + MaterialApp( + theme: theme, + home: Scaffold( + body: Center( + child: SizedBox( + width: 280, + child: StatefulBuilder( + builder: (context, setState) => Column( + mainAxisSize: MainAxisSize.min, + children: [ + const AppTextField(label: 'W', unit: '%'), + AppSwitch( + value: enabled, + onChanged: (value) => setState(() => enabled = value), + ), + AppSlider(value: .5, onChanged: (_) {}), + ], + ), + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect( + tester.widget(find.byType(TextField)).style!.fontFamily, + AppTheme.systemFontFamily( + Theme.of(tester.element(find.byType(TextField))).platform, + ), + ); + await tester.tap(find.byType(Switch)); + await tester.pumpAndSettle(); + expect(enabled, isTrue); + await tester.enterText(find.byType(TextField), '125'); + expect(find.text('125'), findsOneWidget); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + } + }); +} diff --git a/packages/cutdex_ui/test/delayed_loading_indicator_test.dart b/packages/cutdex_ui/test/delayed_loading_indicator_test.dart new file mode 100644 index 0000000..ce024e1 --- /dev/null +++ b/packages/cutdex_ui/test/delayed_loading_indicator_test.dart @@ -0,0 +1,33 @@ +import 'package:cutdex_ui/widgets.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets('brief loading finishes without showing the indicator', ( + tester, + ) async { + const indicator = Key('loading-indicator'); + await tester.pumpWidget( + const DelayedLoadingIndicator(child: SizedBox(key: indicator)), + ); + await tester.pump(const Duration(milliseconds: 100)); + expect(find.byKey(indicator), findsNothing); + + await tester.pumpWidget(const SizedBox()); + await tester.pump(const Duration(milliseconds: 200)); + expect(find.byKey(indicator), findsNothing); + expect(tester.takeException(), isNull); + }); + + testWidgets('slow loading shows the indicator after the shared delay', ( + tester, + ) async { + const indicator = Key('loading-indicator'); + await tester.pumpWidget( + const DelayedLoadingIndicator(child: SizedBox(key: indicator)), + ); + await tester.pump(DelayedLoadingIndicator.delay); + await tester.pump(); + expect(find.byKey(indicator), findsOneWidget); + }); +} diff --git a/packages/cutdex_ui/test/native_context_menu_test.dart b/packages/cutdex_ui/test/native_context_menu_test.dart new file mode 100644 index 0000000..b5f296c --- /dev/null +++ b/packages/cutdex_ui/test/native_context_menu_test.dart @@ -0,0 +1,84 @@ +import 'package:cutdex_ui/widgets.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + const channel = MethodChannel('cutdex_native/context_menu'); + setUp(() => debugDefaultTargetPlatformOverride = TargetPlatform.macOS); + tearDown(() { + debugDefaultTargetPlatformOverride = null; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, null); + }); + + test( + 'native entries preserve nested actions, disabled items and coordinates', + () async { + var invoked = false; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (call) async { + expect(call.method, 'show'); + final args = call.arguments as Map; + expect(args['x'], 120.0); + expect(args['y'], 80.0); + final items = args['items'] as List; + expect(items[0]['enabled'], false); + expect(items[1]['separator'], true); + expect(items[2]['children'][0]['selected'], true); + return 1; + }); + expect( + await showNativeContextMenu( + [ + const AppMenuItem(label: 'Disabled'), + const AppMenuSeparator(), + AppSubmenu( + label: 'More', + items: [ + AppMenuItem( + label: 'Selected', + selected: true, + onPressed: () => invoked = true, + ), + ], + ), + ], + const Offset(120, 80), + () => true, + ), + isTrue, + ); + expect(invoked, isTrue); + }, + ); + + test('dismissal and disposed owners do not invoke actions', () async { + var invoked = false; + final items = [ + AppMenuItem(label: 'Action', onPressed: () => invoked = true), + ]; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (_) async => null); + expect(await showNativeContextMenu(items, Offset.zero, () => true), isTrue); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (_) async => 0); + expect( + await showNativeContextMenu(items, Offset.zero, () => false), + isTrue, + ); + expect(invoked, isFalse); + }); + + test('missing native plugin falls back to Flutter', () async { + expect( + await showNativeContextMenu( + [const AppMenuItem(label: 'Action')], + Offset.zero, + () => true, + ), + isFalse, + ); + }); +} diff --git a/packages/cutdex_ui/test/resource_download_progress_test.dart b/packages/cutdex_ui/test/resource_download_progress_test.dart new file mode 100644 index 0000000..aa04a23 --- /dev/null +++ b/packages/cutdex_ui/test/resource_download_progress_test.dart @@ -0,0 +1,71 @@ +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex_ui/widgets.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets('active resource progress omits a redundant status suffix', ( + tester, + ) async { + await tester.pumpWidget( + const MaterialApp( + home: Scaffold( + body: ResourceDownloadProgress( + downloadedBytes: 7100000, + totalBytes: 618000000, + status: '', + ), + ), + ), + ); + expect(find.text('0 B/s - 7.1 MB/618 MB'), findsOneWidget); + }); + + testWidgets('progress displays the download speed supplied by the task', ( + tester, + ) async { + await tester.pumpWidget( + const MaterialApp( + home: Scaffold( + body: ResourceDownloadProgress( + downloadedBytes: 7100000, + totalBytes: 618000000, + bytesPerSecond: 1200000, + status: '', + ), + ), + ), + ); + expect(find.text('1.2 MB/s - 7.1 MB/618 MB'), findsOneWidget); + }); + + testWidgets('resource download shows byte progress above a thin track', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + theme: AppTheme.penDark, + home: const Scaffold( + body: SizedBox( + width: 300, + child: ResourceDownloadProgress( + downloadedBytes: 7100000, + totalBytes: 618000000, + status: '已暂停', + paused: true, + ), + ), + ), + ), + ); + + final label = find.text('7.1 MB/618 MB, 已暂停'); + final bar = find.byType(LinearProgressIndicator); + expect(label, findsOneWidget); + expect(tester.getRect(label).bottom, lessThan(tester.getRect(bar).top)); + final indicator = tester.widget(bar); + expect(indicator.value, closeTo(7.1 / 618, 0.00001)); + expect(indicator.minHeight, 3); + expect(indicator.backgroundColor, AppTheme.penDark.dividerColor); + }); +} diff --git a/pubspec.lock b/pubspec.lock new file mode 100644 index 0000000..ce4c4d5 --- /dev/null +++ b/pubspec.lock @@ -0,0 +1,1104 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + _fe_analyzer_shared: + dependency: transitive + description: + name: _fe_analyzer_shared + sha256: fdcd9f70f9eb80df3bc5ed0fa67280df2595fd481948df8a9ab082e6a40ad04b + url: "https://pub.dev" + source: hosted + version: "108.0.0" + analysis_server_plugin: + dependency: transitive + description: + name: analysis_server_plugin + sha256: "3460f040e1f77647fcd82db9bd3bb117de04d04a3d67c39ad361794331147a4e" + url: "https://pub.dev" + source: hosted + version: "0.3.23" + analyzer: + dependency: transitive + description: + name: analyzer + sha256: a51c769bff3b6dfbe9d60199b8606d808290702a296bef0c26a4ca391d414e46 + url: "https://pub.dev" + source: hosted + version: "14.4.0" + analyzer_buffer: + dependency: transitive + description: + name: analyzer_buffer + sha256: f890a2e708e38fbf4238ad2f9fd3d506538acdddb0cd8eb2c3e8c7bd17784b57 + url: "https://pub.dev" + source: hosted + version: "0.3.4" + analyzer_plugin: + dependency: transitive + description: + name: analyzer_plugin + sha256: "9a3518eb84e8e26665874d9867534961d855493e9c5eb0eb55cbd46edd995529" + url: "https://pub.dev" + source: hosted + version: "0.14.17" + args: + dependency: transitive + description: + name: args + sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04 + url: "https://pub.dev" + source: hosted + version: "2.7.0" + async: + dependency: transitive + description: + name: async + sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37 + url: "https://pub.dev" + source: hosted + version: "2.13.1" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + build: + dependency: transitive + description: + name: build + sha256: "8a5c5761af8e31748bba3c82f68925ace40f3225c3eea25be9beb57eca7cd7a8" + url: "https://pub.dev" + source: hosted + version: "4.0.11" + build_config: + dependency: transitive + description: + name: build_config + sha256: d466ed2dc9c6cd1d169948879b84ee061eb5e22c64a7c6089879c6296d272a8d + url: "https://pub.dev" + source: hosted + version: "1.3.3" + build_daemon: + dependency: transitive + description: + name: build_daemon + sha256: e1d40ef3f7934986d5da2271b1ba07794921ce263e44d622fb6c406d76589e33 + url: "https://pub.dev" + source: hosted + version: "4.1.6" + build_runner: + dependency: "direct dev" + description: + name: build_runner + sha256: "894c243f6bc32015fec466ce30a6925bd537a77a426ee5bf481120477eb3de67" + url: "https://pub.dev" + source: hosted + version: "2.16.1" + built_collection: + dependency: transitive + description: + name: built_collection + sha256: "44922ecebd8e3d0cef743dadd3b54df4e87e2a4c52a29465a1872aa9e192caa8" + url: "https://pub.dev" + source: hosted + version: "5.1.2" + built_value: + dependency: transitive + description: + name: built_value + sha256: f87ea98192116f7093cb214551ce1929caae0681fdba282b3d8b4462adee7bb7 + url: "https://pub.dev" + source: hosted + version: "8.13.0" + characters: + dependency: transitive + description: + name: characters + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b + url: "https://pub.dev" + source: hosted + version: "1.4.1" + charcode: + dependency: transitive + description: + name: charcode + sha256: fb0f1107cac15a5ea6ef0a6ef71a807b9e4267c713bb93e00e92d737cc8dbd8a + url: "https://pub.dev" + source: hosted + version: "1.4.0" + checked_yaml: + dependency: transitive + description: + name: checked_yaml + sha256: "959525d3162f249993882720d52b7e0c833978df229be20702b33d48d91de70f" + url: "https://pub.dev" + source: hosted + version: "2.0.4" + cli_util: + dependency: transitive + description: + name: cli_util + sha256: "89b8801ba49f8b593fbf2d3e59efd0f566c46cd4ba6837ae2610c72b52a0f899" + url: "https://pub.dev" + source: hosted + version: "0.6.0" + clock: + dependency: transitive + description: + name: clock + sha256: e51d50bca3217c9a9fa2b41a30e4a38971133f5f9ec7a3d57bae095007f1d28e + url: "https://pub.dev" + source: hosted + version: "1.1.3" + code_assets: + dependency: transitive + description: + name: code_assets + sha256: "828110d598123b5ea96c00c9f3c72105bf79f8ee36c20a39b26209ade421ec57" + url: "https://pub.dev" + source: hosted + version: "2.1.0" + code_builder: + dependency: transitive + description: + name: code_builder + sha256: aa5932e94c6c39c2f9ec4e5e06dfdd11a9430a61f6c41b6ba75b28ce0c481baf + url: "https://pub.dev" + source: hosted + version: "4.12.0" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" + source: hosted + version: "1.19.1" + convert: + dependency: transitive + description: + name: convert + sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68 + url: "https://pub.dev" + source: hosted + version: "3.1.2" + crypto: + dependency: "direct main" + description: + name: crypto + sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf + url: "https://pub.dev" + source: hosted + version: "3.0.7" + cupertino_ui: + dependency: transitive + description: + name: cupertino_ui + sha256: c23816577a1280cff409e989541767887011f8f1d8c1863a794ed308af46f2a9 + url: "https://pub.dev" + source: hosted + version: "1.1.1" + cutdex_agent: + dependency: "direct main" + description: + path: "." + resolved-ref: "45200eb60e6d35c899fe814c5de70aab042e0745" + tag-pattern: "v{{version}}" + url: "https://github.com/cutdex-ai/cutdex_agent.git" + source: git + version: "0.1.0" + cutdex_editor: + dependency: transitive + description: + path: "packages/editor" + ref: "113eee1d63d546470db5d5d4f0d4aa0c312e7cac" + resolved-ref: "113eee1d63d546470db5d5d4f0d4aa0c312e7cac" + url: "git@github.com:lingjhf/cutdex_sdk.git" + source: git + version: "0.1.0" + cutdex_mcp: + dependency: transitive + description: + path: "packages/mcp" + ref: "113eee1d63d546470db5d5d4f0d4aa0c312e7cac" + resolved-ref: "113eee1d63d546470db5d5d4f0d4aa0c312e7cac" + url: "git@github.com:lingjhf/cutdex_sdk.git" + source: git + version: "0.1.0" + cutdex_preview: + dependency: transitive + description: + path: "packages/preview" + ref: "113eee1d63d546470db5d5d4f0d4aa0c312e7cac" + resolved-ref: "113eee1d63d546470db5d5d4f0d4aa0c312e7cac" + url: "git@github.com:lingjhf/cutdex_sdk.git" + source: git + version: "0.1.0" + cutdex_project: + dependency: transitive + description: + path: "packages/project" + ref: "113eee1d63d546470db5d5d4f0d4aa0c312e7cac" + resolved-ref: "113eee1d63d546470db5d5d4f0d4aa0c312e7cac" + url: "git@github.com:lingjhf/cutdex_sdk.git" + source: git + version: "0.1.0" + cutdex_runtime: + dependency: transitive + description: + path: "packages/runtime" + ref: "113eee1d63d546470db5d5d4f0d4aa0c312e7cac" + resolved-ref: "113eee1d63d546470db5d5d4f0d4aa0c312e7cac" + url: "git@github.com:lingjhf/cutdex_sdk.git" + source: git + version: "0.0.1" + cutdex_sdk: + dependency: "direct main" + description: + path: "." + ref: "v0.1.0" + resolved-ref: "113eee1d63d546470db5d5d4f0d4aa0c312e7cac" + url: "git@github.com:lingjhf/cutdex_sdk.git" + source: git + version: "0.1.0" + cutdex_timeline: + dependency: transitive + description: + path: "packages/timeline" + ref: "113eee1d63d546470db5d5d4f0d4aa0c312e7cac" + resolved-ref: "113eee1d63d546470db5d5d4f0d4aa0c312e7cac" + url: "git@github.com:lingjhf/cutdex_sdk.git" + source: git + version: "0.2.0" + cutdex_timeline_ui: + dependency: transitive + description: + path: "packages/timeline_ui" + ref: "113eee1d63d546470db5d5d4f0d4aa0c312e7cac" + resolved-ref: "113eee1d63d546470db5d5d4f0d4aa0c312e7cac" + url: "git@github.com:lingjhf/cutdex_sdk.git" + source: git + version: "0.1.0" + cutdex_tools: + dependency: transitive + description: + path: "packages/tools" + ref: "113eee1d63d546470db5d5d4f0d4aa0c312e7cac" + resolved-ref: "113eee1d63d546470db5d5d4f0d4aa0c312e7cac" + url: "git@github.com:lingjhf/cutdex_sdk.git" + source: git + version: "0.1.0" + dart_style: + dependency: transitive + description: + name: dart_style + sha256: "82ade9fc4273f29ed673e33166944465225b4f7fc5d4aaef48605cc751c18fc1" + url: "https://pub.dev" + source: hosted + version: "3.1.13" + deskup: + dependency: "direct main" + description: + name: deskup + sha256: "5a7fb021ba3207e5a85d440d378832156896d2eea616838ad21547aa0af68df1" + url: "https://pub.dev" + source: hosted + version: "0.1.0" + drift: + dependency: "direct main" + description: + name: drift + sha256: a21a6a7a9e6a0bcabdf47a9af4247c556d38dc9bfe9f05c4fdf72a488bb57eab + url: "https://pub.dev" + source: hosted + version: "2.35.1" + drift_dev: + dependency: "direct dev" + description: + name: drift_dev + sha256: e0d16aaa21f3408cbe2dd4bfc56c36cea43e53a537e6613b91380c0924b3bd30 + url: "https://pub.dev" + source: hosted + version: "2.35.1" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" + url: "https://pub.dev" + source: hosted + version: "1.3.3" + ffi: + dependency: transitive + description: + name: ffi + sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + ffi_leak_tracker: + dependency: transitive + description: + name: ffi_leak_tracker + sha256: "4093d4ef9ca06ffe2786e73bfb25e22aa92112b9bb4ec941f11e3e6b61489a97" + url: "https://pub.dev" + source: hosted + version: "0.1.2" + file: + dependency: transitive + description: + name: file + sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 + url: "https://pub.dev" + source: hosted + version: "7.0.1" + filegate: + dependency: "direct main" + description: + name: filegate + sha256: "1a3650abadf2f566c11d0d26711e84194e0068b076a57a851bc67583287e3e24" + url: "https://pub.dev" + source: hosted + version: "1.10.0" + fixnum: + dependency: transitive + description: + name: fixnum + sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be + url: "https://pub.dev" + source: hosted + version: "1.1.1" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_driver: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "3105dc8492f6183fb076ccf1f351ac3d60564bff92e20bfc4af9cc1651f4e7e1" + url: "https://pub.dev" + source: hosted + version: "6.0.0" + flutter_localizations: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_riverpod: + dependency: "direct main" + description: + name: flutter_riverpod + sha256: "2b7f9d2a3c730ac1a98221b420cef966b990fca7ab546ede324642ca57a533e3" + url: "https://pub.dev" + source: hosted + version: "3.4.3" + flutter_secure_storage: + dependency: "direct main" + description: + name: flutter_secure_storage + sha256: d4e1fb6b2cb524868929e78dc0282fa000554b22060fb53789dc481c9fc95bb8 + url: "https://pub.dev" + source: hosted + version: "11.2.0" + flutter_secure_storage_darwin: + dependency: transitive + description: + name: flutter_secure_storage_darwin + sha256: a031ceac9b070e62ef183cd7f7d1a8798ebde402d5049f0fe6eb3a51bd797a21 + url: "https://pub.dev" + source: hosted + version: "0.4.3" + flutter_secure_storage_linux: + dependency: transitive + description: + name: flutter_secure_storage_linux + sha256: caa75bd78f017422912e3a904933113b2428eb79f981ac37acd2dd2a700458ea + url: "https://pub.dev" + source: hosted + version: "3.0.3" + flutter_secure_storage_platform_interface: + dependency: transitive + description: + name: flutter_secure_storage_platform_interface + sha256: "64951127f001f546891c86f414972bf49ef2c4c8a4c92c65f5790cc0c9100045" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + flutter_secure_storage_web: + dependency: transitive + description: + name: flutter_secure_storage_web + sha256: "073a62b3aeb866ab4ce795f960413948e51e5a42a9b0c8333b6daf5bb3208a1c" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + flutter_secure_storage_windows: + dependency: transitive + description: + name: flutter_secure_storage_windows + sha256: "471951813a97006d899db4948acc654a4f28c440083ea08178935ce20b173ec1" + url: "https://pub.dev" + source: hosted + version: "4.2.2" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + freezed: + dependency: "direct dev" + description: + name: freezed + sha256: "3af98c92d7d4dd182ea1393193e69a840fcbaee1f66f1158bd20504e5f3f6f4f" + url: "https://pub.dev" + source: hosted + version: "4.0.2" + freezed_annotation: + dependency: "direct main" + description: + name: freezed_annotation + sha256: "7294967ff0a6d98638e7acb774aac3af2550777accd8149c90af5b014e6d44d8" + url: "https://pub.dev" + source: hosted + version: "3.1.0" + fuchsia_remote_debug_protocol: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + glob: + dependency: transitive + description: + name: glob + sha256: "218aeb56050c714f62a3182775320dfa04602b55074873e24e31bbd39bda96fb" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + go_router: + dependency: "direct main" + description: + name: go_router + sha256: "530dcbb298dc7c319aea9e3b7c580a61effb2abee2c93825d2dd8d5af0e230f1" + url: "https://pub.dev" + source: hosted + version: "18.0.2" + graphs: + dependency: transitive + description: + name: graphs + sha256: "741bbf84165310a68ff28fe9e727332eef1407342fca52759cb21ad8177bb8d0" + url: "https://pub.dev" + source: hosted + version: "2.3.2" + hooks: + dependency: transitive + description: + name: hooks + sha256: eaac480a35ec0814146c2c48d96aaa829e0e44a7662c88ae84c9edf4bc35651f + url: "https://pub.dev" + source: hosted + version: "2.2.0" + http_multi_server: + dependency: transitive + description: + name: http_multi_server + sha256: aa6199f908078bb1c5efb8d8638d4ae191aac11b311132c3ef48ce352fb52ef8 + url: "https://pub.dev" + source: hosted + version: "3.2.2" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" + url: "https://pub.dev" + source: hosted + version: "4.1.2" + integration_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + intl: + dependency: "direct main" + description: + name: intl + sha256: "1ca20c894b1717686a2319b8548763d812bc0aabdac580420a44c5178c57a867" + url: "https://pub.dev" + source: hosted + version: "0.20.3" + io: + dependency: transitive + description: + name: io + sha256: "2635216ca6a737e60de577ffa1a48a0bec76ca8a62917cfc1bb88c14c570646f" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + jni: + dependency: transitive + description: + name: jni + sha256: "6b9ca0602fef0230e83149afbe3f9f8227e94f2bbe84a1da4f14d699742f402d" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + jni_flutter: + dependency: transitive + description: + name: jni_flutter + sha256: c399ad579bfba12eb20c924f7a23160a42902f3023a871e1cad40a8a679656a4 + url: "https://pub.dev" + source: hosted + version: "1.0.4" + jni_util: + dependency: transitive + description: + name: jni_util + sha256: "1ba86da04a5f2bf18fde2edb235587e70c5b0fc5bd4ba955f46b00942c3fc35f" + url: "https://pub.dev" + source: hosted + version: "1.0.0" + json_annotation: + dependency: "direct main" + description: + name: json_annotation + sha256: "2a743920d81b7910627f68ee2c9ac1fc0bfee32b9fc3403587d7c6791ca12f80" + url: "https://pub.dev" + source: hosted + version: "4.12.0" + json_serializable: + dependency: "direct dev" + description: + name: json_serializable + sha256: e45aefa0324f08c683caafbb94b72837aa6193c61822799c916e45f4a263113d + url: "https://pub.dev" + source: hosted + version: "6.14.1" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" + url: "https://pub.dev" + source: hosted + version: "11.0.2" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" + url: "https://pub.dev" + source: hosted + version: "3.0.10" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + lints: + dependency: transitive + description: + name: lints + sha256: "12f842a479589fea194fe5c5a3095abc7be0c1f2ddfa9a0e76aed1dbd26a87df" + url: "https://pub.dev" + source: hosted + version: "6.1.0" + listen: + dependency: transitive + description: + name: listen + sha256: "47501a08016a43fcad79252439d723f50f14f88fa7bfd8a177e0a417e5c9e1f2" + url: "https://pub.dev" + source: hosted + version: "1.0.1" + logging: + dependency: transitive + description: + name: logging + sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 + url: "https://pub.dev" + source: hosted + version: "1.3.0" + matcher: + dependency: transitive + description: + name: matcher + sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd" + url: "https://pub.dev" + source: hosted + version: "0.12.20" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" + url: "https://pub.dev" + source: hosted + version: "0.13.0" + material_ui: + dependency: transitive + description: + name: material_ui + sha256: "32d98f11cf5942a095a8c3e01b03e4de3b17941437713dcf36b1088fb62e23d2" + url: "https://pub.dev" + source: hosted + version: "1.5.0" + meta: + dependency: transitive + description: + name: meta + sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9" + url: "https://pub.dev" + source: hosted + version: "1.19.0" + mime: + dependency: transitive + description: + name: mime + sha256: bd47de35f07e27267e69c8c8b22edf9473bfee170a60d60fcc93730c5144b7f6 + url: "https://pub.dev" + source: hosted + version: "2.1.0" + mockito: + dependency: transitive + description: + name: mockito + sha256: "6c1970612452260366064d4df80fdb3eece1ec5e52610ae34a0e51f2f3d8e64f" + url: "https://pub.dev" + source: hosted + version: "5.8.1" + native_toolchain_c: + dependency: transitive + description: + name: native_toolchain_c + sha256: "90eaad8059ebc2004a63810a4696ea9acdb02473e47ed3b6b3bafb100ac77e31" + url: "https://pub.dev" + source: hosted + version: "0.19.5" + objective_c: + dependency: transitive + description: + name: objective_c + sha256: "5c80c2ad6e2c0397de5db38c6d653e69616a3397e13aa7633bf39eb668f2041b" + url: "https://pub.dev" + source: hosted + version: "9.6.2" + package_config: + dependency: transitive + description: + name: package_config + sha256: ffcf4cf3d6c0b74ac43708d9f56625506e8a68aa935abe9d267a7330f320eb5d + url: "https://pub.dev" + source: hosted + version: "3.0.0" + path: + dependency: "direct main" + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + path_provider: + dependency: "direct main" + description: + name: path_provider + sha256: a7f4874f987173da295a61c181b8ee71dab59b332a486b391babf26a1b884825 + url: "https://pub.dev" + source: hosted + version: "2.1.6" + path_provider_android: + dependency: transitive + description: + name: path_provider_android + sha256: "69cbd515a62b94d32a7944f086b2f82b4ac40a1d45bebfc00813a430ab2dabcd" + url: "https://pub.dev" + source: hosted + version: "2.3.1" + path_provider_foundation: + dependency: transitive + description: + name: path_provider_foundation + sha256: "2a376b7d6392d80cd3705782d2caa734ca4727776db0b6ec36ef3f1855197699" + url: "https://pub.dev" + source: hosted + version: "2.6.0" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: "58c2005f147315b11e9b4a7bc889cd5203e250cba8e3f012dae259b4972b5c16" + url: "https://pub.dev" + source: hosted + version: "2.2.2" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "484838772624c3a4b94f1e44a3e19897fee738f2d5c4ce448443b0417f7c9dda" + url: "https://pub.dev" + source: hosted + version: "2.1.3" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.dev" + source: hosted + version: "2.3.0" + platform: + dependency: transitive + description: + name: platform + sha256: a36d119c13416516a7b5913fbe8af8531e11633d784c550b2125f76c758524ec + url: "https://pub.dev" + source: hosted + version: "3.2.0" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" + pool: + dependency: transitive + description: + name: pool + sha256: "4177f68c237ea2128d1bee66ac17b2ce05ba3dbaafcbdd54c5d40a39d0b6b11c" + url: "https://pub.dev" + source: hosted + version: "1.5.3" + process: + dependency: transitive + description: + name: process + sha256: "4242ba3508d37e01808bdf71ad1d5bb93a8d671bf2e7450e6b1b353fb0808891" + url: "https://pub.dev" + source: hosted + version: "5.0.6" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "261236774e8b1d69cfc6b9eabbc96c40f25e7a2d6b171f3385d4f65d5734fb24" + url: "https://pub.dev" + source: hosted + version: "2.2.1" + pubspec_parse: + dependency: transitive + description: + name: pubspec_parse + sha256: c38b81cbf34450b67e0265d73433569d12e34782e30ed769c9cc99c9d5f2e796 + url: "https://pub.dev" + source: hosted + version: "1.6.0" + recase: + dependency: transitive + description: + name: recase + sha256: e4eb4ec2dcdee52dcf99cb4ceabaffc631d7424ee55e56f280bc039737f89213 + url: "https://pub.dev" + source: hosted + version: "4.1.0" + record_use: + dependency: transitive + description: + name: record_use + sha256: "1cb8564af8d43b464294411db9217f5ec04891c6f22ee2c32d73ae05e88a6bd2" + url: "https://pub.dev" + source: hosted + version: "1.1.1" + riverpod: + dependency: transitive + description: + name: riverpod + sha256: "484dfc873ea4c4f4240e5635444fa066f87b07862b7279ebd004a2b71fba4b7a" + url: "https://pub.dev" + source: hosted + version: "3.4.3" + riverpod_analyzer_utils: + dependency: transitive + description: + name: riverpod_analyzer_utils + sha256: bb13cb3985815840cc103eda1027158358c5fdc00f308fc6f76574d0594107af + url: "https://pub.dev" + source: hosted + version: "1.0.0-dev.12" + riverpod_annotation: + dependency: "direct main" + description: + name: riverpod_annotation + sha256: "322e56ad198928ef26ba240f85421bfff2493bd65665c887b1299e6386b6206d" + url: "https://pub.dev" + source: hosted + version: "4.0.7" + riverpod_generator: + dependency: "direct dev" + description: + name: riverpod_generator + sha256: c94dcb8b60ff4805d2bb8cacca969c48237bcb563e2ab0b5afb50204470c7636 + url: "https://pub.dev" + source: hosted + version: "4.0.9" + riverpod_lint: + dependency: "direct dev" + description: + name: riverpod_lint + sha256: "215cb3cd54a97e09bc3512535fa4e8bedd3bf2a06dc2ae015ac8e0050fc71bd1" + url: "https://pub.dev" + source: hosted + version: "3.1.9" + shelf: + dependency: transitive + description: + name: shelf + sha256: e7dd780a7ffb623c57850b33f43309312fc863fb6aa3d276a754bb299839ef12 + url: "https://pub.dev" + source: hosted + version: "1.4.2" + shelf_web_socket: + dependency: transitive + description: + name: shelf_web_socket + sha256: "3632775c8e90d6c9712f883e633716432a27758216dfb61bd86a8321c0580925" + url: "https://pub.dev" + source: hosted + version: "3.0.0" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_gen: + dependency: transitive + description: + name: source_gen + sha256: "11b6047da8e4eb6c643ccac3d0fda3f9c9e11651695f7da24a85ade8aff15a44" + url: "https://pub.dev" + source: hosted + version: "4.3.0" + source_helper: + dependency: transitive + description: + name: source_helper + sha256: "5e6f216fdf6376c9f3852381ae037499797a3385377d388b011dac98d303c67c" + url: "https://pub.dev" + source: hosted + version: "1.3.13" + source_span: + dependency: transitive + description: + name: source_span + sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" + url: "https://pub.dev" + source: hosted + version: "1.10.2" + sqlite3: + dependency: "direct main" + description: + name: sqlite3 + sha256: cc62d72dbf16bb1f6ae8954b238016de1473e53df060ed0c332eed0a41dd1848 + url: "https://pub.dev" + source: hosted + version: "3.7.0" + sqlparser: + dependency: transitive + description: + name: sqlparser + sha256: "772bb2f6f5bce0631a60f26b57d6e8882e1105c22345b05c163ee6ee5d7ba32d" + url: "https://pub.dev" + source: hosted + version: "0.45.0" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "277654b3034d17ac6f9f1cb5595db011b1d5d41e8806866db28e0abaa101c490" + url: "https://pub.dev" + source: hosted + version: "1.12.2" + state_notifier: + dependency: transitive + description: + name: state_notifier + sha256: b8677376aa54f2d7c58280d5a007f9e8774f1968d1fb1c096adcb4792fba29bb + url: "https://pub.dev" + source: hosted + version: "1.0.0" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + stream_transform: + dependency: transitive + description: + name: stream_transform + sha256: a00e5f18bffc764f923e7dec1038527f7fe7a1791361a7117f0358193f13d53a + url: "https://pub.dev" + source: hosted + version: "2.1.2" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.dev" + source: hosted + version: "1.4.1" + sync_http: + dependency: transitive + description: + name: sync_http + sha256: "7f0cd72eca000d2e026bcd6f990b81d0ca06022ef4e32fb257b30d3d1014a961" + url: "https://pub.dev" + source: hosted + version: "0.3.1" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" + url: "https://pub.dev" + source: hosted + version: "1.2.2" + test_api: + dependency: transitive + description: + name: test_api + sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11" + url: "https://pub.dev" + source: hosted + version: "0.7.12" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + uuid: + dependency: "direct main" + description: + name: uuid + sha256: "9b129329f58692f6e6578329498a8fe9fbe98f090beb764ffbb8ee2eadd01dcd" + url: "https://pub.dev" + source: hosted + version: "4.6.0" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: "92b9910f66ed1057fd4da7b040ae7c74cafacf885bdc81be496928d5049b032d" + url: "https://pub.dev" + source: hosted + version: "2.4.3" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "5f37239c4851efcef929cea7824e76df7f2f0970aef85d66bbc430afa40e72f0" + url: "https://pub.dev" + source: hosted + version: "15.3.0" + watcher: + dependency: transitive + description: + name: watcher + sha256: "1398c9f081a753f9226febe8900fce8f7d0a67163334e1c94a2438339d79d635" + url: "https://pub.dev" + source: hosted + version: "1.2.1" + web: + dependency: transitive + description: + name: web + sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" + url: "https://pub.dev" + source: hosted + version: "1.1.1" + web_socket: + dependency: transitive + description: + name: web_socket + sha256: "34d64019aa8e36bf9842ac014bb5d2f5586ca73df5e4d9bf5c936975cae6982c" + url: "https://pub.dev" + source: hosted + version: "1.0.1" + web_socket_channel: + dependency: transitive + description: + name: web_socket_channel + sha256: d645757fb0f4773d602444000a8131ff5d48c9e47adfe9772652dd1a4f2d45c8 + url: "https://pub.dev" + source: hosted + version: "3.0.3" + webdriver: + dependency: transitive + description: + name: webdriver + sha256: "28b82ec894fed45dd71c23ba62d1af973ed97dd59a4f5790a4d38b0b13e5657e" + url: "https://pub.dev" + source: hosted + version: "3.2.0" + win32: + dependency: transitive + description: + name: win32 + sha256: a0b93865d5644f11cf6a8c3f6db909f1ec168958b5805f6cc684adea957cd63d + url: "https://pub.dev" + source: hosted + version: "6.4.0" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + yaml: + dependency: transitive + description: + name: yaml + sha256: f67cdd8e07d3c6329146aaef1ba043542b3134c12489f553ca9a7435d1068aea + url: "https://pub.dev" + source: hosted + version: "3.1.4" + yaml_edit: + dependency: transitive + description: + name: yaml_edit + sha256: "07c9e63ba42519745182b88ca12264a7ba2484d8239958778dfe4d44fe760488" + url: "https://pub.dev" + source: hosted + version: "2.2.4" +sdks: + dart: ">=3.13.4 <4.0.0" + flutter: ">=3.47.2" diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100644 index 0000000..375d80b --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,67 @@ +name: cutdex +description: "Cutdex video editing application." +publish_to: none + +version: 1.0.0+1 + +environment: + sdk: ^3.13.2 + +workspace: + - packages/* + +dependencies: + cutdex_ui: ^0.1.0 + cutdex_native: ^0.1.0 + deskup: ^0.1.0 + flutter: + sdk: flutter + + flutter_localizations: + sdk: flutter + intl: ^0.20.3 + flutter_secure_storage: ^11.2.0 + + cutdex_sdk: + git: + url: git@github.com:lingjhf/cutdex_sdk.git + ref: v0.1.0 + cutdex_agent: + git: + url: https://github.com/cutdex-ai/cutdex_agent.git + tag_pattern: v{{version}} + version: ^0.1.0 + flutter_riverpod: ^3.4.3 + riverpod_annotation: ^4.0.7 + freezed_annotation: ^3.1.0 + go_router: ^18.0.2 + filegate: ^1.10.0 + drift: ^2.35.1 + sqlite3: ^3.7.0 + path: ^1.9.1 + path_provider: ^2.1.6 + crypto: ^3.0.7 + uuid: ^4.6.0 + json_annotation: ^4.12.0 + +dev_dependencies: + integration_test: + sdk: flutter + flutter_test: + sdk: flutter + + flutter_lints: ^6.0.0 + riverpod_generator: ^4.0.9 + freezed: ^4.0.2 + build_runner: ^2.16.1 + drift_dev: ^2.35.1 + json_serializable: ^6.14.1 + riverpod_lint: ^3.1.9 + +flutter: + config: + enable-swift-package-manager: true + + default-flavor: development + generate: true + uses-material-design: true diff --git a/pubspec_overrides.yaml.example b/pubspec_overrides.yaml.example new file mode 100644 index 0000000..834f1c2 --- /dev/null +++ b/pubspec_overrides.yaml.example @@ -0,0 +1,7 @@ +# Default SDK dependency is the pinned remote Git tag. +# Copy to ignored pubspec_overrides.yaml only for local source development. +dependency_overrides: + cutdex_sdk: + path: ../cutdex_sdk + cutdex_agent: + path: ../cutdex_agent diff --git a/test/adaptive_workspace_test.dart b/test/adaptive_workspace_test.dart new file mode 100644 index 0000000..0994161 --- /dev/null +++ b/test/adaptive_workspace_test.dart @@ -0,0 +1,1130 @@ +import 'package:cutdex/errors/app_failure.dart'; + +import 'dart:async'; + +import 'package:cutdex/features/assistant/agent_composer_store.dart'; +import 'package:cutdex/features/projects/conversation_sidebar.dart'; +import 'package:cutdex/integrations/platform/file_picker.dart'; +import 'package:cutdex/workspace/external_media_import.dart'; +import 'package:cutdex/workspace/media_import.dart'; +import 'package:cutdex/app/adaptive/workspace_layout_policy.dart'; +import 'package:cutdex/app/app.dart'; +import 'package:cutdex/features/assistant/agent_chat_panel.dart'; +import 'package:cutdex/features/editor/editor_page.dart'; +import 'package:cutdex/features/media/media_browser_controller.dart'; +import 'package:cutdex/features/media/media_browser_page.dart'; +import 'package:cutdex/features/media/media_panel.dart'; +import 'package:cutdex/features/properties/properties_editor_page.dart'; +import 'package:cutdex/features/properties/properties_panel.dart'; +import 'package:cutdex/features/preview/preview_panel.dart'; +import 'package:cutdex/features/timeline/timeline_panel.dart'; +import 'package:cutdex/integrations/agent/conversation_repository.dart'; +import 'package:cutdex/integrations/platform/device_experience.dart'; +import 'package:cutdex/persistence/app_database.dart'; +import 'package:cutdex/persistence/app_settings_repositories.dart'; +import 'package:cutdex/shared/layout/workspace_layout_metrics.dart'; +import 'package:cutdex/workspace/media_availability.dart'; +import 'package:cutdex/workspace/project_state.dart'; +import 'package:cutdex/workspace/projects.dart'; +import 'package:cutdex/workspace/timeline_provider.dart'; +import 'package:cutdex/workspace/timeline_session.dart'; +import 'package:cutdex/workspace/view_settings.dart'; +import 'package:cutdex/workspace/workspace_mode.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:drift/native.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'support/empty_conversation_repository.dart'; +import 'support/preview_fixture.dart'; + +void main() { + test('space classes and two-pane decisions do not depend on workflow', () { + expect(WorkspaceLayoutPolicy.desktopNavigationFits(560), isFalse); + expect(WorkspaceLayoutPolicy.desktopNavigationFits(561), isTrue); + expect(WorkspaceLayoutPolicy.showAgentBesideEditor(839), isFalse); + expect(WorkspaceLayoutPolicy.showAgentBesideEditor(840), isTrue); + }); + + Future< + ({ + ProviderContainer container, + EditorTimelineSession session, + String projectId, + Future Function() close, + }) + > + mount( + WidgetTester tester, + Size size, { + DeviceExperience experience = DeviceExperience.desktop, + MediaFileResolver? delayedResolver, + AppFilePicker? picker, + ConversationRepository? conversations, + MediaImportResult? importResult, + }) async { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final fixture = (await tester.runAsync( + () => + createPreviewFixture(Uri.file('/test/photo.png'), mediaType: 'image'), + ))!; + final database = AppDatabase(NativeDatabase.memory()); + final projectId = fixture.workspace.project!.info.id; + final container = ProviderContainer( + overrides: [ + deviceExperienceProvider.overrideWithValue(experience), + if (picker != null) filePickerProvider.overrideWithValue(picker), + if (delayedResolver != null) + mediaFileResolverProvider.overrideWithValue(delayedResolver), + appDatabaseProvider.overrideWithValue(database), + timelineViewSettingsRepositoryProvider.overrideWithValue( + _TimelineViewRepository(), + ), + projectsProvider.overrideWith( + () => _FixtureProjects(projectId, fixture.timeline, importResult), + ), + conversationRepositoryProvider.overrideWith( + (ref) async => conversations ?? EmptyConversationRepository(), + ), + editorPreviewProvider.overrideWith((ref, ids) => null), + mediaAvailabilityProvider.overrideWith( + (ref, ids) async => MediaAvailability.missing, + ), + ], + ); + var closed = false; + Future close() async { + if (closed) return; + closed = true; + await tester.pump(); + await tester.pumpWidget(const SizedBox()); + container.dispose(); + await tester.pump(); + await tester.runAsync(() async { + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + await database.close(); + }); + } + + addTearDown(close); + // The app owns the scope; this harness deliberately provides its container. + // ignore: riverpod_lint/provider_scope_placement + await tester.pumpWidget( + UncontrolledProviderScope(container: container, child: const CutdexApp()), + ); + await tester.pumpAndSettle(); + return ( + container: container, + session: fixture.timeline, + projectId: projectId, + close: close, + ); + } + + Future setMode( + WidgetTester tester, + ProviderContainer container, + WorkspaceMode mode, + ) async { + container.read(workspaceViewSettingsProvider.notifier).setMode(mode); + await tester.pumpAndSettle(); + } + + testWidgets('Windows caption space follows real workspace pane changes', ( + tester, + ) async { + debugDefaultTargetPlatformOverride = TargetPlatform.windows; + const channel = MethodChannel('cutdex_native/window'); + const dropChannel = MethodChannel('cutdex_native/file_drop/timeline'); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + messenger.setMockMethodCallHandler( + channel, + (call) async => call.method == 'configureChrome' + ? (call.arguments as Map)['enabled'] + : null, + ); + messenger.setMockMethodCallHandler(dropChannel, (call) async => null); + addTearDown(() { + debugDefaultTargetPlatformOverride = null; + messenger.setMockMethodCallHandler(channel, null); + messenger.setMockMethodCallHandler(dropChannel, null); + }); + final mounted = await mount(tester, const Size(1200, 800)); + for (final mode in [WorkspaceMode.agent, WorkspaceMode.cut]) { + await setMode(tester, mounted.container, mode); + for (final width in [1200.0, 700.0, 400.0, 1200.0]) { + tester.view.physicalSize = Size(width, 800); + await tester.pumpAndSettle(); + final controlsLeft = tester + .getTopLeft(find.byKey(const Key('window-minimize'))) + .dx; + for (final key in [ + 'editor-media-button', + 'editor-properties-button', + 'project-settings-button', + 'expand-editor-button', + ]) { + final finder = find.byKey(Key(key)); + for (final element in finder.evaluate()) { + var rect = tester.getRect(find.byWidget(element.widget)); + // Narrow headers can scroll. Assert the visible control bounds, + // respecting each scroll viewport's clip. + element.visitAncestorElements((ancestor) { + if (ancestor.widget case SingleChildScrollView( + scrollDirection: Axis.horizontal, + )) { + rect = rect.intersect( + tester.getRect(find.byWidget(ancestor.widget)), + ); + } + return true; + }); + if (rect.isEmpty) continue; + expect( + rect.right, + lessThanOrEqualTo(controlsLeft + 0.1), + reason: '$key at $width in $mode', + ); + } + } + expect(tester.takeException(), isNull, reason: '$width in $mode'); + } + } + await mounted.close(); + debugDefaultTargetPlatformOverride = null; + }); + + testWidgets( + 'desktop resizing retains desktop interactions, session, undo and composer', + (tester) async { + final mounted = await mount(tester, const Size(1200, 800)); + final session = mounted.session; + final sequence = session.activeSequenceId!; + final view = session.view(sequence); + final input = find.descendant( + of: find.byKey(const Key('agent-composer')), + matching: find.byType(TextField), + ); + await tester.enterText(input, 'Keep my draft'); + await tester.drag( + find.byKey(const Key('agent-panel-resize')), + const Offset(40, 0), + ); + await tester.pumpAndSettle(); + final agentWidth = tester.getSize(find.byType(AgentChatPanel)).width; + view.setSelection([ + view.version.kernelVersion.query().elementById(ElementId('clip'))!, + ]); + view.seekTo(TimelineClock.ticksPerSecond); + await tester.runAsync(() async { + view.cutSelectionAtPlayhead(); + await session.flush(); + }); + final selected = view.selectedIdentities.toList(); + final version = session.version; + expect(view.canUndo, isTrue); + + for (final size in [ + const Size(390, 844), + const Size(780, 1024), + const Size(900, 600), + const Size(1200, 800), + ]) { + tester.view.physicalSize = size; + await tester.pumpAndSettle(); + expect( + find.byKey(const Key('desktop-workspace-shell')), + findsOneWidget, + ); + expect(find.byType(NavigationBar), findsNothing); + expect(find.byType(NavigationRail), findsNothing); + await setMode(tester, mounted.container, WorkspaceMode.cut); + expect(find.byType(EditorTimelinePanel), findsOneWidget); + expect( + await mounted.container.read( + editorTimelineProvider(mounted.projectId, 'project').future, + ), + same(session), + ); + expect(session.view(sequence), same(view)); + expect(view.selectedIdentities, selected); + expect(view.playheadTick, TimelineClock.ticksPerSecond); + expect(session.version, version); + expect(view.canUndo, isTrue); + final rect = tester.getRect(find.byType(EditorTimelinePanel)); + expect(rect.right, lessThanOrEqualTo(size.width)); + expect(rect.bottom, lessThanOrEqualTo(size.height)); + await setMode(tester, mounted.container, WorkspaceMode.agent); + expect( + tester.widget(input).controller!.text, + 'Keep my draft', + ); + expect(tester.takeException(), isNull); + } + expect(tester.getSize(find.byType(AgentChatPanel)).width, agentWidth); + await tester.runAsync(() async { + view.undo(); + await session.flush(); + }); + expect( + view.version.kernelVersion.query().elementById(ElementId('clip')), + isNotNull, + ); + expect(view.canRedo, isTrue); + await mounted.close(); + }, + ); + + testWidgets( + 'desktop tools overlay in limited editor space and restore fixed sidebars', + (tester) async { + final mounted = await mount(tester, const Size(1200, 800)); + await setMode(tester, mounted.container, WorkspaceMode.cut); + await tester.tap(find.byKey(const Key('editor-media-button'))); + await tester.tap(find.byKey(const Key('editor-properties-button'))); + await tester.pumpAndSettle(); + expect( + tester.getSize(find.byType(MediaPanel)).width, + WorkspaceLayoutMetrics.mediaPanelWidth, + ); + expect( + tester.getSize(find.byType(EditorPropertiesPanel)).width, + WorkspaceLayoutMetrics.propertiesPanelWidth, + ); + expect(find.byKey(const Key('editor-tool-surface')), findsNothing); + + await setMode(tester, mounted.container, WorkspaceMode.agent); + expect(find.byKey(const Key('editor-tool-surface')), findsOneWidget); + expect(find.byType(EditorPropertiesPanel), findsOneWidget); + expect(find.byType(PropertiesEditorPage), findsNothing); + expect(find.byType(EditorTimelinePanel), findsOneWidget); + expect( + mounted.container + .read(projectViewSettingsProvider(mounted.projectId)) + .requireValue + .propertiesOpen, + isTrue, + ); + await tester.tap(find.byKey(const Key('editor-media-button'))); + await tester.pumpAndSettle(); + expect(find.byType(MediaPanel), findsOneWidget); + + expect(find.byType(MediaBrowserDrawer), findsNothing); + expect(find.byType(PropertiesToolPanel), findsNothing); + expect( + tester + .widget(find.byKey(const Key('editor-media-button'))) + .isSelected, + isTrue, + ); + await setMode(tester, mounted.container, WorkspaceMode.cut); + expect(find.byKey(const Key('editor-tool-surface')), findsNothing); + expect( + tester.getSize(find.byType(MediaPanel)).width, + WorkspaceLayoutMetrics.mediaPanelWidth, + ); + expect( + tester.getSize(find.byType(EditorPropertiesPanel)).width, + WorkspaceLayoutMetrics.propertiesPanelWidth, + ); + expect( + await mounted.container.read( + editorTimelineProvider(mounted.projectId, 'project').future, + ), + same(mounted.session), + ); + expect(tester.takeException(), isNull); + await mounted.close(); + }, + ); + + testWidgets( + 'phone tools use independent pages without changing desktop preferences', + (tester) async { + final mounted = await mount( + tester, + const Size(390, 844), + experience: DeviceExperience.phone, + ); + final container = mounted.container; + await tester.tap(find.byKey(const Key('workspace-cut-destination'))); + await tester.pumpAndSettle(); + expect(find.byType(EditorWorkspace), findsOneWidget); + final session = mounted.session; + final view = session.view(session.activeSequenceId!); + view.setSelection([ + view.version.kernelVersion.query().elementById(ElementId('clip'))!, + ]); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('editor-properties-button'))); + await tester.pumpAndSettle(); + expect(find.byType(PropertiesEditorPage), findsOneWidget); + expect(find.byKey(const Key('property-category-picker')), findsOneWidget); + expect( + container + .read(projectViewSettingsProvider(mounted.projectId)) + .requireValue + .propertiesOpen, + isFalse, + ); + final category = container.read( + propertyCategoryProvider(( + mounted.projectId, + 'project', + '${session.activeSequenceId!.value}/clip', + )), + ); + category.value = PropertyCategory.animation; + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('editor-tool-close'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('editor-media-button'))); + await tester.pumpAndSettle(); + expect(find.byType(MediaBrowserPage), findsOneWidget); + expect(find.byKey(const Key('media-add-selected')), findsOneWidget); + container.read(mediaBrowserProvider(mounted.projectId)).filter = + MediaFilter.image; + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('editor-tool-close'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('workspace-agent-destination'))); + await tester.pumpAndSettle(); + expect(find.byType(EditorWorkspace), findsNothing); + await tester.tap(find.byKey(const Key('workspace-cut-destination'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('editor-properties-button'))); + await tester.pumpAndSettle(); + expect( + tester + .widget>( + find.byKey(const Key('property-category-picker')), + ) + .value, + PropertyCategory.animation, + ); + tester.view.physicalSize = const Size(780, 1024); + await tester.pumpAndSettle(); + expect(find.byType(PropertiesEditorPage), findsOneWidget); + expect(find.byType(PropertiesToolPanel), findsNothing); + expect( + tester + .widget>( + find.byKey(const Key('property-category-picker')), + ) + .value, + PropertyCategory.animation, + ); + tester.view.physicalSize = const Size(1200, 800); + await tester.pumpAndSettle(); + expect(find.byType(PropertiesEditorPage), findsOneWidget); + expect(find.byKey(const Key('phone-workspace-shell')), findsOneWidget); + expect(find.byType(NavigationBar), findsOneWidget); + expect(find.byType(NavigationRail), findsNothing); + expect( + container.read(mediaBrowserProvider(mounted.projectId)).filter, + MediaFilter.image, + ); + expect(tester.takeException(), isNull); + await mounted.close(); + }, + ); + + for (final experience in DeviceExperience.values) { + testWidgets( + '${experience.name} keeps its navigation and media interaction across widths', + (tester) async { + final mounted = await mount( + tester, + const Size(1200, 800), + experience: experience, + ); + await setMode(tester, mounted.container, WorkspaceMode.cut); + await tester.tap(find.byKey(const Key('editor-media-button'))); + await tester.pumpAndSettle(); + final browser = mounted.container.read( + mediaBrowserProvider(mounted.projectId), + ); + browser.filter = MediaFilter.image; + browser.selectedAssetId = 'media'; + for (final size in [ + const Size(390, 844), + const Size(600, 800), + const Size(1200, 800), + ]) { + tester.view.physicalSize = size; + await tester.pumpAndSettle(); + expect( + find.byKey(Key('${experience.name}-workspace-shell')), + findsOneWidget, + ); + expect( + find.byType(NavigationBar), + experience == DeviceExperience.phone + ? findsOneWidget + : findsNothing, + ); + expect( + find.byType(NavigationRail), + experience == DeviceExperience.tablet + ? findsOneWidget + : findsNothing, + ); + final panel = find.byKey(const Key('media-panel-surface')); + expect( + find.byType(MediaPanel), + experience == DeviceExperience.desktop + ? findsOneWidget + : findsNothing, + ); + expect( + find.byType(MediaBrowserPage), + experience == DeviceExperience.phone + ? findsOneWidget + : findsNothing, + ); + expect( + find.byType(MediaBrowserDrawer), + experience == DeviceExperience.tablet + ? findsOneWidget + : findsNothing, + ); + expect( + find.byKey(const Key('media-add-selected')), + experience == DeviceExperience.desktop + ? findsNothing + : findsOneWidget, + ); + if (experience == DeviceExperience.desktop) { + expect( + find.byKey(const Key('editor-timeline-resize')), + findsOneWidget, + ); + } + final rect = tester.getRect(panel); + expect(rect.left, greaterThanOrEqualTo(0)); + expect(rect.right, lessThanOrEqualTo(size.width)); + expect(rect.bottom, lessThanOrEqualTo(size.height)); + expect(browser.filter, MediaFilter.image); + expect(browser.selectedAssetId, 'media'); + expect(tester.takeException(), isNull); + } + await mounted.close(); + }, + ); + } + + testWidgets( + 'tablet split screen keeps rail and tool panel with mouse and keyboard', + (tester) async { + final mounted = await mount( + tester, + const Size(1200, 800), + experience: DeviceExperience.tablet, + ); + final input = find.descendant( + of: find.byKey(const Key('agent-composer')), + matching: find.byType(TextField), + ); + await tester.enterText(input, 'Tablet draft'); + expect(find.byType(EditorTimelinePanel), findsOneWidget); + tester.view.physicalSize = const Size(390, 844); + tester.view.viewInsets = const FakeViewPadding(bottom: 300); + addTearDown(tester.view.resetViewInsets); + await tester.pumpAndSettle(); + expect(find.byType(NavigationRail), findsOneWidget); + expect(find.byType(NavigationBar), findsNothing); + expect( + tester.getRect(find.byKey(const Key('agent-composer'))).bottom, + lessThanOrEqualTo(544), + ); + expect(tester.widget(input).controller!.text, 'Tablet draft'); + tester.view.resetViewInsets(); + await setMode(tester, mounted.container, WorkspaceMode.cut); + await tester.tap(find.byKey(const Key('editor-properties-button'))); + await tester.pumpAndSettle(); + expect(find.byType(PropertiesToolPanel), findsOneWidget); + expect(find.byType(PropertiesEditorPage), findsNothing); + final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse); + await mouse.addPointer(location: const Offset(200, 24)); + await mouse.moveTo(const Offset(250, 24)); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('tablet-workspace-shell')), findsOneWidget); + expect(find.byType(PropertiesToolPanel), findsOneWidget); + await mouse.removePointer(); + final prefs = mounted.container + .read(projectViewSettingsProvider(mounted.projectId)) + .requireValue; + expect(prefs.propertiesOpen, isFalse); + expect(tester.takeException(), isNull); + await mounted.close(); + }, + ); + + testWidgets( + 'phone navigation and landscape remain usable with keyboard and scaled text', + (tester) async { + final mounted = await mount( + tester, + const Size(390, 844), + experience: DeviceExperience.phone, + ); + await tester.tap(find.byKey(const Key('workspace-navigation-button'))); + await tester.pumpAndSettle(); + expect( + find.byKey(ValueKey('sidebar-project-${mounted.projectId}')), + findsOneWidget, + ); + await tester.tap( + find.byKey(ValueKey('sidebar-project-${mounted.projectId}')), + ); + await tester.pumpAndSettle(); + expect( + find.byKey(const Key('sidebar-projects-conversations')), + findsNothing, + ); + expect(find.byType(AgentChatPanel), findsOneWidget); + tester.view.viewInsets = const FakeViewPadding(bottom: 300); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('phone-workspace-shell')), findsOneWidget); + expect( + tester.getRect(find.byKey(const Key('agent-composer'))).bottom, + lessThanOrEqualTo(544), + ); + tester.view.resetViewInsets(); + addTearDown(tester.view.resetViewInsets); + await setMode(tester, mounted.container, WorkspaceMode.cut); + tester.view.physicalSize = const Size(844, 390); + tester.platformDispatcher.textScaleFactorTestValue = 2; + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); + await tester.pumpAndSettle(); + final timeline = tester.getRect(find.byType(EditorTimelinePanel)); + expect(timeline.right, lessThanOrEqualTo(844)); + expect(timeline.bottom, lessThanOrEqualTo(390)); + expect(tester.takeException(), isNull); + await mounted.close(); + }, + ); + for (final experience in [DeviceExperience.phone, DeviceExperience.tablet]) { + testWidgets( + '$experience navigation exposes touch actions and closes after new conversation', + (tester) async { + final mounted = await mount( + tester, + const Size(390, 844), + experience: experience, + ); + final selection = conversationSelectionProvider(mounted.projectId); + final before = mounted.container.read(selection).draftKey; + await tester.tap(find.byKey(const Key('workspace-navigation-button'))); + await tester.pumpAndSettle(); + final create = find.byKey(const Key('create-project')); + expect(tester.getSize(create).height, greaterThanOrEqualTo(48)); + final action = find.byKey( + ValueKey('new-agent-conversation-${mounted.projectId}'), + ); + expect(tester.getSize(action).height, greaterThanOrEqualTo(48)); + await tester.tap(action); + await tester.pumpAndSettle(); + expect(mounted.container.read(selection).draftKey, isNot(before)); + expect( + find.byKey(const Key('sidebar-projects-conversations')), + findsNothing, + ); + expect(tester.takeException(), isNull); + }, + ); + } + + for (final experience in [DeviceExperience.phone, DeviceExperience.tablet]) { + testWidgets( + '$experience system back closes both tool pages while keeping the editing session', + (tester) async { + final mounted = await mount( + tester, + const Size(390, 844), + experience: experience, + ); + await setMode(tester, mounted.container, WorkspaceMode.cut); + for (final button in [ + 'editor-media-button', + 'editor-properties-button', + ]) { + await tester.tap(find.byKey(Key(button))); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('editor-tool-surface')), findsOneWidget); + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('editor-tool-surface')), findsNothing); + expect(find.byType(EditorTimelinePanel), findsOneWidget); + expect( + await mounted.container.read( + editorTimelineProvider(mounted.projectId, 'project').future, + ), + same(mounted.session), + ); + } + }, + ); + + testWidgets( + '$experience back closes the navigation drawer before the tool page', + (tester) async { + final mounted = await mount( + tester, + const Size(390, 844), + experience: experience, + ); + await setMode(tester, mounted.container, WorkspaceMode.cut); + await tester.tap(find.byKey(const Key('editor-media-button'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('workspace-navigation-button'))); + await tester.pumpAndSettle(); + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + expect( + find.byKey(const Key('sidebar-projects-conversations')), + findsNothing, + ); + expect(find.byKey(const Key('editor-tool-surface')), findsOneWidget); + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('editor-tool-surface')), findsNothing); + }, + ); + } + + testWidgets('phone new conversation from a tool drawer returns to Agent', ( + tester, + ) async { + final mounted = await mount( + tester, + const Size(390, 844), + experience: DeviceExperience.phone, + ); + await setMode(tester, mounted.container, WorkspaceMode.cut); + await tester.tap(find.byKey(const Key('editor-media-button'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('workspace-navigation-button'))); + await tester.pumpAndSettle(); + await tester.tap( + find.byKey(ValueKey('new-agent-conversation-${mounted.projectId}')), + ); + await tester.pumpAndSettle(); + expect( + find.byKey(const Key('sidebar-projects-conversations')), + findsNothing, + ); + expect(find.byType(AgentChatPanel), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets( + 'phone property category survives closing and remounting the inspector', + (tester) async { + final mounted = await mount( + tester, + const Size(390, 844), + experience: DeviceExperience.phone, + ); + final sequence = mounted.session.activeSequenceId!; + final view = mounted.session.view(sequence); + view.setSelection([ + view.version.kernelVersion.query().elementById(ElementId('clip'))!, + ]); + await setMode(tester, mounted.container, WorkspaceMode.cut); + await tester.tap(find.byKey(const Key('editor-properties-button'))); + await tester.pumpAndSettle(); + final picker = find.byKey(const Key('property-category-picker')); + final dropdown = tester.widget>(picker); + dropdown.onChanged!(PropertyCategory.animation); + await tester.pumpAndSettle(); + expect( + tester.widget>(picker).value, + PropertyCategory.animation, + ); + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + await setMode(tester, mounted.container, WorkspaceMode.agent); + await setMode(tester, mounted.container, WorkspaceMode.cut); + await tester.tap(find.byKey(const Key('editor-properties-button'))); + await tester.pumpAndSettle(); + expect( + tester.widget>(picker).value, + PropertyCategory.animation, + ); + expect(tester.takeException(), isNull); + }, + ); + + testWidgets( + 'phone attachment import completes while the composer is hidden', + (tester) async { + final resolver = _DelayedResolver(); + final mounted = await mount( + tester, + const Size(390, 844), + experience: DeviceExperience.phone, + delayedResolver: resolver, + picker: const _PhotoPicker(), + ); + final selection = mounted.container.read( + conversationSelectionProvider(mounted.projectId), + ); + final composer = mounted.container + .read(agentComposerStoreProvider) + .composer(mounted.projectId, selection.draftKey); + final add = find.descendant( + of: find.byKey(const Key('agent-composer')), + matching: find.byIcon(Icons.add), + ); + await tester.tap(add); + await tester.pump(); + expect(resolver.started, isTrue); + await setMode(tester, mounted.container, WorkspaceMode.cut); + expect(find.byType(AgentChatPanel), findsNothing); + resolver.gate.complete(); + await tester.pumpAndSettle(); + expect(composer.attachments.single.id, 'media'); + await setMode(tester, mounted.container, WorkspaceMode.agent); + expect(find.byKey(const Key('agent-attachment-media')), findsOneWidget); + expect(tester.takeException(), isNull); + }, + ); + + testWidgets( + 'phone media import updates browser selection after the tool is closed', + (tester) async { + final resolver = _DelayedResolver(); + final mounted = await mount( + tester, + const Size(390, 844), + experience: DeviceExperience.phone, + delayedResolver: resolver, + picker: const _PhotoPicker(), + ); + await setMode(tester, mounted.container, WorkspaceMode.cut); + await tester.tap(find.byKey(const Key('editor-media-button'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('media-import-button'))); + await tester.pump(); + expect(resolver.started, isTrue); + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + resolver.gate.complete(); + await tester.pumpAndSettle(); + expect( + mounted.container + .read(mediaBrowserProvider(mounted.projectId)) + .selectedAssetId, + 'media', + ); + expect(tester.takeException(), isNull); + }, + ); + testWidgets( + 'created conversation preserves follow-up text and pending imports', + (tester) async { + final resolver = _DelayedResolver(); + final mounted = await mount( + tester, + const Size(390, 844), + experience: DeviceExperience.phone, + delayedResolver: resolver, + picker: const _PhotoPicker(), + conversations: _WorkspaceConversationRepository(), + ); + final selectionProvider = conversationSelectionProvider( + mounted.projectId, + ); + final draftKey = mounted.container.read(selectionProvider).draftKey; + final store = mounted.container.read(agentComposerStoreProvider); + final input = find.descendant( + of: find.byKey(const Key('agent-composer')), + matching: find.byType(TextField), + ); + await tester.enterText( + input, + 'Follow-up while the first message is saved', + ); + final draftInput = store.input(mounted.projectId, null); + final composer = store.composer(mounted.projectId, draftKey); + await tester.tap( + find.descendant( + of: find.byKey(const Key('agent-composer')), + matching: find.byIcon(Icons.add), + ), + ); + await tester.pump(); + expect(resolver.started, isTrue); + final now = DateTime.utc(2026); + final created = ConversationMetadata( + id: 'created-chat', + pending: false, + responseDurationsMs: const [], + projectId: mounted.projectId, + title: 'Created', + createdAt: now, + updatedAt: now, + providerId: 'provider', + modelId: 'model', + timelineId: 'project', + ); + await mounted.container + .read(conversationSidebarProvider.notifier) + .updateListing(created, selectIfDraftKey: draftKey); + await tester.pumpAndSettle(); + expect(mounted.container.read(selectionProvider).selectedId, created.id); + expect(store.input(mounted.projectId, created.id), same(draftInput)); + expect(store.composer(mounted.projectId, created.id), same(composer)); + expect( + tester.widget(input).controller!.text, + 'Follow-up while the first message is saved', + ); + resolver.gate.complete(); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('agent-attachment-media')), findsOneWidget); + expect(composer.busy, isFalse); + mounted.container + .read(conversationSidebarProvider.notifier) + .newConversation(); + await tester.pumpAndSettle(); + expect(tester.widget(input).controller!.text, isEmpty); + expect(find.byKey(const Key('agent-attachment-media')), findsNothing); + expect( + store.input(mounted.projectId, created.id).text, + 'Follow-up while the first message is saved', + ); + expect(tester.takeException(), isNull); + }, + ); + + for (final target in ['composer', 'media']) { + testWidgets('hidden $target import failure is shown once on return', ( + tester, + ) async { + final resolver = _DelayedResolver(); + final mounted = await mount( + tester, + const Size(390, 844), + experience: DeviceExperience.phone, + delayedResolver: resolver, + picker: const _BadPicker(), + importResult: const MediaImportResult( + assets: [], + added: 0, + duplicates: 0, + failures: [ + MediaImportFailure( + name: 'bad.mov', + failure: AppFailure( + AppErrorCode.diagnostic, + diagnostic: 'File cannot be read', + ), + ), + ], + ), + ); + if (target == 'media') { + await setMode(tester, mounted.container, WorkspaceMode.cut); + await tester.tap(find.byKey(const Key('editor-media-button'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('media-import-button'))); + } else { + await tester.tap( + find.descendant( + of: find.byKey(const Key('agent-composer')), + matching: find.byIcon(Icons.add), + ), + ); + } + await tester.pump(); + expect(resolver.started, isTrue); + if (target == 'media') { + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + } else { + await setMode(tester, mounted.container, WorkspaceMode.cut); + } + resolver.gate.complete(); + await tester.pumpAndSettle(); + expect(find.byType(SnackBar), findsNothing); + if (target == 'media') { + await tester.tap(find.byKey(const Key('editor-media-button'))); + await tester.pumpAndSettle(); + } else { + await setMode(tester, mounted.container, WorkspaceMode.agent); + } + expect(find.byType(SnackBar), findsOneWidget); + expect(find.textContaining('bad.mov:'), findsOneWidget); + final feedback = target == 'media' + ? mounted.container + .read(mediaBrowserProvider(mounted.projectId)) + .feedback + : mounted.container + .read(agentComposerStoreProvider) + .composer( + mounted.projectId, + mounted.container + .read(conversationSelectionProvider(mounted.projectId)) + .draftKey, + ) + .feedback; + expect(feedback.hasPending, isFalse); + ScaffoldMessenger.of(tester.element(find.byType(SnackBar))) + .removeCurrentSnackBar(); + await tester.pumpAndSettle(); + await setMode(tester, mounted.container, WorkspaceMode.cut); + await setMode(tester, mounted.container, WorkspaceMode.agent); + if (target == 'media') { + await setMode(tester, mounted.container, WorkspaceMode.cut); + await tester.tap(find.byKey(const Key('editor-media-button'))); + await tester.pumpAndSettle(); + } + expect(find.byType(SnackBar), findsNothing); + expect(tester.takeException(), isNull); + }); + } + + testWidgets( + 'extremely narrow desktop keeps safe layout and splitter bounds', + (tester) async { + final mounted = await mount(tester, const Size(200, 800)); + expect(find.byKey(const Key('desktop-workspace-shell')), findsOneWidget); + expect(find.byKey(const Key('agent-panel-resize')), findsNothing); + expect(tester.takeException(), isNull); + tester.view.physicalSize = const Size(240, 800); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('agent-panel-resize')), findsOneWidget); + await tester.drag( + find.byKey(const Key('agent-panel-resize')), + const Offset(-20, 0), + ); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + tester.view.physicalSize = const Size(200, 800); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('agent-panel-resize')), findsNothing); + expect(tester.takeException(), isNull); + tester.view.physicalSize = const Size(1200, 800); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('agent-panel-resize')), findsOneWidget); + await tester.drag( + find.byKey(const Key('agent-panel-resize')), + const Offset(-20, 0), + ); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('desktop-workspace-shell')), findsOneWidget); + expect(tester.takeException(), isNull); + await mounted.close(); + }, + ); +} + +class _FixtureProjects extends Projects { + _FixtureProjects(this.projectId, this.session, this.importResult); + final MediaImportResult? importResult; + final String projectId; + final EditorTimelineSession session; + @override + Future build() async { + final project = RecentProject( + id: projectId, + name: 'Adaptive test', + path: '/test/Adaptive.cutdex', + ); + return ProjectState( + activeProject: project, + recent: [project], + timeline: session.document, + timelines: const [ + TimelineSummary(id: 'project', name: 'Timeline', revision: 1), + ], + assets: [ + AssetDocument( + id: 'media', + name: 'Photo', + storage: AssetStorage.external, + location: 'file:///test/photo.png', + metadata: {'kind': 'image'}, + ), + ], + ); + } + + @override + Future importExternalMedia( + String projectId, + List files, { + bool Function()? isCancelled, + }) async => + importResult ?? + await super.importExternalMedia( + projectId, + files, + isCancelled: isCancelled, + ); + + @override + EditorTimelineSession? cachedTimelineSession( + String projectId, + String timelineId, + ) => session; +} + +class _TimelineViewRepository implements TimelineViewSettingsRepository { + @override + Future load(String projectId, String timelineId) async => + const TimelineViewState(); + @override + Future save( + String projectId, + String timelineId, + SequenceId sequenceId, + TimelineSequenceViewState state, + ) async {} +} + +class _PhotoPicker extends AppFilePicker { + const _PhotoPicker(); + @override + Future> pickFiles({ + required List allowedExtensions, + }) async => [const ExternalMediaFile(path: '/test/photo.png')]; +} + +class _DelayedResolver extends MediaFileResolver { + final gate = Completer(); + bool started = false; + @override + Future>> resolve( + List files, + List assets, + ) async { + started = true; + await gate.future; + return super.resolve(files, assets); + } +} + +class _BadPicker extends AppFilePicker { + const _BadPicker(); + @override + Future> pickFiles({ + required List allowedExtensions, + }) async => [const ExternalMediaFile(path: '/test/bad.mov')]; +} + +class _WorkspaceConversationRepository extends EmptyConversationRepository { + @override + Future select(String projectId, String? conversationId) async {} +} diff --git a/test/agent_attachment_composer_test.dart b/test/agent_attachment_composer_test.dart new file mode 100644 index 0000000..a9dfe6f --- /dev/null +++ b/test/agent_attachment_composer_test.dart @@ -0,0 +1,595 @@ +import 'package:cutdex/app/editor_theme.dart'; + +import 'dart:async'; + +import 'package:cutdex/features/assistant/agent_chat_panel.dart'; +import 'package:cutdex/features/assistant/chat_controller.dart'; +import 'package:cutdex/features/assistant/chat_state.dart'; +import 'package:cutdex/features/assistant/composer_document.dart'; +import 'package:cutdex/features/assistant/composer_suggestion_surface.dart'; +import 'package:cutdex/features/media/media_asset_drag.dart'; +import 'package:cutdex/integrations/agent/agent_provider.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex/shared/widgets/drop_to_add_overlay.dart'; +import 'package:cutdex/workspace/project_state.dart'; +import 'package:cutdex/workspace/projects.dart'; +import 'package:cutdex/workspace/media_import.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +class _AttachmentProjects extends Projects { + @visibleForTesting + int importCalls = 0; + + @override + Future importExternalMedia( + String projectId, + List files, { + bool Function()? isCancelled, + }) async { + importCalls++; + return null; + } + + @override + Future build() async => ProjectState( + activeProject: const RecentProject( + id: 'project', + name: 'Project', + path: '/Project.cutdex', + ), + assets: [ + AssetDocument( + id: 'asset-1', + name: '片段.mov', + storage: AssetStorage.external, + location: Uri.file('/tmp/片段.mov').toString(), + metadata: const {'kind': 'file'}, + ), + ], + timelines: const [ + TimelineSummary(id: 'timeline', name: '主时间线', revision: 1), + ], + ); +} + +class _MessagesChatController extends ChatController { + @override + ChatState build( + String projectId, { + String? conversationId, + String? draftKey, + }) => const ChatState( + messages: [ + ChatMessage(text: 'Assistant reply'), + ChatMessage(text: 'User prompt', isUser: true), + ], + ); +} + +void main() { + testWidgets('conversation content aligns with the composer at both widths', ( + tester, + ) async { + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetDevicePixelRatio); + addTearDown(tester.view.resetPhysicalSize); + for (final width in [1200.0, 500.0]) { + tester.view.physicalSize = Size(width, 800); + await tester.pumpWidget( + ProviderScope( + overrides: [ + projectsProvider.overrideWith(_AttachmentProjects.new), + chatControllerProvider('project') + .overrideWith(_MessagesChatController.new), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + theme: EditorTheme.penDark, + home: const Scaffold(body: AgentChatPanel(projectId: 'project')), + ), + ), + ); + await tester.pumpAndSettle(); + final conversation = tester.getRect( + find.byKey(const Key('agent-conversation-content')), + ); + final composer = tester.getRect(find.byKey(const Key('agent-composer'))); + expect(conversation.left, composer.left); + expect(conversation.right, composer.right); + } + }); + + testWidgets('left and right arrows cross an inline reference as one item', ( + tester, + ) async { + final controller = ComposerDocumentController(text: '@时间线 1'); + addTearDown(controller.dispose); + controller.insertReference( + 0, + 4, + const ComposerReference( + kind: ComposerReferenceKind.timeline, + projectId: 'project', + id: 'timeline', + label: '时间线', + ), + ); + await tester.pumpWidget( + MaterialApp( + theme: EditorTheme.penDark, + home: Scaffold(body: TextField(controller: controller)), + ), + ); + await tester.tap(find.byType(TextField)); + controller.selection = TextSelection.collapsed( + offset: controller.text.length, + ); + await tester.pump(); + for (var index = 0; index < 2; index++) { + await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); + } + expect(controller.selection.extentOffset, controller.marks.single.end); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft); + expect(controller.selection.extentOffset, controller.marks.single.start); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); + expect(controller.selection.extentOffset, controller.marks.single.end); + }); + + testWidgets('keyboard selection scrolls grouped suggestions into view', ( + tester, + ) async { + final controller = ComposerDocumentController(); + addTearDown(controller.dispose); + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + theme: EditorTheme.penDark, + home: Scaffold( + body: Align( + alignment: Alignment.bottomCenter, + child: ComposerSuggestionSurface( + controller: controller, + width: 260, + projectId: 'project', + assets: [ + for (var index = 0; index < 20; index++) + AssetDocument( + id: 'asset-$index', + name: '片段 $index', + storage: AssetStorage.external, + location: 'file:///tmp/$index', + ), + ], + timelines: const [ + TimelineSummary(id: 'timeline', name: '主时间线', revision: 1), + ], + onSend: () {}, + builder: (context, focus) => + TextField(controller: controller, focusNode: focus), + ), + ), + ), + ), + ); + await tester.enterText(find.byType(TextField), '@'); + await tester.pumpAndSettle(); + final list = find.byKey(const Key('agent-composer-suggestion-list')); + ScrollController scroll() => tester.widget(list).controller!; + + for (var index = 0; index < 15; index++) { + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + } + await tester.pumpAndSettle(); + expect(scroll().offset, greaterThan(0)); + final scrolledOffset = scroll().offset; + final selected = find.byKey(const Key('agent-suggestion-media-asset-15')); + expect(selected, findsOneWidget); + expect(tester.getRect(list).overlaps(tester.getRect(selected)), isTrue); + + for (var index = 0; index < 15; index++) { + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + } + await tester.pumpAndSettle(); + expect(scroll().offset, lessThan(scrolledOffset)); + expect( + tester + .getRect(list) + .overlaps( + tester.getRect( + find.byKey(const Key('agent-suggestion-media-asset-0')), + ), + ), + isTrue, + ); + + await tester.sendKeyEvent(LogicalKeyboardKey.arrowUp); + await tester.pumpAndSettle(); + expect( + find.byKey(const Key('agent-suggestion-timeline-timeline')), + findsOneWidget, + ); + expect(scroll().offset, greaterThan(0)); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.pumpAndSettle(); + expect( + tester + .getRect(list) + .overlaps( + tester.getRect( + find.byKey(const Key('agent-suggestion-media-asset-0')), + ), + ), + isTrue, + ); + }); + + testWidgets( + 'composer @ menu inserts an atomic asset reference and empty triggers stay open', + (tester) async { + final platform = SystemChannels.platform; + String? copiedText; + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + messenger.setMockMethodCallHandler(platform, (call) async { + if (call.method == 'Clipboard.setData') { + copiedText = (call.arguments as Map)['text'] as String?; + } + if (call.method == 'Clipboard.hasStrings') { + return {'value': copiedText != null}; + } + if (call.method == 'Clipboard.getData') { + return {'text': copiedText}; + } + return null; + }); + addTearDown(() => messenger.setMockMethodCallHandler(platform, null)); + final controller = ComposerDocumentController(); + var outsideTaps = 0; + addTearDown(controller.dispose); + await tester.pumpWidget( + ProviderScope( + overrides: [ + projectsProvider.overrideWith(_AttachmentProjects.new), + agentRuntimeProvider.overrideWithValue(const AsyncData(null)), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + theme: EditorTheme.penDark, + home: Scaffold( + body: Stack( + children: [ + AgentChatPanel( + projectId: 'project', + timelineId: 'timeline', + inputController: controller, + ), + Align( + alignment: Alignment.topLeft, + child: TextButton( + onPressed: () => outsideTaps++, + child: const Text('outside target'), + ), + ), + ], + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + final field = find.byType(TextField).last; + await tester.enterText(field, '@片'); + await tester.pumpAndSettle(); + expect( + find.byKey(const Key('agent-composer-suggestions')), + findsOneWidget, + ); + expect( + find.byKey(const Key('agent-suggestion-media-asset-1')), + findsOneWidget, + ); + expect( + find.byKey(const Key('agent-suggestion-group-media')), + findsOneWidget, + ); + expect( + find.byKey(const Key('agent-suggestion-group-timeline')), + findsNothing, + ); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + expect(controller.marks.single.reference.id, 'asset-1'); + expect(controller.text, '@片段.mov '); + expect(controller.selection.extentOffset, controller.text.length); + final assetSpan = controller.buildTextSpan( + context: tester.element(field), + withComposing: false, + ); + final referenceColor = AppTheme.composerReferenceColor( + tester.element(field), + ); + expect( + referenceColor, + isNot(Theme.of(tester.element(field)).colorScheme.onSurface), + ); + final assetIcon = + ((assetSpan.children!.first as WidgetSpan).child as Padding).child + as Icon; + expect(assetIcon.icon, Icons.attach_file); + expect(assetIcon.color, referenceColor); + expect((assetSpan.children![1] as TextSpan).style?.color, referenceColor); + expect( + tester.getSemantics(find.byType(EditableText).last).value, + contains('片段.mov'), + ); + controller.selection = TextSelection( + baseOffset: 0, + extentOffset: controller.text.length, + ); + tester + .state(find.byType(EditableText).last) + .copySelection(SelectionChangedCause.keyboard); + await tester.pump(); + expect(copiedText, '@片段.mov '); + controller.clearDocument(); + await tester.pump(); + await tester + .state(find.byType(EditableText).last) + .pasteText(SelectionChangedCause.keyboard); + await tester.pump(); + expect(controller.text, '@片段.mov '); + expect(controller.marks, isEmpty); + controller.clearDocument(); + await tester.enterText(field, '@'); + await tester.pumpAndSettle(); + expect( + find.byKey(const Key('agent-suggestion-group-media')), + findsOneWidget, + ); + expect( + find.byKey(const Key('agent-suggestion-group-timeline')), + findsOneWidget, + ); + await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + expect(controller.marks.single.reference.id, 'timeline'); + final timelineSpan = controller.buildTextSpan( + context: tester.element(field), + withComposing: false, + ); + final timelineIcon = + ((timelineSpan.children!.first as WidgetSpan).child as Padding).child + as Icon; + expect(timelineIcon.icon, Icons.view_timeline_outlined); + expect(timelineIcon.color, referenceColor); + final timelineLabel = timelineSpan.children![1] as TextSpan; + expect(timelineLabel.text, '主时间线'); + expect(timelineLabel.style?.color, referenceColor); + controller.selection = TextSelection.collapsed( + offset: controller.text.length, + ); + await tester.sendKeyEvent(LogicalKeyboardKey.backspace); + await tester.pumpAndSettle(); + expect(controller.marks.single.reference.id, 'timeline'); + await tester.sendKeyEvent(LogicalKeyboardKey.backspace); + await tester.pumpAndSettle(); + expect(controller.marks, isEmpty); + expect(controller.text, isEmpty); + controller.clearDocument(); + await tester.enterText(field, '@主'); + await tester.pumpAndSettle(); + expect( + find.byKey(const Key('agent-suggestion-group-media')), + findsNothing, + ); + expect( + find.byKey(const Key('agent-suggestion-group-timeline')), + findsOneWidget, + ); + await tester.tap( + find.byKey(const Key('agent-suggestion-timeline-timeline')), + ); + await tester.pumpAndSettle(); + expect(controller.marks.single.reference.id, 'timeline'); + controller.clearDocument(); + await tester.enterText(field, '/'); + await tester.pumpAndSettle(); + expect(find.text('暂无可用选项'), findsOneWidget); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('agent-composer-suggestions')), findsNothing); + await tester.enterText(field, '/a'); + await tester.pumpAndSettle(); + expect(find.text('暂无可用选项'), findsOneWidget); + await tester.tap(find.text('outside target')); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('agent-composer-suggestions')), findsNothing); + expect(outsideTaps, 1); + controller.clearDocument(); + await tester.enterText(field, r'$'); + await tester.pumpAndSettle(); + expect(find.text('暂无可用选项'), findsOneWidget); + controller.clearDocument(); + controller.value = const TextEditingValue( + text: '@片', + selection: TextSelection.collapsed(offset: 2), + composing: TextRange(start: 1, end: 2), + ); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('agent-composer-suggestions')), findsNothing); + controller.value = controller.value.copyWith(composing: TextRange.empty); + await tester.pumpAndSettle(); + expect( + find.byKey(const Key('agent-suggestion-media-asset-1')), + findsOneWidget, + ); + }, + ); + testWidgets('project asset can be dropped anywhere in the Agent panel', ( + tester, + ) async { + await tester.pumpWidget( + ProviderScope( + overrides: [ + projectsProvider.overrideWith(_AttachmentProjects.new), + agentRuntimeProvider.overrideWithValue(const AsyncData(null)), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + theme: EditorTheme.penDark, + home: Scaffold( + body: Row( + children: [ + Draggable( + data: MediaAssetDrag( + projectId: 'project', + assetId: 'asset-1', + ), + feedback: const Material(child: Text('dragging')), + child: const SizedBox( + width: 100, + height: 100, + child: Text('素材'), + ), + ), + const Expanded( + child: AgentChatPanel( + projectId: 'project', + timelineId: 'timeline', + ), + ), + ], + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + final gesture = await tester.startGesture( + tester.getCenter(find.text('素材')), + ); + await gesture.moveBy(const Offset(20, 0)); + await tester.pump(); + await gesture.moveTo( + tester.getCenter(find.byKey(const Key('agent-conversation'))), + ); + await tester.pump(); + final overlay = find.byKey(const Key('agent-drop-overlay')); + expect(overlay, findsOneWidget); + expect(tester.widget(overlay), isA()); + expect(find.text('松手即可添加'), findsOneWidget); + expect( + tester.getRect(overlay), + tester.getRect(find.byType(AgentChatPanel)), + ); + await gesture.up(); + await tester.pumpAndSettle(); + expect(overlay, findsNothing); + expect(find.byKey(const Key('agent-attachment-asset-1')), findsOneWidget); + final duplicate = await tester.startGesture( + tester.getCenter(find.text('素材')), + ); + await duplicate.moveBy(const Offset(20, 0)); + await tester.pump(); + await duplicate.moveTo( + tester.getCenter(find.byKey(const Key('agent-conversation'))), + ); + await tester.pump(); + expect(overlay, findsNothing); + await duplicate.up(); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('agent-attachment-asset-1')), findsOneWidget); + await tester.tap(find.byKey(const Key('agent-attachment-remove-asset-1'))); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('agent-attachment-asset-1')), findsNothing); + }); + + testWidgets('Finder drop reuses an existing project asset without flashing', ( + tester, + ) async { + const channel = MethodChannel('cutdex_native/file_drop/attachments'); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + messenger.setMockMethodCallHandler(channel, (_) async => null); + addTearDown(() => messenger.setMockMethodCallHandler(channel, null)); + final container = ProviderContainer( + overrides: [ + projectsProvider.overrideWith(_AttachmentProjects.new), + agentRuntimeProvider.overrideWithValue(const AsyncData(null)), + ], + ); + addTearDown(container.dispose); + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + theme: EditorTheme.penDark, + home: const Scaffold( + body: AgentChatPanel(projectId: 'project', timelineId: 'timeline'), + ), + ), + ), + ); + await tester.pumpAndSettle(); + Future event(String phase, int session) async { + final done = Completer(); + tester.binding.defaultBinaryMessenger.handlePlatformMessage( + 'cutdex_native/file_drop/attachments', + const StandardMethodCodec().encodeMethodCall( + MethodCall('event', { + 'phase': phase, + 'session': session, + 'files': [ + const {'path': '/tmp/片段.mov'}, + ], + }), + ), + (_) => done.complete(), + ); + await done.future; + await tester.pump(); + } + + await event('enter', 1); + expect(find.byKey(const Key('agent-drop-overlay')), findsOneWidget); + await event('drop', 1); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('agent-drop-overlay')), findsNothing); + expect(find.byKey(const Key('agent-attachment-asset-1')), findsOneWidget); + expect( + (container.read( + projectsProvider.notifier, + ) as _AttachmentProjects).importCalls, + 0, + ); + + await event('enter', 2); + expect(find.byKey(const Key('agent-drop-overlay')), findsNothing); + await event('drop', 2); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('agent-attachment-asset-1')), findsOneWidget); + expect( + (container.read( + projectsProvider.notifier, + ) as _AttachmentProjects).importCalls, + 0, + ); + }, variant: TargetPlatformVariant.only(TargetPlatform.macOS)); +} diff --git a/test/agent_context_budget_test.dart b/test/agent_context_budget_test.dart new file mode 100644 index 0000000..37f9c62 --- /dev/null +++ b/test/agent_context_budget_test.dart @@ -0,0 +1,397 @@ +import 'dart:convert'; + +import 'package:cutdex/integrations/agent/agent_models.dart'; +import 'package:cutdex/integrations/agent/agent_prompt_policy.dart'; +import 'package:cutdex/integrations/agent/editor_agent_tools.dart'; +import 'package:cutdex_agent/cutdex_agent.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:cutdex_sdk/tools.dart'; +import 'package:cutdex_sdk/editor/commands.dart'; + +class _CatalogHost implements EditorCommandHost { + _CatalogHost([this.operations]); + final Set? operations; + @override + Set get supportedOperations => + operations ?? EditorOperation.values.toSet(); + @override + Future execute( + EditorCommand command, + CommandContext context, + ) => throw UnimplementedError('Only declarations are read by this test'); +} + +class _SnapshotHost extends _CatalogHost { + _SnapshotHost(this.result); + final CommandResult result; + @override + Future execute( + EditorCommand command, + CommandContext context, + ) async => result; +} + +void main() { + test('Agent capabilities do not repeat already registered schemas', () async { + final source = CommandResult( + status: CommandStatus.succeeded, + message: 'Available tools', + data: { + 'tools': editorToolDefinitions.map((tool) => tool.toJson()).toList(), + }, + ); + final tools = editorAgentTools({ + 'timeline': EditorToolDispatcher(host: _SnapshotHost(source)), + }); + final tool = tools.singleWhere((tool) => tool.name == 'tools_capabilities'); + final result = await tool.execute( + ToolCall( + id: 'c', + name: tool.name, + arguments: {'workspaceId': 'timeline'}, + ), + ToolContext( + sessionId: 's', + runId: 'r', + operationId: 'c', + cancellation: CancellationToken(), + onProgress: (_) {}, + ), + ); + final declarations = ((result.data['data'] as Map)['tools'] as List) + .cast>(); + expect(declarations, hasLength(editorToolDefinitions.length)); + expect( + declarations.map((d) => d['name']), + editorToolDefinitions.map((d) => d.name), + ); + expect(declarations.every((d) => !d.containsKey('inputSchema')), isTrue); + expect((source.data['tools'] as List).first, contains('inputSchema')); + }); + + test( + 'multi-lane mask queries retain edit values and fit repeated verification', + () async { + final parameters = [ + 'canvas.position.x', + 'canvas.scale.x', + 'canvas.rotation', + for (final mask in ['ellipse', 'hole']) + for (final field in [ + 'center.x', + 'center.y', + 'width', + 'height', + 'rotation', + 'feather', + 'shape', + 'enabled', + 'inverted', + 'mode', + 'order', + ]) + 'mask.$mask.$field', + ]; + final source = CommandResult( + status: CommandStatus.succeeded, + message: 'Timeline', + data: { + 'duration': {'numerator': '35', 'denominator': 1}, + 'saveState': 'saved', + 'clips': [ + for (var i = 0; i < 8; i++) + { + 'clipId': 'clip-$i', + 'parameters': [ + for (final id + in i < 2 + ? parameters + : ['canvas.position.x', 'canvas.position.y']) + { + 'id': id, + 'defaultValue': .5, + 'minimum': -1000000, + 'maximum': 1000000, + 'unit': '', + 'keyframes': id == 'canvas.position.x' + ? [ + { + 'sourceTime': { + 'numerator': '5', + 'denominator': 1, + }, + 'value': 0, + 'interpolation': 'linear', + }, + { + 'sourceTime': { + 'numerator': '15', + 'denominator': 1, + }, + 'value': .15625, + 'interpolation': 'linear', + }, + ] + : [], + }, + ], + }, + ], + }, + ); + final tools = editorAgentTools({ + 'timeline': EditorToolDispatcher(host: _SnapshotHost(source)), + }); + final query = tools.singleWhere((tool) => tool.name == 'timeline_query'); + final result = await query.execute( + ToolCall( + id: 'q', + name: query.name, + arguments: {'workspaceId': 'timeline'}, + ), + ToolContext( + sessionId: 's', + runId: 'r', + operationId: 'q', + cancellation: CancellationToken(), + onProgress: (_) {}, + ), + ); + final data = result.data['data'] as Map; + final actual = + ((data['clips'] as List).first as Map)['parameters'] as List; + final original = + ((source.data['clips'] as List).first as Map)['parameters'] as List; + expect(actual.first['keyframes'], original.first['keyframes']); + expect( + actual.map((p) => p['defaultValue']), + original.map((p) => p['defaultValue']), + ); + expect(data['duration'], source.data['duration']); + expect(original.first['maximum'], 1000000); + List history(String text) => [ + AgentMessage( + role: MessageRole.user, + text: 'Split all lanes, verify, undo and redo.', + ), + for (var i = 0; i < 5; i++) ...[ + AgentMessage( + role: MessageRole.assistant, + calls: [ + ToolCall( + id: 'q$i', + name: query.name, + arguments: {'workspaceId': 'timeline'}, + ), + ], + ), + AgentMessage(role: MessageRole.tool, callId: 'q$i', text: text), + ], + ]; + final builder = HarnessContextBuilder(maxResultBytes: 1024); + final raw = jsonEncode( + ToolResult(source.message, data: source.toJson()).toJson(), + ); + expect( + builder.measureInput( + system: AgentPromptPolicy.editorAssistant, + history: history(raw), + tools: tools, + ), + greaterThan(builder.maxInputTokens), + ); + final request = await builder.build( + system: AgentPromptPolicy.editorAssistant, + history: history(jsonEncode(result.toJson())), + tools: tools, + cancellation: CancellationToken(), + ); + expect(request.messages, hasLength(11)); + final fullHistory = history(jsonEncode(result.toJson())); + final changed = jsonDecode(fullHistory[4].text); + changed['data']['data']['clips'][0]['parameters'][1]['defaultValue'] = + .75; + fullHistory[4] = AgentMessage.fromJson({ + ...fullHistory[4].toJson(), + 'text': jsonEncode(changed), + }); + final projection = HarnessContextBuilder(maxResultBytes: 1024); + final bounded = await projection.build( + system: AgentPromptPolicy.editorAssistant, + history: fullHistory, + tools: tools, + cancellation: CancellationToken(), + ); + expect(bounded.messages, hasLength(fullHistory.length)); + expect(jsonDecode(bounded.messages[4].text)['resultId'], 'q1'); + expect(jsonDecode(bounded.messages[4].text)['omitted'], isTrue); + expect(fullHistory[4].text, contains('"defaultValue":0.75')); + final snapshot = SessionSnapshot(id: 's', history: fullHistory); + final reader = projection + .runtimeTools(() => snapshot, tools) + .singleWhere((tool) => tool.name == 'read_tool_result'); + final recovered = await reader.execute( + ToolCall( + id: 'read', + name: reader.name, + arguments: { + 'resultId': 'q1', + 'path': '/data/data/clips/0/parameters/1/defaultValue', + }, + ), + ToolContext( + sessionId: 's', + runId: 'r', + operationId: 'read', + cancellation: CancellationToken(), + onProgress: (_) {}, + ), + ); + expect(recovered.data['value'], .75); + expect( + bounded.messages.map((m) => m.callId), + fullHistory.map((m) => m.callId), + ); + }, + ); + + test('workspace discovery identifies timeline tools and rejects application routing', () async { + final tools = editorAgentTools({ + 'application': EditorToolDispatcher( + host: _CatalogHost({EditorOperation.queryProjects}), + ), + 'timeline-id': EditorToolDispatcher( + host: _CatalogHost({ + EditorOperation.queryTimeline, + EditorOperation.split, + }), + ), + }); + final listing = await tools.first.execute( + ToolCall(id: 'list', name: 'cutdex_workspaces'), + ToolContext( + sessionId: 'session', + runId: 'run', + operationId: 'op', + cancellation: CancellationToken(), + onProgress: (_) {}, + ), + ); + final data = jsonDecode(listing.text); + final targets = data['targets'] as List; + expect( + data['toolSets'][targets.last['toolSetId']], + contains('timeline_split'), + ); + expect( + data['toolSets'][targets.first['toolSetId']], + isNot(contains('timeline_split')), + ); + final query = tools.firstWhere((tool) => tool.name == 'timeline_query'); + expect( + query.validate({'workspaceId': 'application'}), + contains('timeline-id'), + ); + expect(query.validate({'workspaceId': 'timeline-id'}), isNull); + expect( + query.validate({'workspaceId': 'timeline-typo'}), + contains('timeline-id'), + ); + }); + + test( + 'large workspace discovery is lossless and shares a single tool catalog', + () async { + final dispatcher = EditorToolDispatcher(host: _CatalogHost()); + final tool = editorAgentTools({ + for (var i = 0; i < 100; i++) 'timeline-$i': dispatcher, + }).first; + final listing = await tool.execute( + ToolCall(id: 'list', name: tool.name), + ToolContext( + sessionId: 's', + runId: 'r', + operationId: 'list', + cancellation: CancellationToken(), + onProgress: (_) {}, + ), + ); + final data = jsonDecode(listing.text); + expect(data['targets'], hasLength(100)); + expect(data['toolSets'], hasLength(1)); + final original = AgentMessage( + role: MessageRole.tool, + callId: 'list', + text: jsonEncode(listing.toJson()), + ); + final projected = HarnessContextBuilder(maxResultBytes: 1024) + .projectHistory([original]); + expect(jsonDecode(projected.single.text)['resultId'], 'list'); + expect(original.text, jsonEncode(listing.toJson())); + }, + ); + + test('workspace growth does not duplicate IDs into every tool schema', () { + final dispatcher = EditorToolDispatcher(host: _CatalogHost()); + final one = editorAgentTools({'first': dispatcher}); + final many = editorAgentTools({ + for (var i = 0; i < 100; i++) 'project/timeline-$i': dispatcher, + }); + String schema(List tools) => + jsonEncode(tools.map((t) => t.declaration).toList()); + expect(schema(many), schema(one)); + final operation = many.firstWhere( + (tool) => tool.name != 'cutdex_workspaces', + ); + expect(operation.validate.call({'workspaceId': 'missing'}), isNotNull); + }); + test( + 'greeting loads runtime tools without the full editor catalog', + () async { + final tools = editorAgentTools({}, dynamicWorkspaces: true); + const model = AgentModelSettings(id: 'custom-model'); + final builder = HarnessContextBuilder( + directTools: const {'cutdex_workspaces'}, + maxInputTokens: model.effectiveMaxInputTokens, + maxOutputTokens: model.effectiveMaxOutputTokens, + ); + final history = [AgentMessage(role: MessageRole.user, text: 'hi')]; + final input = builder.measureInput( + system: AgentPromptPolicy.editorAssistant, + history: history, + tools: tools, + ); + // Keep a real catalog regression rather than a small placeholder tool. + expect(tools.length, greaterThan(20)); + final request = await builder.build( + system: AgentPromptPolicy.editorAssistant, + history: history, + tools: [ + ...tools, + ...builder.runtimeTools( + () => SessionSnapshot(id: 's', history: history), + tools, + ), + ], + cancellation: CancellationToken(), + ); + expect( + request.tools.map((t) => t.name), + unorderedEquals([ + 'cutdex_workspaces', + 'tool_search', + 'read_tool_result', + 'update_plan', + ]), + ); + expect(request.messages.single.text, 'hi'); + final projectedInput = builder.measureInput( + system: request.system, + history: request.messages, + tools: request.tools, + ); + expect(projectedInput, lessThan(input)); + expect(projectedInput, lessThan(model.effectiveMaxInputTokens * .8)); + }, + ); +} diff --git a/test/agent_conversation_service_test.dart b/test/agent_conversation_service_test.dart new file mode 100644 index 0000000..9bf5292 --- /dev/null +++ b/test/agent_conversation_service_test.dart @@ -0,0 +1,774 @@ +import 'package:cutdex/integrations/agent/editor_agent_tools.dart'; + +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:cutdex/features/assistant/agent_conversation_service.dart'; +import 'package:cutdex/features/assistant/agent_message_codec.dart'; +import 'package:cutdex/features/assistant/composer_document.dart'; +import 'package:cutdex/features/assistant/chat_state.dart'; +import 'package:cutdex/integrations/agent/agent_runtime.dart'; +import 'package:cutdex/integrations/editor_tools.dart'; +import 'package:cutdex/integrations/agent/conversation_repository.dart'; +import 'package:cutdex_agent/cutdex_agent.dart'; +import 'package:flutter_test/flutter_test.dart'; + +class _Model implements ModelAdapter { + int calls = 0; + + @override + Stream stream( + ModelRequest request, + CancellationToken cancellation, + ) async* { + calls++; + yield ModelResponse(text: 'done'); + } +} + +class _ProgressModel implements ModelAdapter { + int calls = 0; + @override + Stream stream( + ModelRequest request, + CancellationToken token, + ) async* { + await Future.delayed(Duration.zero); + switch (calls++) { + case 0: + yield ModelResponse( + calls: [ToolCall(id: 'edit', name: 'clip_edit')], + ); + case 1: + yield ModelResponse( + calls: [ToolCall(id: 'query', name: 'timeline_query')], + ); + default: + yield ModelResponse(text: 'done'); + } + } +} + +class _ProgressSummary implements ContextSummarizer { + @override + String get source => 'test'; + @override + Future summarize( + List messages, + CancellationToken token, + ) async { + await Future.delayed(Duration.zero); + return 'Completed: edit saved. Pending: query and verify.'; + } +} + +class _SlowPublishRepository extends ConversationRepository { + _SlowPublishRepository(super.root); + final entered = Completer(); + final release = Completer(); + @override + Future publish(ConversationMetadata item) async { + entered.complete(); + await release.future; + return super.publish(item); + } +} + +class _EarlyTextModel implements ModelAdapter { + final emitted = Completer(); + final finish = Completer(); + @override + Stream stream( + ModelRequest request, + CancellationToken token, + ) async* { + yield const TextDelta('early reply'); + emitted.complete(); + await finish.future; + yield ModelResponse(text: 'early reply complete'); + } +} + +class _ExportThenDisconnect implements ModelAdapter { + int calls = 0; + bool retry = false; + bool disconnected = true; + @override + Stream stream( + ModelRequest request, + CancellationToken token, + ) async* { + calls++; + if (retry) { + expect(request.tools, isEmpty); + if (disconnected) { + throw const ModelConnectionException(kind: ModelConnectionKind.socket); + } + expect( + request.messages.any( + (m) => + m.role == MessageRole.tool && m.text.contains('/test/export.mp4'), + ), + isTrue, + ); + yield ModelResponse(text: 'Exported /test/export.mp4; edits saved.'); + } else if (calls == 1) { + yield ModelResponse( + calls: [ToolCall(id: 'export-once', name: 'project_export')], + ); + } else { + throw const ModelConnectionException( + kind: ModelConnectionKind.socket, + osErrorCode: 61, + ); + } + } +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + test( + 'referenced timeline is loaded by ID without changing the run target', + () async { + final root = await Directory.systemTemp.createTemp('agent-timeline-ref-'); + addTearDown(() => root.delete(recursive: true)); + final loadedRuns = []; + final loadedReferences = []; + final service = AgentConversationService( + projectId: 'project', + conversationId: null, + loadRepository: () async => ConversationRepository(root), + loadRuntime: (_) async => AgentRuntime( + model: _Model(), + contextBuilder: ContextBuilder(), + revision: 0, + sessionIdentity: 'test', + ), + loadTools: (timelineId) async { + loadedRuns.add(timelineId); + return EditorAgentBinding( + owner: Object(), + tools: const [], + ensureTimeline: (id) async => loadedReferences.add(id), + ); + }, + ); + addTearDown(service.dispose); + const reference = ComposerReference( + kind: ComposerReferenceKind.timeline, + projectId: 'project', + id: 'other-timeline', + label: '另一条时间线', + ); + final result = await service.send( + AgentComposerMessage.encodeDocument(const [ + ComposerSegment.text('看看 '), + ComposerSegment.reference(reference), + ], const []), + timelineId: 'current-timeline', + onPrepared: (_) {}, + onTextDelta: (_) {}, + ); + expect(result.completed, isTrue); + expect(loadedRuns, ['current-timeline']); + expect(loadedReferences, ['other-timeline']); + }, + ); + test('reply elapsed times survive reopening the conversation', () async { + final root = await Directory.systemTemp.createTemp('agent-elapsed-'); + addTearDown(() => root.delete(recursive: true)); + final repository = ConversationRepository(root); + AgentConversationService service(String? id) => AgentConversationService( + projectId: 'project', + conversationId: id, + loadRepository: () async => repository, + loadRuntime: (_) async => AgentRuntime( + model: _Model(), + contextBuilder: ContextBuilder(), + revision: 0, + sessionIdentity: 'test', + ), + loadTools: (_) async => + const EditorAgentBinding(owner: 'test', tools: []), + ); + final original = service(null); + addTearDown(original.dispose); + final first = await original.send( + 'first', + timelineId: 'timeline', + onPrepared: (_) {}, + onTextDelta: (_) {}, + ); + final second = await original.send( + 'second', + timelineId: 'timeline', + onPrepared: (_) {}, + onTextDelta: (_) {}, + ); + expect(first.elapsedMs, isNotNull); + expect(second.elapsedMs, isNotNull); + final id = second.conversation!.id; + expect((await repository.read('project', id))!.responseDurationsMs, [ + first.elapsedMs, + second.elapsedMs, + ]); + original.dispose(); + final reopened = service(id); + addTearDown(reopened.dispose); + final replies = (await reopened.restore())!.messages + .where((message) => !message.isUser) + .toList(); + expect(replies.map((message) => message.elapsedMs), [ + first.elapsedMs, + second.elapsedMs, + ]); + }); + + test('export receipt survives disconnect, disk restart and summary-only retry without replay', () async { + final root = await Directory.systemTemp.createTemp('export-recovery-'); + addTearDown(() => root.delete(recursive: true)); + final model = _ExportThenDisconnect(); + var exports = 0; + var toolLoads = 0; + AgentConversationService service(String? id) => AgentConversationService( + projectId: 'project', + conversationId: id, + loadRepository: () async => ConversationRepository(root), + loadRuntime: (_) async => AgentRuntime( + model: model, + contextBuilder: ContextBuilder(), + revision: 0, + sessionIdentity: 'test', + ), + loadTools: (_) async { + toolLoads++; + return EditorAgentBinding( + owner: Object(), + tools: [ + AgentTool( + name: 'project_export', + description: 'export', + parameters: {'type': 'object'}, + validate: (_) => null, + execute: (_, _) async { + exports++; + return ToolResult( + 'Sequence exported', + data: { + 'status': 'succeeded', + 'data': {'destination': '/test/export.mp4'}, + }, + ); + }, + ), + ], + ); + }, + ); + final first = service(null); + addTearDown(first.dispose); + final result = await first.send( + 'export', + timelineId: 't', + onPrepared: (_) {}, + onTextDelta: (_) {}, + ); + expect(result.exportReplyFailed, isTrue); + expect(result.failure, RunFailure.connection); + expect(exports, 1); + final id = result.conversation!.id; + first.dispose(); + final restarted = service(id); + addTearDown(restarted.dispose); + expect((await restarted.restore())!.exportReplyFailed, isTrue); + model.retry = true; + final stillOffline = await restarted.send( + 'Retry summary', + summaryOnly: true, + timelineId: 't', + onPrepared: (_) {}, + onTextDelta: (_) {}, + ); + expect(stillOffline.exportReplyFailed, isTrue); + expect(exports, 1); + expect(toolLoads, 1); + restarted.dispose(); + final online = service(id); + addTearDown(online.dispose); + expect((await online.restore())!.exportReplyFailed, isTrue); + model.disconnected = false; + final recovered = await online.send( + 'Retry summary', + summaryOnly: true, + timelineId: 't', + onPrepared: (_) {}, + onTextDelta: (_) {}, + ); + expect(recovered.completed, isTrue); + expect(recovered.exportReplyFailed, isFalse); + expect(recovered.response, contains('/test/export.mp4')); + expect(exports, 1); + expect(toolLoads, 1); + expect((await online.restore())!.exportReplyFailed, isFalse); + }); + + test('service exposes editing, compaction and verification phases', () async { + final root = await Directory.systemTemp.createTemp('agent-progress-'); + addTearDown(() => root.delete(recursive: true)); + final repository = ConversationRepository(root); + final service = AgentConversationService( + projectId: 'project', + conversationId: null, + loadRepository: () async => repository, + loadRuntime: (_) async => AgentRuntime( + model: _ProgressModel(), + contextBuilder: ContextBuilder( + maxInputTokens: 5000, + summarizer: _ProgressSummary(), + ), + revision: 0, + sessionIdentity: 'test', + ), + loadTools: (_) async => EditorAgentBinding( + owner: Object(), + tools: [ + for (final name in ['clip_edit', 'timeline_query']) + AgentTool( + name: name, + description: name, + parameters: {'type': 'object'}, + validate: (_) => null, + execute: (_, _) async => ToolResult( + name == 'clip_edit' ? 'saved ' * 5000 : 'verified', + ), + ), + ], + ), + ); + addTearDown(service.dispose); + final activities = []; + final subscription = service.changes.listen( + (_) => activities.add(service.activity), + ); + addTearDown(subscription.cancel); + final result = await service.send( + 'edit then verify', + timelineId: 'timeline', + onPrepared: (_) {}, + onTextDelta: (_) {}, + ); + expect(result.completed, isTrue); + expect( + activities, + containsAllInOrder([ + AgentChatActivity.editing, + AgentChatActivity.compacting, + AgentChatActivity.verifying, + ]), + ); + expect(service.busy, isFalse); + final reports = await Directory('${root.path}/diagnostics').list().toList(); + expect(reports, hasLength(1)); + final encoded = await File(reports.single.path).readAsString(); + final report = jsonDecode(encoded) as Map; + expect(report['outcome'], 'completed'); + expect(report['preparationUs'], isA()); + final stages = (report['runs'][0]['spans'] as List).map((s) => s['stage']); + expect( + stages, + containsAll(['model', 'tool', 'save', 'summary', 'prepare']), + ); + expect(encoded, isNot(contains('edit then verify'))); + }); + + test('default runtime sends with all real editor tools attached', () async { + final model = _Model(); + final root = await Directory.systemTemp.createTemp('full-catalog-send-'); + addTearDown(() => root.delete(recursive: true)); + final repository = ConversationRepository(root); + final service = AgentConversationService( + projectId: 'project', + conversationId: null, + loadRepository: () async => repository, + loadRuntime: (_) async => AgentRuntime( + model: model, + contextBuilder: ContextBuilder(), + revision: 0, + sessionIdentity: 'model', + ), + loadTools: (_) async => EditorAgentBinding( + owner: Object(), + tools: editorAgentTools({}, dynamicWorkspaces: true), + ), + ); + addTearDown(service.dispose); + final outcome = await service.send( + 'hi', + timelineId: 'timeline', + onPrepared: (_) {}, + onTextDelta: (_) {}, + ); + expect(outcome.completed, isTrue); + expect(outcome.response, 'done'); + expect(model.calls, 1); + expect(await repository.list('project'), hasLength(1)); + }); + + test( + 'unfinished runs require explicit resume without appending another prompt', + () async { + final root = await Directory.systemTemp.createTemp('recovered-chat-'); + addTearDown(() => root.delete(recursive: true)); + final repository = ConversationRepository(root); + final item = await repository.begin( + projectId: 'project', + timelineId: 'timeline', + providerId: 'model', + modelId: 'model', + title: 'interrupted', + ); + await repository + .store(item) + .save( + SessionSnapshot( + id: item.id, + runId: 'interrupted', + status: RunStatus.paused, + turns: 20, + maxTurns: 20, + history: [AgentMessage(role: MessageRole.user, text: 'old task')], + ), + expectedRevision: null, + ); + await repository.publish(item); + final model = _Model(); + final service = AgentConversationService( + projectId: 'project', + conversationId: item.id, + loadRepository: () async => repository, + loadRuntime: (_) async => AgentRuntime( + model: model, + contextBuilder: ContextBuilder(), + revision: 0, + sessionIdentity: 'model', + ), + loadTools: (_) async => + // Keep a fresh owner for each tool binding. + // ignore: prefer_const_constructors + EditorAgentBinding(owner: Object(), tools: const []), + ); + addTearDown(service.dispose); + AgentConversationPreparation? preparation; + final blocked = await service.send( + 'new task', + timelineId: 'timeline', + onPrepared: (_) {}, + onTextDelta: (_) {}, + ); + expect(blocked.recoveryRequired, isTrue); + expect(model.calls, 0); + final outcome = await service.send( + 'continue task', + resumeOnly: true, + timelineId: 'timeline', + onPrepared: (value) => preparation = value, + onTextDelta: (_) {}, + ); + expect(outcome.completed, isTrue); + expect(model.calls, 1); + expect(preparation!.messages.map((m) => m.text), ['old task']); + expect( + (await repository.store(item).read(item.id))!.history + .where((m) => m.role == MessageRole.user), + hasLength(1), + ); + }, + ); + + test( + 'stream listener is attached before slow conversation publication', + () async { + final root = await Directory.systemTemp.createTemp('early-text-'); + addTearDown(() => root.delete(recursive: true)); + final repository = _SlowPublishRepository(root); + final model = _EarlyTextModel(); + final service = AgentConversationService( + projectId: 'project', + conversationId: null, + loadRepository: () async => repository, + loadRuntime: (_) async => AgentRuntime( + model: model, + contextBuilder: ContextBuilder(), + revision: 0, + sessionIdentity: 'test', + ), + loadTools: (_) async => + // Keep a fresh owner for each tool binding. + // ignore: prefer_const_constructors + EditorAgentBinding(owner: Object(), tools: const []), + ); + addTearDown(service.dispose); + final deltas = []; + final sending = service.send( + 'hello', + timelineId: 'timeline', + onPrepared: (_) {}, + onTextDelta: deltas.add, + ); + await repository.entered.future; + await model.emitted.future; + await Future.delayed(Duration.zero); + final beforePublication = List.of(deltas); + repository.release.complete(); + model.finish.complete(); + final outcome = await sending; + expect(beforePublication, ['early reply']); + expect(outcome.response, 'early reply complete'); + expect(outcome.completed, true); + }, + ); + + test( + 'unconfirmed write recovery is reported without replay or a new prompt', + () async { + final root = await Directory.systemTemp.createTemp('unknown-edit-'); + addTearDown(() => root.delete(recursive: true)); + final repository = ConversationRepository(root); + final item = await repository.begin( + projectId: 'project', + timelineId: 'timeline', + providerId: 'model', + modelId: 'model', + title: 'interrupted', + ); + final call = ToolCall(id: 'write', name: 'edit'); + await repository + .store(item) + .save( + SessionSnapshot( + id: item.id, + runId: 'old', + status: RunStatus.running, + history: [ + AgentMessage(role: MessageRole.user, text: 'edit'), + AgentMessage(role: MessageRole.assistant, calls: [call]), + ], + pending: [ + CallRecord( + call: call, + operationId: 'stable', + status: CallStatus.started, + ), + ], + ), + expectedRevision: null, + ); + await repository.publish(item); + final model = _Model(); + var writes = 0; + final service = AgentConversationService( + projectId: 'project', + conversationId: item.id, + loadRepository: () async => repository, + loadRuntime: (_) async => AgentRuntime( + model: model, + contextBuilder: ContextBuilder(), + revision: 0, + sessionIdentity: 'model', + ), + loadTools: (_) async => EditorAgentBinding( + owner: Object(), + tools: [ + AgentTool( + name: 'edit', + description: 'edit', + parameters: {'type': 'object'}, + validate: (_) => null, + execute: (_, _) async { + writes++; + return ToolResult('saved'); + }, + ), + ], + ), + ); + addTearDown(service.dispose); + // A fresh process must surface the uncertain write before another send. + expect((await service.restore())!.recoveryRequired, isTrue); + final result = await service.send( + 'continue', + resumeOnly: true, + timelineId: 'timeline', + onPrepared: (_) {}, + onTextDelta: (_) {}, + ); + expect(result.recoveryRequired, true); + expect(result.completed, false); + expect(model.calls, 0); + expect(writes, 0); + final stored = (await repository.store(item).read(item.id))!; + expect(stored.status, RunStatus.waiting); + expect((await service.restore())!.recoveryRequired, isTrue); + expect( + stored.history.where((m) => m.role == MessageRole.user), + hasLength(1), + ); + }, + ); + + test( + 'restored history hides final replies rejected by artifact verification', + () async { + final root = await Directory.systemTemp.createTemp('verified-chat-'); + addTearDown(() => root.delete(recursive: true)); + final repository = ConversationRepository(root); + final item = await repository.begin( + projectId: 'project', + timelineId: 'timeline', + providerId: 'model', + modelId: 'model', + title: 'verification', + ); + await repository + .store(item) + .save( + SessionSnapshot( + id: item.id, + runId: 'run', + status: RunStatus.paused, + completionEvidence: { + 'result': {'isError': true}, + }, + history: [ + AgentMessage(role: MessageRole.user, text: 'Translate'), + AgentMessage( + role: MessageRole.assistant, + text: 'Done prematurely', + ), + AgentMessage( + role: MessageRole.user, + text: '[Runtime artifact verification, not a new user request] missing cues', + runtimeNotice: true, + ), + AgentMessage( + role: MessageRole.assistant, + text: 'Still not verified', + ), + ], + ), + expectedRevision: null, + ); + await repository.publish(item); + final service = AgentConversationService( + projectId: 'project', + conversationId: item.id, + loadRepository: () async => repository, + loadRuntime: (_) async => AgentRuntime( + model: _Model(), + contextBuilder: ContextBuilder(), + revision: 0, + sessionIdentity: 'model', + ), + loadTools: (_) async => + // Keep a fresh owner for each tool binding. + // ignore: prefer_const_constructors + EditorAgentBinding(owner: Object(), tools: const []), + ); + addTearDown(service.dispose); + expect((await service.restore())!.messages.map((m) => m.text), [ + 'Translate', + ]); + }, + ); + + test('budget preflight creates no conversation or model request', () async { + final model = _Model(); + final root = await Directory.systemTemp.createTemp('budget-preflight-'); + addTearDown(() => root.delete(recursive: true)); + final repository = ConversationRepository(root); + final service = AgentConversationService( + projectId: 'project', + conversationId: null, + loadRepository: () async => repository, + loadRuntime: (_) async => AgentRuntime( + model: model, + contextBuilder: ContextBuilder(maxInputTokens: 1), + revision: 0, + sessionIdentity: 'model', + ), + loadTools: (_) async => + // Keep a fresh owner for each tool binding. + // ignore: prefer_const_constructors + EditorAgentBinding(owner: Object(), tools: const []), + ); + addTearDown(service.dispose); + await expectLater( + service.send( + 'hello', + timelineId: 'timeline', + onPrepared: (_) {}, + onTextDelta: (_) {}, + ), + throwsA( + isA().having( + (e) => e.failure, + 'failure', + AgentConversationFailure.contextBudget, + ), + ), + ); + expect(model.calls, 0); + expect(await repository.list('project'), isEmpty); + }); + + for (final dispose in [false, true]) { + test( + '${dispose ? 'dispose' : 'cancel'} during preparation stops before opening storage', + () async { + final model = _Model(); + final entered = Completer(); + final binding = Completer(); + final root = await Directory.systemTemp.createTemp( + 'conversation-test-', + ); + addTearDown(() => root.delete(recursive: true)); + final repository = ConversationRepository(root); + final service = AgentConversationService( + projectId: 'project', + conversationId: null, + loadRepository: () async => repository, + loadRuntime: (_) async => AgentRuntime( + model: model, + contextBuilder: ContextBuilder(), + revision: 0, + sessionIdentity: 'model', + ), + loadTools: (_) { + entered.complete(); + return binding.future; + }, + ); + addTearDown(service.dispose); + final sending = service.send( + 'hello', + timelineId: 'timeline', + onPrepared: (_) {}, + onTextDelta: (_) {}, + ); + // Disposal may reject the caller; neither path may start more work. + final settled = sending.then((_) {}, onError: (Object _) {}); + await entered.future; + if (dispose) { + service.dispose(); + } else { + await service.cancel(); + } + binding.complete(const EditorAgentBinding(owner: 'test', tools: [])); + await settled; + expect(await repository.list('project'), isEmpty); + expect(model.calls, 0); + }, + ); + } +} diff --git a/test/agent_image_preview_test.dart b/test/agent_image_preview_test.dart new file mode 100644 index 0000000..145b6e4 --- /dev/null +++ b/test/agent_image_preview_test.dart @@ -0,0 +1,62 @@ +import 'package:cutdex/app/editor_theme.dart'; + +import 'dart:convert'; +import 'dart:io'; + +import 'package:cutdex/features/assistant/agent_attachment_card.dart'; +import 'package:cutdex/integrations/runtime/media_thumbnails.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets('a dropped image uses its pixels in the attachment preview', ( + tester, + ) async { + late AssetDocument asset; + late MediaThumbnails thumbnails; + final preview = await tester.runAsync(() async { + final directory = await Directory.systemTemp.createTemp( + 'cutdex-image-preview-', + ); + addTearDown(() => directory.delete(recursive: true)); + final file = File('${directory.path}/picture.png'); + await file.writeAsBytes( + base64Decode( + 'iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAAEElEQVR4nGP4z8AARAwQCgAf7gP9i18U1AAAAABJRU5ErkJggg==', + ), + ); + asset = AssetDocument( + id: 'image-1', + name: 'picture.png', + storage: AssetStorage.external, + location: file.uri.toString(), + metadata: const {'kind': 'image'}, + ); + thumbnails = MediaThumbnails( + loadMedia: (asset, action) => + action(MediaReference(id: asset.id, uri: file.uri, isImage: true)), + ); + return thumbnails.load(asset); + }); + expect(preview, isNotNull); + await tester.pumpWidget( + ProviderScope( + overrides: [mediaThumbnailsProvider.overrideWithValue(thumbnails)], + child: MaterialApp( + theme: EditorTheme.penDark, + home: Scaffold(body: AgentAttachmentCard(asset: asset)), + ), + ), + ); + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 20)), + ); + await tester.pumpAndSettle(); + expect(find.byType(Image), findsOneWidget); + expect(find.text('picture.png'), findsOneWidget); + expect(tester.takeException(), isNull); + }); +} diff --git a/test/agent_message_codec_test.dart b/test/agent_message_codec_test.dart new file mode 100644 index 0000000..b187671 --- /dev/null +++ b/test/agent_message_codec_test.dart @@ -0,0 +1,82 @@ +import 'package:cutdex/features/assistant/agent_media_attachments.dart'; +import 'package:cutdex/features/assistant/agent_message_codec.dart'; +import 'package:cutdex/features/assistant/composer_document.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + test('inline references coexist with attachment cards', () { + const reference = ComposerReference( + kind: ComposerReferenceKind.timeline, + projectId: 'project', + id: 'timeline-2', + label: '另一条时间线', + ); + const segments = [ + ComposerSegment.text('查看 '), + ComposerSegment.reference(reference), + ]; + final encoded = AgentComposerMessage.encodeDocument(segments, const [ + AgentMediaAttachment(id: 'media-1', name: '片段.mp4', kind: 'video'), + ]); + final decoded = AgentComposerMessage.decode(encoded); + expect(decoded.text, '查看 另一条时间线'); + expect(decoded.references.single.id, 'timeline-2'); + expect(decoded.segments, segments); + expect(decoded.attachments.single.id, 'media-1'); + expect(encoded, contains('"projectId":"project"')); + }); + test('media references survive encode and decode without leaking into the chat text', () { + const attachments = [ + AgentMediaAttachment(id: 'media-1', name: '画面.mp4', kind: 'video'), + AgentMediaAttachment(id: 'media-2', name: '声音.mp3', kind: 'audio'), + ]; + final prompt = AgentComposerMessage.encodeDocument(const [ + ComposerSegment.text('剪辑这两个素材'), + ], attachments); + expect(prompt, contains('media-1')); + expect(prompt, contains('media-2')); + final decoded = AgentComposerMessage.decode(prompt); + expect(decoded.text, '剪辑这两个素材'); + expect(decoded.attachments.map((item) => item.name), ['画面.mp4', '声音.mp3']); + }); + + test('attachment-only and ordinary chat text remain displayable', () { + const attachment = AgentMediaAttachment( + id: 'a', + name: '片段.mov', + kind: 'video', + ); + final decoded = AgentComposerMessage.decode( + AgentComposerMessage.encodeDocument(const [], [attachment]), + ); + expect(decoded.text, isEmpty); + expect(decoded.attachments.single.id, 'a'); + expect(AgentComposerMessage.decode('普通文本').text, '普通文本'); + expect( + AgentComposerMessage.decode('[Cutdex composer message] broken').text, + '[Cutdex composer message] broken', + ); + }); + + test( + 'damaged message data stays visible without partial resource references', + () { + for (final data in [ + 'broken', + '{"text":"hello","attachments":[{"id":"a","name":"A",' + '"kind":"video"}]}', + '{"text":"hello","attachments":[{"id":"a"}]}', + '{"text":"hello","segments":[{"runtimeType":"unknown"}]}', + '{"text":"hello","segments":[{"runtimeType":"reference",' + '"value":{"kind":"unknown","projectId":"p","id":"a",' + '"label":"a"}}]}', + ]) { + final message = '[Cutdex composer message] $data\n\nInstructions'; + final decoded = AgentComposerMessage.decode(message); + expect(decoded.text, message); + expect(decoded.references, isEmpty); + expect(decoded.attachments, isEmpty); + } + }, + ); +} diff --git a/test/agent_model_picker_test.dart b/test/agent_model_picker_test.dart new file mode 100644 index 0000000..c2c2a38 --- /dev/null +++ b/test/agent_model_picker_test.dart @@ -0,0 +1,287 @@ +import 'package:cutdex/app/editor_theme.dart'; + +import 'dart:io'; + +import 'package:cutdex/features/assistant/agent_chat_panel.dart'; +import 'package:cutdex/features/assistant/agent_conversation_service.dart'; +import 'package:cutdex/features/assistant/chat_controller.dart'; +import 'package:cutdex/features/settings/agent_settings_panel.dart'; +import 'package:cutdex/integrations/agent/agent_credentials.dart'; +import 'package:cutdex/integrations/agent/agent_provider.dart'; +import 'package:cutdex/integrations/agent/conversation_repository.dart'; +import 'package:cutdex/integrations/editor_tools.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex/persistence/app_settings_repositories.dart'; +import 'package:cutdex_agent/cutdex_agent.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +class _Settings implements AgentSettingsRepository { + AgentSettingsState value = const AgentSettingsState( + enabled: true, + selectedProviderId: 'one', + selectedModelId: 'model-one', + providers: [ + AgentProviderSettings( + id: 'one', + name: 'Provider One', + apiType: 'openAiResponses', + baseUrl: 'https://example.com/v1', + models: [ + AgentModelSettings(id: 'model-one'), + AgentModelSettings(id: 'model-two'), + ], + ), + AgentProviderSettings( + id: 'off', + name: 'Disabled Provider', + apiType: 'openAiResponses', + enabled: false, + baseUrl: 'https://example.com/v1', + models: [AgentModelSettings(id: 'hidden-model')], + ), + AgentProviderSettings( + id: 'two', + name: 'Provider Two', + apiType: 'anthropicMessages', + baseUrl: 'https://example.com/v1', + models: [AgentModelSettings(id: 'claude-test')], + ), + ], + ); + @override + Future load() async => value; + @override + Future save(AgentSettingsState settings) async => value = settings; +} + +class _Model implements ModelAdapter { + final requests = []; + @override + Stream stream( + ModelRequest request, + CancellationToken cancellation, + ) async* { + requests.add(request); + yield ModelResponse(text: 'reply'); + } +} + +void main() { + late Directory root; + late ConversationRepository repository; + late _Settings settings; + late _Model model; + late ProviderContainer container; + setUp(() async { + root = await Directory.systemTemp.createTemp('model-picker-'); + repository = ConversationRepository(root); + settings = _Settings(); + model = _Model(); + container = ProviderContainer( + overrides: [ + agentSettingsRepositoryProvider.overrideWithValue(settings), + agentCredentialStoreProvider.overrideWithValue( + MemoryAgentCredentialStore(), + ), + conversationRepositoryProvider.overrideWith((ref) async => repository), + agentConversationToolsResolverProvider.overrideWithValue( + (_, _) async => const EditorAgentBinding(owner: 'test', tools: []), + ), + agentConversationRuntimeResolverProvider.overrideWithValue( + (item) async => AgentRuntime( + model: model, + contextBuilder: ContextBuilder(), + revision: settings.value.revision, + sessionIdentity: + '${item?.providerId ?? settings.value.selectedProviderId}/${item?.modelId ?? settings.value.selectedModelId}', + providerId: item?.providerId ?? settings.value.selectedProviderId, + modelId: item?.modelId ?? settings.value.selectedModelId, + ), + ), + ], + ); + }); + tearDown(() async { + container.dispose(); + await root.delete(recursive: true); + }); + Future panel(WidgetTester tester, {String? conversationId}) async { + await tester.binding.setSurfaceSize(const Size(1000, 760)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + theme: EditorTheme.penDark, + home: Scaffold( + body: SizedBox( + width: 360, + child: AgentChatPanel( + projectId: 'project', + timelineId: 'timeline', + conversationId: conversationId, + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + if (conversationId != null) { + final provider = chatControllerProvider( + 'project', + conversationId: conversationId, + ); + for ( + var i = 0; + i < 50 && container.read(provider).conversation == null; + i++ + ) { + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 10)), + ); + await tester.pump(); + } + await tester.pumpAndSettle(); + } + } + + Future existing() async { + final item = await repository.begin( + projectId: 'project', + timelineId: 'timeline', + providerId: 'one', + modelId: 'model-one', + title: 'Original', + ); + final manager = SessionManager(model: model, store: repository.store(item)); + await manager.create(id: item.id, system: 'policy'); + await (await manager.prompt(item.id, 'original-context')).done; + return repository.publish(item); + } + + testWidgets('picker groups available models and remembers the selection', ( + tester, + ) async { + await panel(tester); + expect(find.text('model-one'), findsOneWidget); + await tester.tap(find.byKey(const Key('agent-model-picker'))); + await tester.pumpAndSettle(); + expect(find.text('Provider One'), findsOneWidget); + expect(find.text('Provider Two'), findsOneWidget); + expect(find.text('hidden-model'), findsNothing); + expect(find.text('Disabled Provider'), findsNothing); + await tester.runAsync(() async { + await tester.tap(find.text('claude-test')); + await Future.delayed(const Duration(milliseconds: 30)); + }); + await tester.pumpAndSettle(); + expect(settings.value.selectedProviderId, 'two'); + expect(settings.value.selectedModelId, 'claude-test'); + expect(find.text('claude-test'), findsOneWidget); + await tester.pumpWidget(const SizedBox()); + }); + testWidgets( + 'missing configuration opens the Agent tab and keeps the input usable', + (tester) async { + settings.value = const AgentSettingsState(); + container.invalidate(agentSettingsProvider); + await panel(tester); + await tester.enterText(find.byType(TextField), 'draft'); + await tester.pump(); + expect( + tester + .widget( + find.widgetWithIcon(IconButton, Icons.arrow_upward), + ) + .onPressed, + isNull, + ); + await tester.tap(find.byKey(const Key('agent-configure-model'))); + await tester.pumpAndSettle(); + expect(find.byType(AgentSettingsPanel), findsOneWidget); + await tester.pumpWidget(const SizedBox()); + }, + ); + testWidgets( + 'an existing conversation stays pinned and disabled providers block sending', + (tester) async { + final item = (await tester.runAsync(existing))!; + settings.value = AgentSettingsState( + enabled: true, + providers: settings.value.providers, + selectedProviderId: 'two', + selectedModelId: 'claude-test', + ); + await panel(tester, conversationId: item.id); + expect(find.text('model-one'), findsOneWidget); + expect(find.text('claude-test'), findsNothing); + await container + .read(agentSettingsProvider.notifier) + .setProviderEnabled('one', false); + await tester.pumpAndSettle(); + expect(find.text('Select model'), findsOneWidget); + expect( + find.text( + 'The model for this conversation is unavailable. Select another model to start a new conversation.', + ), + findsOneWidget, + ); + await tester.enterText(find.byType(TextField), 'draft'); + await tester.pump(); + expect( + tester + .widget( + find.widgetWithIcon(IconButton, Icons.arrow_upward), + ) + .onPressed, + isNull, + ); + expect( + (await tester.runAsync(() => repository.read('project', item.id)))! + .providerId, + 'one', + ); + await tester.pumpWidget(const SizedBox()); + }, + ); + test( + 'explicit model changes start a new conversation without old context', + () async { + final item = await existing(); + final provider = chatControllerProvider( + 'project', + conversationId: item.id, + ); + final subscription = container.listen(provider, (_, _) {}); + addTearDown(subscription.close); + for ( + var i = 0; + i < 50 && container.read(provider).conversation == null; + i++ + ) { + await Future.delayed(const Duration(milliseconds: 10)); + } + expect(container.read(provider).conversation?.id, item.id); + final controller = container.read(provider.notifier); + await controller.selectModel('two', 'claude-test'); + expect(container.read(provider).messages, isEmpty); + await controller.send('new-context', timelineId: 'timeline'); + final state = container.read(provider); + expect(state.error, isNull); + expect(state.conversation!.id, isNot(item.id)); + expect(state.conversation!.modelId, 'claude-test'); + expect( + model.requests.last.messages.any( + (m) => m.text.contains('original-context'), + ), + false, + ); + expect((await repository.read('project', item.id))!.modelId, 'model-one'); + }, + ); +} diff --git a/test/agent_settings_panel_test.dart b/test/agent_settings_panel_test.dart new file mode 100644 index 0000000..856c7ae --- /dev/null +++ b/test/agent_settings_panel_test.dart @@ -0,0 +1,301 @@ +import 'package:cutdex/app/editor_theme.dart'; +import 'package:cutdex/features/settings/agent_settings_panel.dart'; +import 'package:cutdex/integrations/agent/agent_credentials.dart'; +import 'package:cutdex/integrations/agent/agent_models.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex/persistence/app_settings_repositories.dart'; +import 'package:cutdex_ui/theme.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +class _Repository implements AgentSettingsRepository { + AgentSettingsState value = const AgentSettingsState(); + + @override + Future load() async => value; + + @override + Future save(AgentSettingsState settings) async => value = settings; +} + +void main() { + testWidgets('provider model fields stack in a narrow settings viewport', ( + tester, + ) async { + await tester.binding.setSurfaceSize(const Size(390, 640)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + await tester.pumpWidget( + ProviderScope( + overrides: [ + agentSettingsRepositoryProvider.overrideWithValue(_Repository()), + agentCredentialStoreProvider.overrideWithValue( + MemoryAgentCredentialStore(), + ), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + theme: EditorTheme.penDark, + home: const Scaffold( + body: AgentSettingsPanel( + contentPadding: AppSettingsMetrics.contentPadding, + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('Add provider')); + await tester.pumpAndSettle(); + final model = tester.getRect(find.byKey(const Key('agent-model-id-0'))); + final budget = tester.getRect( + find.byKey(const Key('agent-model-context-0')), + ); + expect(budget.top, greaterThan(model.bottom)); + expect(budget.left, model.left); + expect(budget.width, model.width); + expect(tester.takeException(), isNull); + }); + + testWidgets('inline Provider form has one stable scroll region', ( + tester, + ) async { + await tester.binding.setSurfaceSize(const Size(1000, 420)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + await tester.pumpWidget( + ProviderScope( + overrides: [ + agentSettingsRepositoryProvider.overrideWithValue(_Repository()), + agentCredentialStoreProvider.overrideWithValue( + MemoryAgentCredentialStore(), + ), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + theme: EditorTheme.penDark, + home: const Scaffold(body: AgentSettingsPanel()), + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('Add provider')); + await tester.pumpAndSettle(); + final scroll = find.byKey(const Key('agent-settings-scroll')); + final controller = tester.widget(scroll).controller!; + final extent = controller.position.maxScrollExtent; + expect(extent, greaterThan(0)); + expect(find.byType(Scrollbar), findsOneWidget); + for (var i = 0; i < 3; i++) { + await tester.drag(scroll, const Offset(0, -80)); + await tester.pumpAndSettle(); + final offset = controller.offset; + await tester.pump(const Duration(milliseconds: 200)); + expect(controller.offset, offset); + expect(controller.position.maxScrollExtent, extent); + } + // Desktop edge scrolling must not stretch the viewport or thumb. + controller.jumpTo(extent); + await tester.pumpAndSettle(); + await tester.drag(scroll, const Offset(0, -160)); + await tester.pump(); + expect(controller.offset, extent); + expect(controller.position.maxScrollExtent, extent); + await tester.pumpAndSettle(); + controller.jumpTo(0); + await tester.pumpAndSettle(); + await tester.drag(scroll, const Offset(0, 160)); + await tester.pump(); + expect(controller.offset, 0); + expect(controller.position.maxScrollExtent, extent); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('agent-provider-back'))); + await tester.pumpAndSettle(); + expect(controller.offset, 0); + expect(controller.position.maxScrollExtent, 0); + expect(tester.takeException(), isNull); + }); + + test('all supported non-English locales translate Agent settings', () { + final english = lookupAppLocalizations(const Locale('en')); + for (final languageCode in [ + 'de', + 'es', + 'fr', + 'it', + 'ja', + 'ko', + 'pt', + 'ru', + ]) { + final localized = lookupAppLocalizations(Locale(languageCode)); + expect( + localized.agentAddProvider, + isNot(english.agentAddProvider), + reason: languageCode, + ); + expect( + localized.agentConversationLocation, + isNot(english.agentConversationLocation), + reason: languageCode, + ); + expect( + localized.agentTrash, + isNot(english.agentTrash), + reason: languageCode, + ); + expect( + localized.agentDeleteProviderDescription('Example'), + contains('Example'), + reason: languageCode, + ); + } + }); + + testWidgets('renders Agent settings in Chinese', (tester) async { + await tester.pumpWidget( + ProviderScope( + overrides: [ + agentSettingsRepositoryProvider.overrideWithValue(_Repository()), + agentCredentialStoreProvider.overrideWithValue( + MemoryAgentCredentialStore(), + ), + ], + child: MaterialApp( + locale: const Locale('zh'), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + theme: EditorTheme.penDark, + home: const Scaffold(body: AgentSettingsPanel()), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(find.text('自定义 Provider'), findsNothing); + expect(find.text('添加 Provider'), findsOneWidget); + expect(find.text('请先添加 Provider,再启用助手。'), findsNothing); + expect(find.byType(Switch), findsNothing); + }); + + testWidgets('adds provider inline and returns to the provider list', ( + tester, + ) async { + final repository = _Repository(); + final credentials = MemoryAgentCredentialStore(); + await tester.binding.setSurfaceSize(const Size(1000, 760)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + await tester.pumpWidget( + ProviderScope( + overrides: [ + agentSettingsRepositoryProvider.overrideWithValue(repository), + agentCredentialStoreProvider.overrideWithValue(credentials), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + theme: EditorTheme.penDark, + home: const Scaffold(body: AgentSettingsPanel()), + ), + ), + ); + await tester.pumpAndSettle(); + + await tester.tap(find.text('Add provider')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 70)); + expect( + tester + .widget( + find.byKey(const Key('agent-provider-page-transition')), + ) + .opacity + .value, + lessThan(1), + ); + expect(find.byKey(const Key('agent-provider-list')), findsOneWidget); + expect(find.byKey(const Key('agent-provider-editor')), findsNothing); + await tester.pumpAndSettle(); + expect(find.byType(Dialog), findsNothing); + expect(find.byKey(const Key('agent-provider-editor')), findsOneWidget); + await tester.enterText( + find.byKey(const Key('agent-provider-name')), + 'Unsaved', + ); + await tester.tap(find.byKey(const Key('agent-provider-back'))); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('agent-provider-list')), findsOneWidget); + expect(repository.value.providers, isEmpty); + await tester.tap(find.text('Add provider')); + await tester.pumpAndSettle(); + await tester.enterText( + find.byKey(const Key('agent-provider-name')), + 'Local provider', + ); + await tester.enterText( + find.byKey(const Key('agent-provider-base-url')), + 'http://127.0.0.1:11434/v1', + ); + await tester.enterText( + find.byKey(const Key('agent-provider-api-key')), + 'secret', + ); + await tester.enterText( + find.byKey(const Key('agent-model-id-0')), + 'local-model', + ); + await tester.tap(find.text('Save provider')); + await tester.pumpAndSettle(); + + expect(find.text('Local provider'), findsOneWidget); + expect(find.byKey(const Key('agent-provider-list')), findsOneWidget); + expect(find.byKey(const Key('agent-provider-editor')), findsNothing); + expect(repository.value.providers.single.models.single.id, 'local-model'); + expect( + await credentials.read(repository.value.providers.single.credentialId!), + 'secret', + ); + + expect(find.byType(Switch), findsOneWidget); + final providerId = repository.value.providers.single.id; + await tester.tap(find.byKey(ValueKey('agent-provider-edit-$providerId'))); + await tester.pumpAndSettle(); + expect( + tester + .widget(find.byKey(const Key('agent-provider-name'))) + .controller! + .text, + 'Local provider', + ); + expect( + tester + .widget( + find.byKey(const Key('agent-provider-api-key')), + ) + .controller! + .text, + isEmpty, + ); + expect(find.text('Leave blank to keep the saved key.'), findsOneWidget); + await tester.enterText( + find.byKey(const Key('agent-provider-name')), + 'Edited provider', + ); + await tester.ensureVisible(find.text('Save provider')); + await tester.tap(find.text('Save provider')); + await tester.pumpAndSettle(); + expect(repository.value.providers.length, 1); + expect(repository.value.providers.single.id, providerId); + expect(repository.value.providers.single.name, 'Edited provider'); + expect( + await credentials.read(repository.value.providers.single.credentialId!), + 'secret', + ); + await tester.tap(find.byType(Switch)); + await tester.pumpAndSettle(); + expect(repository.value.providers.single.enabled, false); + expect(repository.value.selectedProviderId, isNull); + expect(tester.takeException(), isNull); + }); +} diff --git a/test/agent_settings_test.dart b/test/agent_settings_test.dart new file mode 100644 index 0000000..7ba8367 --- /dev/null +++ b/test/agent_settings_test.dart @@ -0,0 +1,435 @@ +import 'package:cutdex/integrations/agent/agent_runtime_factory.dart'; +import 'package:cutdex/integrations/agent/agent_credentials.dart'; +import 'package:cutdex/integrations/agent/agent_models.dart'; +import 'package:cutdex/integrations/agent/agent_settings.dart'; +import 'package:cutdex/persistence/app_settings_repositories.dart'; +import 'package:cutdex_agent/io.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +class _MemoryRepository implements AgentSettingsRepository { + AgentSettingsState value = const AgentSettingsState(); + + @override + Future load() async => value; + + @override + Future save(AgentSettingsState settings) async => value = settings; +} + +class _FailingDeleteCredentials extends MemoryAgentCredentialStore { + @override + Future delete(String id) => throw StateError('keychain unavailable'); +} + +class _FailingSaveRepository extends _MemoryRepository { + _FailingSaveRepository(this.failure); + + final Object failure; + + @override + Future save(AgentSettingsState settings) => Future.error(failure); +} + +void main() { + test( + 'rejects positive input budget too small for mandatory instructions', + () async { + final repository = _MemoryRepository(); + final credentials = MemoryAgentCredentialStore(); + final container = ProviderContainer( + overrides: [ + agentSettingsRepositoryProvider.overrideWithValue(repository), + agentCredentialStoreProvider.overrideWithValue(credentials), + ], + ); + addTearDown(container.dispose); + await container.read(agentSettingsProvider.future); + await expectLater( + container + .read(agentSettingsProvider.notifier) + .upsertProvider( + name: 'small', + apiType: AgentApiType.openAiResponses, + baseUrl: 'https://example.com/v1', + apiKey: 'secret', + models: const [ + AgentModelSettings( + id: 'model', + contextWindow: 8192, + maxOutputTokens: 8191, + ), + ], + ), + throwsArgumentError, + ); + expect(repository.value.providers, isEmpty); + }, + ); + + for (final apiType in AgentApiType.values) { + test( + '${apiType.name} persists and constructs the matching adapter', + () async { + final repository = _MemoryRepository(); + final container = ProviderContainer( + overrides: [ + agentSettingsRepositoryProvider.overrideWithValue(repository), + agentCredentialStoreProvider.overrideWithValue( + MemoryAgentCredentialStore(), + ), + ], + ); + addTearDown(container.dispose); + await container.read(agentSettingsProvider.future); + final settings = container.read(agentSettingsProvider.notifier); + await settings.upsertProvider( + id: 'provider', + name: 'Provider', + apiType: apiType, + baseUrl: 'https://api.example.com/v1', + apiKey: 'test-only', + models: const [AgentModelSettings(id: 'test-model')], + ); + await settings.setEnabled(true); + expect(repository.value.providers.single.apiType, apiType.name); + final runtime = await container.read(agentRuntimeProvider.future); + expect(runtime, isNotNull); + switch (apiType) { + case AgentApiType.openAiChatCompletions: + expect(runtime!.model, isA()); + case AgentApiType.openAiResponses: + expect(runtime!.model, isA()); + case AgentApiType.anthropicMessages: + expect(runtime!.model, isA()); + } + }, + ); + } + + test( + 'provider toggles normalize selection and block disabled runtimes', + () async { + final repository = _MemoryRepository(); + final credentials = MemoryAgentCredentialStore(); + final container = ProviderContainer( + overrides: [ + agentSettingsRepositoryProvider.overrideWithValue(repository), + agentCredentialStoreProvider.overrideWithValue(credentials), + ], + ); + addTearDown(container.dispose); + await container.read(agentSettingsProvider.future); + final settings = container.read(agentSettingsProvider.notifier); + for (final id in ['one', 'two']) { + await settings.upsertProvider( + id: id, + name: id, + apiType: AgentApiType.openAiResponses, + baseUrl: 'https://example.com/v1', + apiKey: 'secret-$id', + models: [AgentModelSettings(id: 'model-$id')], + ); + } + expect(repository.value.enabled, true); + expect(repository.value.selectedProviderId, 'one'); + await settings.setProviderEnabled('one', false); + expect(repository.value.selectedProviderId, 'two'); + expect(repository.value.selectedModelId, 'model-two'); + await expectLater( + settings.selectModel('one', 'model-one'), + throwsArgumentError, + ); + final factory = AgentRuntimeFactory(credentials); + expect( + await factory.createFor( + repository.value, + providerId: 'one', + modelId: 'model-one', + ), + isNull, + ); + await settings.upsertProvider( + id: 'one', + name: 'Edited', + apiType: AgentApiType.anthropicMessages, + baseUrl: 'https://edited.example/v1', + models: const [AgentModelSettings(id: 'edited-model')], + ); + expect( + repository.value.providers.where((p) => p.id == 'one').single.enabled, + false, + ); + expect(await credentials.read('cutdex-agent-provider-one'), 'secret-one'); + await settings.setProviderEnabled('two', false); + expect(repository.value.selectedProviderId, isNull); + expect(repository.value.selectedModelId, isNull); + expect(await factory.create(repository.value), isNull); + await settings.setProviderEnabled('one', true); + expect(repository.value.selectedProviderId, 'one'); + expect(repository.value.selectedModelId, 'edited-model'); + expect( + (await factory.create(repository.value))!.model, + isA(), + ); + }, + ); + + test( + 'loading preserves disabled Agent settings until a model is selected', + () async { + final repository = _MemoryRepository(); + repository.value = const AgentSettingsState( + providers: [ + AgentProviderSettings( + id: 'provider', + name: 'Provider', + apiType: 'openAiResponses', + baseUrl: 'https://example.com/v1', + models: [AgentModelSettings(id: 'model')], + ), + ], + selectedProviderId: 'provider', + selectedModelId: 'model', + ); + final container = ProviderContainer( + overrides: [ + agentSettingsRepositoryProvider.overrideWithValue(repository), + agentCredentialStoreProvider.overrideWithValue( + MemoryAgentCredentialStore(), + ), + ], + ); + addTearDown(container.dispose); + await container.read(agentSettingsProvider.future); + expect(repository.value.enabled, false); + expect(repository.value.revision, 0); + final runtime = container.listen(agentRuntimeProvider, (_, _) {}); + addTearDown(runtime.close); + expect(await container.read(agentRuntimeProvider.future), isNull); + await container + .read(agentSettingsProvider.notifier) + .selectModel('provider', 'model'); + expect(repository.value.enabled, true); + expect(await container.read(agentRuntimeProvider.future), isNotNull); + }, + ); + + test('overlapping settings commands preserve both changes', () async { + final repository = _MemoryRepository(); + final container = ProviderContainer( + overrides: [ + agentSettingsRepositoryProvider.overrideWithValue(repository), + agentCredentialStoreProvider.overrideWithValue( + MemoryAgentCredentialStore(), + ), + ], + ); + addTearDown(container.dispose); + await container.read(agentSettingsProvider.future); + final settings = container.read(agentSettingsProvider.notifier); + await Future.wait([ + settings.upsertProvider( + id: 'one', + name: 'One', + apiType: AgentApiType.openAiChatCompletions, + baseUrl: 'http://localhost/v1', + models: const [AgentModelSettings(id: 'model')], + ), + settings.setEnabled(true), + ]); + expect(repository.value.providers.map((provider) => provider.id), ['one']); + expect(repository.value.enabled, isTrue); + expect(repository.value.revision, 2); + }); + + test('provider rejects a window too small for editor instructions', () async { + final repository = _MemoryRepository(); + final container = ProviderContainer( + overrides: [ + agentSettingsRepositoryProvider.overrideWithValue(repository), + agentCredentialStoreProvider.overrideWithValue( + MemoryAgentCredentialStore(), + ), + ], + ); + addTearDown(container.dispose); + await container.read(agentSettingsProvider.future); + final settings = container.read(agentSettingsProvider.notifier); + const model = AgentModelSettings(id: 'model', contextWindow: 2048); + expect( + model.effectiveMaxInputTokens + model.effectiveMaxOutputTokens, + 2048, + ); + expect(model.hasInstructionBudget, isFalse); + await expectLater( + settings.upsertProvider( + id: 'small', + name: 'Small', + apiType: AgentApiType.openAiChatCompletions, + baseUrl: 'http://localhost/v1', + models: const [model], + ), + throwsArgumentError, + ); + expect( + container.read(agentSettingsProvider).requireValue.providers, + isEmpty, + ); + }); + + test( + 'provider settings build runtime and keep API keys out of metadata', + () async { + final repository = _MemoryRepository(); + final credentials = MemoryAgentCredentialStore(); + final container = ProviderContainer( + overrides: [ + agentSettingsRepositoryProvider.overrideWithValue(repository), + agentCredentialStoreProvider.overrideWithValue(credentials), + ], + ); + addTearDown(container.dispose); + await container.read(agentSettingsProvider.future); + + await container + .read(agentSettingsProvider.notifier) + .upsertProvider( + id: 'provider', + name: 'Local', + apiType: AgentApiType.openAiChatCompletions, + baseUrl: 'http://127.0.0.1:11434/v1', + apiKey: 'secret', + models: const [ + AgentModelSettings( + id: 'model', + contextWindow: 16000, + maxOutputTokens: 2000, + ), + ], + ); + await container.read(agentSettingsProvider.notifier).setEnabled(true); + + final savedProvider = repository.value.providers.single; + expect(savedProvider.credentialId, 'cutdex-agent-provider-provider'); + expect(savedProvider.baseUrl, isNot(contains('secret'))); + expect(await credentials.read(savedProvider.credentialId!), 'secret'); + final runtime = await container.read(agentRuntimeProvider.future); + expect(runtime?.model, isA()); + expect(runtime?.contextBuilder.maxInputTokens, 14000); + expect(runtime?.contextBuilder.maxOutputTokens, 2000); + + await container + .read(agentSettingsProvider.notifier) + .deleteProvider('provider'); + expect(await credentials.read('cutdex-agent-provider-provider'), isNull); + expect(repository.value.selectedProviderId, isNull); + expect(repository.value.selectedModelId, isNull); + }, + ); + + test('invalid provider data is rejected before persistence', () async { + final repository = _MemoryRepository(); + final container = ProviderContainer( + overrides: [ + agentSettingsRepositoryProvider.overrideWithValue(repository), + agentCredentialStoreProvider.overrideWithValue( + MemoryAgentCredentialStore(), + ), + ], + ); + addTearDown(container.dispose); + await container.read(agentSettingsProvider.future); + + await expectLater( + container + .read(agentSettingsProvider.notifier) + .upsertProvider( + name: 'Broken', + apiType: AgentApiType.openAiChatCompletions, + baseUrl: 'file:///tmp/model', + models: const [AgentModelSettings(id: 'model')], + ), + throwsArgumentError, + ); + expect(repository.value.providers, isEmpty); + }); + + test('credential cleanup failure does not undo saved metadata', () async { + final repository = _MemoryRepository(); + final credentials = _FailingDeleteCredentials(); + final container = ProviderContainer( + overrides: [ + agentSettingsRepositoryProvider.overrideWithValue(repository), + agentCredentialStoreProvider.overrideWithValue(credentials), + ], + ); + addTearDown(container.dispose); + await container.read(agentSettingsProvider.future); + await container + .read(agentSettingsProvider.notifier) + .upsertProvider( + id: 'provider', + name: 'Local', + apiType: AgentApiType.openAiChatCompletions, + baseUrl: 'http://127.0.0.1:11434/v1', + apiKey: 'secret', + models: const [AgentModelSettings(id: 'model')], + ); + + await container + .read(agentSettingsProvider.notifier) + .deleteProvider('provider'); + + expect(repository.value.providers, isEmpty); + expect( + container.read(agentSettingsProvider).requireValue.providers, + isEmpty, + ); + }); + + test('failed metadata save removes a newly written credential', () async { + final failure = StateError('metadata unavailable'); + final repository = _FailingSaveRepository(failure) + ..value = const AgentSettingsState( + enabled: true, + providers: [ + AgentProviderSettings( + id: 'provider', + name: 'Local', + apiType: 'openAiChatCompletions', + baseUrl: 'http://127.0.0.1:11434/v1', + credentialId: 'existing-id', + models: [AgentModelSettings(id: 'model')], + ), + ], + selectedProviderId: 'provider', + selectedModelId: 'model', + ); + final credentials = MemoryAgentCredentialStore(); + final container = ProviderContainer( + overrides: [ + agentSettingsRepositoryProvider.overrideWithValue(repository), + agentCredentialStoreProvider.overrideWithValue(credentials), + ], + ); + addTearDown(container.dispose); + await container.read(agentSettingsProvider.future); + + await expectLater( + container + .read(agentSettingsProvider.notifier) + .upsertProvider( + id: 'provider', + name: 'Local', + apiType: AgentApiType.openAiChatCompletions, + baseUrl: 'http://127.0.0.1:11434/v1', + apiKey: 'new-secret', + models: const [AgentModelSettings(id: 'model')], + ), + throwsA(same(failure)), + ); + expect(await credentials.read('existing-id'), isNull); + expect(repository.value.revision, 0); + }); +} diff --git a/test/agent_tool_recovery_test.dart b/test/agent_tool_recovery_test.dart new file mode 100644 index 0000000..c88607c --- /dev/null +++ b/test/agent_tool_recovery_test.dart @@ -0,0 +1,117 @@ +import 'dart:io'; + +import 'package:cutdex/integrations/agent/editor_agent_tools.dart'; +import 'package:cutdex_agent/cutdex_agent.dart'; +import 'package:cutdex_agent/io.dart'; +import 'package:cutdex_sdk/editor/commands.dart'; +import 'package:cutdex_sdk/tools.dart'; +import 'package:flutter_test/flutter_test.dart'; + +class _Host implements EditorCommandHost { + int reads = 0; + int writes = 0; + @override + Set get supportedOperations => + EditorOperation.values.toSet(); + @override + Future execute( + EditorCommand command, + CommandContext context, + ) async { + if (command is QueryTimeline) { + reads++; + } else { + writes++; + } + return CommandResult( + status: CommandStatus.succeeded, + message: 'fresh state', + version: 'new-process:0', + ); + } +} + +class _Model implements ModelAdapter { + int requests = 0; + @override + Stream stream( + ModelRequest request, + CancellationToken cancellation, + ) async* { + requests++; + expect(request.messages.last.role, MessageRole.tool); + yield ModelResponse(text: 'verified'); + } +} + +void main() { + for (final (name, status) in [ + ('cutdex_workspaces', CallStatus.started), + ('timeline_query', CallStatus.started), + ('clip_setAudio', CallStatus.started), + ('clip_setAudio', CallStatus.planned), + ]) { + test('restart recovery of $name $status preserves replay safety', () async { + final root = await Directory.systemTemp.createTemp('agent-recovery-'); + addTearDown(() => root.delete(recursive: true)); + final call = ToolCall( + id: 'call', + name: name, + arguments: { + if (name != 'cutdex_workspaces') 'workspaceId': 'timeline', + if (name == 'clip_setAudio') ...{ + 'clipId': 'clip', + 'db': -10, + 'muted': false, + 'expectedVersion': status == CallStatus.planned + ? 'new-process:0' + : 'old-process:1', + }, + }, + ); + await FileSessionStore(root).save( + SessionSnapshot( + id: 'session', + runId: 'interrupted', + status: RunStatus.running, + history: [ + AgentMessage(role: MessageRole.user, text: 'do the task'), + AgentMessage(role: MessageRole.assistant, calls: [call]), + ], + pending: [ + CallRecord( + call: call, + operationId: 'stable-operation', + status: status, + ), + ], + ), + expectedRevision: null, + ); + // All dispatcher memory is fresh, as after a process restart. + final host = _Host(); + final model = _Model(); + final manager = SessionManager( + model: model, + store: FileSessionStore(root), + tools: editorAgentTools({'timeline': EditorToolDispatcher(host: host)}), + ); + final run = await manager.resume('session'); + final result = await run.done; + expect(host.writes, status == CallStatus.planned ? 1 : 0); + if (name == 'clip_setAudio' && status == CallStatus.started) { + expect(result.status, RunStatus.waiting); + expect(result.pending.single.operationId, 'stable-operation'); + expect(model.requests, 0); + } else { + expect(result.status, RunStatus.completed); + expect(model.requests, 1); + expect(host.reads, name == 'timeline_query' ? 1 : 0); + expect( + result.history.where((m) => m.role == MessageRole.tool), + hasLength(1), + ); + } + }); + } +} diff --git a/test/app_database_test.dart b/test/app_database_test.dart new file mode 100644 index 0000000..043d29a --- /dev/null +++ b/test/app_database_test.dart @@ -0,0 +1,400 @@ +import 'dart:io'; + +import 'package:cutdex/integrations/agent/agent_models.dart'; +import 'package:cutdex/persistence/app_database.dart'; +import 'package:cutdex/persistence/app_settings_repositories.dart'; +import 'package:cutdex/workspace/project_state.dart'; +import 'package:cutdex/workspace/workspace_mode.dart'; +import 'package:cutdex/workspace/persistence/recent_projects.dart'; +import 'package:drift/native.dart'; +import 'package:drift/drift.dart' show Value; +import 'package:cutdex_sdk/timeline/layout.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as p; +import 'package:sqlite3/sqlite3.dart'; + +void main() { + test( + 'old app settings schema is rejected without changing its data', + () async { + final directory = await Directory.systemTemp.createTemp('app-schema-'); + addTearDown(() => directory.delete(recursive: true)); + final file = File(p.join(directory.path, 'app.sqlite')); + final current = AppDatabase(NativeDatabase(file)); + await DriftWorkspaceViewSettingsRepository(current) + .save(const WorkspaceViewSettingsData(mode: WorkspaceMode.cut)); + await current.close(); + final old = sqlite3.open(file.path); + try { + old.execute( + 'ALTER TABLE workspace_view_configurations RENAME COLUMN mode TO layout_mode', + ); + old.userVersion = 1; + } finally { + old.close(); + } + final before = await file.readAsBytes(); + final reopened = AppDatabase(NativeDatabase(file)); + addTearDown(reopened.close); + await expectLater( + DriftWorkspaceViewSettingsRepository(reopened).load(), + throwsStateError, + ); + expect(await file.readAsBytes(), orderedEquals(before)); + }, + ); + + test('unknown stored language falls back to the system locale', () async { + final database = AppDatabase(NativeDatabase.memory()); + addTearDown(database.close); + await database + .into(database.languageConfigurations) + .insert( + LanguageConfigurationsCompanion.insert( + id: const Value(0), + language: 'unknown', + ), + ); + expect( + await DriftLanguageSettingsRepository(database).load(), + AppLanguage.system, + ); + }); + + test('provider enabled state persists across repository loads', () async { + final database = AppDatabase(NativeDatabase.memory()); + addTearDown(database.close); + final repository = DriftAgentSettingsRepository(database); + await repository.save( + const AgentSettingsState( + providers: [ + AgentProviderSettings( + id: 'disabled', + name: 'Disabled', + apiType: 'anthropicMessages', + baseUrl: 'https://example.com/v1', + enabled: false, + models: [AgentModelSettings(id: 'model')], + ), + ], + ), + ); + final loaded = await repository.load(); + expect(loaded.providers.single.enabled, false); + expect(loaded.providers.single.models.single.id, 'model'); + }); + + test('typed app repositories share one Drift database', () async { + final database = AppDatabase(NativeDatabase.memory()); + addTearDown(database.close); + expect( + (await database.customSelect('PRAGMA user_version').getSingle()) + .read('user_version'), + 2, + ); + + final appearance = DriftAppearanceSettingsRepository(database); + expect(await appearance.load(), AppAppearance.system); + await appearance.save(AppAppearance.penLight); + expect(await appearance.load(), AppAppearance.penLight); + await appearance.save(AppAppearance.penDark); + expect(await appearance.load(), AppAppearance.penDark); + + final language = DriftLanguageSettingsRepository(database); + expect(await language.load(), AppLanguage.system); + await language.save(AppLanguage.japanese); + expect(await language.load(), AppLanguage.japanese); + await language.save(AppLanguage.system); + expect(await language.load(), AppLanguage.system); + + final conversationLocation = DriftConversationLocationSettingsRepository( + database, + ); + expect(await conversationLocation.load(), isNull); + await conversationLocation.save('/conversations'); + expect(await conversationLocation.load(), '/conversations'); + + final projectLocation = DriftProjectLocationSettingsRepository(database); + expect(await projectLocation.load(), isNull); + await projectLocation.save('/projects'); + expect(await projectLocation.load(), '/projects'); + + final resourceLocation = DriftResourceLocationSettingsRepository(database); + expect(await resourceLocation.load(), isNull); + await resourceLocation.save('/resources'); + expect(await resourceLocation.load(), '/resources'); + + final mcp = DriftMcpSettingsRepository(database); + expect(await mcp.load(), isNull); + await mcp.save( + const McpSettingsValue(enabled: true, port: 47831, token: 'token'), + ); + final mcpValue = await mcp.load(); + expect(mcpValue?.enabled, isTrue); + expect(mcpValue?.port, 47831); + expect(mcpValue?.token, 'token'); + + final agent = DriftAgentSettingsRepository(database); + await agent.save( + const AgentSettingsState( + enabled: true, + selectedProviderId: 'provider', + selectedModelId: 'model', + revision: 3, + providers: [ + AgentProviderSettings( + id: 'provider', + name: 'Provider', + apiType: 'openAiChatCompletions', + baseUrl: 'https://example.com/v1', + credentialId: 'credential', + models: [ + AgentModelSettings( + id: 'model', + contextWindow: 32000, + maxOutputTokens: 4096, + ), + ], + ), + ], + ), + ); + final agentValue = await agent.load(); + expect(agentValue.enabled, isTrue); + expect(agentValue.selectedModelId, 'model'); + expect(agentValue.providers.single.credentialId, 'credential'); + expect(agentValue.providers.single.models.single.contextWindow, 32000); + + final workspaceView = DriftWorkspaceViewSettingsRepository(database); + final columns = await database + .customSelect('PRAGMA table_info(workspace_view_configurations)') + .get(); + expect(columns.map((row) => row.read('name')), contains('mode')); + expect( + columns.map((row) => row.read('name')), + isNot(contains('layout_mode')), + ); + final initialWorkspace = await workspaceView.load(); + expect(initialWorkspace.hasSavedState, isFalse); + expect(initialWorkspace.mode, WorkspaceMode.agent); + await workspaceView.save( + const WorkspaceViewSettingsData( + activeProjectId: 'two', + sidebarCollapsed: true, + sidebarWidth: 312, + ), + ); + final workspaceValue = await workspaceView.load(); + expect(workspaceValue.hasSavedState, isTrue); + expect(workspaceValue.activeProjectId, 'two'); + expect(workspaceValue.sidebarCollapsed, isTrue); + expect(workspaceValue.sidebarWidth, 312); + + final projectView = DriftProjectViewSettingsRepository(database); + await projectView.save( + 'two', + const ProjectViewSettingsData(propertiesOpen: true, timelineHeight: 280), + ); + final projectValue = await projectView.load('two'); + expect(projectValue.propertiesOpen, isTrue); + expect(projectValue.timelineHeight, 280); + + final timelineView = DriftTimelineViewSettingsRepository(database); + await timelineView.save( + 'two', + 'timeline', + SequenceId('one'), + TimelineSequenceViewState( + playheadTick: 120, + camera: TimelineCamera( + baseTick: 40, + fractionalTick: .25, + pixelsPerTick: .5, + verticalOffset: 18, + ), + ), + ); + await timelineView.save( + 'two', + 'timeline', + SequenceId('two'), + TimelineSequenceViewState( + playheadTick: 240, + camera: TimelineCamera( + baseTick: 80, + pixelsPerTick: .75, + verticalOffset: 24, + ), + ), + ); + final timelineValue = await timelineView.load('two', 'timeline'); + expect(timelineValue.activeSequenceId, SequenceId('two')); + expect(timelineValue.sequences.keys, { + SequenceId('one'), + SequenceId('two'), + }); + expect(timelineValue.sequences[SequenceId('one')]?.playheadTick, 120); + expect(timelineValue.sequences[SequenceId('one')]?.camera.baseTick, 40); + + final recent = DriftRecentProjectsRepository(database); + const first = RecentProject(id: 'one', name: 'One', path: '/one'); + const second = RecentProject(id: 'two', name: 'Two', path: '/two'); + await recent.save([second, first]); + expect(await recent.load(), [second, first]); + await expectLater( + recent.save([first, first]), + throwsA(isA()), + ); + expect(await recent.load(), [second, first]); + await recent.rememberTimeline('two', 'timeline'); + expect(await recent.lastTimeline('two'), 'timeline'); + await recent.save([]); + expect(await recent.load(), isEmpty); + }); + + test( + 'project location defaults to Documents/Cutdex/Projects and is persisted', + () async { + final database = AppDatabase(NativeDatabase.memory()); + addTearDown(database.close); + final documents = await Directory.systemTemp.createTemp( + 'cutdex-documents-', + ); + addTearDown(() => documents.delete(recursive: true)); + final stored = DriftProjectLocationSettingsRepository(database); + final repository = DefaultingProjectLocationSettingsRepository( + stored, + documentsDirectory: () async => documents, + ); + + final location = await repository.load(); + + expect(location, p.join(documents.path, 'Cutdex', 'Projects')); + expect(await Directory(location).exists(), isFalse); + expect(await stored.load(), location); + await Directory(location).create(recursive: true); + await Directory(location).delete(); + expect(await repository.load(), location); + expect(await Directory(location).exists(), isFalse); + }, + ); + + test('resource location creates the managed directory layout', () async { + final database = AppDatabase(NativeDatabase.memory()); + addTearDown(database.close); + final documents = await Directory.systemTemp.createTemp( + 'cutdex-resource-documents-', + ); + addTearDown(() => documents.delete(recursive: true)); + final stored = DriftResourceLocationSettingsRepository(database); + final repository = DefaultingResourceLocationSettingsRepository( + stored, + documentsDirectory: () async => documents, + ); + + final location = await repository.load(); + + expect(location, p.join(documents.path, 'Cutdex', 'Resources')); + for (final name in ['Processing', 'Downloads', 'Cache']) { + expect(await Directory(p.join(location, name)).exists(), isTrue); + } + expect(await stored.load(), location); + }); + + test('app settings survive closing and reopening the database', () async { + final directory = await Directory.systemTemp.createTemp('cutdex-app-db-'); + final file = File('${directory.path}/app.sqlite'); + addTearDown(() => directory.delete(recursive: true)); + + final first = AppDatabase(NativeDatabase(file)); + await DriftAppearanceSettingsRepository(first).save(AppAppearance.penLight); + await DriftProjectLocationSettingsRepository(first).save('/projects'); + await DriftLanguageSettingsRepository(first) + .save(AppLanguage.simplifiedChinese); + await DriftConversationLocationSettingsRepository(first) + .save('/conversations'); + await DriftMcpSettingsRepository(first).save( + const McpSettingsValue(enabled: true, port: 47832, token: 'persisted'), + ); + await DriftAgentSettingsRepository(first).save( + const AgentSettingsState( + enabled: true, + selectedProviderId: 'provider', + selectedModelId: 'model', + revision: 1, + providers: [ + AgentProviderSettings( + id: 'provider', + name: 'Provider', + apiType: 'openAiChatCompletions', + baseUrl: 'https://example.com/v1', + models: [AgentModelSettings(id: 'model')], + ), + ], + ), + ); + await DriftRecentProjectsRepository(first) + .rememberTimeline('project', 'timeline'); + await DriftWorkspaceViewSettingsRepository(first).save( + const WorkspaceViewSettingsData( + activeProjectId: 'project', + mode: WorkspaceMode.cut, + sidebarWidth: 300, + ), + ); + await DriftProjectViewSettingsRepository(first) + .save('project', const ProjectViewSettingsData(propertiesOpen: true)); + await DriftTimelineViewSettingsRepository(first).save( + 'project', + 'timeline', + SequenceId('sequence'), + TimelineSequenceViewState( + playheadTick: 360, + camera: TimelineCamera(baseTick: 120, pixelsPerTick: .5), + ), + ); + await first.close(); + + final reopened = AppDatabase(NativeDatabase(file)); + addTearDown(reopened.close); + expect( + await DriftAppearanceSettingsRepository(reopened).load(), + AppAppearance.penLight, + ); + expect( + await DriftProjectLocationSettingsRepository(reopened).load(), + '/projects', + ); + expect( + await DriftLanguageSettingsRepository(reopened).load(), + AppLanguage.simplifiedChinese, + ); + expect( + await DriftConversationLocationSettingsRepository(reopened).load(), + '/conversations', + ); + final mcp = await DriftMcpSettingsRepository(reopened).load(); + expect((mcp?.enabled, mcp?.port, mcp?.token), (true, 47832, 'persisted')); + final agent = await DriftAgentSettingsRepository(reopened).load(); + expect((agent.enabled, agent.selectedModelId), (true, 'model')); + expect( + await DriftRecentProjectsRepository(reopened).lastTimeline('project'), + 'timeline', + ); + final workspace = await DriftWorkspaceViewSettingsRepository(reopened) + .load(); + expect(workspace.activeProjectId, 'project'); + expect(workspace.mode, WorkspaceMode.cut); + expect(workspace.sidebarWidth, 300); + expect( + (await DriftProjectViewSettingsRepository(reopened).load('project')) + .propertiesOpen, + isTrue, + ); + final timeline = await DriftTimelineViewSettingsRepository(reopened) + .load('project', 'timeline'); + expect(timeline.activeSequenceId, SequenceId('sequence')); + expect(timeline.sequences[SequenceId('sequence')]?.playheadTick, 360); + }); +} diff --git a/test/app_failure_test.dart b/test/app_failure_test.dart new file mode 100644 index 0000000..d7e201d --- /dev/null +++ b/test/app_failure_test.dart @@ -0,0 +1,107 @@ +import 'dart:io'; + +import 'package:cutdex/errors/app_failure.dart'; +import 'package:cutdex/integrations/app_failure_adapter.dart'; +import 'package:cutdex/l10n/l10n.dart'; +import 'package:cutdex/workspace/project_state.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + test('SDK rejection codes translate regardless of diagnostic wording', () { + final en = lookupAppLocalizations(const Locale('en')); + final zh = lookupAppLocalizations(const Locale('zh')); + for (final diagnostic in [ + 'Old wording', + 'Different punctuation!', + '任意描述', + ]) { + final failure = appFailureFromError( + CommandRejected('missingMedia', diagnostic), + ); + expect(failure.code, AppErrorCode.mediaNoLongerExists); + expect(failure.diagnostic, diagnostic); + expect(en.failureMessage(failure), en.mediaNoLongerExists); + expect(zh.failureMessage(failure), zh.mediaNoLongerExists); + } + expect( + appFailureFromError(const CommandRejected('staleVersion', 'Changed')) + .code, + AppErrorCode.timelineChanged, + ); + expect( + appFailureFromError( + const ProjectFileException(ProjectFileError.notFound, 'Any wording'), + ).code, + AppErrorCode.projectMissingDirectory, + ); + }); + + test( + 'unknown diagnostics are preserved without guessing from their wording', + () { + final en = lookupAppLocalizations(const Locale('en')); + const error = CommandRejected('futureCode', '素材已不存在'); + expect(appFailureFromError(error).code, AppErrorCode.diagnostic); + expect(en.errorMessage(error), error.message); + final io = const FileSystemException('Native detail', '/missing'); + final failure = projectFailureFromError(io); + expect(failure.code, AppErrorCode.projectAccessFailed); + expect(failure.diagnostic, io.toString()); + expect(en.failureMessage(failure), en.projectAccessFailed); + }, + ); + + test( + 'project location actions depend on the code, not the displayed text', + () { + const failure = AppFailure( + AppErrorCode.projectLocationUnavailable, + diagnostic: 'No Chinese keywords', + ); + expect(failure.requiresProjectLocation, isTrue); + expect( + const AppFailure( + AppErrorCode.diagnostic, + diagnostic: '项目位置 保存位置', + ).requiresProjectLocation, + isFalse, + ); + }, + ); + + testWidgets( + 'an existing error follows locale changes without changing state', + (tester) async { + const state = ProjectState( + error: AppFailure( + AppErrorCode.mediaReadFailed, + diagnostic: 'Low-level read failure', + ), + ); + Widget view(Locale locale) => MaterialApp( + locale: locale, + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Builder( + builder: (context) => Text(context.l10n.failureMessage(state.error!)), + ), + ); + await tester.pumpWidget(view(const Locale('en'))); + await tester.pumpAndSettle(); + expect( + find.text(lookupAppLocalizations(const Locale('en')).mediaReadFailed), + findsOneWidget, + ); + await tester.pumpWidget(view(const Locale('zh'))); + await tester.pumpAndSettle(); + expect( + find.text(lookupAppLocalizations(const Locale('zh')).mediaReadFailed), + findsOneWidget, + ); + expect(state.error!.diagnostic, 'Low-level read failure'); + }, + ); +} diff --git a/test/app_update_bridge_test.dart b/test/app_update_bridge_test.dart new file mode 100644 index 0000000..8411dde --- /dev/null +++ b/test/app_update_bridge_test.dart @@ -0,0 +1,112 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; + +import 'package:cutdex/integrations/app_update_bridge.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + const channel = MethodChannel('deskup-test'); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + + Future nativeCall(String method, [Object? arguments]) async { + final response = Completer(); + await messenger.handlePlatformMessage( + method == 'prepareToQuit' ? appLifecycleChannel.name : channel.name, + const StandardMethodCodec().encodeMethodCall( + MethodCall(method, arguments), + ), + (data) { + try { + response.complete( + data == null + ? null + : const StandardMethodCodec().decodeEnvelope(data), + ); + } catch (error, stack) { + response.completeError(error, stack); + } + }, + ); + return response.future; + } + + setUp(() { + debugDefaultTargetPlatformOverride = TargetPlatform.macOS; + messenger.setMockMethodCallHandler(appLifecycleChannel, (_) async => null); + }); + tearDown(() { + messenger.setMockMethodCallHandler(channel, null); + messenger.setMockMethodCallHandler(appLifecycleChannel, null); + debugDefaultTargetPlatformOverride = null; + }); + + test( + 'bridge initializes once and delegates native quit preparation', + () async { + var ready = 0; + var quits = 0; + messenger.setMockMethodCallHandler(channel, (call) async { + if (call.method == 'ready') ready++; + return null; + }); + final bridge = AppUpdateBridge(channel); + addTearDown(bridge.dispose); + Future prepare() async { + quits++; + } + + bridge.start( + () async => fail('The obsolete quit coordinator was invoked'), + ); + bridge.start(prepare); + expect(await nativeCall('prepareToQuit'), isTrue); + expect(ready, 1); + expect(quits, 1); + }, + ); + + test('disposing a bridge closes its own event stream', () async { + messenger.setMockMethodCallHandler(channel, (_) async => null); + final bridge = AppUpdateBridge(channel); + bridge.start(() async {}); + addTearDown(bridge.dispose); + final events = expectLater( + bridge.events.map((status) => status.phase), + emitsInOrder([UpdatePhase.ready, emitsDone]), + ); + await nativeCall('statusChanged', {'phase': 'ready'}); + bridge.dispose(); + await events; + // No handler survives disposal to invoke business logic or publish events. + expect(await nativeCall('prepareToQuit'), isNull); + }); + + test( + 'failed save refuses quit and a later successful save acknowledges it', + () async { + messenger.setMockMethodCallHandler(channel, (_) async => null); + var saveFails = true; + final bridge = AppUpdateBridge(channel); + addTearDown(bridge.dispose); + bridge.start(() async { + if (saveFails) throw PlatformException(code: 'workspaceBusy'); + }); + await expectLater( + nativeCall('prepareToQuit'), + throwsA( + isA().having( + (error) => error.code, + 'code', + 'workspaceBusy', + ), + ), + ); + saveFails = false; + expect(await nativeCall('prepareToQuit'), isTrue); + }, + ); +} diff --git a/test/app_update_recovery_test.dart b/test/app_update_recovery_test.dart new file mode 100644 index 0000000..e80e733 --- /dev/null +++ b/test/app_update_recovery_test.dart @@ -0,0 +1,104 @@ +import 'dart:io'; + +import 'package:cutdex/features/assistant/agent_conversation_service.dart'; +import 'package:cutdex/features/properties/canvas_presets.dart'; +import 'package:cutdex/features/settings/update_controller.dart'; +import 'package:cutdex/integrations/app_updates.dart'; +import 'package:cutdex/settings/settings_operation.dart'; +import 'package:cutdex/workspace/persistence/recent_projects.dart'; +import 'package:cutdex/workspace/projects.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'support/memory_app_settings.dart'; +import 'support/project_write_lock.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + for (final saveFails in [false, true]) { + test( + 'Windows ${saveFails ? 'save failure prevents install' : 'failed updater restores saved workspace'}', + () async { + debugDefaultTargetPlatformOverride = TargetPlatform.windows; + final root = await Directory.systemTemp.createTemp( + 'cutdex-update-recovery-', + ); + final path = '${root.path}/Test.cutdex'; + void Function()? releaseWriteLock; + final container = ProviderContainer( + overrides: [ + recentProjectsProvider.overrideWithValue( + MemoryRecentProjectsRepository(), + ), + agentConversationRegistryProvider.overrideWithValue( + AgentConversationRegistry(), + ), + ], + ); + addTearDown(() async { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(appUpdatesChannel, null); + releaseWriteLock?.call(); + try { + await container.read(projectsProvider.notifier).prepareToQuit(); + } catch (_) {} + container.dispose(); + debugDefaultTargetPlatformOverride = null; + await root.delete(recursive: true); + }); + var installs = 0; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(appUpdatesChannel, (call) async { + if (call.method == 'status') { + return {'configured': true, 'canCheck': true, 'phase': 'ready'}; + } + if (call.method == 'install') { + installs++; + throw PlatformException(code: 'installFailed'); + } + return null; + }); + final projects = container.read(projectsProvider.notifier); + await projects.open(path, name: 'Update recovery'); + await projects.createTimeline(); + final before = container.read(projectsProvider).requireValue; + final session = await projects.openTimelineSession( + before.activeProject!.id, + before.timeline!.id, + ); + if (saveFails) { + releaseWriteLock = blockProjectWrites(path); + } + session.commands.setCanvas(ProjectCanvasPresets.values['4:3']!); + final listener = container.listen(updateControllerProvider, (_, _) {}); + addTearDown(listener.close); + await container.read(updateControllerProvider.future); + await container.read(updateControllerProvider.notifier).install(); + expect( + container.read(settingsOperationProvider('updates')).hasError, + isTrue, + ); + expect(installs, saveFails ? 0 : 1); + final after = container.read(projectsProvider).requireValue; + expect(after.projectBusy, isFalse); + expect(after.activeProject?.id, before.activeProject!.id); + expect(after.timeline?.id, before.timeline!.id); + final recovered = await container + .read(projectsProvider.notifier) + .openTimelineSession(before.activeProject!.id, before.timeline!.id); + expect(recovered.acceptsEdits, isTrue); + if (saveFails) { + expect(recovered.dirty, isTrue); + } else { + expect(recovered.document.settings['renderSize'], { + 'width': 1440.0, + 'height': 1080.0, + }); + } + }, + ); + } +} diff --git a/test/app_update_shutdown_test.dart b/test/app_update_shutdown_test.dart new file mode 100644 index 0000000..78fe9ed --- /dev/null +++ b/test/app_update_shutdown_test.dart @@ -0,0 +1,180 @@ +import 'dart:io'; +import 'dart:async'; + +import 'package:cutdex/features/properties/canvas_presets.dart'; +import 'package:cutdex/workspace/projects.dart'; +import 'package:cutdex/workspace/persistence/recent_projects.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'support/memory_app_settings.dart'; +import 'support/project_write_lock.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + for (final opening in [false, true]) { + test( + 'shutdown refuses to interrupt timeline ${opening ? 'opening' : 'creation'}', + () async { + final root = await Directory.systemTemp.createTemp( + 'cutdex-update-timeline-', + ); + var container = ProviderContainer( + overrides: [ + recentProjectsProvider.overrideWithValue( + MemoryRecentProjectsRepository(), + ), + ], + ); + var projects = container.read(projectsProvider.notifier); + addTearDown(() async { + try { + await projects.prepareToQuit(); + } catch (_) {} + container.dispose(); + await root.delete(recursive: true); + }); + expect( + await projects.open('${root.path}/Test.cutdex', name: 'Test'), + isTrue, + ); + String? target; + if (opening) { + await projects.createTimeline(); + target = container.read(projectsProvider).requireValue.timeline!.id; + await projects.createTimeline(); + await projects.prepareToQuit(); + container.dispose(); + container = ProviderContainer( + overrides: [ + recentProjectsProvider.overrideWithValue( + MemoryRecentProjectsRepository(), + ), + ], + ); + projects = container.read(projectsProvider.notifier); + expect(await projects.open('${root.path}/Test.cutdex'), isTrue); + } + final projectId = container + .read(projectsProvider) + .requireValue + .activeProject! + .id; + final started = Completer(); + container.listen(projectsProvider, (_, next) { + final busy = opening + ? next.value?.openingTimelineId != null + : next.value?.creatingTimeline == true; + if (busy && !started.isCompleted) started.complete(); + }); + final operation = opening + ? projects.openTimeline(projectId, target!) + : projects.createTimeline(); + await started.future; + Object? shutdown; + try { + shutdown = await projects.prepareToQuit(); + } catch (error) { + shutdown = error; + } + final completed = await operation; + expect( + shutdown, + isA().having( + (error) => error.code, + 'code', + 'workspaceBusy', + ), + ); + expect(completed, isTrue); + }, + ); + } + + test( + 'update shutdown flushes dirty edits before releasing the project', + () async { + final root = await Directory.systemTemp.createTemp('cutdex-update-save-'); + final container = ProviderContainer( + overrides: [ + recentProjectsProvider.overrideWithValue( + MemoryRecentProjectsRepository(), + ), + ], + ); + final projects = container.read(projectsProvider.notifier); + final path = '${root.path}/Test.cutdex'; + expect(await projects.open(path, name: 'Update test'), isTrue); + expect(await projects.createTimeline(), isTrue); + final state = container.read(projectsProvider).requireValue; + final session = await projects.openTimelineSession( + state.activeProject!.id, + state.timeline!.id, + ); + session.commands.setCanvas(ProjectCanvasPresets.values['4:3']!); + expect(session.dirty, isTrue); + expect(await projects.prepareToQuit(), isTrue); + expect(await projects.createTimeline(), isFalse); + final saved = await ProjectFile.open(Directory(path)); + expect( + (await saved.loadTimeline(state.timeline!.id)).settings['renderSize'], + {'width': 1440.0, 'height': 1080.0}, + ); + await saved.close(); + container.dispose(); + await root.delete(recursive: true); + }, + ); + + test( + 'a blocked save cancels update shutdown and keeps edits available', + () async { + final root = await Directory.systemTemp.createTemp( + 'cutdex-update-conflict-', + ); + final container = ProviderContainer( + overrides: [ + recentProjectsProvider.overrideWithValue( + MemoryRecentProjectsRepository(), + ), + ], + ); + final projects = container.read(projectsProvider.notifier); + final path = '${root.path}/Test.cutdex'; + await projects.open(path, name: 'Update conflict'); + await projects.createTimeline(); + final state = container.read(projectsProvider).requireValue; + final session = await projects.openTimelineSession( + state.activeProject!.id, + state.timeline!.id, + ); + final release = blockProjectWrites(path); + addTearDown(release); + session.commands.setCanvas(ProjectCanvasPresets.values['4:3']!); + await expectLater( + projects.prepareToQuit(), + throwsA( + isA().having( + (error) => error.code, + 'code', + 'saveFailed', + ), + ), + ); + expect(session.dirty, isTrue); + expect(session.acceptsEdits, isTrue); + expect( + container.read(projectsProvider).requireValue.projectBusy, + isFalse, + ); + release(); + expect(await projects.prepareToQuit(), isTrue); + container.dispose(); + await root.delete(recursive: true); + }, + ); +} diff --git a/test/app_updates_test.dart b/test/app_updates_test.dart new file mode 100644 index 0000000..2e3a239 --- /dev/null +++ b/test/app_updates_test.dart @@ -0,0 +1,228 @@ +import 'package:cutdex/app/editor_theme.dart'; + +import 'dart:async'; + +import 'package:cutdex/features/settings/update_settings.dart'; +import 'package:cutdex/integrations/app_updates.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + tearDown(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(appUpdatesChannel, null); + }); + + Widget app() => MaterialApp( + theme: EditorTheme.penLight, + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: const Scaffold(body: UpdateSettings()), + ); + + testWidgets( + 'configured updates check natively and persist automatic checks', + (tester) async { + var automatic = false; + var checks = 0; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(appUpdatesChannel, (call) async { + switch (call.method) { + case 'status': + return { + 'configured': true, + 'canCheck': true, + 'automaticChecks': automatic, + 'version': '1.0.0', + 'build': '42', + }; + case 'check': + checks++; + case 'automaticChecks': + automatic = call.arguments as bool; + } + return null; + }); + await tester.pumpWidget(ProviderScope(child: app())); + await tester.pumpAndSettle(); + expect(find.text('1.0.0 (42)'), findsOneWidget); + await tester.tap(find.byKey(const Key('check-for-updates'))); + await tester.pumpAndSettle(); + expect(checks, 1); + await tester.tap(find.byType(Switch)); + await tester.pumpAndSettle(); + expect(automatic, isTrue); + }, + variant: const TargetPlatformVariant({ + TargetPlatform.macOS, + TargetPlatform.windows, + }), + ); + + testWidgets('missing native configuration disables checks', (tester) async { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + appUpdatesChannel, + (_) async => {'configured': false}, + ); + await tester.pumpWidget(ProviderScope(child: app())); + await tester.pumpAndSettle(); + final button = tester.widget( + find.byKey(const Key('check-for-updates')), + ); + expect(button.onPressed, isNull); + expect(find.text('Updates are unavailable in this build.'), findsOneWidget); + }, variant: TargetPlatformVariant.only(TargetPlatform.macOS)); + + testWidgets('native failure is visible and permits retry', (tester) async { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(appUpdatesChannel, (call) async { + if (call.method == 'status') { + return {'configured': true, 'canCheck': true}; + } + throw PlatformException(code: 'failed'); + }); + await tester.pumpWidget(ProviderScope(child: app())); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('check-for-updates'))); + await tester.pumpAndSettle(); + expect( + find.text('Could not check for updates. Please try again.'), + findsOneWidget, + ); + expect( + tester + .widget(find.byKey(const Key('check-for-updates'))) + .onPressed, + isNotNull, + ); + }, variant: TargetPlatformVariant.only(TargetPlatform.macOS)); + + testWidgets('Windows download progress leads to an explicit restart action', ( + tester, + ) async { + var downloads = 0; + var status = { + 'configured': true, + 'canCheck': true, + 'phase': 'available', + 'availableVersion': '1.0.0-build.2', + }; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(appUpdatesChannel, (call) async { + if (call.method == 'status') return status; + if (call.method == 'download') { + downloads++; + status = { + ...status, + 'canCheck': false, + 'phase': 'downloading', + 'progress': 35, + }; + } + return null; + }); + await tester.pumpWidget(ProviderScope(child: app())); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('install-update')), findsNothing); + await tester.tap(find.byKey(const Key('download-update'))); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + expect(downloads, 1); + expect(find.text('Downloading update: 35%'), findsOneWidget); + expect( + tester + .widget(find.byKey(const Key('check-for-updates'))) + .onPressed, + isNull, + ); + final message = const StandardMethodCodec().encodeMethodCall( + MethodCall('statusChanged', { + ...status, + 'phase': 'ready', + 'progress': 100, + 'canCheck': true, + }), + ); + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .handlePlatformMessage(appUpdatesChannel.name, message, (_) {}); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('download-update')), findsNothing); + expect(find.text('Restart to update'), findsOneWidget); + expect(find.byType(LinearProgressIndicator), findsNothing); + }, variant: TargetPlatformVariant.only(TargetPlatform.windows)); + + testWidgets('Windows corrupt download exposes retry instead of install', ( + tester, + ) async { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + appUpdatesChannel, + (call) async => call.method == 'status' + ? { + 'configured': true, + 'canCheck': true, + 'phase': 'available', + 'availableVersion': '1.0.0-build.2', + 'error': 'Checksum failed', + } + : null, + ); + await tester.pumpWidget(ProviderScope(child: app())); + await tester.pumpAndSettle(); + expect( + find.text('Could not update. Finish active tasks and try again.'), + findsOneWidget, + ); + expect(find.byKey(const Key('install-update')), findsNothing); + expect( + tester + .widget(find.byKey(const Key('download-update'))) + .onPressed, + isNotNull, + ); + }, variant: TargetPlatformVariant.only(TargetPlatform.windows)); + + testWidgets('late status response preserves the newer Windows update event', ( + tester, + ) async { + final response = Completer>(); + var loads = 0; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(appUpdatesChannel, (call) async { + if (call.method == 'status') { + if (++loads > 1) return response.future; + return {'configured': true, 'canCheck': true}; + } + return null; + }); + await tester.pumpWidget(ProviderScope(child: app())); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('check-for-updates'))); + await tester.pump(); + expect(loads, 2); + final message = const StandardMethodCodec().encodeMethodCall( + const MethodCall('statusChanged', { + 'configured': true, + 'canCheck': true, + 'phase': 'ready', + 'availableVersion': '1.0.0-build.2', + }), + ); + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .handlePlatformMessage(appUpdatesChannel.name, message, (_) {}); + await tester.pump(); + response.complete({ + 'configured': true, + 'canCheck': false, + 'phase': 'checking', + }); + await tester.pumpAndSettle(); + expect(find.text('Restart to update'), findsOneWidget); + expect(find.text('Checking for updates…'), findsNothing); + }, variant: TargetPlatformVariant.only(TargetPlatform.windows)); +} diff --git a/test/appearance_settings_test.dart b/test/appearance_settings_test.dart new file mode 100644 index 0000000..bb2495a --- /dev/null +++ b/test/appearance_settings_test.dart @@ -0,0 +1,50 @@ +import 'package:cutdex/features/settings/appearance_settings.dart'; +import 'package:cutdex/persistence/app_settings_repositories.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'support/memory_app_settings.dart'; + +void main() { + test( + 'theme persists across providers and failed saves retain current mode', + () async { + final repository = MemoryAppearanceSettingsRepository(); + ProviderContainer container() => ProviderContainer( + overrides: [ + appearanceSettingsRepositoryProvider.overrideWithValue(repository), + ], + ); + final first = container(); + addTearDown(first.dispose); + expect( + await first.read(appearanceSettingsProvider.future), + AppAppearance.system, + ); + await first + .read(appearanceSettingsProvider.notifier) + .setMode(AppAppearance.penLight); + expect( + first.read(appearanceSettingsProvider).requireValue, + AppAppearance.penLight, + ); + final restored = container(); + addTearDown(restored.dispose); + expect( + await restored.read(appearanceSettingsProvider.future), + AppAppearance.penLight, + ); + repository.failWrites = true; + await expectLater( + restored + .read(appearanceSettingsProvider.notifier) + .setMode(AppAppearance.penDark), + throwsStateError, + ); + expect( + restored.read(appearanceSettingsProvider).requireValue, + AppAppearance.penLight, + ); + }, + ); +} diff --git a/test/application_tools_test.dart b/test/application_tools_test.dart new file mode 100644 index 0000000..b304354 --- /dev/null +++ b/test/application_tools_test.dart @@ -0,0 +1,590 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:cutdex/integrations/editor_tools.dart'; +import 'package:cutdex/workspace/projects.dart'; +import 'package:cutdex/workspace/project_state.dart'; +import 'package:cutdex/workspace/persistence/recent_projects.dart'; +import 'package:cutdex/workspace/preview_target.dart'; +import 'package:cutdex/workspace/timeline_provider.dart'; +import 'package:cutdex_agent/cutdex_agent.dart'; +import 'package:cutdex_sdk/tools.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex/persistence/app_settings_repositories.dart'; + +import 'support/memory_app_settings.dart'; + +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +class MemoryRecent implements RecentProjectsRepository { + List records = []; + final projects = {}; + @override + Future> load() async => records; + @override + Future save(List projects) async { + records = projects; + } + + @override + Future lastTimeline(String projectId) async => projects[projectId]; + @override + Future rememberTimeline(String projectId, String timelineId) async { + projects[projectId] = timelineId; + } +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late Directory root; + late ProviderContainer container; + late EditorToolAccess access; + late int port; + const token = "test-only-application-token-0123456789"; + const native = MethodChannel('cutdex_runtime'); + const events = MethodChannel('cutdex_runtime/sessions/source-test'); + final calls = []; + Completer? blockedProbe; + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + setUp(() async { + root = await Directory.systemTemp.createTemp('cutdex-application-tools-'); + final reservation = await ServerSocket.bind( + InternetAddress.loopbackIPv4, + 0, + ); + port = reservation.port; + await reservation.close(); + container = ProviderContainer( + retry: (_, _) => null, + overrides: [ + recentProjectsProvider.overrideWithValue(MemoryRecent()), + projectLocationSettingsRepositoryProvider.overrideWithValue( + MemoryProjectLocationSettingsRepository(root.path), + ), + resourceLocationSettingsRepositoryProvider.overrideWithValue( + MemoryResourceLocationSettingsRepository(root.path), + ), + editorMcpConfigurationProvider.overrideWithValue( + EditorMcpConfiguration(port: port, token: token), + ), + ], + ); + access = container.read(applicationToolAccessProvider); + calls.clear(); + blockedProbe = null; + messenger.setMockMethodCallHandler(events, (call) async { + if (call.method == 'listen') { + scheduleMicrotask( + () => messenger.handlePlatformMessage( + events.name, + const StandardMethodCodec().encodeSuccessEnvelope({ + 'type': 'attached', + }), + (_) {}, + ), + ); + } + return null; + }); + messenger.setMockMethodCallHandler(native, (call) async { + calls.add(call); + switch (call.method) { + case 'probe': + await blockedProbe?.future; + return { + 'duration': MediaTime(10, 1).toMap(), + 'videoTrackCount': 1, + 'videoTrackIds': [1], + 'audioTrackCount': 0, + 'audioTrackIds': [], + 'audioTracks': [], + 'isProtected': false, + 'videoDisplaySizes': [ + {'width': 1080.0, 'height': 1920.0}, + ], + }; + case 'createSession': + return {'sessionId': 'source-test'}; + case 'load': + return '1'; + default: + return null; + } + }); + }); + tearDown(() async { + final state = container.read(projectsProvider).asData?.value; + if (state?.activeProject != null && state?.timeline != null) { + await container + .read( + previewTargetProvider(state!.activeProject!.id, state.timeline!.id), + ) + .closeSource(); + } + await access.dispose(); + // UI/provider disposal owns the project; allow its async cleanup to finish. + container.dispose(); + await Future.delayed(const Duration(milliseconds: 50)); + await root.delete(recursive: true); + messenger.setMockMethodCallHandler(native, null); + messenger.setMockMethodCallHandler(events, null); + }); + + test( + 'opening a known path with a wrong project ID is a definite rejection', + () async { + final projects = container.read(projectsProvider.notifier); + final path = '${root.path}/Mismatch.cutdex'; + expect(await projects.open(path, name: 'Mismatch'), isTrue); + final before = container.read(projectsProvider).requireValue; + final result = await access.workspaces['application']!.invoke( + name: 'project.open', + arguments: {'path': path, 'projectId': 'wrong-id'}, + context: CommandContext( + operationId: 'mismatch', + isCancelled: () => false, + ), + ); + expect(result.status, CommandStatus.rejected); + expect(result.code, 'projectIdMismatch'); + expect(result.message, contains(before.activeProject!.id)); + expect( + container.read(projectsProvider).requireValue.activeProject!.id, + before.activeProject!.id, + ); + }, + ); + + test('Agent adds explicitly created timelines to its run binding', () async { + final projects = container.read(projectsProvider.notifier); + expect( + await projects.open( + '${root.path}/AgentCreate.cutdex', + name: 'AgentCreate', + ), + true, + ); + final state = container.read(projectsProvider).requireValue; + final projectId = state.activeProject!.id; + final binding = await container.read( + FutureProvider( + (ref) => createEditorAgentBinding(ref, projectId, state.timeline!.id), + ).future, + ); + addTearDown(() async => binding.release?.call()); + Future call(String name, Map arguments) => + binding.tools + .singleWhere((tool) => tool.name == name) + .execute( + ToolCall(id: name, name: name, arguments: arguments), + ToolContext( + sessionId: 's', + runId: 'r', + operationId: name, + cancellation: CancellationToken(), + onProgress: (_) {}, + ), + ); + final created = await call('timeline_create', { + 'workspaceId': 'application', + 'projectId': projectId, + 'name': 'Commentary', + }); + expect(created.isError, false); + final current = container.read(projectsProvider).requireValue; + expect(current.timeline!.id, isNot(state.timeline!.id)); + final target = 'sequence:${current.timeline!.sequences.first.id.value}'; + final workspaces = await call('cutdex_workspaces', {}); + expect(workspaces.text, contains(target)); + expect( + workspaces.text, + contains('sequence:${state.timeline!.sequences.first.id.value}'), + ); + final query = await call('timeline_query', {'workspaceId': target}); + expect(query.isError, false); + expect(query.data.toString(), contains(current.timeline!.id)); + }); + + test( + 'Agent tool binding keeps its timeline after switching projects', + () async { + final projects = container.read(projectsProvider.notifier); + expect( + await projects.open('${root.path}/Pinned.cutdex', name: 'Pinned'), + isTrue, + ); + final first = container.read(projectsProvider).requireValue; + final projectId = first.activeProject!.id; + final timelineId = first.timeline!.id; + final bindingProvider = FutureProvider( + (ref) => createEditorAgentBinding(ref, projectId, timelineId), + ); + final binding = await container.read(bindingProvider.future); + var released = false; + addTearDown(() async { + if (!released) await binding.release?.call(); + }); + final catalog = binding.tools.singleWhere( + (tool) => tool.name == 'cutdex_workspaces', + ); + final before = await catalog.execute( + ToolCall(id: 'before', name: catalog.name, arguments: const {}), + ToolContext( + sessionId: 'session', + runId: 'run', + operationId: 'before', + cancellation: CancellationToken(), + onProgress: (_) {}, + ), + ); + expect( + before.text, + contains('sequence:${first.timeline!.sequences.first.id.value}'), + ); + + expect( + await projects.open('${root.path}/Other.cutdex', name: 'Other'), + isTrue, + ); + final after = await catalog.execute( + ToolCall(id: 'after', name: catalog.name, arguments: const {}), + ToolContext( + sessionId: 'session', + runId: 'run', + operationId: 'after', + cancellation: CancellationToken(), + onProgress: (_) {}, + ), + ); + expect(after.text, before.text); + final workspaceId = ((jsonDecode(after.text) as Map)['targets'] as List) + .map((target) => (target as Map)['workspaceId'] as String) + .firstWhere((id) => id != 'application'); + final query = binding.tools.singleWhere( + (tool) => tool.name == 'timeline_query', + ); + final queried = await query.execute( + ToolCall( + id: 'query', + name: query.name, + arguments: {'workspaceId': workspaceId}, + ), + ToolContext( + sessionId: 'session', + runId: 'run', + operationId: 'query', + cancellation: CancellationToken(), + onProgress: (_) {}, + ), + ); + expect(queried.isError, isFalse); + final manifest = File('${root.path}/Pinned.cutdex/manifest.json'); + final backup = await manifest.rename('${manifest.path}.backup'); + final cancellation = CancellationToken(); + await expectLater( + catalog.execute( + ToolCall(id: 'missing', name: catalog.name, arguments: const {}), + ToolContext( + sessionId: 'session', + runId: 'run', + operationId: 'missing', + cancellation: cancellation, + onProgress: (_) {}, + ), + ), + throwsA(isA()), + ); + expect(cancellation.isCancelled, isTrue); + await backup.rename(manifest.path); + await binding.release?.call(); + released = true; + }, + ); + + test('one MCP connection creates projects and switches projects; Agent catalog stays usable', () async { + final subscription = container.listen( + applicationMcpConnectionProvider, + (_, _) {}, + ); + addTearDown(subscription.close); + await container.read(applicationMcpConnectionProvider.future); + final socket = await Socket.connect(InternetAddress.loopbackIPv4, port); + final lines = StreamIterator( + socket + .cast>() + .transform(utf8.decoder) + .transform(const LineSplitter()), + ); + addTearDown(() async { + socket.destroy(); + await lines.cancel(); + }); + socket.writeln(token); + var requestId = 0; + Future> invoke( + String name, + Map args, { + String workspace = 'application', + String? operation, + }) async { + socket.writeln( + jsonEncode({ + 'jsonrpc': '2.0', + 'id': ++requestId, + 'method': 'tools/call', + 'params': { + '_meta': { + 'io.modelcontextprotocol/protocolVersion': '2026-07-28', + 'io.modelcontextprotocol/clientCapabilities': {}, + }, + 'name': name, + 'arguments': { + if (name != 'cutdex.workspaces') 'workspaceId': workspace, + 'operationId': ?operation, + ...args, + }, + }, + }), + ); + expect(await lines.moveNext().timeout(const Duration(seconds: 5)), true); + final response = jsonDecode(lines.current) as Map; + expect(response['error'], isNull, reason: '$response'); + return (response['result'] as Map)['structuredContent'] as Map; + } + + // Cache Agent declarations before any project exists. + final agentTools = access.agentTools; + final created = await invoke('project.create', { + 'name': 'A', + }, operation: 'project'); + expect(created['status'], 'succeeded', reason: '$created'); + expect((created['data'] as Map)['activeTimelineId'], isA()); + final project = + ((created['data'] as Map)['project'] as Map)['projectId'] as String; + final first = await invoke('timeline.create', { + 'projectId': project, + 'name': 'One', + }, operation: 'one'); + expect(first['status'], 'succeeded', reason: '$first'); + final one = (first['data'] as Map)['timelineId'] as String; + expect((first['data'] as Map)['activeTimelineId'], one); + final originalWorkspace = access.workspaces.keys.singleWhere( + (id) => id != 'application', + ); + final edited = await invoke( + 'project.setCanvas', + {'width': 1080, 'height': 1920}, + workspace: originalWorkspace, + operation: 'canvas', + ); + expect(edited['edit'], 'committed'); + final second = await invoke('timeline.create', { + 'projectId': project, + 'name': 'Two', + }, operation: 'two'); + final two = (second['data'] as Map)['timelineId'] as String; + final opened = await invoke('timeline.open', { + 'projectId': project, + 'timelineId': two, + }, operation: 'open-two'); + expect(opened['status'], 'succeeded', reason: '$opened'); + expect((opened['data'] as Map)['activeTimelineId'], two); + expect(access.workspaces.containsKey(originalWorkspace), false); + final receipt = await invoke('cutdex.operation', { + 'operationId': 'canvas', + }, workspace: originalWorkspace); + expect(receipt['code'], 'unknownWorkspace'); + final query = agentTools.singleWhere( + (tool) => tool.name == 'timeline_query', + ); + final workspace = access.workspaces.keys.singleWhere( + (id) => id != 'application', + ); + final args = {'workspaceId': workspace}; + expect(query.validate(args), isNull); + final agentResult = await query.execute( + ToolCall(id: 'query', name: query.name, arguments: args), + ToolContext( + sessionId: 's', + runId: 'r', + operationId: 'query', + cancellation: CancellationToken(), + onProgress: (_) {}, + ), + ); + expect(agentResult.isError, false); + expect(agentResult.text, 'Timeline'); + expect(agentResult.data['status'], 'succeeded'); + expect(agentResult.data['data'], contains('clips')); + final reopened = await invoke('timeline.open', { + 'projectId': project, + 'timelineId': one, + }, operation: 'return-one'); + expect(reopened['status'], 'succeeded', reason: '$reopened'); + final session = await container.read( + editorTimelineProvider(project, one).future, + ); + expect(session.canvas.width, 1080); + expect(session.canvas.height, 1920); + final version = session.version; + final selected = await invoke('sequence.select', { + 'projectId': project, + 'timelineId': one, + 'sequenceId': session.document.sequences.first.id.value, + }, operation: 'select'); + expect(selected['status'], 'succeeded'); + expect(session.version, version); + final missing = await invoke('timeline.open', { + 'projectId': project, + 'timelineId': 'missing', + }, operation: 'missing'); + expect(missing['status'], 'rejected'); + expect(missing['code'], 'missingTimeline'); + expect(session.acceptsEdits, true); + final projects = await invoke('project.query', {}); + expect(jsonEncode(projects), contains('A.cutdex')); + final b = await invoke('project.create', { + 'name': 'B', + }, operation: 'project-b'); + expect(b['status'], 'succeeded', reason: '$b'); + final back = await invoke('project.open', { + 'path': '${root.path}/A.cutdex', + 'projectId': project, + }, operation: 'back-a'); + expect(back['status'], 'succeeded', reason: '$back'); + final listed = await invoke('timeline.list', {'projectId': project}); + expect(listed['status'], 'succeeded'); + final listData = listed['data'] as Map; + expect(listData['activeTimelineId'], one); + expect( + (listData['timelines'] as List).map( + (item) => (item as Map)['timelineId'], + ), + containsAll([one, two]), + ); + expect(listData.containsKey('projects'), isFalse); + final replay = await invoke('timeline.create', { + 'projectId': project, + 'name': 'Two', + }, operation: 'two'); + expect((replay['data'] as Map)['timelineId'], two); + }); + + test( + 'source tools share target, preserve timeline and reuse one native player', + () async { + final tools = access.workspaces['application']!; + var operation = 0; + Future invoke(String name, Map args) => + tools.invoke( + name: name, + arguments: args, + context: CommandContext(operationId: 'source-${++operation}'), + ); + final created = await invoke('project.create', {'name': 'Sources'}); + final projectId = (created.data['project'] as Map)['projectId'] as String; + final timelineId = + (await invoke('timeline.create', { + 'projectId': projectId, + 'name': 'Timeline', + })).data['timelineId'] + as String; + final sequence = access.workspaces.values.last; + final file = await File('${root.path}/video.mov') + .writeAsString('fixture'); + await sequence.invoke( + name: 'media.import', + arguments: {'path': file.path}, + context: const CommandContext(operationId: 'import'), + ); + final asset = container.read(projectsProvider).requireValue.assets.single; + final target = container.read( + previewTargetProvider(projectId, timelineId), + ); + final session = await container.read( + editorTimelineProvider(projectId, timelineId).future, + ); + final version = session.version; + final ids = {'projectId': projectId, 'timelineId': timelineId}; + final opened = await invoke('sourcePreview.open', { + ...ids, + 'mediaId': asset.id, + }); + expect( + opened.status.name, + 'succeeded', + reason: '${opened.toJson()} native: ${target.source?.error}', + ); + expect(target.asset?.id, asset.id); + await invoke('sourcePreview.open', {...ids, 'mediaId': asset.id}); + final source = target.source; + expect( + (await invoke('sourcePreview.play', { + ...ids, + 'mediaId': asset.id, + })).status.name, + 'succeeded', + ); + expect( + (await invoke('sourcePreview.pause', { + ...ids, + 'mediaId': asset.id, + })).status.name, + 'succeeded', + ); + final seek = await invoke('sourcePreview.seek', { + ...ids, + 'mediaId': asset.id, + 'at': {'numerator': '3', 'denominator': 2}, + }); + expect(seek.status.name, 'succeeded', reason: '${seek.toJson()}'); + expect(target.source, same(source)); + expect(calls.where((c) => c.method == 'createSession'), hasLength(1)); + expect(calls.any((c) => c.method == 'pause'), true); + expect( + (await invoke('sourcePreview.seek', { + ...ids, + 'mediaId': 'wrong', + 'at': {'numerator': '0', 'denominator': 1}, + })).status.name, + 'rejected', + ); + expect(session.version, version); + expect(session.dirty, false); + expect( + (await invoke('sourcePreview.close', ids)).status.name, + 'succeeded', + ); + expect(target.asset, isNull); + expect(calls.where((c) => c.method == 'close'), hasLength(1)); + expect( + (await invoke('sourcePreview.query', ids)).data['available'], + false, + ); + + blockedProbe = Completer(); + final count = calls.where((call) => call.method == 'probe').length; + final opening = invoke('sourcePreview.open', { + ...ids, + 'mediaId': asset.id, + }); + for ( + var i = 0; + i < 100 && + calls.where((call) => call.method == 'probe').length == count; + i++ + ) { + await Future.delayed(const Duration(milliseconds: 2)); + } + target.showTimeline(); + blockedProbe!.complete(); + expect((await opening).status.name, 'unknown'); + await target.closeSource(); + expect(target.source, isNull); + }, + ); +} diff --git a/test/audio_beat_tools_test.dart b/test/audio_beat_tools_test.dart new file mode 100644 index 0000000..4e0c5e0 --- /dev/null +++ b/test/audio_beat_tools_test.dart @@ -0,0 +1,527 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:cutdex/integrations/agent/editor_acceptance.dart'; +import 'package:cutdex/integrations/agent/editor_agent_tools.dart'; +import 'package:cutdex/integrations/editor_command_host.dart'; +import 'package:cutdex/workspace/timeline_session.dart'; +import 'package:cutdex_agent/cutdex_agent.dart'; +import 'package:cutdex_agent/io.dart'; +import 'package:cutdex/integrations/agent/agent_prompt_policy.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/runtime/contracts.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter_test/flutter_test.dart'; + +class _AudioMedia implements EditorMediaService, EditorAudioSource { + _AudioMedia(this.source); + final Uri source; + bool silent = false; + void Function()? onRead; + @override + Future> query() async => [ + EditorMediaAsset(id: 'source', name: 'Original'), + ]; + @override + Future prepare(String id) async => PreparedEditorMedia( + asset: EditorMediaAsset(id: id, name: 'Original'), + uri: source, + duration: RationalTime.seconds(12), + kind: EditorMediaKind.audio, + hasAudio: true, + ); + @override + Future importFile( + String path, { + bool Function()? isCancelled, + }) => throw UnimplementedError(); + @override + Future waveform(String id, int track) async { + onRead?.call(); + final nativePath = Platform.environment['CUTDEX_BEAT_NATIVE_WAVEFORM']; + if (nativePath != null && !silent) { + return MediaWaveform.fromMap( + jsonDecode(await File(nativePath).readAsString()) as Map, + ); + } + + final values = []; + for (var i = 0; i < 1200; i++) { + final v = silent + ? 0.0 + : i % 50 == 10 + ? (i % 200 == 10 ? .9 : .4) + : .01; + values.addAll([-v, v, v]); + } + return MediaWaveform.fromMap({ + 'sampleRate': 1000, + 'sourceStartSeconds': 0, + 'frameCount': 12000, + 'trackId': track, + 'channelCount': 1, + 'levels': [ + { + 'samplesPerBucket': 10, + 'channels': [values], + }, + ], + }); + } +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late Directory root; + late ProjectFile project; + late EditorTimelineSession session; + late List originals; + late EditorAcceptance acceptance; + late Map tools; + final sequence = SequenceId('main'); + var serial = 0; + final history = []; + ToolContext context() => ToolContext( + sessionId: 'trial', + runId: 'run', + operationId: 'op-${serial++}', + cancellation: CancellationToken(), + onProgress: (_) {}, + ); + Future invoke( + String name, + Map args, { + bool record = true, + }) async { + final call = ToolCall( + id: 'call-${serial++}', + name: name, + arguments: {'workspaceId': 'timeline', ...args}, + ); + final t = tools[name]!; + expect(t.validate(call.arguments), isNull); + final result = await t.execute(call, context()); + if (record) { + history.add(AgentMessage(role: MessageRole.assistant, calls: [call])); + history.add( + AgentMessage( + role: MessageRole.tool, + callId: call.id, + text: jsonEncode(result.toJson()), + isError: result.isError, + ), + ); + } + return result; + } + + Future version() async => + (await invoke('timeline_query', {}, record: false)).data['version'] + as String; + Future save() async { + expect( + (await invoke('project_save', { + 'expectedVersion': await version(), + }, record: false)).isError, + false, + ); + } + + Future check() => acceptance.check( + SessionSnapshot(id: 'trial', runId: 'run', history: history), + CancellationToken(), + ); + setUp(() async { + history.clear(); + serial = 0; + root = await Directory.systemTemp.createTemp('cutdex-acceptance-'); + project = await ProjectFile.create( + Directory('${root.path}/acceptance.cutdex'), + name: 'Acceptance', + ); + await project.saveAsset( + AssetDocument( + id: 'source', + name: 'Original', + storage: AssetStorage.external, + location: Uri.file('${root.path}/source.wav').toString(), + ), + ); + final document = TimelineDocument( + id: 'p', + name: 'Acceptance', + sequences: [ + TimelineDto( + id: sequence, + format: TimelineFormat.fps30, + primaryStorylineId: StorylineId('primary'), + storylines: [ + StorylineDto(id: StorylineId('primary'), elementIds: []), + ], + elements: [], + ), + ], + ); + await project.saveTimeline(document); + session = EditorTimelineSession( + document: await project.loadTimeline('p'), + persistence: await project.openTimelineSaveSession('p'), + media: _AudioMedia(Uri.file('${root.path}/source.wav')), + ); + session.insertAsset( + sequenceId: sequence, + assetId: 'source', + assetName: 'Original', + uri: Uri.file('${root.path}/source.wav'), + duration: RationalTime.seconds(12), + position: 0, + kind: 'audio', + hasAudio: true, + clipId: ElementId('clip'), + ); + session.insertAsset( + sequenceId: sequence, + assetId: 'source', + assetName: 'Reference', + uri: Uri.file('${root.path}/source.wav'), + duration: RationalTime.seconds(12), + position: 12 * TimelineClock.ticksPerSecond, + kind: 'audio', + hasAudio: true, + clipId: ElementId('music'), + ); + session.commands.applyEdit( + sequence, + PlaceClip( + clipId: 'music', + at: CommandTime(0, 1), + side: ClipPlacement.above, + ), + ); + originals = editorAgentTools({ + 'timeline': editorToolsFor(session, sequence), + }); + acceptance = EditorAcceptance(originals); + tools = { + for (final t in [...originals, ...acceptance.tools]) t.name: t, + }; + }); + tearDown(() async { + await session.close(); + await project.close(); + await root.delete(recursive: true); + }); + + test( + 'real tool chain plans, cuts, saves and verifies every second beat', + () async { + final plan = await invoke('timeline_planBeatCuts', { + 'audioClipId': 'music', + 'clipIds': ['clip'], + 'durationSeconds': 12, + 'every': 2, + 'requireCuts': true, + }); + expect(plan.isError, false, reason: plan.text); + final data = plan.data['data'] as Map; + final actions = data['actions'] as List; + expect(actions.length, 12); + expect((await check()).isError, true); + for (final action in actions) { + final result = await invoke(action['tool'] as String, { + ...(action['arguments'] as Map).cast(), + 'expectedVersion': await version(), + }); + expect(result.isError, false, reason: result.text); + } + await save(); + final verified = await check(); + expect(verified.isError, false, reason: jsonEncode(verified.toJson())); + final stored = await project.loadTimeline('p'); + expect(stored.sequences.single.elements.length, 14); + // An extra off-beat split must invalidate the old receipt. + final extra = await invoke('timeline_split', { + 'clipId': 'clip', + 'at': {'numerator': '1', 'denominator': 30}, + 'expectedVersion': await version(), + }); + expect(extra.isError, false, reason: extra.text); + await save(); + expect((await check()).isError, true); + }, + ); + test( + 'read-only plans do not demand edits; source trim and speed map beats', + () async { + await invoke('clip_setSpeed', { + 'clipId': 'music', + 'speed': 2, + 'expectedVersion': await version(), + }); + final plan = await invoke('timeline_planBeatCuts', { + 'audioClipId': 'music', + 'clipIds': ['clip'], + 'durationSeconds': 12, + 'every': 2, + }); + expect(plan.isError, false, reason: plan.text); + final data = plan.data['data'] as Map; + final actions = data['actions'] as List; + final last = (actions.last['arguments'] as Map)['at'] as Map; + final t = + double.parse(last['numerator'] as String) / + (last['denominator'] as int); + expect(t, closeTo(2 / 30, 0.000001)); + await save(); + expect((await check()).isError, false); + }, + ); + + test( + 'low-confidence audio and concurrent timeline edits cannot authorize cuts', + () async { + final media = session.media as _AudioMedia; + media.silent = true; + final silent = await invoke('timeline_planBeatCuts', { + 'audioClipId': 'music', + 'clipIds': ['clip'], + 'durationSeconds': 12, + 'requireCuts': true, + }); + expect(silent.isError, true); + expect(silent.data['code'], 'uncertainBeat'); + media.silent = false; + media.onRead = () => session.commands.applyEdit( + sequence, + const SetClipAudio(clipId: 'clip', db: -3), + ); + final stale = await invoke('audio_analyze', { + 'clipId': 'music', + 'durationSeconds': 12, + }); + expect(stale.isError, true); + expect(stale.data['code'], 'staleVersion'); + }, + ); + test( + 'trimmed reference maps only beats inside the retained source range', + () async { + final trim = await invoke('timeline_trim', { + 'clipId': 'music', + 'duration': {'numerator': '10', 'denominator': 1}, + 'leading': true, + 'expectedVersion': await version(), + }); + expect(trim.isError, false, reason: trim.text); + final plan = await invoke('timeline_planBeatCuts', { + 'audioClipId': 'music', + 'clipIds': ['clip'], + 'durationSeconds': 12, + 'every': 2, + }); + expect(plan.isError, false, reason: plan.text); + final actions = (plan.data['data'] as Map)['actions'] as List; + expect(actions.length, 10); + final time = actions.last['arguments']['at'] as Map; + expect( + double.parse(time['numerator'] as String) / + (time['denominator'] as num), + closeTo(2.1, 0.000001), + ); + }, + ); + + test('montage mode trims three shots to successive beats and verifies saved ranges', () async { + for (var i = 2; i <= 3; i++) { + session.insertAsset( + sequenceId: sequence, + assetId: 'source', + assetName: 'Shot $i', + uri: Uri.file('${root.path}/source.wav'), + duration: RationalTime.seconds(12), + position: (i - 1) * 12 * TimelineClock.ticksPerSecond, + kind: 'video', + hasAudio: false, + clipId: ElementId('shot$i'), + ); + } + final plan = await invoke('timeline_planBeatCuts', { + 'audioClipId': 'music', + 'clipIds': ['clip', 'shot2', 'shot3'], + 'durationSeconds': 4, + 'every': 2, + 'phase': 1, + 'mode': 'fitClips', + 'requireCuts': true, + }); + expect(plan.isError, false, reason: plan.text); + expect((await check()).isError, true); + for (final action in (plan.data['data'] as Map)['actions'] as List) { + final result = await invoke(action['tool'] as String, { + ...(action['arguments'] as Map).cast(), + 'expectedVersion': await version(), + }); + expect(result.isError, false, reason: result.text); + } + await save(); + final verified = await check(); + expect(verified.isError, false, reason: jsonEncode(verified.toJson())); + final stored = (await project.loadTimeline('p')).sequences.single; + expect( + stored.elements + .singleWhere((e) => e.id == ElementId('clip')) + .duration + .seconds, + closeTo(.6, .00001), + ); + expect( + stored.elements + .singleWhere((e) => e.id == ElementId('shot2')) + .duration + .seconds, + 1, + ); + expect( + stored.elements + .singleWhere((e) => e.id == ElementId('shot3')) + .duration + .seconds, + 1, + ); + }); + test( + 'live agent discovers audio tools and completes beat editing', + () async { + final config = + jsonDecode(Platform.environment['CUTDEX_BEAT_LIVE']!) as Map; + final overrides = HttpOverrides.current; + HttpOverrides.global = null; + addTearDown(() => HttpOverrides.global = overrides); + final model = OpenAiResponsesAdapter( + baseUrl: Uri.parse(config['baseUrl'] as String), + model: config['model'] as String, + apiKey: config['key'] as String, + ); + final manager = SessionManager( + model: model, + store: InMemorySessionStore(), + tools: tools.values, + completionCheck: acceptance.check, + contextBuilder: HarnessContextBuilder( + directTools: const {'cutdex_workspaces'}, + maxInputTokens: 32000, + summarizer: ModelContextSummarizer( + model: model, + budget: ContextBuilder(maxInputTokens: 32000), + ), + ), + ); + final conversation = await manager.create( + system: AgentPromptPolicy.editorAssistant, + ); + final end = await (await manager.prompt( + conversation.id, + '对timeline工作区的clip片段做音乐卡点,参考music音频素材前4秒,每两拍切一次;实际执行分割,保留全部画面内容和音频,保存并核验。', + maxTurns: 45, + )).done; + expect(end.status, RunStatus.completed, reason: end.error); + final evidence = + (end.completionEvidence!['result'] as Map)['data'] as Map; + expect(evidence['contracts'], 1); + expect(evidence['issues'], isEmpty); + final current = await invoke('timeline_query', {}, record: false); + expect( + ((current.data['data'] as Map)['primaryClipIds'] as List).length, + 5, + ); + stdout.writeln( + 'LIVE_BEAT_EDIT_VERIFIED turns=${end.turns} evidence=${jsonEncode(end.completionEvidence)}', + ); + }, + skip: Platform.environment['CUTDEX_BEAT_LIVE'] == null, + timeout: const Timeout(Duration(minutes: 5)), + ); + test( + 'live agent trims a montage to beat-aligned shot changes', + () async { + for (var i = 2; i <= 3; i++) { + session.insertAsset( + sequenceId: sequence, + assetId: 'source', + assetName: 'Shot $i', + uri: Uri.file('${root.path}/source.wav'), + duration: RationalTime.seconds(12), + position: (i - 1) * 12 * TimelineClock.ticksPerSecond, + kind: 'video', + hasAudio: false, + clipId: ElementId('shot$i'), + ); + } + final config = + jsonDecode(Platform.environment['CUTDEX_BEAT_LIVE']!) as Map; + final overrides = HttpOverrides.current; + HttpOverrides.global = null; + addTearDown(() => HttpOverrides.global = overrides); + final model = OpenAiResponsesAdapter( + baseUrl: Uri.parse(config['baseUrl'] as String), + model: config['model'] as String, + apiKey: config['key'] as String, + ); + final manager = SessionManager( + model: model, + store: InMemorySessionStore(), + tools: tools.values, + completionCheck: acceptance.check, + contextBuilder: HarnessContextBuilder( + directTools: const {'cutdex_workspaces'}, + maxInputTokens: 32000, + summarizer: ModelContextSummarizer( + model: model, + budget: ContextBuilder(maxInputTokens: 32000), + ), + ), + ); + final conversation = await manager.create( + system: AgentPromptPolicy.editorAssistant, + ); + final end = await (await manager.prompt( + conversation.id, + '在timeline工作区,把clip、shot2、shot3三个主时间线镜头按现有顺序做卡点换镜头。参考music音频素材前4秒,从第2个检测到的节拍开始每两拍一个切点,裁短每个镜头尾部来匹配连续切点;保留音乐,不要只把原片段分割,实际执行、保存并核验。', + maxTurns: 45, + )).done; + expect(end.status, RunStatus.completed, reason: end.error); + final evidence = + (end.completionEvidence!['result'] as Map)['data'] as Map; + expect(evidence['contracts'], 1); + expect(evidence['issues'], isEmpty); + final stored = (await project.loadTimeline('p')).sequences.single; + expect( + stored.elements + .singleWhere((e) => e.id == ElementId('clip')) + .duration + .seconds, + closeTo(.6, .00001), + ); + expect( + stored.elements + .singleWhere((e) => e.id == ElementId('shot2')) + .duration + .seconds, + 1, + ); + expect( + stored.elements + .singleWhere((e) => e.id == ElementId('shot3')) + .duration + .seconds, + 1, + ); + stdout.writeln( + 'LIVE_BEAT_MONTAGE_VERIFIED turns=${end.turns} evidence=${jsonEncode(end.completionEvidence)}', + ); + }, + skip: Platform.environment['CUTDEX_BEAT_LIVE'] == null, + timeout: const Timeout(Duration(minutes: 5)), + ); +} diff --git a/test/audio_properties_test.dart b/test/audio_properties_test.dart new file mode 100644 index 0000000..7e64c13 --- /dev/null +++ b/test/audio_properties_test.dart @@ -0,0 +1,373 @@ +import 'package:cutdex/app/editor_theme.dart'; +import 'package:cutdex/integrations/runtime/timeline_waveforms.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex/features/properties/audio_gain_scale.dart'; +import 'package:cutdex/features/properties/audio_properties.dart'; +import 'package:cutdex_ui/widgets.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:cutdex_sdk/timeline/engine.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'support/preview_fixture.dart'; + +void main() { + test( + 'gain mapping is monotonic, reversible and reserves a mute endpoint', + () { + var previous = -91.0; + for (var i = 0; i <= 1020; i++) { + final db = -90 + i / 10; + final position = AudioGainScale.positionAt(db); + expect(position, greaterThan(0)); + expect(AudioGainScale.dbAt(position), closeTo(db, 1e-10)); + expect(db, greaterThan(previous)); + previous = db; + } + expect( + AudioGainScale.positionAt(6) - AudioGainScale.positionAt(-24), + closeTo(.7, 1e-10), + ); + expect(AudioGainScale.dbAt(1), closeTo(12, 1e-10)); + expect(() => AudioGainScale.positionAt(double.nan), throwsArgumentError); + }, + ); + + testWidgets( + 'detached audio shows restore and preserves the independent clip', + (tester) async { + final f = (await tester.runAsync( + () => createPreviewFixture(Uri.file('/test/video.mov'), hasAudio: true), + ))!; + final sequence = SequenceId('one'); + final id = ElementId('clip'); + final waveforms = RuntimeTimelineWaveforms( + resolveMedia: (ref) => f.timeline.mediaBinding(ref)?.media, + ); + addTearDown(waveforms.dispose); + final view = f.timeline.view(sequence); + ElementRecord current() { + final q = view.version.kernelVersion.query(); + return q.element(q.elementById(id)!); + } + + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + theme: EditorTheme.penLight, + home: Scaffold( + body: SizedBox( + width: 225, + child: AudioProperties( + session: f.timeline, + sequence: sequence, + clip: current(), + hasAudio: true, + ), + ), + ), + ), + ); + await tester.runAsync(() async { + f.timeline.commands.setAudio( + sequence: sequence, + clip: id, + db: -18, + muted: true, + ); + await f.timeline.flush(); + }); + await tester.pumpAndSettle(); + expect(find.text('音频已分离'), findsNothing); + expect(waveforms.hasAudioFor(current()), isTrue); + late ElementId detached; + await tester.runAsync(() async { + f.timeline.commands.setAudio( + sequence: sequence, + clip: id, + muted: false, + ); + detached = f.timeline.detachAudio(sequence, id); + await f.timeline.flush(); + }); + await tester.pumpAndSettle(); + expect(find.text('音频已分离'), findsOneWidget); + expect(find.byKey(const Key('audio-slider')), findsNothing); + final before = view.version.kernelVersion; + final q = before.query(); + final copy = q.element(q.elementById(detached)!); + final speedPreview = f.timeline.previewClipSpeed(sequence, detached, 2)!; + expect(view.version.kernelVersion, same(before)); + final speedQuery = speedPreview.result.version.kernelVersion.query(); + expect( + speedQuery.element(speedQuery.elementById(detached)!).duration, + copy.duration ~/ 2, + ); + expect( + speedQuery.element(speedQuery.elementById(id)!).duration, + q.element(q.elementById(id)!).duration, + ); + speedPreview.cancel(); + // Keep the audio region while suppressing only its waveform. + expect(waveforms.hasAudioFor(current()), isTrue); + expect(waveforms.waveformFor(current()), isNull); + expect(waveforms.hasAudioFor(copy), isTrue); + await tester.runAsync(() async { + await tester.tap(find.byKey(const Key('audio-restore'))); + await tester.pump(); + await f.timeline.flush(); + }); + await tester.pumpAndSettle(); + expect(find.text('音频已分离'), findsNothing); + expect(find.byKey(const Key('audio-slider')), findsOneWidget); + expect(ClipAudioGain.fromRecord(current()).muted, isFalse); + expect(waveforms.hasAudioFor(current()), isTrue); + expect(ClipAudioGain.fromRecord(current()).db, -18); + final restored = view.version.kernelVersion.query(); + expect(restored.element(restored.elementById(detached)!), same(copy)); + await tester.runAsync(() async { + f.timeline.undo(sequence); + await f.timeline.flush(); + }); + await tester.pumpAndSettle(); + expect(view.version.kernelVersion, same(before)); + expect(find.text('音频已分离'), findsOneWidget); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.runAsync(() async { + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + }, + ); + + testWidgets('gain input, mute, drag history, reset and persistence', ( + tester, + ) async { + final f = (await tester.runAsync( + () => createPreviewFixture(Uri.file('/test/video.mov'), hasAudio: true), + ))!; + final sequence = SequenceId('one'); + final view = f.timeline.view(sequence); + final query = view.version.kernelVersion.query(); + final clip = query.element(query.elementById(ElementId('clip'))!); + ClipAudioGain current() { + final q = view.version.kernelVersion.query(); + return ClipAudioGain.fromRecord(q.element(q.elementById(clip.id)!)); + } + + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + theme: EditorTheme.penLight, + home: Scaffold( + body: SizedBox( + width: 225, + child: AudioProperties( + session: f.timeline, + sequence: sequence, + clip: clip, + hasAudio: true, + ), + ), + ), + ), + ); + final field = find.byType(TextField); + await tester.enterText(field, '-18'); + await tester.testTextInput.receiveAction(TextInputAction.done); + await tester.pump(); + expect(current().db, -18); + await tester.tap(find.byKey(const Key('audio-mute'))); + await tester.pump(); + expect(current().muted, isTrue); + expect(current().db, -18); + await tester.tap(find.byKey(const Key('audio-mute'))); + await tester.pump(); + expect(current().muted, isFalse); + final before = view.version.kernelVersion; + AppSlider slider() => tester.widget(find.byType(AppSlider)); + slider().onChangeStart!(.5); + for (final p in [.3, .4, .8]) { + slider().onChanged!(p); + await tester.pump(); + expect(view.version.kernelVersion, same(before)); + expect( + f.timeline.waveformGain(clip), + closeTo(ClipAudioGain(AudioGainScale.dbAt(p)).amplitudeScale, .02), + ); + } + slider().onChangeEnd!(.8); + await tester.pump(); + expect(current().db, 1.7); + expect(f.timeline.audioGainPreview.value, isNull); + view.undo(); + await tester.pump(); + expect(view.version.kernelVersion, same(before)); + expect(current().db, -18); + slider().onChangeStart!(.5); + slider().onChanged!(0); + await tester.pump(); + expect(f.timeline.waveformGain(clip), 0); + slider().onChangeEnd!(0); + await tester.pump(); + expect(current().muted, isTrue); + await tester.runAsync(() async { + await f.timeline.flush(); + final saved = await f.workspace.project!.loadTimeline('project'); + final curves = saved.sequences.first.elements.single.parameters; + expect( + curves + .firstWhere((p) => p.definition.id == ClipAudioGain.muteId) + .definition + .defaultValue, + 0, + ); + expect(curves.every((p) => p.definition.defaultValue.isFinite), isTrue); + expect( + saved.settings['parameterTargets'], + containsPair(ClipAudioGain.muteId, 'audioVolume'), + ); + final compiled = const ExecutionCompiler().compile( + ExecutionInput( + timeline: f.timeline.persistence.timeline(sequence), + renderSize: RenderSize(64, 64), + parameterTargets: ClipAudioGain.targets, + media: { + PayloadRef('source'): ExecutionMediaBinding( + media: MediaReference( + id: 'media', + uri: Uri.file('/test/video.mov'), + ), + audioTrackSelection: TrackSelection.index(0), + ), + }, + ), + ); + final automation = compiled.plan.audioLayers.single.automation; + expect( + automation.firstWhere((a) => a.target == 'audioVolume').defaultValue, + 0, + ); + expect( + automation.firstWhere((a) => a.target == 'audioGainDb').defaultValue, + -18, + ); + expect(compiled.plan.visualLayers, isNotEmpty); + }); + await tester.tap(find.byKey(const Key('audio-reset'))); + await tester.pump(); + expect(current().db, 0); + expect(current().muted, isFalse); + await tester.enterText(field, '20'); + await tester.testTextInput.receiveAction(TextInputAction.done); + await tester.pump(); + expect(current().db, 0); + expect(find.text('请输入 -90 到 +12 之间的数值'), findsOneWidget); + expect(tester.takeException(), isNull); + slider().onChangeStart!(.5); + slider().onChanged!(.9); + await tester.pump(); + expect(f.timeline.audioGainPreview.value, isNotNull); + await tester.pumpWidget(const SizedBox()); + expect(f.timeline.audioGainPreview.value, isNull); + await tester.runAsync(() async { + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + }); + testWidgets( + 'volume keys interpolate, retain mute edits and survive undo and save', + (tester) async { + final f = (await tester.runAsync( + () => createPreviewFixture(Uri.file('/test/video.mov'), hasAudio: true), + ))!; + final sequence = SequenceId('one'); + final view = f.timeline.view(sequence); + final id = ElementId('clip'); + ElementRecord record() { + final q = view.version.kernelVersion.query(); + return q.element(q.elementById(id)!); + } + + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + theme: EditorTheme.penLight, + home: Scaffold( + body: SizedBox( + width: 225, + child: AudioProperties( + session: f.timeline, + sequence: sequence, + clip: record(), + hasAudio: true, + ), + ), + ), + ), + ); + expect( + tester.getCenter(find.byKey(const Key('audio-slider'))).dy, + closeTo(tester.getCenter(find.byKey(const Key('audio-db'))).dy, .01), + ); + await tester.tap(find.byKey(const Key('audio-key'))); + await tester.pump(); + expect(record().parameters?[ClipAudioGain.gainId]?.length, 1); + view.seekTo(TimelineClock.ticksPerSecond); + await tester.pump(); + await tester.enterText(find.byType(TextField), '-12'); + await tester.testTextInput.receiveAction(TextInputAction.done); + await tester.pump(); + expect(record().parameters?[ClipAudioGain.gainId]?.length, 2); + view.seekTo(TimelineClock.ticksPerSecond ~/ 2); + await tester.pump(); + expect( + tester.widget(find.byType(TextField)).controller!.text, + '-6.0', + ); + await tester.tap(find.byKey(const Key('audio-mute'))); + await tester.pump(); + expect(record().parameters?[ClipAudioGain.gainId]?.length, 2); + expect(ClipAudioGain.fromRecord(record()).muted, isTrue); + view.undo(); + await tester.pump(); + expect(ClipAudioGain.fromRecord(record()).muted, isFalse); + view.seekTo(TimelineClock.ticksPerSecond); + await tester.pump(); + await tester.tap(find.byKey(const Key('audio-key'))); + await tester.pump(); + expect(record().parameters?[ClipAudioGain.gainId]?.length, 1); + view.undo(); + await tester.pump(); + expect(record().parameters?[ClipAudioGain.gainId]?.length, 2); + await tester.runAsync(f.timeline.flush); + final saved = f.timeline.persistence + .timeline(sequence) + .exportDto() + .elements + .singleWhere((element) => element.id == id); + expect( + saved.parameters + .firstWhere((curve) => curve.definition.id == ClipAudioGain.gainId) + .keyframes + .length, + 2, + ); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + await tester.runAsync(() async { + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + }, + ); +} diff --git a/test/breakable_selectable_text_test.dart b/test/breakable_selectable_text_test.dart new file mode 100644 index 0000000..c42c8ae --- /dev/null +++ b/test/breakable_selectable_text_test.dart @@ -0,0 +1,77 @@ +import 'package:cutdex/features/assistant/breakable_selectable_text.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets('long path wraps by character and copies without soft breaks', ( + tester, + ) async { + const path = '/Users/example/Desktop/包含中文的长截图文件名.png'; + String? copied; + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + messenger.setMockMethodCallHandler(SystemChannels.platform, (call) async { + if (call.method == 'Clipboard.setData') { + copied = (call.arguments as Map)['text'] as String?; + } + return null; + }); + addTearDown( + () => messenger.setMockMethodCallHandler(SystemChannels.platform, null), + ); + await tester.pumpWidget( + const MaterialApp( + home: Scaffold( + body: SizedBox( + width: 220, + child: BreakableSelectableText( + text: path, + style: TextStyle(fontSize: 16), + ), + ), + ), + ), + ); + + final selectable = tester.widget( + find.byType(SelectableText), + ); + expect(selectable.data, contains('\u200B')); + expect(selectable.data!.replaceAll('\u200B', ''), path); + final paragraph = TextPainter( + text: TextSpan(text: selectable.data, style: selectable.style), + textDirection: TextDirection.ltr, + )..layout(maxWidth: 220); + expect(paragraph.computeLineMetrics().first.width, greaterThan(190)); + + await tester.tap(find.byType(SelectableText)); + final editable = tester.state(find.byType(EditableText)); + editable.userUpdateTextEditingValue( + editable.textEditingValue.copyWith( + selection: TextSelection( + baseOffset: 0, + extentOffset: selectable.data!.length, + ), + ), + SelectionChangedCause.keyboard, + ); + await tester.pump(); + await tester.sendKeyDownEvent(LogicalKeyboardKey.metaLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.keyC); + await tester.sendKeyUpEvent(LogicalKeyboardKey.metaLeft); + await tester.pump(); + expect(copied, path); + + copied = null; + final menu = selectable.contextMenuBuilder!( + tester.element(find.byType(SelectableText)), + editable, + ) as AdaptiveTextSelectionToolbar; + menu.buttonItems! + .singleWhere((button) => button.type == ContextMenuButtonType.copy) + .onPressed!(); + await tester.pump(); + expect(copied, path); + }); +} diff --git a/test/chat_controller_test.dart b/test/chat_controller_test.dart new file mode 100644 index 0000000..6892803 --- /dev/null +++ b/test/chat_controller_test.dart @@ -0,0 +1,1055 @@ +import 'package:cutdex/app/editor_theme.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; + +import 'dart:async'; +import 'dart:io'; + +import 'package:cutdex/features/assistant/chat_controller.dart'; +import 'package:cutdex/features/assistant/agent_conversation_service.dart'; +import 'package:cutdex/features/assistant/agent_chat_panel.dart'; +import 'package:cutdex/features/assistant/chat_state.dart'; +import 'package:cutdex_ui/widgets.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:cutdex/integrations/agent/agent_provider.dart'; +import 'package:cutdex/integrations/agent/conversation_repository.dart'; +import 'package:cutdex/integrations/editor_tools.dart'; +import 'package:cutdex_agent/cutdex_agent.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +class _Model implements ModelAdapter { + final requests = []; + final streams = >[]; + + @override + Stream stream( + ModelRequest request, + CancellationToken cancellation, + ) { + requests.add(request); + final stream = StreamController(); + streams.add(stream); + unawaited(cancellation.whenCancelled.then((_) => stream.close())); + return stream.stream; + } +} + +class _DelayedRestoreConversation extends AgentConversationService { + _DelayedRestoreConversation() + : super( + projectId: 'project', + conversationId: null, + loadRepository: () async => throw UnimplementedError(), + loadRuntime: (_) async => null, + loadTools: (_) async => + const EditorAgentBinding(owner: 'test', tools: []), + ); + bool pauseOutcome = false; + bool recoveryOutcome = false; + bool exportOutcome = false; + bool? lastSummaryOnly; + bool? lastResumeOnly; + final entered = Completer(); + final restored = Completer(); + @override + Future restore() { + entered.complete(); + return restored.future; + } + + @override + Future send( + String text, { + required String timelineId, + bool summaryOnly = false, + bool resumeOnly = false, + required void Function(AgentConversationPreparation) onPrepared, + required void Function(String) onTextDelta, + void Function(ConversationMetadata)? onCreated, + }) async { + lastSummaryOnly = summaryOnly; + lastResumeOnly = resumeOnly; + return AgentConversationOutcome( + response: pauseOutcome || recoveryOutcome ? '' : 'new answer', + completed: !pauseOutcome && !recoveryOutcome, + failed: false, + paused: pauseOutcome, + recoveryRequired: recoveryOutcome, + exportReplyFailed: exportOutcome, + ); + } +} + +Future _until(bool Function() check) async { + for (var attempt = 0; attempt < 1000; attempt++) { + if (check()) return; + await Future.delayed(const Duration(milliseconds: 1)); + } + fail('Expected state was not reached'); +} + +void main() { + late _Model model; + late Directory conversationsRoot; + late ConversationRepository conversationRepository; + late ProviderContainer container; + setUp(() async { + model = _Model(); + conversationsRoot = await Directory.systemTemp.createTemp('chat-test-'); + conversationRepository = ConversationRepository(conversationsRoot); + container = ProviderContainer( + overrides: [ + conversationRepositoryProvider.overrideWith( + (ref) async => conversationRepository, + ), + agentConversationRuntimeResolverProvider.overrideWithValue( + (_) async => AgentRuntime( + model: model, + contextBuilder: ContextBuilder(), + revision: 1, + sessionIdentity: 'default', + ), + ), + agentConversationToolsResolverProvider.overrideWithValue( + (_, _) async => const EditorAgentBinding(owner: 'test', tools: []), + ), + agentRuntimeProvider.overrideWithValue( + AsyncData( + AgentRuntime( + model: model, + contextBuilder: ContextBuilder(), + revision: 1, + sessionIdentity: 'default', + ), + ), + ), + editorAgentToolsProvider.overrideWith( + (ref, ids) async => + const EditorAgentBinding(owner: 'test', tools: []), + ), + ], + ); + }); + tearDown(() async { + container.dispose(); + await conversationsRoot.delete(recursive: true); + }); + + test('turn budget pause is visible instead of silently stopping', () async { + final service = _DelayedRestoreConversation()..pauseOutcome = true; + service.restored.complete(null); + final isolated = ProviderContainer( + overrides: [ + agentConversationServiceProvider.overrideWith((ref, ids) => service), + ], + ); + addTearDown(isolated.dispose); + final provider = chatControllerProvider('project'); + final subscription = isolated.listen(provider, (_, _) {}); + addTearDown(subscription.close); + await isolated + .read(provider.notifier) + .send('complex edit', timelineId: 'timeline'); + expect(isolated.read(provider).error, AgentChatError.turnLimit); + expect(isolated.read(provider).busy, false); + }); + + test('unknown edit recovery is distinguished from network failure', () async { + final service = _DelayedRestoreConversation()..recoveryOutcome = true; + service.restored.complete(null); + final isolated = ProviderContainer( + overrides: [ + agentConversationServiceProvider.overrideWith((ref, ids) => service), + ], + ); + addTearDown(isolated.dispose); + final provider = chatControllerProvider('project'); + final subscription = isolated.listen(provider, (_, _) {}); + addTearDown(subscription.close); + await isolated + .read(provider.notifier) + .send('continue', timelineId: 'timeline'); + expect(isolated.read(provider).error, AgentChatError.recoveryRequired); + expect(isolated.read(provider).busy, false); + }); + + test('late history restore cannot overwrite a completed new turn', () async { + final service = _DelayedRestoreConversation(); + final isolated = ProviderContainer( + overrides: [ + agentConversationServiceProvider.overrideWith((ref, ids) => service), + ], + ); + addTearDown(isolated.dispose); + final provider = chatControllerProvider('project'); + final subscription = isolated.listen(provider, (_, _) {}); + addTearDown(subscription.close); + await service.entered.future; + await isolated + .read(provider.notifier) + .send('new question', timelineId: 'timeline'); + service.restored.complete( + const AgentConversationHistory([ + AgentConversationMessage(text: 'old answer', isUser: false), + ]), + ); + await Future.delayed(Duration.zero); + expect(isolated.read(provider).messages.map((message) => message.text), [ + 'new question', + 'new answer', + ]); + }); + + testWidgets( + 'restored export failure shows success and a summary-only retry', + (tester) async { + final service = _DelayedRestoreConversation(); + service.restored.complete( + const AgentConversationHistory([], exportReplyFailed: true), + ); + await tester.pumpWidget( + ProviderScope( + overrides: [ + agentConversationServiceProvider.overrideWith( + (ref, ids) => service, + ), + agentRuntimeProvider.overrideWithValue(const AsyncData(null)), + agentSessionStoreProvider.overrideWithValue( + AsyncData(InMemorySessionStore()), + ), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + theme: EditorTheme.penDark, + home: const Scaffold( + body: AgentChatPanel(projectId: 'p', timelineId: 't'), + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect(find.textContaining('视频已成功导出'), findsOneWidget); + await tester.tap(find.widgetWithText(TextButton, '重试总结')); + await tester.pumpAndSettle(); + expect(service.lastSummaryOnly, isTrue); + expect(find.widgetWithText(TextButton, '重试总结'), findsNothing); + expect(find.text('new answer'), findsOneWidget); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + }, + ); + + testWidgets('restored uncertain write shows recovery warning immediately', ( + tester, + ) async { + final service = _DelayedRestoreConversation(); + service.restored.complete( + const AgentConversationHistory([], recoveryRequired: true), + ); + await tester.pumpWidget( + ProviderScope( + overrides: [ + agentConversationServiceProvider.overrideWith((ref, ids) => service), + agentRuntimeProvider.overrideWithValue(const AsyncData(null)), + agentSessionStoreProvider.overrideWithValue( + AsyncData(InMemorySessionStore()), + ), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + theme: EditorTheme.penDark, + home: const Scaffold( + body: AgentChatPanel(projectId: 'p', timelineId: 't'), + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect(find.textContaining('上次操作的结果尚未确认'), findsOneWidget); + await tester.tap(find.widgetWithText(TextButton, '继续任务')); + await tester.pumpAndSettle(); + expect(service.lastResumeOnly, isTrue); + expect(find.text('继续任务'), findsNothing); + expect(find.widgetWithText(TextButton, '重试总结'), findsNothing); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + }); + + testWidgets( + 'unconfigured service still allows clicking and editing a timeline', + (tester) async { + await tester.pumpWidget( + ProviderScope( + overrides: [ + agentRuntimeProvider.overrideWithValue(const AsyncData(null)), + agentSessionStoreProvider.overrideWithValue( + AsyncData(InMemorySessionStore()), + ), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + theme: EditorTheme.penDark, + home: const Scaffold( + body: SizedBox( + width: 280, + child: AgentChatPanel(projectId: 'lib', timelineId: 'project'), + ), + ), + ), + ), + ); + await tester.tap(find.byType(TextField)); + await tester.pump(); + expect(tester.testTextInput.hasAnyClients, isTrue); + await tester.enterText(find.byType(TextField), '尚未发送的消息'); + await tester.pump(); + expect(find.text('尚未发送的消息'), findsOneWidget); + final send = tester.widget( + find.widgetWithIcon(IconButton, Icons.arrow_upward), + ); + expect(send.onPressed, isNull); + final conversation = find.byKey(const Key('agent-conversation')); + final composer = find.byKey(const Key('agent-composer')); + expect(tester.getSize(conversation).width, 280); + expect(tester.getSize(composer).width, 248); + final panelRect = tester.getRect(find.byType(AgentChatPanel)); + final composerRect = tester.getRect(composer); + expect(composerRect.left - panelRect.left, 16); + expect(panelRect.right - composerRect.right, 16); + expect(panelRect.bottom - composerRect.bottom, 16); + expect( + tester.getRect(conversation).center.dx, + tester.getRect(composer).center.dx, + ); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + }, + ); + + testWidgets('chat input sends, streams and stops from the panel', ( + tester, + ) async { + await tester.binding.setSurfaceSize(const Size(1000, 600)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + theme: EditorTheme.penDark, + home: const Scaffold( + body: SizedBox( + width: 1000, + child: AgentChatPanel(projectId: 'lib', timelineId: 'project'), + ), + ), + ), + ), + ); + await tester.enterText(find.byType(TextField), '测试发送'); + await tester.pump(); + final composerInput = tester.widget(find.byType(TextField)); + final composerCard = tester.widget( + find.byKey(const Key('agent-composer')), + ); + expect(composerCard.color, const Color(0xFF2F2F2F)); + expect( + (composerCard.shape! as RoundedRectangleBorder).borderRadius, + BorderRadius.circular(22), + ); + expect(tester.getSize(find.byKey(const Key('agent-composer'))).height, 98); + expect(composerInput.style?.height, 20 / 13); + expect(composerInput.minLines, 1); + expect(composerInput.style?.fontSize, 13); + expect(composerInput.decoration?.hintStyle?.fontSize, 13); + final sendButton = tester.widget( + find.widgetWithIcon(IconButton, Icons.arrow_upward), + ); + expect( + sendButton.style?.shape?.resolve({}), + isA(), + ); + expect( + sendButton.style?.backgroundColor?.resolve({}), + Colors.white, + ); + expect( + sendButton.style?.foregroundColor?.resolve({}), + Colors.black, + ); + await tester.runAsync(() async { + await tester.tap(find.byTooltip('发送消息')); + await _until(() => model.requests.isNotEmpty); + }); + await tester.pumpAndSettle(); + expect(model.requests.single.messages.single.text, '测试发送'); + final conversation = find.byKey(const Key('agent-conversation')); + final composer = find.byKey(const Key('agent-composer')); + final conversationScrollbar = find.byKey( + const Key('agent-conversation-scrollbar'), + ); + expect(tester.getSize(conversation).width, 1000); + expect(tester.getSize(composer).width, 768); + expect( + tester.getRect(conversationScrollbar), + tester.getRect(find.byType(AgentChatPanel)), + ); + expect( + tester.getRect(conversation).bottom, + tester.getRect(find.byType(AgentChatPanel)).bottom, + ); + final fade = tester.widget(find.byType(ScrollEdgeFade)); + final chatList = tester.widget( + find.descendant(of: conversation, matching: find.byType(ListView)).first, + ); + expect(chatList.padding, EdgeInsets.only(bottom: fade.bottomInset)); + expect( + tester.getRect(conversation).bottom - fade.bottomInset, + lessThan(tester.getRect(composer).top), + ); + await tester.enterText( + find.byType(TextField), + List.filled(12, 'draft').join('\n'), + ); + await tester.pumpAndSettle(); + final expandedFade = tester.widget( + find.byType(ScrollEdgeFade), + ); + expect(expandedFade.bottomInset, greaterThan(fade.bottomInset)); + expect( + tester + .widget( + find + .descendant(of: conversation, matching: find.byType(ListView)) + .first, + ) + .padding, + EdgeInsets.only(bottom: expandedFade.bottomInset), + ); + await tester.enterText(find.byType(TextField), ''); + await tester.pumpAndSettle(); + expect( + tester.getRect(conversation).center.dx, + tester.getRect(composer).center.dx, + ); + expect( + ((tester + .widgetList(find.byType(Container)) + .firstWhere( + (widget) => + widget.decoration is BoxDecoration && + (widget.decoration! as BoxDecoration).color == + EditorTheme.penDark.colorScheme.onSurface + .withValues(alpha: .08), + ) + .decoration!) + as BoxDecoration) + .borderRadius, + BorderRadius.circular(20), + ); + await tester.runAsync(() async { + model.streams.single.add(const TextDelta('正在生成的内容')); + await _until( + () => container + .read(chatControllerProvider('lib')) + .partialResponse + .isNotEmpty, + ); + }); + await tester.pumpAndSettle(); + expect(find.text('正在生成的内容'), findsOneWidget); + await tester.runAsync(() async { + await tester.tap(find.byTooltip('停止回复')); + await container.read(chatControllerProvider('lib').notifier).stop(); + await _until(() => !container.read(chatControllerProvider('lib')).busy); + }); + await tester.pumpAndSettle(); + expect(find.text('回复已中断'), findsOneWidget); + expect(container.read(chatControllerProvider('lib')).busy, isFalse); + await tester.enterText(find.byType(TextField), '继续'); + await tester.pumpAndSettle(); + expect(find.byTooltip('发送消息'), findsOneWidget); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + }); + + testWidgets( + 'switching timelines keeps the same chat visible without restoring again', + (tester) async { + final service = _DelayedRestoreConversation(); + service.restored.complete( + const AgentConversationHistory([ + AgentConversationMessage(text: '第一条消息', isUser: true), + AgentConversationMessage( + text: '第一条回复', + isUser: false, + elapsedMs: 23000, + ), + ]), + ); + final isolated = ProviderContainer( + overrides: [ + agentConversationServiceProvider.overrideWith((ref, ids) => service), + agentRuntimeProvider.overrideWithValue(const AsyncData(null)), + agentSessionStoreProvider.overrideWithValue( + AsyncData(InMemorySessionStore()), + ), + ], + ); + addTearDown(isolated.dispose); + final provider = chatControllerProvider('project', draftKey: 'same-chat'); + final subscription = isolated.listen(provider, (_, _) {}); + addTearDown(subscription.close); + await tester.pump(); + await tester.runAsync( + () => _until(() => isolated.read(provider).messages.length == 2), + ); + final controller = isolated.read(provider.notifier); + expect(isolated.read(provider).messages.last.elapsedMs, 23000); + + Widget panel(String? timelineId, {Locale locale = const Locale('zh')}) => + UncontrolledProviderScope( + container: isolated, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: locale, + theme: EditorTheme.penDark, + home: Scaffold( + body: AgentChatPanel( + projectId: 'project', + timelineId: timelineId, + draftKey: 'same-chat', + ), + ), + ), + ); + + await tester.pumpWidget(panel('first')); + await tester.pumpAndSettle(); + expect(find.text('第一条消息'), findsOneWidget); + expect(find.text('第一条回复'), findsOneWidget); + expect(find.text('用时 23秒'), findsOneWidget); + expect( + find.descendant( + of: find.byKey(const Key('agent-conversation')), + matching: find.byType(Divider), + ), + findsOneWidget, + ); + await tester.enterText(find.byType(TextField), '未发送草稿'); + + await tester.pumpWidget(panel(null)); + await tester.pump(); + expect(find.text('第一条消息'), findsOneWidget); + expect(find.text('未发送草稿'), findsOneWidget); + expect( + tester + .widget( + find.widgetWithIcon(IconButton, Icons.arrow_upward), + ) + .onPressed, + isNull, + ); + + await tester.pumpWidget(panel('second')); + await tester.pump(); + expect(isolated.read(provider.notifier), same(controller)); + expect(find.text('第一条消息'), findsOneWidget); + expect(find.text('第一条回复'), findsOneWidget); + expect(find.text('未发送草稿'), findsOneWidget); + for (final (locale, elapsed) in [ + (const Locale('en'), 'Took 23s'), + (const Locale('fr'), 'Durée 23 s'), + ( + const Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hant'), + '耗時 23秒', + ), + ]) { + await tester.pumpWidget(panel('second', locale: locale)); + await tester.pumpAndSettle(); + expect(find.text(elapsed), findsOneWidget); + expect(find.text('未发送草稿'), findsOneWidget); + expect(isolated.read(provider.notifier), same(controller)); + } + await tester.pumpWidget(const SizedBox()); + }, + ); + + testWidgets('project selector is available only before a chat starts', ( + tester, + ) async { + Widget panel({String? conversationId}) => UncontrolledProviderScope( + container: container, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + theme: EditorTheme.penDark, + home: Scaffold( + body: AgentChatPanel( + key: ValueKey(conversationId ?? 'new'), + projectId: 'project', + timelineId: 'timeline', + conversationId: conversationId, + projectSelector: const SizedBox( + key: Key('test-project-selector'), + height: 32, + ), + ), + ), + ), + ); + + await tester.pumpWidget(panel()); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('test-project-selector')), findsOneWidget); + + await tester.enterText(find.byType(TextField), '开始聊天'); + await tester.pump(); + await tester.runAsync(() async { + await tester.tap(find.byTooltip('发送消息')); + await _until(() => model.streams.isNotEmpty); + }); + await tester.pump(); + expect(find.byKey(const Key('test-project-selector')), findsNothing); + + await tester.runAsync(() async { + model.streams.single.add(ModelResponse(text: '已经开始')); + await model.streams.single.close(); + await _until( + () => !container.read(chatControllerProvider('project')).busy, + ); + }); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('test-project-selector')), findsNothing); + + await tester.pumpWidget(panel(conversationId: 'existing')); + await tester.pump(); + expect(find.byKey(const Key('test-project-selector')), findsNothing); + await tester.pumpWidget(const SizedBox()); + }); + + testWidgets( + 'composer grows to its viewport limit, scrolls and sends with Enter', + (tester) async { + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + theme: EditorTheme.penDark, + home: const Scaffold( + body: SizedBox( + width: 280, + child: AgentChatPanel(projectId: 'lib', timelineId: 'project'), + ), + ), + ), + ), + ); + final input = find.byType(TextField); + final initialHeight = tester.getSize(input).height; + await tester.enterText(input, 'first'); + await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); + await tester.pump(); + expect(model.requests, isEmpty); + // The platform IME delivers the newline after the unhandled Shift+Enter. + await tester.enterText(input, 'first\n'); + await tester.pumpAndSettle(); + final twoLineHeight = tester.getSize(input).height; + expect(twoLineHeight, initialHeight); + await tester.enterText(input, 'first\n\n'); + await tester.pumpAndSettle(); + expect(tester.getSize(input).height, greaterThan(twoLineHeight)); + await tester.enterText(input, List.filled(12, 'line').join('\n')); + await tester.pumpAndSettle(); + final maxHeight = tester.getSize(input).height; + await tester.enterText(input, List.filled(15, 'line').join('\n')); + await tester.pumpAndSettle(); + expect(tester.getSize(input).height, maxHeight); + final scrollbar = find.byKey(const Key('agent-input-scrollbar')); + expect(tester.widget(scrollbar).thumbVisibility, isTrue); + expect( + tester + .widget(input) + .scrollController! + .position + .maxScrollExtent, + greaterThan(0), + ); + await tester.runAsync(() async { + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await _until(() => model.requests.isNotEmpty); + }); + await tester.pumpAndSettle(); + expect( + model.requests.single.messages.single.text.split('\n'), + hasLength(15), + ); + expect(tester.getSize(input).height, initialHeight); + expect(tester.widget(scrollbar).thumbVisibility, isFalse); + await tester.runAsync(() async { + model.streams.single.add(ModelResponse(text: 'ok')); + await model.streams.single.close(); + await _until(() => !container.read(chatControllerProvider('lib')).busy); + }); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + }, + ); + + test( + 'streams, blocks duplicate send, preserves context and isolates projects', + () async { + final provider = chatControllerProvider('project'); + final subscription = container.listen(provider, (_, _) {}); + addTearDown(subscription.close); + final controller = container.read(provider.notifier); + final sending = controller.send('你好', timelineId: 'first'); + await _until(() => model.streams.isNotEmpty); + await controller.send('重复', timelineId: 'first'); + expect(model.requests, hasLength(1)); + model.streams[0].add(const TextDelta('你好呀')); + await _until(() => container.read(provider).partialResponse == '你好呀'); + expect(container.read(provider).busy, isTrue); + model.streams[0].add(ModelResponse(text: '你好呀!')); + await model.streams[0].close(); + await sending; + expect(container.read(provider).messages.last.text, '你好呀!'); + expect(container.read(provider).partialResponse, isEmpty); + + final second = controller.send('接着说', timelineId: 'second'); + await _until(() => model.requests.length == 2); + expect(model.requests[1].messages.map((m) => m.text), [ + '你好', + '你好呀!', + '接着说', + ]); + model.streams[1].add(ModelResponse(text: '继续')); + await model.streams[1].close(); + await second; + expect( + (await conversationRepository.list('project')).single.timelineId, + 'second', + ); + + final otherProvider = chatControllerProvider('other-project'); + final otherSubscription = container.listen(otherProvider, (_, _) {}); + addTearDown(otherSubscription.close); + final other = container + .read(otherProvider.notifier) + .send('新会话', timelineId: 'timeline'); + await _until(() => model.requests.length == 3); + expect(model.requests.last.messages.map((m) => m.text), ['新会话']); + model.streams[2].add(ModelResponse(text: '新回答')); + await model.streams[2].close(); + await other; + expect(container.read(provider).messages, hasLength(4)); + }, + ); + + test('cancel retains partial text and allows the next request', () async { + final provider = chatControllerProvider('project'); + final subscription = container.listen(provider, (_, _) {}); + addTearDown(subscription.close); + final controller = container.read(provider.notifier); + final sending = controller.send('开始', timelineId: 'timeline'); + await _until(() => model.streams.isNotEmpty); + model.streams[0].add(const TextDelta('部分回复')); + await _until(() => container.read(provider).partialResponse.isNotEmpty); + controller.stop(); + await sending; + expect(container.read(provider).busy, isFalse); + expect(container.read(provider).messages.last.text, '部分回复'); + expect(container.read(provider).messages.last.interrupted, isTrue); + final next = controller.send('再来', timelineId: 'timeline'); + await _until(() => model.streams.length == 2); + model.streams[1].add(ModelResponse(text: '完成')); + await model.streams[1].close(); + await next; + expect(container.read(provider).messages.last.interrupted, isFalse); + }); + + test('two conversations in one project keep separate journals', () async { + final firstProvider = chatControllerProvider( + 'project', + draftKey: 'draft-one', + ); + final secondProvider = chatControllerProvider( + 'project', + draftKey: 'draft-two', + ); + final firstSubscription = container.listen(firstProvider, (_, _) {}); + final secondSubscription = container.listen(secondProvider, (_, _) {}); + addTearDown(firstSubscription.close); + addTearDown(secondSubscription.close); + final first = container + .read(firstProvider.notifier) + .send('第一条', timelineId: 'timeline'); + await _until(() => model.streams.length == 1); + model.streams[0].add(ModelResponse(text: '第一答')); + await model.streams[0].close(); + await first; + final second = container + .read(secondProvider.notifier) + .send('第二条', timelineId: 'timeline'); + await _until(() => model.streams.length == 2); + expect(model.requests[1].messages.map((message) => message.text), ['第二条']); + model.streams[1].add(ModelResponse(text: '第二答')); + await model.streams[1].close(); + await second; + final items = await conversationRepository.list('project'); + expect(items, hasLength(2)); + final histories = {}; + for (final item in items) { + final snapshot = await conversationRepository.store(item).read(item.id); + histories.add(snapshot!.history.first.text); + } + expect(histories, {'第一条', '第二条'}); + }); + + test( + 'restores conversation history in a new application container', + () async { + final provider = chatControllerProvider('project'); + var subscription = container.listen(provider, (_, _) {}); + final first = container + .read(provider.notifier) + .send('保留这段对话', timelineId: 'timeline'); + await _until(() => model.streams.isNotEmpty); + model.streams.single.add(ModelResponse(text: '已经保存')); + await model.streams.single.close(); + await first; + final conversationId = (await conversationRepository.list('project')) + .single + .id; + subscription.close(); + container.dispose(); + + container = ProviderContainer( + overrides: [ + conversationRepositoryProvider.overrideWith( + (ref) async => conversationRepository, + ), + agentConversationRuntimeResolverProvider.overrideWithValue( + (_) async => AgentRuntime( + model: model, + contextBuilder: ContextBuilder(), + revision: 1, + sessionIdentity: 'default', + ), + ), + agentConversationToolsResolverProvider.overrideWithValue( + (_, _) async => const EditorAgentBinding(owner: 'test', tools: []), + ), + agentRuntimeProvider.overrideWithValue( + AsyncData( + AgentRuntime( + model: model, + contextBuilder: ContextBuilder(), + revision: 1, + sessionIdentity: 'default', + ), + ), + ), + editorAgentToolsProvider.overrideWith( + (ref, ids) async => + const EditorAgentBinding(owner: 'test', tools: []), + ), + ], + ); + final restoredProvider = chatControllerProvider( + 'project', + conversationId: conversationId, + ); + subscription = container.listen(restoredProvider, (_, _) {}); + addTearDown(subscription.close); + await _until(() => container.read(restoredProvider).messages.length == 2); + expect( + container + .read(restoredProvider) + .messages + .map((message) => message.text), + ['保留这段对话', '已经保存'], + ); + + final continued = container + .read(restoredProvider.notifier) + .send('继续', timelineId: 'timeline'); + await _until(() => model.requests.length == 2); + expect(model.requests.last.messages.map((message) => message.text), [ + '保留这段对话', + '已经保存', + '继续', + ]); + model.streams.last.add(ModelResponse(text: '继续完成')); + await model.streams.last.close(); + await continued; + }, + ); + + test( + 'changing the default model does not change an existing conversation', + () async { + final firstModel = _Model(); + final secondModel = _Model(); + final originalRuntime = AgentRuntime( + model: firstModel, + contextBuilder: ContextBuilder(), + revision: 1, + sessionIdentity: 'first', + ); + var runtime = originalRuntime; + final switchingContainer = ProviderContainer( + overrides: [ + conversationRepositoryProvider.overrideWith( + (ref) async => conversationRepository, + ), + agentConversationRuntimeResolverProvider.overrideWithValue( + (item) async => + item?.modelId == 'first' ? originalRuntime : runtime, + ), + agentConversationToolsResolverProvider.overrideWithValue( + (_, _) async => const EditorAgentBinding(owner: 'test', tools: []), + ), + agentRuntimeProvider.overrideWith((ref) async => runtime), + agentSessionStoreProvider.overrideWithValue( + AsyncData(InMemorySessionStore()), + ), + editorAgentToolsProvider.overrideWith( + (ref, ids) async => + const EditorAgentBinding(owner: 'test', tools: []), + ), + ], + ); + addTearDown(switchingContainer.dispose); + final provider = chatControllerProvider('project'); + final subscription = switchingContainer.listen(provider, (_, _) {}); + addTearDown(subscription.close); + + final first = switchingContainer + .read(provider.notifier) + .send('旧会话', timelineId: 'timeline'); + await _until(() => firstModel.streams.isNotEmpty); + firstModel.streams.single.add(ModelResponse(text: '旧回答')); + await firstModel.streams.single.close(); + await first; + + runtime = AgentRuntime( + model: secondModel, + contextBuilder: ContextBuilder(), + revision: 2, + sessionIdentity: 'second', + ); + switchingContainer.invalidate(agentRuntimeProvider); + final second = switchingContainer + .read(provider.notifier) + .send('继续会话', timelineId: 'timeline'); + await _until(() => firstModel.streams.length == 2); + expect(firstModel.requests.last.messages.map((message) => message.text), [ + '旧会话', + '旧回答', + '继续会话', + ]); + expect(secondModel.requests, isEmpty); + expect( + switchingContainer + .read(provider) + .messages + .map((message) => message.text), + ['旧会话', '旧回答', '继续会话'], + ); + firstModel.streams.last.add(ModelResponse(text: '新回答')); + await firstModel.streams.last.close(); + await second; + expect( + switchingContainer + .read(provider) + .messages + .map((message) => message.text), + ['旧会话', '旧回答', '继续会话', '新回答'], + ); + }, + ); + + for (final entry in { + const ModelHttpException(401): AgentChatError.authentication, + const ModelConnectionException(): AgentChatError.connection, + const ModelProtocolException('bad stream'): AgentChatError.protocol, + const ContextOverflow('oversized turn'): AgentChatError.contextBudget, + }.entries) { + test('shows ${entry.value} without an empty interrupted reply', () async { + final provider = chatControllerProvider('project'); + final subscription = container.listen(provider, (_, _) {}); + addTearDown(subscription.close); + final sending = container + .read(provider.notifier) + .send('hello', timelineId: 'timeline'); + await _until(() => model.streams.isNotEmpty); + model.streams.single.addError(entry.key); + await model.streams.single.close(); + await sending; + expect(container.read(provider).error, entry.value); + expect(container.read(provider).messages.map((m) => m.text), ['hello']); + }); + } + test('service failures are sanitized and allow another request', () async { + final provider = chatControllerProvider('project'); + final subscription = container.listen(provider, (_, _) {}); + addTearDown(subscription.close); + final controller = container.read(provider.notifier); + final sending = controller.send('开始', timelineId: 'timeline'); + await _until(() => model.streams.isNotEmpty); + model.streams[0].addError(StateError('sensitive remote payload')); + await model.streams[0].close(); + await sending; + expect(container.read(provider).error, AgentChatError.replyFailed); + expect(container.read(provider).busy, isFalse); + final item = (await conversationRepository.list('project')).single; + expect( + (await conversationRepository.store(item).read(item.id))!.history + .where((message) => message.role == MessageRole.user) + .map((message) => message.text), + ['开始'], + ); + final next = controller.send('重试', timelineId: 'timeline'); + await _until(() => model.streams.length == 2); + model.streams[1].add(ModelResponse(text: '成功')); + await model.streams[1].close(); + await next; + expect(container.read(provider).error, isNull); + }); + + test('stop during initialization and dispose both settle requests', () async { + final provider = chatControllerProvider('project'); + final subscription = container.listen(provider, (_, _) {}); + final controller = container.read(provider.notifier); + final early = controller.send('停止', timelineId: 'timeline'); + controller.stop(); + await early; + expect(container.read(provider).busy, isFalse); + final later = controller.send('再次开始', timelineId: 'timeline'); + await _until(() => model.streams.isNotEmpty); + subscription.close(); + container.dispose(); + await later; + }); +} diff --git a/test/clip_animation_test.dart b/test/clip_animation_test.dart new file mode 100644 index 0000000..37cbe92 --- /dev/null +++ b/test/clip_animation_test.dart @@ -0,0 +1,135 @@ +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'support/preview_fixture.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + test( + 'grouped keys interpolate, retain other channels, undo and persist', + () async { + final f = await createPreviewFixture( + Uri.file('/test/video.mov'), + clipDuration: RationalTime.seconds(5), + ); + addTearDown(() async { + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + final id = SequenceId('one'); + final clip = ElementId('clip'); + final view = f.timeline.view(id); + ClipAnimation at(int second) { + final q = view.version.kernelVersion.query(); + return ClipAnimation.at( + q, + q.elementById(clip)!, + second * TimelineClock.ticksPerSecond, + TimelineClock.ticksPerSecond ~/ 30, + ); + } + + void commit(List curves) => + f.timeline.commitParameters( + id, + f.timeline.previewParameters(id, clip, curves), + parameterTargets: ClipTransform.targets, + ); + commit(at(0).toggle(TransformChannel.position)); + commit(at(2).edit(at(2).value.copyWith(x: .4, y: .2))); + expect(at(1).value.x, closeTo(.2, 1e-10)); + expect(at(1).value.y, closeTo(.1, 1e-10)); + expect(at(2).keyed(TransformChannel.position), isTrue); + expect(at(0).keyTimes(TransformChannel.position), [ + 0, + 2 * TimelineClock.ticksPerSecond, + ]); + commit(at(1).edit(at(1).value.copyWith(rotation: 45))); + expect(at(0).value.rotation, 45); + expect(at(2).value.x, .4); + final before = view.version.kernelVersion; + commit( + at(0).setInterpolation( + TransformChannel.position, + ParameterInterpolation.hold, + ), + ); + expect(at(1).value.x, 0); + view.undo(); + expect(view.version.kernelVersion, same(before)); + expect(at(1).value.x, closeTo(.2, 1e-10)); + view.redo(); + expect(at(1).value.x, 0); + view.undo(); + await f.timeline.flush(); + final saved = await f.workspace.project!.loadTimeline('project'); + final savedClip = saved.sequences.first.elements.single; + expect( + savedClip.parameters + .firstWhere((p) => p.definition.id == 'canvas.position.x') + .keyframes + .length, + 2, + ); + expect( + saved.settings['parameterTargets'], + containsPair('canvas.position.y', 'position.y'), + ); + commit(at(2).toggle(TransformChannel.position)); + expect(at(2).value.x, 0); + commit(at(0).toggle(TransformChannel.position)); + expect(at(0).animated(TransformChannel.position), isFalse); + }, + ); + + test( + 'independent dimensions remain grouped and clearing holds evaluated values', + () async { + final f = await createPreviewFixture( + Uri.file('/test/video.mov'), + clipDuration: RationalTime.seconds(5), + ); + addTearDown(() async { + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + final id = SequenceId('one'); + final clip = ElementId('clip'); + final view = f.timeline.view(id); + ClipAnimation at(int seconds) { + final q = view.version.kernelVersion.query(); + return ClipAnimation.at( + q, + q.elementById(clip)!, + seconds * TimelineClock.ticksPerSecond, + TimelineClock.ticksPerSecond ~/ 30, + ); + } + + void commit(List curves) => + f.timeline.commitParameters( + id, + f.timeline.previewParameters(id, clip, curves), + parameterTargets: ClipTransform.targets, + ); + commit(at(0).toggle(TransformChannel.scale)); + commit(at(2).edit(at(2).value.copyWith(scaleY: 3))); + expect(at(1).value.scale, 1); + expect(at(1).value.scaleY, 2); + expect(at(2).keyed(TransformChannel.scale), isTrue); + commit(at(1).clear(TransformChannel.scale)); + expect(at(0).animated(TransformChannel.scale), isFalse); + expect(at(0).value.scaleY, 2); + expect(at(4).value.scaleY, 2); + expect(at(5).containsPlayhead, isFalse); + expect(() => at(5).toggle(TransformChannel.scale), throwsStateError); + commit(at(2).toggle(TransformChannel.rotation)); + commit(at(2).edit(at(2).value.copyWith(rotation: 90))); + commit(at(2).toggle(TransformChannel.rotation)); + expect(at(0).animated(TransformChannel.rotation), isFalse); + expect(at(0).value.rotation, 90); + }, + ); +} diff --git a/test/clip_mask_test.dart b/test/clip_mask_test.dart new file mode 100644 index 0000000..27b9ef0 --- /dev/null +++ b/test/clip_mask_test.dart @@ -0,0 +1,50 @@ +import 'package:cutdex/features/properties/animation_labels.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'support/preview_fixture.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + test( + 'mask grouped animation retains values, interpolates, and survives undo', + () async { + final f = await createPreviewFixture( + Uri.file('/test/video.mov'), + clipDuration: RationalTime.seconds(5), + ); + addTearDown(() async { + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + final sequence = SequenceId('one'); + final id = ElementId('clip'); + final view = f.timeline.view(sequence); + ClipMaskAnimation at(int seconds) { + final query = view.version.kernelVersion.query(); + return ClipMaskAnimation( + query.element(query.elementById(id)!), + seconds * TimelineClock.ticksPerSecond, + maskId: 'first', + ); + } + + void commit(List curves) => + f.timeline.commitParameters( + sequence, + f.timeline.previewParameters(sequence, id, curves), + ); + commit(at(0).edit(const ClipMask(shape: ClipMaskShape.rectangle))); + commit(at(0).toggle(maskChannels['position']!)); + commit(at(2).edit(at(2).value.copyWith(x: .9))); + expect(at(1).value.x, closeTo(.7, 1e-9)); + expect(at(1).value.y, .5); + expect(at(2).keyed(maskChannels['position']!), isTrue); + view.undo(); + expect(at(2).value.x, .5); + view.redo(); + expect(at(2).value.x, .9); + }, + ); +} diff --git a/test/composer_document_test.dart b/test/composer_document_test.dart new file mode 100644 index 0000000..f86c6c9 --- /dev/null +++ b/test/composer_document_test.dart @@ -0,0 +1,100 @@ +import 'package:cutdex/features/assistant/composer_document.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +const _media = ComposerReference( + kind: ComposerReferenceKind.media, + projectId: 'project', + id: 'media-1', + label: '片段.mp4', +); + +void main() { + test('reference insertion adds one separating space and places the caret after it', () { + final atEnd = ComposerDocumentController(text: '看 @片段'); + addTearDown(atEnd.dispose); + atEnd.insertReference(2, 5, _media); + expect(atEnd.text, '看 @片段.mp4 '); + expect(atEnd.selection.extentOffset, atEnd.text.length); + expect(atEnd.marks.single.end, atEnd.text.length - 1); + + final beforeSpace = ComposerDocumentController(text: '@片段 后面'); + addTearDown(beforeSpace.dispose); + beforeSpace.insertReference(0, 3, _media); + expect(beforeSpace.text, '@片段.mp4 后面'); + expect( + beforeSpace.selection.extentOffset, + beforeSpace.marks.single.end + 1, + ); + }); + + test('reference insertion, atomic deletion and undo/redo', () { + final controller = ComposerDocumentController(text: '看 @片段 后面'); + addTearDown(controller.dispose); + controller.insertReference(2, 5, _media); + expect(controller.text, '看 @片段.mp4 后面'); + expect( + controller.segments.map( + (segment) => switch (segment) { + ComposerText() => null, + ComposerReferenceSegment(:final value) => value.id, + }, + ), + [null, 'media-1', null], + ); + + final mark = controller.marks.single; + controller.value = controller.value.copyWith( + text: controller.text.replaceRange(mark.end - 1, mark.end, ''), + selection: TextSelection.collapsed(offset: mark.end - 1), + ); + expect(controller.text, '看 后面'); + expect(controller.marks, isEmpty); + controller.undoDocument(); + expect(controller.text, '看 @片段.mp4 后面'); + expect(controller.marks.single.reference.id, 'media-1'); + controller.redoDocument(); + expect(controller.marks, isEmpty); + }); + + test('caret and selection cannot split a reference', () { + final controller = ComposerDocumentController(text: 'a @m z'); + addTearDown(controller.dispose); + controller.insertReference(2, 4, _media); + final mark = controller.marks.single; + controller.selection = TextSelection.collapsed(offset: mark.start + 1); + expect(controller.selection.extentOffset, mark.start); + controller.selection = TextSelection( + baseOffset: mark.start + 1, + extentOffset: mark.end + 1, + ); + expect(controller.selection.start, mark.start); + expect(controller.selection.end, mark.end + 1); + }); + + test('Chinese composing range and plain paste remain text', () { + final controller = ComposerDocumentController(); + addTearDown(controller.dispose); + controller.value = const TextEditingValue( + text: '拼', + selection: TextSelection.collapsed(offset: 1), + composing: TextRange(start: 0, end: 1), + ); + expect(controller.value.composing, const TextRange(start: 0, end: 1)); + controller.value = const TextEditingValue( + text: '图片.png', + selection: TextSelection.collapsed(offset: 6), + ); + expect(controller.marks, isEmpty); + }); + + test('invalid reference blocks send until project is restored', () { + final controller = ComposerDocumentController(text: '@'); + addTearDown(controller.dispose); + controller.insertReference(0, 1, _media); + controller.updateValidity((reference) => reference.projectId == 'other'); + expect(controller.hasInvalidReferences, isTrue); + controller.updateValidity((reference) => reference.projectId == 'project'); + expect(controller.hasInvalidReferences, isFalse); + }); +} diff --git a/test/composer_reference_validator_test.dart b/test/composer_reference_validator_test.dart new file mode 100644 index 0000000..a7301a0 --- /dev/null +++ b/test/composer_reference_validator_test.dart @@ -0,0 +1,75 @@ +import 'package:cutdex/features/assistant/composer_document.dart'; +import 'package:cutdex/features/assistant/composer_reference_validator.dart'; +import 'package:cutdex/workspace/project_state.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + const media = ComposerReference( + kind: ComposerReferenceKind.media, + projectId: 'project', + id: 'asset', + label: '旧名称.mp4', + ); + const timeline = ComposerReference( + kind: ComposerReferenceKind.timeline, + projectId: 'project', + id: 'timeline', + label: '时间线', + ); + final workspace = ProjectState( + activeProject: const RecentProject( + id: 'project', + name: '项目', + path: '/project.cutdex', + ), + assets: [ + AssetDocument( + id: 'asset', + name: '新名称.mp4', + storage: AssetStorage.external, + location: 'file:///tmp/asset', + ), + ], + timelines: const [ + TimelineSummary(id: 'timeline', name: '时间线', revision: 1), + ], + ); + + test('rename keeps the stable media ID valid, deletion invalidates it', () { + final controller = ComposerDocumentController(text: '@'); + addTearDown(controller.dispose); + controller.insertReference(0, 1, media); + ComposerReferenceValidator( + workspace: workspace, + projectId: 'project', + ).validate(controller); + expect(controller.hasInvalidReferences, isFalse); + expect(controller.marks.single.reference.label, '旧名称.mp4'); + ComposerReferenceValidator( + workspace: workspace.copyWith(assets: const []), + projectId: 'project', + ).validate(controller); + expect(controller.hasInvalidReferences, isTrue); + }); + + test( + 'draft references follow the active project without changing their IDs', + () { + final controller = ComposerDocumentController(text: '@'); + addTearDown(controller.dispose); + controller.insertReference(0, 1, timeline); + ComposerReferenceValidator( + workspace: workspace, + projectId: 'other', + ).validate(controller); + expect(controller.hasInvalidReferences, isTrue); + ComposerReferenceValidator( + workspace: workspace, + projectId: 'project', + ).validate(controller); + expect(controller.hasInvalidReferences, isFalse); + expect(controller.marks.single.reference.id, 'timeline'); + }, + ); +} diff --git a/test/composer_suggestions_test.dart b/test/composer_suggestions_test.dart new file mode 100644 index 0000000..3cabe2c --- /dev/null +++ b/test/composer_suggestions_test.dart @@ -0,0 +1,98 @@ +import 'package:cutdex/features/assistant/composer_suggestions.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex/l10n/app_localizations_en.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + test('all triggers appear at word boundaries but not in paths or email', () { + for (final trigger in ['@', '/', r'$']) { + final value = TextEditingValue( + text: 'hello $trigger片段', + selection: TextSelection.collapsed(offset: 'hello $trigger片段'.length), + ); + final query = findComposerTrigger(value, const []); + expect(query?.trigger, trigger); + expect(query?.query, '片段'); + } + for (final plain in ['foo@example.com', '/Users/name', r'price$100']) { + expect( + findComposerTrigger( + TextEditingValue( + text: plain, + selection: TextSelection.collapsed(offset: plain.length), + ), + const [], + ), + isNull, + ); + } + const chinese = '看看@片段'; + expect( + findComposerTrigger( + const TextEditingValue( + text: chinese, + selection: TextSelection.collapsed(offset: 5), + ), + const [], + )?.query, + '片段', + ); + expect( + findComposerTrigger( + const TextEditingValue( + text: '@p', + selection: TextSelection.collapsed(offset: 2), + composing: TextRange(start: 1, end: 2), + ), + const [], + ), + isNull, + ); + }); + + test( + 'built-in current-project options distinguish equal names and filter', + () { + final options = ComposerOptionCatalog.forTrigger( + '@', + l10n: AppLocalizationsEn(), + projectId: 'project', + assets: [ + AssetDocument( + id: 'asset', + name: '片段', + storage: AssetStorage.external, + location: 'file:///tmp/a', + ), + ], + timelines: [ + const TimelineSummary(id: 'timeline', name: '片段', revision: 1), + ], + ); + expect(options.length, 2); + expect(options.map((option) => option.subtitle).toSet().length, 2); + expect(filterComposerOptions(options, '片').length, 2); + expect( + ComposerOptionCatalog.forTrigger( + '/', + l10n: AppLocalizationsEn(), + projectId: 'project', + assets: const [], + timelines: const [], + ), + isEmpty, + ); + expect( + ComposerOptionCatalog.forTrigger( + r'$', + l10n: AppLocalizationsEn(), + projectId: 'project', + assets: const [], + timelines: const [], + ), + isEmpty, + ); + }, + ); +} diff --git a/test/conversation_metadata_test.dart b/test/conversation_metadata_test.dart new file mode 100644 index 0000000..a954ecb --- /dev/null +++ b/test/conversation_metadata_test.dart @@ -0,0 +1,56 @@ +import 'dart:convert'; + +import 'package:cutdex/integrations/agent/conversation_repository.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:freezed_annotation/freezed_annotation.dart'; + +void main() { + final metadata = ConversationMetadata( + id: 'conversation', + projectId: 'project', + title: 'Hello', + createdAt: DateTime.utc(2026, 10, 1, 2), + updatedAt: DateTime.utc(2026, 10, 1, 3), + providerId: 'provider', + modelId: 'model', + timelineId: 'timeline', + pending: false, + responseDurationsMs: const [null, 1234], + ); + + test('metadata persists identity, dates and missing reply durations', () { + final restored = ConversationMetadata.fromJson( + (jsonDecode(jsonEncode(metadata.toJson())) as Map) + .cast(), + ); + expect(restored, metadata); + expect(restored.copyWith(title: 'Renamed').responseDurationsMs, [ + null, + 1234, + ]); + }); + + test('new metadata stores explicit pending state and empty durations', () { + final encoded = metadata.copyWith(responseDurationsMs: []).toJson(); + expect(encoded['pending'], false); + expect(encoded['responseDurationsMs'], isEmpty); + expect(encoded.containsKey('version'), false); + }); + + for (final field in ['pending', 'responseDurationsMs']) { + test('stored metadata requires an explicit $field field', () { + final json = metadata.toJson()..remove(field); + expect( + () => ConversationMetadata.fromJson(json), + throwsA(isA()), + ); + }); + test('stored metadata rejects null $field values', () { + final json = metadata.toJson()..[field] = null; + expect( + () => ConversationMetadata.fromJson(json), + throwsA(isA()), + ); + }); + } +} diff --git a/test/conversation_repository_test.dart b/test/conversation_repository_test.dart new file mode 100644 index 0000000..56e9e13 --- /dev/null +++ b/test/conversation_repository_test.dart @@ -0,0 +1,317 @@ +import 'package:cutdex/errors/app_failure.dart'; + +import 'dart:convert'; +import 'dart:io'; + +import 'package:cutdex/integrations/agent/conversation_repository.dart'; +import 'package:cutdex_agent/cutdex_agent.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:cutdex/persistence/app_database.dart'; +import 'package:cutdex/persistence/app_settings_repositories.dart'; +import 'package:drift/native.dart'; +import 'package:path/path.dart' as p; + +void main() { + late Directory root; + late ConversationRepository repository; + + setUp(() async { + root = await Directory.systemTemp.createTemp('cutdex-conversations-'); + repository = ConversationRepository( + Directory('${root.path}/Conversations'), + ); + }); + tearDown(() async => root.delete(recursive: true)); + + Future pending([String title = 'Hello']) => + repository.begin( + projectId: 'project-1', + timelineId: 'timeline-1', + providerId: 'provider-1', + modelId: 'model-1', + title: title, + ); + + Future saveUser(ConversationMetadata item) => repository + .store(item) + .save( + SessionSnapshot( + id: item.id, + history: [AgentMessage(role: MessageRole.user, text: 'Hello')], + ), + expectedRevision: null, + ); + + test('project and empty draft create no conversation files', () async { + expect(await repository.list('project-1'), isEmpty); + expect(await repository.root.exists(), isFalse); + }); + + test( + 'first persisted user message publishes a durable conversation', + () async { + final item = await pending(); + expect(await repository.list('project-1'), isEmpty); + await saveUser(item); + final published = await repository.publish(item); + expect(published.pending, isFalse); + expect(await repository.selected('project-1'), item.id); + final reopened = ConversationRepository(repository.root); + expect((await reopened.list('project-1')).single.id, item.id); + expect( + (await reopened.store(item).read(item.id))!.history.single.text, + 'Hello', + ); + expect(await reopened.list('project-2'), isEmpty); + }, + ); + + test( + 'startup discards empty pending draft but recovers saved user message', + () async { + final empty = await pending('empty'); + final recoverable = await pending('saved'); + await saveUser(recoverable); + final reopened = ConversationRepository(repository.root); + expect((await reopened.list('project-1')).map((item) => item.id), [ + recoverable.id, + ]); + expect( + await repository.directory('project-1', empty.id).exists(), + isFalse, + ); + }, + ); + + test( + 'permanent deletion removes active history and selection only', + () async { + final first = await pending('delete'); + final second = await pending('keep'); + await saveUser(first); + await saveUser(second); + await repository.publish(second); + await repository.publish(first); + await repository.deletePermanently(first.projectId, first.id); + expect(await repository.selected(first.projectId), second.id); + expect( + await repository.directory(first.projectId, first.id).exists(), + isFalse, + ); + expect((await repository.list(first.projectId)).single.id, second.id); + expect(await repository.list(first.projectId, trash: true), isEmpty); + await repository.deletePermanently(first.projectId, first.id); + await repository.trash(second.projectId, second.id); + await repository.deletePermanently(second.projectId, second.id); + expect(await repository.list(second.projectId, trash: true), isEmpty); + }, + ); + + test( + 'trash is reversible and does not affect another conversation', + () async { + final first = await pending('first'); + final second = await pending('second'); + await saveUser(first); + await saveUser(second); + await repository.publish(first); + await repository.publish(second); + await repository.trash('project-1', first.id); + expect((await repository.list('project-1')).map((item) => item.id), [ + second.id, + ]); + expect( + (await repository.list('project-1', trash: true)).single.id, + first.id, + ); + await repository.restore('project-1', first.id); + expect((await repository.list('project-1')).length, 2); + }, + ); + + test('malformed metadata does not hide other conversations', () async { + final healthy = await pending('healthy'); + final damaged = await pending('damaged'); + await saveUser(healthy); + await repository.publish(healthy); + await File( + '${repository.directory('project-1', damaged.id).path}/metadata.json', + ).writeAsString('{"id":42}'); + final reopened = ConversationRepository(repository.root); + expect((await reopened.list('project-1')).map((item) => item.id), [ + healthy.id, + ]); + }); + + test('metadata requires a timeline identity', () async { + final item = await pending('missing timeline'); + final file = File( + '${repository.directory('project-1', item.id).path}/metadata.json', + ); + final json = + (jsonDecode(await file.readAsString()) as Map).cast() + ..remove('timelineId'); + await file.writeAsString(jsonEncode(json)); + + expect(await repository.list('project-1'), isEmpty); + await expectLater( + repository.read('project-1', item.id), + throwsA(isA()), + ); + }); + + for (final field in ['pending', 'responseDurationsMs']) { + test( + 'metadata missing $field is skipped without being rewritten', + () async { + final healthy = await pending('healthy'); + await saveUser(healthy); + await repository.publish(healthy); + final item = await pending('missing field'); + await repository.select(item.projectId, item.id); + final file = File( + '${repository.directory('project-1', item.id).path}/metadata.json', + ); + final json = (jsonDecode( + await file.readAsString(), + ) as Map).cast()..remove(field); + final stored = jsonEncode(json); + await file.writeAsString(stored); + final reopened = ConversationRepository(repository.root); + expect((await reopened.list('project-1')).map((item) => item.id), [ + healthy.id, + ]); + expect(await reopened.selected('project-1'), healthy.id); + expect(await file.readAsString(), stored); + }, + ); + } + + test('selection state requires version 1', () async { + final older = await pending('older'); + await saveUser(older); + await repository.publish(older); + await Future.delayed(const Duration(milliseconds: 2)); + final newer = await pending('newer'); + await saveUser(newer); + await repository.publish(newer); + final state = File( + '${repository.directory('project-1', older.id).parent.path}/state.json', + ); + await state.writeAsString( + jsonEncode({'version': 2, 'conversationId': older.id}), + ); + + expect(await repository.selected('project-1'), newer.id); + }); + + test( + 'unset conversation location uses Documents without creating files', + () async { + final database = AppDatabase(NativeDatabase.memory()); + addTearDown(database.close); + final settings = DriftConversationLocationSettingsRepository(database); + final location = ConversationLocation( + settings, + documentsDirectory: () async => root, + ); + final directory = await location.load(); + expect(directory.path, p.join(root.path, 'Cutdex', 'Conversations')); + expect(await directory.exists(), isFalse); + expect(await settings.load(), isNull); + }, + ); + + test( + 'selected conversation directory persists after reopening the database', + () async { + final file = File('${root.path}/app.sqlite'); + final database = AppDatabase(NativeDatabase(file)); + final item = await pending(); + await saveUser(item); + await repository.publish(item); + final location = ConversationLocation( + DriftConversationLocationSettingsRepository(database), + ); + await location.useExisting(repository.root); + await database.close(); + + final reopened = AppDatabase(NativeDatabase(file)); + addTearDown(reopened.close); + final restored = ConversationLocation( + DriftConversationLocationSettingsRepository(reopened), + ); + expect((await restored.load()).path, repository.root.path); + expect( + (await ConversationRepository(await restored.load()).list('project-1')) + .single + .id, + item.id, + ); + await expectLater( + restored.useExisting(Directory('${root.path}/missing')), + throwsA( + isA().having( + (error) => error.failure.code, + 'code', + AppErrorCode.agentLocationUnavailable, + ), + ), + ); + expect((await restored.load()).path, repository.root.path); + }, + ); + + test('location relocation verifies journals and retains source', () async { + final database = AppDatabase(NativeDatabase.memory()); + addTearDown(database.close); + final location = ConversationLocation( + DriftConversationLocationSettingsRepository(database), + ); + final item = await pending(); + await saveUser(item); + await repository.publish(item); + await repository.trash('project-1', item.id); + final target = Directory('${root.path}/Moved'); + await location.relocate(repository.root, target); + expect((await location.load()).path, target.path); + expect(await repository.root.exists(), isTrue); + expect( + (await ConversationRepository( + target, + ).list('project-1', trash: true)).single.id, + item.id, + ); + await target.delete(recursive: true); + await expectLater( + location.load(), + throwsA( + isA().having( + (error) => error.failure.code, + 'code', + AppErrorCode.agentLocationUnavailable, + ), + ), + ); + expect(await repository.root.exists(), isTrue); + }); + + test('relocation refuses a destination inside its source', () async { + final database = AppDatabase(NativeDatabase.memory()); + addTearDown(database.close); + final location = ConversationLocation( + DriftConversationLocationSettingsRepository(database), + ); + final item = await pending(); + await saveUser(item); + await repository.publish(item); + await expectLater( + location.relocate( + repository.root, + Directory('${repository.root.path}/nested/Conversations'), + ), + throwsA(isA()), + ); + expect((await repository.list('project-1')).single.id, item.id); + }); +} diff --git a/test/device_experience_test.dart b/test/device_experience_test.dart new file mode 100644 index 0000000..2fc111e --- /dev/null +++ b/test/device_experience_test.dart @@ -0,0 +1,128 @@ +import 'package:cutdex/integrations/platform/device_experience.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + const channel = MethodChannel('cutdex_native/device_info'); + tearDown(() => messenger.setMockMethodCallHandler(channel, null)); + + Future detect( + TargetPlatform platform, { + Size displaySize = const Size(390, 844), + double pixelRatio = 1, + bool web = false, + }) => DeviceExperienceDetector.detect( + platform: platform, + displaySize: displaySize, + pixelRatio: pixelRatio, + web: web, + ); + + test('desktop and web hosts do not query mobile device facts', () async { + var nativeCalls = 0; + messenger.setMockMethodCallHandler(channel, (call) async { + nativeCalls++; + return {'interfaceIdiom': 'phone'}; + }); + for (final platform in [ + TargetPlatform.macOS, + TargetPlatform.windows, + TargetPlatform.linux, + ]) { + expect(await detect(platform), DeviceExperience.desktop); + } + expect( + await detect(TargetPlatform.android, web: true), + DeviceExperience.phone, + ); + expect(nativeCalls, 0); + }); + + test('iOS device identity takes precedence over display size', () async { + for (final entry in { + 'phone': DeviceExperience.phone, + 'pad': DeviceExperience.tablet, + 'mac': DeviceExperience.desktop, + }.entries) { + messenger.setMockMethodCallHandler(channel, (call) async { + expect(call.method, 'getDeviceInfo'); + return {'interfaceIdiom': entry.key}; + }); + expect(await detect(TargetPlatform.iOS), entry.value); + } + }); + + test( + 'Android classification applies the app threshold to native bounds', + () async { + for (final entry in { + 599.5: DeviceExperience.phone, + 600.0: DeviceExperience.tablet, + 800.0: DeviceExperience.tablet, + }.entries) { + messenger.setMockMethodCallHandler( + channel, + (call) async => {'displayShortestSideDp': entry.key}, + ); + expect(await detect(TargetPlatform.android), entry.value); + } + messenger.setMockMethodCallHandler( + channel, + (call) async => {'displayShortestSideDp': 390}, + ); + expect( + await detect( + TargetPlatform.android, + displaySize: const Size(1600, 2560), + pixelRatio: 2, + ), + DeviceExperience.phone, + ); + }, + ); + + test( + 'missing platform facts fall back to full display logical size', + () async { + for (final value in [ + {}, + {'interfaceIdiom': 'pad'}, + {'displayShortestSideDp': 0}, + ]) { + messenger.setMockMethodCallHandler(channel, (call) async => value); + expect( + await detect( + TargetPlatform.android, + displaySize: const Size(1200, 1920), + pixelRatio: 2, + ), + DeviceExperience.tablet, + ); + } + messenger.setMockMethodCallHandler( + channel, + (call) async => {'displayShortestSideDp': 800}, + ); + expect(await detect(TargetPlatform.iOS), DeviceExperience.phone); + messenger.setMockMethodCallHandler(channel, (call) async { + throw PlatformException(code: 'unavailable'); + }); + expect( + await detect( + TargetPlatform.iOS, + displaySize: const Size(1170, 2532), + pixelRatio: 3, + ), + DeviceExperience.phone, + ); + messenger.setMockMethodCallHandler(channel, null); + expect( + await detect(TargetPlatform.android, displaySize: Size.zero), + DeviceExperience.phone, + ); + }, + ); +} diff --git a/test/diagnostic_settings_test.dart b/test/diagnostic_settings_test.dart new file mode 100644 index 0000000..21be81e --- /dev/null +++ b/test/diagnostic_settings_test.dart @@ -0,0 +1,142 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:cutdex/app/editor_theme.dart'; +import 'package:cutdex/diagnostics/app_diagnostics.dart'; +import 'package:cutdex/diagnostics/diagnostic_store.dart'; +import 'package:cutdex/features/settings/diagnostic_settings.dart'; +import 'package:cutdex/integrations/platform/file_picker.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex/settings/settings_operation.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +class _Picker extends AppFilePicker { + _Picker(this.destination); + final String? destination; + @override + Future pickDirectory({ + String? initialDirectory, + String? confirmButtonText, + }) async => destination; +} + +void main() { + late Directory root; + setUp(() { + root = Directory.systemTemp.createTempSync('cutdex-export-ui-'); + AppDiagnostics.instance = AppDiagnostics( + DiagnosticStore(Directory('${root.path}/logs')), + ); + }); + tearDown(() async { + await AppDiagnostics.instance?.store.flush(); + AppDiagnostics.instance = null; + await root.delete(recursive: true); + }); + Future show( + WidgetTester tester, + String? destination, + ) async { + final container = ProviderContainer( + overrides: [filePickerProvider.overrideWithValue(_Picker(destination))], + ); + addTearDown(container.dispose); + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: MaterialApp( + theme: EditorTheme.penLight, + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: const Scaffold(body: DiagnosticSettings()), + ), + ), + ); + await tester.pumpAndSettle(); + return container; + } + + Future click(WidgetTester tester, ProviderContainer container) async { + await tester.runAsync(() async { + await tester.tap(find.byKey(const Key('export-diagnostics'))); + for ( + var i = 0; + i < 2000 && + container + .read(settingsOperationProvider('diagnosticsExport')) + .isLoading; + i++ + ) { + await Future.delayed(const Duration(milliseconds: 1)); + } + expect( + container + .read(settingsOperationProvider('diagnosticsExport')) + .isLoading, + isFalse, + ); + }); + await tester.pumpAndSettle(); + } + + testWidgets('exports a diagnostic package into the selected directory', ( + tester, + ) async { + final container = await show(tester, '${root.path}/export'); + await tester.runAsync(() async { + AppDiagnostics.report( + const DiagnosticEvent( + component: 'preview', + operation: 'test', + error: 'Bearer PRIVATE', + ), + ); + await AppDiagnostics.instance!.store.flush(); + }); + await click(tester, container); + expect(find.text('Diagnostic package saved.'), findsOneWidget); + final directory = Directory('${root.path}/export'); + final files = directory.listSync().cast().toList(); + expect(files, hasLength(1)); + final contents = files.single.readAsStringSync(); + expect(jsonDecode(contents)['events'], hasLength(1)); + expect(contents, isNot(contains('PRIVATE'))); + expect(tester.takeException(), isNull); + }); + + testWidgets( + 'canceling directory selection leaves no success message or export', + (tester) async { + final container = await show(tester, null); + await click(tester, container); + expect(find.text('Diagnostic package saved.'), findsNothing); + expect( + container.read(settingsOperationProvider('diagnosticsExport')).hasError, + isFalse, + ); + expect(root.listSync(), isEmpty); + }, + ); + + testWidgets('export failures show feedback and leave the button usable', ( + tester, + ) async { + final blocked = File('${root.path}/blocked')..writeAsStringSync('file'); + final container = await show(tester, blocked.path); + await click(tester, container); + expect( + find.text('Could not export diagnostics. Please try again.'), + findsOneWidget, + ); + expect( + tester + .widget(find.byKey(const Key('export-diagnostics'))) + .onPressed, + isNotNull, + ); + expect(tester.takeException(), isNull); + }); +} diff --git a/test/diagnostics/agent_request_diagnostics_test.dart b/test/diagnostics/agent_request_diagnostics_test.dart new file mode 100644 index 0000000..fe39616 --- /dev/null +++ b/test/diagnostics/agent_request_diagnostics_test.dart @@ -0,0 +1,44 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:cutdex/diagnostics/agent_request_diagnostics.dart'; +import 'package:cutdex/diagnostics/request_report.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + test('concurrent request publication retains the most recent 20 complete reports', () async { + final root = await Directory.systemTemp.createTemp( + 'cutdex-request-retention-', + ); + addTearDown(() => root.delete(recursive: true)); + await Future.wait( + List.generate( + 25, + (index) => AgentRequestDiagnostics.persist( + root, + RequestReport( + outcome: 'completed', + elapsedUs: index, + frames: const RequestFrameReport( + count: 0, + slowFrames: 0, + maxBuildUs: 0, + maxRasterUs: 0, + maxTimerDelayUs: 0, + ), + runs: const [], + ), + ), + ), + ); + final directory = Directory('${root.path}/diagnostics'); + final files = await directory.list().cast().toList(); + expect(files, hasLength(20)); + final reports = await Future.wait( + files.map((file) async => jsonDecode(await file.readAsString()) as Map), + ); + final retained = reports.map((r) => r['elapsedUs'] as int).toList()..sort(); + expect(retained, orderedEquals(List.generate(20, (i) => i + 5))); + expect(files.any((f) => f.path.endsWith('.tmp')), isFalse); + }); +} diff --git a/test/diagnostics/app_diagnostics_test.dart b/test/diagnostics/app_diagnostics_test.dart new file mode 100644 index 0000000..24b142d --- /dev/null +++ b/test/diagnostics/app_diagnostics_test.dart @@ -0,0 +1,189 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:cutdex/diagnostics/app_diagnostics.dart'; +import 'package:cutdex/diagnostics/diagnostic_store.dart'; +import 'package:cutdex/diagnostics/request_report.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late Directory root; + late AppDiagnostics diagnostics; + setUp(() async { + root = await Directory.systemTemp.createTemp('cutdex-app-diagnostics-'); + diagnostics = AppDiagnostics( + DiagnosticStore(Directory('${root.path}/logs')), + sessionId: 'session', + ); + AppDiagnostics.instance = diagnostics; + }); + tearDown(() async { + AppDiagnostics.instance = null; + await diagnostics.store.flush(); + await root.delete(recursive: true); + }); + Future> exported() async => jsonDecode( + await (await diagnostics.export(Directory('${root.path}/out'))) + .readAsString(), + ) as Map; + + test( + 'SDK events and Agent reports share request and session identifiers', + () async { + const requestId = '12345678-1234-1234-1234-123456789abc'; + await withDiagnosticContext({'requestId': requestId}, () async { + AppDiagnostics.failure( + 'preview', + 'start', + const RuntimeException( + code: 'failed', + message: 'decode', + domain: 'playback', + details: {'nativeCode': '-11841'}, + ), + StackTrace.fromString('ORIGINAL STACK'), + ); + await diagnostics.request( + const RequestReport( + outcome: 'failed', + elapsedUs: 1, + frames: RequestFrameReport( + count: 0, + slowFrames: 0, + maxBuildUs: 0, + maxRasterUs: 0, + maxTimerDelayUs: 0, + ), + runs: [], + ), + requestId, + ); + }); + final report = await exported(); + final event = (report['events'] as List).single; + expect(event['context']['requestId'], requestId); + expect(event['sessionId'], 'session'); + expect(event['stackTrace'], 'ORIGINAL STACK'); + expect(event['error']['nativeDetails']['nativeCode'], '-11841'); + expect((report['requests'] as List).single['requestId'], requestId); + expect((report['requests'] as List).single['sessionId'], 'session'); + expect((report['requests'] as List).single['at'], isNotNull); + }, + ); + + test( + 'SDK error severity uses reserved capacity without synchronous writes', + () async { + diagnostics = AppDiagnostics( + DiagnosticStore( + Directory('${root.path}/reserved'), + maxPending: 8, + errorReserveRecords: 2, + flushInterval: const Duration(days: 1), + ), + ); + AppDiagnostics.instance = diagnostics; + for (var i = 0; i < 8; i++) { + AppDiagnostics.report( + const DiagnosticEvent( + component: 'editor', + operation: 'split', + level: DiagnosticSeverity.info, + ), + ); + } + AppDiagnostics.failure( + 'editor', + 'setCaption', + StateError('failed'), + StackTrace.fromString('PROPERTY ERROR STACK'), + ); + expect(File('${root.path}/reserved/fatal.jsonl').existsSync(), isFalse); + final events = (await exported())['events'] as List; + final error = events.singleWhere((e) => e['level'] == 'error'); + expect(error['operation'], 'setCaption'); + expect(error['stackTrace'], 'PROPERTY ERROR STACK'); + expect(diagnostics.store.dropped, 2); + expect(diagnostics.store.droppedErrors, 0); + }, + ); + + test( + 'global handlers record errors and preserve existing handler behavior', + () async { + final flutter = FlutterError.onError; + final platform = PlatformDispatcher.instance.onError; + addTearDown(() { + FlutterError.onError = flutter; + PlatformDispatcher.instance.onError = platform; + }); + var flutterCalls = 0, platformCalls = 0; + FlutterError.onError = (_) { + flutterCalls++; + }; + PlatformDispatcher.instance.onError = (_, _) { + platformCalls++; + return true; + }; + diagnostics.installErrorHandlers(); + FlutterError.onError!( + FlutterErrorDetails( + exception: StateError('framework'), + stack: StackTrace.current, + ), + ); + expect( + PlatformDispatcher.instance.onError!( + StateError('async'), + StackTrace.current, + ), + isTrue, + ); + expect(File('${root.path}/logs/fatal.jsonl').existsSync(), isTrue); + final report = await exported(); + expect(flutterCalls, 1); + expect(platformCalls, 1); + expect(report['events'], hasLength(2)); + }, + ); + + test('application metadata reads the installed host version', () async { + const channel = MethodChannel('cutdex_native/device_info'); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (call) async { + expect(call.method, 'getApplicationInfo'); + return {'appVersion': '2.0.0', 'appBuild': '42'}; + }); + addTearDown( + () => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, null), + ); + await diagnostics.readApplicationInfo(); + expect((await exported())['metadata']['appVersion'], '2.0.0'); + expect(diagnostics.metadata['appBuild'], '42'); + }); + + test( + 'format and process failures do not serialize source or arguments', + () async { + AppDiagnostics.failure( + 'test', + 'parse', + const FormatException('Invalid JSON', 'PRIVATE BODY'), + StackTrace.current, + ); + AppDiagnostics.failure( + 'test', + 'spawn', + const ProcessException('/worker', ['PRIVATE PROMPT'], 'Failed', 1), + StackTrace.current, + ); + final encoded = jsonEncode(await exported()); + expect(encoded, isNot(contains('PRIVATE'))); + }, + ); +} diff --git a/test/diagnostics/diagnostic_redactor_test.dart b/test/diagnostics/diagnostic_redactor_test.dart new file mode 100644 index 0000000..5bf776e --- /dev/null +++ b/test/diagnostics/diagnostic_redactor_test.dart @@ -0,0 +1,65 @@ +import 'package:cutdex/diagnostics/diagnostic_redactor.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + test('redacts nested credentials, content, paths and URLs while preserving metrics', () { + final redactor = DiagnosticRedactor(); + final safe = + redactor.value({ + 'nested': { + 'api_key': 'secret', + 'accessToken': 'secret', + 'prompt': 'private text', + }, + 'message': + 'sk-12345abc Bearer abc123 https://u:p@host/path?q=secret', + 'unix': '/Users/person/Media/private.mov', + 'windows': r'C:\Users\person\Media\private.mov', + 'inputTokens': 25, + 'outputTokens': 10, + 'nativeCode': '-11841', + })! + as Map; + expect(safe['nested'], { + 'api_key': '[redacted]', + 'accessToken': '[redacted]', + 'prompt': '[redacted]', + }); + expect(safe['message'], isNot(contains('abc123'))); + expect(safe['message'], isNot(contains('q=secret'))); + expect(safe['unix'], '[local-path]'); + expect(safe['windows'], '[local-path]'); + expect(safe['inputTokens'], 25); + expect(safe['outputTokens'], 10); + expect(safe['nativeCode'], '-11841'); + }); + + test('marker fast paths preserve every existing redaction rule', () { + final redactor = DiagnosticRedactor(); + final cases = { + 'identifier-123': 'identifier-123', + 'BEARER credential': 'Bearer [redacted]', + 'sk-credential': '[redacted]', + 'PASSWORD=credential': 'PASSWORD=[redacted]', + 'api-key: credential': 'api-key=[redacted]', + 'https://user:credential@example.com/path?q=credential': + 'http[local-path]', + 'credential@private.example': '[email]', + r'C:\Users\person\credential.mov': '[local-path]', + r'\\server\share\credential.mov': '[local-path]', + '/Users/person/credential.mov': '[local-path]', + }; + for (final entry in cases.entries) { + expect(redactor.text(entry.key), entry.value); + } + }); + + test('bounds recursion, strings and lists', () { + final redactor = DiagnosticRedactor(); + expect(redactor.text('x' * 10000).length, lessThan(8300)); + expect(redactor.value(List.filled(10000, 1)), hasLength(2048)); + final cyclic = {}; + cyclic['self'] = cyclic; + expect(redactor.value(cyclic).toString(), contains('[truncated]')); + }); +} diff --git a/test/diagnostics/diagnostic_store_test.dart b/test/diagnostics/diagnostic_store_test.dart new file mode 100644 index 0000000..9b089d4 --- /dev/null +++ b/test/diagnostics/diagnostic_store_test.dart @@ -0,0 +1,359 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:cutdex/diagnostics/diagnostic_store.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:uuid/uuid.dart'; + +void main() { + late Directory root; + setUp(() async { + root = await Directory.systemTemp.createTemp('cutdex-diagnostics-'); + }); + tearDown(() => root.delete(recursive: true)); + DiagnosticStore store({int pending = 256}) => DiagnosticStore( + Directory('${root.path}/logs'), + maxFileBytes: 1024, + fileCount: 3, + maxPending: pending, + ); + Future> bundle(DiagnosticStore value) async => + jsonDecode( + await (await value.export( + Directory('${root.path}/out'), + const {}, + )).readAsString(), + ) as Map; + + test( + 'ordinary records wait for the deadline then share one durable append', + () async { + final value = DiagnosticStore( + Directory('${root.path}/logs'), + flushInterval: const Duration(milliseconds: 20), + ); + for (var i = 0; i < 8; i++) { + value.record({'index': i}); + } + expect( + File('${value.directory.path}/events-0.jsonl').existsSync(), + isFalse, + ); + final deadline = Stopwatch()..start(); + while (value.eventWriteBatches == 0 && + deadline.elapsedMilliseconds < 5000) { + await Future.delayed(const Duration(milliseconds: 5)); + } + expect(value.eventWriteBatches, 1); + await value.flush(); + expect(value.eventFlushes, 1); + expect(value.pendingRecords, 0); + expect(value.pendingEventBytes, 0); + expect((await bundle(value))['events'], hasLength(8)); + }, + ); + + test( + 'count threshold writes early and explicit flush drains the remaining tail', + () async { + final value = DiagnosticStore( + Directory('${root.path}/logs'), + batchSize: 32, + flushInterval: const Duration(days: 1), + ); + for (var i = 0; i < 32; i++) { + value.record({'index': i}); + } + final deadline = Stopwatch()..start(); + while (value.pendingRecords != 0 && deadline.elapsedMilliseconds < 5000) { + await Future.delayed(const Duration(milliseconds: 5)); + } + expect(value.pendingRecords, 0); + expect(value.eventFlushes, 1); + value.record({'index': 32}); + await value.flush(); + expect(value.eventFlushes, 2); + expect((await bundle(value))['events'], hasLength(33)); + }, + ); + + test( + 'encoded-byte threshold writes early even below the record count', + () async { + final value = DiagnosticStore( + Directory('${root.path}/logs'), + batchSize: 100, + maxBatchBytes: 100, + flushInterval: const Duration(days: 1), + ); + value.record({'index': 1, 'message': 'x' * 100}); + final deadline = Stopwatch()..start(); + while (value.pendingRecords != 0 && deadline.elapsedMilliseconds < 5000) { + await Future.delayed(const Duration(milliseconds: 5)); + } + expect(value.pendingRecords, 0); + expect(value.eventFlushes, 1); + expect((await bundle(value))['events'], hasLength(1)); + }, + ); + + test( + 'byte budget bounds accepted events and still allows immediate fatal logs', + () async { + final value = DiagnosticStore( + Directory('${root.path}/logs'), + maxPendingBytes: 100, + errorReserveBytes: 0, + ); + value.record({'index': 1, 'message': 'x' * 50}); + value.record({'index': 2, 'message': 'x' * 50}); + expect(value.pendingRecords, 1); + expect(value.pendingEventBytes, lessThanOrEqualTo(100)); + expect(value.dropped, 1); + value.record({'fatal': true}, immediate: true); + expect( + File('${value.directory.path}/fatal.jsonl').readAsStringSync(), + contains('fatal'), + ); + final report = await bundle(value); + expect(report['events'], hasLength(2)); + expect(value.pendingRecords, 0); + expect(value.pendingEventBytes, 0); + }, + ); + + test( + 'full queues skip formatting instead of spending CPU on discarded records', + () async { + final value = store(pending: 1); + value.record({'index': 1}); + final probe = _FormattingProbe(); + value.record({'value': probe}); + expect(probe.calls, 0); + expect(value.dropped, 1); + await value.flush(); + }, + ); + + test( + 'error slots survive an information burst including queued writes', + () async { + final value = DiagnosticStore( + Directory('${root.path}/logs'), + maxPending: 8, + errorReserveRecords: 2, + batchSize: 1, + ); + for (var i = 0; i < 8; i++) { + value.record({'level': 'info', 'index': i}); + } + final rejectedRequest = value.saveRequest({ + 'index': 1, + }, const Uuid().v4()); + // The rejected request must not consume either reserved slot. + for (var i = 0; i < 3; i++) { + value.record({'level': 'error', 'index': i}); + } + expect(value.pendingRecords, 8); + expect(value.dropped, 4); + expect(value.droppedErrors, 1); + await rejectedRequest; + final report = await bundle(value); + final events = report['events'] as List; + expect(events.where((e) => e['level'] == 'info'), hasLength(6)); + expect(events.where((e) => e['level'] == 'error'), hasLength(2)); + expect(report['requests'], isEmpty); + expect(report['storage']['droppedErrors'], 1); + expect(value.pendingRecords, 0); + expect(value.pendingEventBytes, 0); + }, + ); + + test( + 'byte reserve admits errors after warning traffic reaches its limit', + () async { + final value = DiagnosticStore( + Directory('${root.path}/logs'), + maxPendingBytes: 1000, + errorReserveBytes: 500, + flushInterval: const Duration(days: 1), + ); + value.record({'level': 'warning', 'message': 'x' * 300}); + value.record({'level': 'warning', 'message': 'x' * 300}); + value.record({'level': 'error', 'message': 'x' * 300}); + value.record({'level': 'error', 'message': 'x' * 500}); + expect(value.pendingRecords, 2); + expect(value.pendingEventBytes, lessThanOrEqualTo(1000)); + expect(value.dropped, 2); + expect(value.droppedErrors, 1); + value.record({'level': 'error', 'fatal': true}, immediate: true); + final events = (await bundle(value))['events'] as List; + expect(events, hasLength(3)); + expect(events.where((e) => e['level'] == 'error'), hasLength(2)); + expect(value.pendingEventBytes, 0); + }, + ); + + test( + 'buffered values are copied and redacted before callers can mutate them', + () async { + final value = store(); + final input = { + 'context': {'name': 'original', 'apiKey': 'PRIVATE'}, + }; + value.record(input); + input['context']!['name'] = 'changed'; + input['context']!['apiKey'] = 'MUTATED SECRET'; + final event = ((await bundle(value))['events'] as List).single; + expect(event['context']['name'], 'original'); + expect(event['context']['apiKey'], '[redacted]'); + }, + ); + + test('requests and exports drain earlier buffered logs without waiting for the timer', () async { + final value = DiagnosticStore( + Directory('${root.path}/logs'), + flushInterval: const Duration(days: 1), + ); + value.record({'index': 1}); + await value.saveRequest({'index': 1}, const Uuid().v4()); + expect(value.pendingRecords, 0); + value.record({'index': 2}); + final report = await bundle(value); + expect((report['events'] as List).map((e) => e['index']), [1, 2]); + expect(report['requests'], hasLength(1)); + expect(value.pendingRecords, 0); + }); + + test( + 'concurrent writes rotate within bounds and retain newest complete records', + () async { + final value = store(); + for (var i = 0; i < 30; i++) { + value.record({'index': i, 'message': 'x' * 250}); + } + await value.flush(); + final files = await value.directory.list().cast().toList(); + expect(files.length, 3); + for (final file in files) { + expect(await file.length(), lessThanOrEqualTo(1024)); + } + final events = (await bundle(value))['events'] as List; + expect(events.last['index'], 29); + expect( + events.map((e) => e['index']).toList(), + orderedEquals( + List.generate(events.length, (i) => 30 - events.length + i), + ), + ); + }, + ); + + test( + 'queue overload drops predictably without blocking or corrupting output', + () async { + final value = store(pending: 2); + for (var i = 0; i < 10; i++) { + value.record({'index': i}); + } + await value.flush(); + expect(value.dropped, 8); + expect((await bundle(value))['events'], hasLength(2)); + }, + ); + + test( + 'unwritable store retains bounded fallback events that can be exported', + () async { + final blocked = File('${root.path}/blocked')..writeAsStringSync('file'); + final value = DiagnosticStore(Directory(blocked.path)); + for (var i = 0; i < 120; i++) { + value.record({'index': i}); + } + await value.flush(); + final report = await bundle(value); + expect(value.writeFailures, 120); + expect(report['fallbackEvents'], hasLength(100)); + expect((report['fallbackEvents'] as List).last['index'], 119); + expect(jsonEncode(report), isNot(contains(root.path))); + }, + ); + + test( + 'request retention keeps the latest 20 and excludes conversation files', + () async { + final value = store(); + await Future.wait( + List.generate( + 25, + (i) => value.saveRequest({'index': i}, const Uuid().v4()), + ), + ); + File('${value.directory.path}/conversation.json') + .writeAsStringSync('PRIVATE CONVERSATION'); + final report = await bundle(value); + final requests = report['requests'] as List; + expect(requests, hasLength(20)); + expect( + requests.map((r) => r['index']), + orderedEquals(List.generate(20, (i) => 24 - i)), + ); + expect(jsonEncode(report), isNot(contains('PRIVATE CONVERSATION'))); + }, + ); + + test('exports redact secrets and skip an interrupted final append', () async { + final value = store(); + value.record({ + 'token': 'PRIVATE TOKEN', + 'url': 'https://user:secret@example.com/test?api_key=PRIVATE', + 'path': '/Users/person/private.mov', + 'message': 'Bearer SECRET', + }); + await value.flush(); + File('${value.directory.path}/events-0.jsonl') + .writeAsStringSync('{unfinished', mode: FileMode.append); + value.record({'operation': 'afterInterruptedAppend'}); + final report = await bundle(value); + expect(report['events'], hasLength(2)); + final encoded = jsonEncode(report); + for (final secret in ['PRIVATE', 'SECRET', 'private.mov', 'user:secret']) { + expect(encoded, isNot(contains(secret))); + } + }); + + test('failed export does not poison subsequent writes or exports', () async { + final value = store(); + final blocked = File('${root.path}/blocked')..writeAsStringSync('file'); + await expectLater( + value.export(Directory(blocked.path), const {}), + throwsA(isA()), + ); + value.record({'operation': 'afterExportFailure'}); + expect((await bundle(value))['events'], hasLength(1)); + }); + + test( + 'uncaught fatal records are flushed synchronously and bounded separately', + () async { + final value = store(); + for (var i = 0; i < 8; i++) { + value.record({'index': i, 'error': 'x' * 250}, immediate: true); + } + final file = File('${value.directory.path}/fatal.jsonl'); + expect(file.existsSync(), isTrue); + expect(file.lengthSync(), lessThanOrEqualTo(1024)); + final events = (await bundle(value))['events'] as List; + expect(events.last['index'], 7); + }, + ); +} + +class _FormattingProbe { + int calls = 0; + @override + String toString() { + calls++; + return 'value'; + } +} diff --git a/test/diagnostics/edit_operation_diagnostics_test.dart b/test/diagnostics/edit_operation_diagnostics_test.dart new file mode 100644 index 0000000..2cca77c --- /dev/null +++ b/test/diagnostics/edit_operation_diagnostics_test.dart @@ -0,0 +1,424 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:cutdex/app/editor_theme.dart'; +import 'package:cutdex/diagnostics/app_diagnostics.dart'; +import 'package:cutdex/features/properties/speed_properties.dart'; +import 'package:cutdex/features/timeline/timeline_speed_editor.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_ui/widgets.dart'; +import 'package:flutter/material.dart'; +import 'package:cutdex/diagnostics/diagnostic_store.dart'; +import 'package:cutdex/workspace/timeline_session.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:cutdex_sdk/timeline/layout.dart'; +import 'package:flutter_test/flutter_test.dart'; + +final sequence = SequenceId('sequence'); + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late Directory root; + late ProjectFile project; + late _FaultingSession session; + late AppDiagnostics diagnostics; + setUp(() async { + root = await Directory.systemTemp.createTemp('cutdex-edit-log-'); + diagnostics = AppDiagnostics( + DiagnosticStore(Directory('${root.path}/logs')), + ); + project = await ProjectFile.create( + Directory('${root.path}/P.cutdex'), + name: 'P', + ); + await project.saveTimeline( + TimelineDocument( + id: 'timeline', + name: 'Private project name', + defaultSequenceId: sequence, + payloads: [PayloadDocument(id: 'video', type: 'video')], + sequences: [ + TimelineDto( + id: sequence, + format: TimelineFormat.fps30, + primaryStorylineId: StorylineId('primary'), + storylines: [ + StorylineDto( + id: StorylineId('primary'), + elementIds: [ElementId('clip')], + ), + ], + elements: [ + ElementDto( + id: ElementId('clip'), + name: 'Private clip name', + payloadRef: PayloadRef('video'), + structure: ElementStructure.content, + duration: RationalTime.seconds(10), + sourceRange: TimeRange( + start: RationalTime.zero, + duration: RationalTime.seconds(10), + ), + mediaRange: TimeRange( + start: RationalTime.zero, + duration: RationalTime.seconds(10), + ), + ), + ], + ), + ], + ), + ); + session = _FaultingSession( + document: await project.loadTimeline('timeline'), + persistence: await project.openTimelineSaveSession('timeline'), + diagnostics: diagnostics.event, + ); + }); + tearDown(() async { + session.fail = false; + session.failPreparation = false; + await session.close(); + await project.close(); + await diagnostics.store.flush(); + await root.delete(recursive: true); + }); + + Future> events() async { + final output = await diagnostics.export(Directory('${root.path}/out')); + return (jsonDecode(await output.readAsString()) as Map)['events'] as List; + } + + for (final operation in [ + 'setAudio', + 'setTransform', + 'editMask', + 'editKeyframes', + ]) { + test( + 'direct $operation property rejection exports its original context', + () async { + final before = session.version; + expect(() { + switch (operation) { + case 'setAudio': + session.commands.setAudio( + sequence: sequence, + clip: ElementId('missing'), + db: 1, + ); + case 'setTransform': + session.commands.setTransform( + sequence: sequence, + clip: ElementId('missing'), + tick: 10, + change: (v) => v, + ); + case 'editMask': + session.commands.applyEdit( + sequence, + EditMask( + clipId: 'missing', + at: CommandTime(1, 1), + action: MaskAction.add, + ), + ); + default: + session.commands.editKeyframeChannel( + sequence: sequence, + clip: ElementId('missing'), + tick: 10, + parameterIds: [ClipAudioGain.gainId], + ); + } + }, throwsA(isA())); + final event = (await events()).single; + expect(event['operation'], operation); + expect(event['context']['clipIds'], ['missing']); + expect(event['context']['errorCode'], 'missingClip'); + expect(event['context']['operationId'], isNotEmpty); + expect(event['stackTrace'], isNotEmpty); + expect(session.version, before); + }, + ); + } + + test( + 'nested property and typed command failure share one operation ID', + () async { + await expectLater( + session.executeCommand( + sequence, + const SetClipAudio(clipId: 'missing', db: 1), + operationId: 'typed-audio', + ), + throwsA(isA()), + ); + final event = (await events()).single; + expect(event['context']['operationId'], 'typed-audio'); + expect(event['context']['entryPoint'], 'command'); + expect(event['context']['clipIds'], ['missing']); + }, + ); + + Widget surface(Widget child) => MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + theme: EditorTheme.penLight, + home: Scaffold(body: SizedBox(width: 800, height: 600, child: child)), + ); + + testWidgets( + 'speed slider logs the retained preview error only at final commit', + (tester) async { + final view = session.view(sequence); + final before = session.version; + await tester.pumpWidget( + surface( + SpeedProperties( + session: session, + sequence: sequence, + clip: ElementId('clip'), + ), + ), + ); + AppSlider slider() => + tester.widget(find.byKey(const Key('clip-speed-slider'))); + slider().onChangeStart!(0.5); + session.failPreparation = true; + slider().onChanged!(0.5); + slider().onChanged!(0.6); + expect(await tester.runAsync(events), isEmpty); + slider().onChangeEnd!(0.6); + session.failPreparation = false; + final event = (await tester.runAsync(events))!.single; + expect(event['operation'], 'setSpeed'); + expect(event['context']['clipIds'], ['clip']); + expect(event['stackTrace'], 'ORIGINAL SPEED PREVIEW STACK'); + expect(session.version, before); + expect( + view.version.kernelVersion, + same(session.persistence.timeline(sequence).current), + ); + await tester.pumpWidget(const SizedBox.shrink()); + }, + ); + + testWidgets( + 'recovered speed preview commits without logging an earlier failure', + (tester) async { + session.view(sequence); + await tester.pumpWidget( + surface( + SpeedProperties( + session: session, + sequence: sequence, + clip: ElementId('clip'), + ), + ), + ); + AppSlider slider() => + tester.widget(find.byKey(const Key('clip-speed-slider'))); + slider().onChangeStart!(0.5); + session.failPreparation = true; + slider().onChanged!(0.5); + session.failPreparation = false; + slider().onChanged!(0.6); + slider().onChangeEnd!(0.6); + final exported = (await tester.runAsync(events))!; + expect(exported.where((e) => e['level'] == 'error'), isEmpty); + final committed = exported.singleWhere( + (e) => e['context']['outcome'] == 'committed', + ); + expect(committed['operation'], 'setSpeed'); + expect(committed['context']['clipIds'], ['clip']); + await tester.runAsync(() => session.flush()); + expect( + session.editDiagnosticContext['operationId'], + committed['context']['operationId'], + ); + await tester.pumpWidget(const SizedBox.shrink()); + }, + ); + + testWidgets('speed segment drag logs a preview error once when released', ( + tester, + ) async { + final view = session.view(sequence); + session.setCustomSpeedEnabled(sequence, ElementId('clip'), true); + final before = session.version; + await tester.pumpWidget( + surface( + TimelineSpeedEditor( + session: session, + sequence: sequence, + controller: view, + ), + ), + ); + final handle = tester.widget( + find.byKey(const ValueKey('speed-segment-handle-0')), + ); + handle.onPanStart!(DragStartDetails()); + session.failPreparation = true; + handle.onPanUpdate!( + DragUpdateDetails( + delta: const Offset(10, 0), + globalPosition: Offset.zero, + ), + ); + handle.onPanUpdate!( + DragUpdateDetails( + delta: const Offset(10, 0), + globalPosition: Offset.zero, + ), + ); + expect(await tester.runAsync(events), isEmpty); + handle.onPanEnd!(DragEndDetails()); + session.failPreparation = false; + final event = (await tester.runAsync(events))!.single; + expect(event['operation'], 'setSpeedSegment'); + expect(event['context']['clipIds'], ['clip']); + expect(event['context']['segmentIndex'], 0); + expect(event['stackTrace'], 'ORIGINAL SPEED PREVIEW STACK'); + expect(session.version, before); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + for (final operation in ['split', 'trimLeft', 'trimRight', 'delete']) { + test( + 'handled $operation rejection reaches the exported diagnostic package', + () async { + final controller = session.view(sequence); + final query = controller.version.kernelVersion.query(); + if (operation == 'delete') { + controller.setSelection([query.elementById(ElementId('clip'))!]); + } + controller.seekTo(5 * TimelineClock.ticksPerSecond); + final before = session.version; + session.fail = true; + final result = switch (operation) { + 'split' => controller.cutSelectionAtPlayhead(), + 'trimLeft' => controller.trimLeftAtPlayhead(), + 'trimRight' => controller.trimRightAtPlayhead(), + _ => controller.deleteSelection(), + }; + expect(result, isFalse); + expect( + controller.commandRejection, + contains('injected editing failure'), + ); + expect(session.version, before); + final event = (await events()).single; + expect( + event['operation'], + operation.startsWith('trim') ? 'trim' : operation, + ); + expect(event['context']['clipIds'], ['clip']); + expect( + event['context']['playheadTick'], + 5 * TimelineClock.ticksPerSecond, + ); + expect(event['context']['versionBefore'], before); + expect(event['context']['versionAfter'], before); + expect(event['context']['operationId'], isNotEmpty); + expect(event['context']['timelineId'], 'timeline'); + expect(event['stackTrace'], 'ORIGINAL MANUAL EDIT STACK'); + expect(jsonEncode(event), isNot(contains('Private'))); + }, + ); + } + + test( + 'drag commit failure keeps move context and cleans up the gesture', + () async { + final controller = session.view(sequence); + final viewport = TimelineViewportRect(width: 800, height: 400); + final y = + controller.geometry.primaryTop + + controller.geometry.primaryHeight / 2; + expect( + controller.beginDrag(viewport: viewport, position: Offset(100, y)), + isTrue, + ); + session.fail = true; + expect( + () => + controller.finishDrag(viewport: viewport, position: Offset(160, y)), + throwsStateError, + ); + expect(controller.isDragging, isFalse); + final event = (await events()).single; + expect(event['operation'], 'move'); + expect(event['context']['clipIds'], ['clip']); + expect(event['stackTrace'], 'ORIGINAL MANUAL EDIT STACK'); + }, + ); + + test( + 'undo failure is observed without changing the authored history', + () async { + final controller = session.view(sequence); + controller.seekTo(5 * TimelineClock.ticksPerSecond); + expect(controller.cutSelectionAtPlayhead(), isTrue); + final before = session.version; + session.fail = true; + expect(controller.undo, throwsStateError); + expect(session.version, before); + final recorded = await events(); + final committed = recorded.singleWhere( + (e) => e['context']['outcome'] == 'committed', + ); + expect(committed['operation'], 'split'); + final error = recorded.singleWhere((e) => e['error'] != null); + expect(error['operation'], 'undo'); + expect( + error['context']['operationId'], + isNot(committed['context']['operationId']), + ); + }, + ); + + test( + 'a no-op at the clip boundary does not report a false failure', + () async { + final controller = session.view(sequence); + controller.seekTo(0); + expect(controller.cutSelectionAtPlayhead(), isFalse); + expect(await events(), isEmpty); + }, + ); +} + +class _FaultingSession extends EditorTimelineSession { + _FaultingSession({ + required super.document, + required super.persistence, + super.diagnostics, + }); + bool fail = false; + bool failPreparation = false; + @override + TimelineLayoutEngine layout(SequenceId sequenceId) { + if (failPreparation) { + Error.throwWithStackTrace( + StateError('injected speed preparation failure'), + StackTrace.fromString('ORIGINAL SPEED PREVIEW STACK'), + ); + } + return super.layout(sequenceId); + } + + @override + T commit(SequenceId? sequence, T Function() action) { + if (fail) { + Error.throwWithStackTrace( + StateError('injected editing failure'), + StackTrace.fromString('ORIGINAL MANUAL EDIT STACK'), + ); + } + return super.commit(sequence, action); + } +} diff --git a/test/diagnostics/request_report_test.dart b/test/diagnostics/request_report_test.dart new file mode 100644 index 0000000..e2cfc56 --- /dev/null +++ b/test/diagnostics/request_report_test.dart @@ -0,0 +1,34 @@ +import 'dart:convert'; + +import 'package:cutdex/diagnostics/request_report.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + test('diagnostics preserve the disk schema and nested run payloads', () { + final report = RequestReport( + outcome: 'completed', + elapsedUs: 20, + preparationUs: 5, + frames: const RequestFrameReport( + count: 2, + slowFrames: 1, + maxBuildUs: 17, + maxRasterUs: 8, + maxTimerDelayUs: 3, + ), + runs: const [ + { + 'events': [ + {'type': 'request', 'elapsedUs': 4}, + ], + }, + ], + at: DateTime.utc(2026, 10, 2), + ); + final json = + jsonDecode(jsonEncode(report.toJson())) as Map; + expect((json['frames'] as Map)['over16ms'], 1); + expect(json['version'], 1); + expect(RequestReport.fromJson(json), report); + }); +} diff --git a/test/editor_acceptance_test.dart b/test/editor_acceptance_test.dart new file mode 100644 index 0000000..869804e --- /dev/null +++ b/test/editor_acceptance_test.dart @@ -0,0 +1,528 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:cutdex/integrations/agent/editor_acceptance.dart'; +import 'package:cutdex/integrations/agent/agent_prompt_policy.dart'; +import 'package:cutdex/integrations/agent/editor_agent_tools.dart'; +import 'package:cutdex/integrations/editor_command_host.dart'; +import 'package:cutdex/workspace/timeline_session.dart'; +import 'package:cutdex_agent/cutdex_agent.dart'; +import 'package:cutdex_agent/io.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'transcription_tools_test.dart' show Media; + +class _Model implements ModelAdapter { + _Model(this.action); + final Future Function(ModelRequest, int) action; + int requests = 0; + @override + Stream stream(ModelRequest request, CancellationToken c) async* { + yield await action(request, requests++); + } +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late Directory root; + late ProjectFile project; + late EditorTimelineSession session; + late List originals; + late EditorAcceptance acceptance; + late Map tools; + final sequence = SequenceId('main'); + var serial = 0; + final history = []; + ToolContext context() => ToolContext( + sessionId: 'trial', + runId: 'run', + operationId: 'op-${serial++}', + cancellation: CancellationToken(), + onProgress: (_) {}, + ); + Future invoke( + String name, + Map args, { + bool record = true, + }) async { + final call = ToolCall( + id: 'call-${serial++}', + name: name, + arguments: {'workspaceId': 'timeline', ...args}, + ); + final t = tools[name]!; + expect(t.validate(call.arguments), isNull); + final result = await t.execute(call, context()); + if (record) { + history.add(AgentMessage(role: MessageRole.assistant, calls: [call])); + history.add( + AgentMessage( + role: MessageRole.tool, + callId: call.id, + text: jsonEncode(result.toJson()), + isError: result.isError, + ), + ); + } + return result; + } + + Future version() async => + (await invoke('timeline_query', {}, record: false)).data['version'] + as String; + Future save() async { + expect( + (await invoke('project_save', { + 'expectedVersion': await version(), + }, record: false)).isError, + false, + ); + } + + Future check() => acceptance.check( + SessionSnapshot(id: 'trial', runId: 'run', history: history), + CancellationToken(), + ); + setUp(() async { + history.clear(); + serial = 0; + root = await Directory.systemTemp.createTemp('cutdex-acceptance-'); + project = await ProjectFile.create( + Directory('${root.path}/acceptance.cutdex'), + name: 'Acceptance', + ); + await project.saveAsset( + AssetDocument( + id: 'source', + name: 'Original', + storage: AssetStorage.external, + location: Uri.file('${root.path}/source.wav').toString(), + ), + ); + final document = TimelineDocument( + id: 'p', + name: 'Acceptance', + sequences: [ + TimelineDto( + id: sequence, + format: TimelineFormat.fps30, + primaryStorylineId: StorylineId('primary'), + storylines: [ + StorylineDto(id: StorylineId('primary'), elementIds: []), + ], + elements: [], + ), + ], + ); + await project.saveTimeline(document); + session = EditorTimelineSession( + document: await project.loadTimeline('p'), + persistence: await project.openTimelineSaveSession('p'), + media: Media(Uri.file('${root.path}/source.wav')), + ); + session.insertAsset( + sequenceId: sequence, + assetId: 'source', + assetName: 'Original', + uri: Uri.file('${root.path}/source.wav'), + duration: RationalTime.seconds(5), + position: 0, + kind: 'audio', + hasAudio: true, + clipId: ElementId('clip'), + ); + originals = editorAgentTools({ + 'timeline': editorToolsFor(session, sequence), + }); + acceptance = EditorAcceptance(originals); + tools = { + for (final t in [...originals, ...acceptance.tools]) t.name: t, + }; + }); + tearDown(() async { + await session.close(); + await project.close(); + await root.delete(recursive: true); + }); + test('real project readback detects wrong parameter and fresh edits invalidate success', () async { + final registered = await invoke('editor_expect_clips', { + 'clips': [ + { + 'clipId': 'clip', + 'name': 'Original', + 'parameters': [ + {'parameterId': 'cutdex.audio.gainDb', 'value': -12}, + ], + }, + ], + }); + expect(registered.isError, false); + await invoke('clip_setAudio', { + 'clipId': 'clip', + 'db': -6, + 'expectedVersion': await version(), + }); + await save(); + final failed = await check(); + expect(failed.isError, true); + expect(jsonEncode(failed.data), contains('cutdex.audio.gainDb')); + await invoke('clip_setAudio', { + 'clipId': 'clip', + 'db': -12, + 'expectedVersion': await version(), + }); + await save(); + expect((await check()).isError, false); + final persisted = (await project.loadTimeline('p')) + .sequences + .single + .elements + .singleWhere((e) => e.id == ElementId('clip')); + expect( + persisted.parameters + .singleWhere((p) => p.definition.id == 'cutdex.audio.gainDb') + .definition + .defaultValue, + -12, + ); + await invoke('clip_setAudio', { + 'clipId': 'clip', + 'db': -3, + 'expectedVersion': await version(), + }, record: false); + await save(); + expect((await check()).isError, true); + }); + test( + 'saved contracts survive fresh verifier and cannot be weakened', + () async { + await invoke('editor_expect_clips', { + 'clips': [ + {'clipId': 'clip', 'name': 'Expected'}, + ], + }); + acceptance = EditorAcceptance(originals); + expect((await check()).isError, true); + await invoke('editor_expect_clips', { + 'clips': [ + {'clipId': 'clip', 'name': 'Original'}, + ], + }); + final result = await check(); + expect(result.isError, true); + expect(jsonEncode(result.data), contains('contractChanged')); + }, + ); + test( + 'audio edits require the edited field and honor implicit defaults', + () async { + await invoke('editor_expect_clips', { + 'clips': [ + {'clipId': 'clip', 'name': 'Original'}, + ], + }); + await invoke('clip_setAudio', { + 'clipId': 'clip', + 'db': -12, + 'expectedVersion': await version(), + }); + await save(); + expect(jsonEncode((await check()).data), contains('missingExpectation')); + history.clear(); + await invoke('clip_setAudio', { + 'clipId': 'clip', + 'db': 0, + 'muted': false, + 'expectedVersion': await version(), + }, record: false); + await invoke('editor_expect_clips', { + 'clips': [ + { + 'clipId': 'clip', + 'parameters': [ + {'parameterId': 'cutdex.audio.gainDb', 'value': 0}, + {'parameterId': 'cutdex.audio.mute', 'value': 1}, + ], + }, + ], + }); + await save(); + expect((await check()).isError, false); + }, + ); + test('real captions check all pages and detect missing cues without semantic certification', () async { + final a = await invoke('captionTrack_create', { + 'name': '日本語', + 'language': 'ja', + 'expectedVersion': await version(), + }); + final source = ((a.data['data'] as Map)['roleId']) as String; + final b = await invoke('captionTrack_create', { + 'name': '中文', + 'language': 'zh', + 'expectedVersion': await version(), + }); + final target = ((b.data['data'] as Map)['roleId']) as String; + await invoke('caption_add', { + 'roleId': source, + 'cues': [ + for (var i = 0; i < 101; i++) + { + 'text': '字幕$i', + 'start': {'numerator': '${i * 2}', 'denominator': 1}, + 'duration': {'numerator': '1', 'denominator': 1}, + }, + ], + 'expectedVersion': await version(), + }); + expect( + (await invoke('editor_expect_translation', { + 'sourceRoleId': source, + 'targetRoleId': target, + })).isError, + false, + ); + final page = await invoke('caption_list', { + 'roleId': source, + 'limit': 100, + }, record: false); + final cues = (page.data['data'] as Map)['cues'] as List; + await invoke('caption_addTranslations', { + 'roleId': target, + 'cues': [ + for (final c in cues) {'sourceCaptionId': c['captionId'], 'text': '译文'}, + ], + 'expectedVersion': await version(), + }); + await save(); + expect((await check()).isError, true); + final rest = await invoke('caption_list', { + 'roleId': source, + 'offset': 100, + 'limit': 100, + }, record: false); + final last = ((rest.data['data'] as Map)['cues'] as List).single; + await invoke('caption_addTranslations', { + 'roleId': target, + 'cues': [ + {'sourceCaptionId': last['captionId'], 'text': '译文'}, + ], + 'expectedVersion': await version(), + }); + await save(); + final result = await check(); + expect(result.isError, false); + expect(result.data['semanticQuality'], 'unverified'); + var changed = false; + acceptance = EditorAcceptance( + originals.map( + (tool) => tool.name != 'caption_list' + ? tool + : AgentTool( + name: tool.name, + description: tool.description, + parameters: tool.parameters, + validate: tool.validate, + execute: (call, context) async { + final result = await tool.execute(call, context); + if (!changed && call.arguments['roleId'] == source) { + changed = true; + await invoke('clip_setAudio', { + 'clipId': 'clip', + 'db': -3, + 'expectedVersion': await version(), + }, record: false); + } + return result; + }, + ), + ), + ); + expect(jsonEncode((await check()).data), contains('unavailableEvidence')); + acceptance = EditorAcceptance(originals); + await invoke('caption_set', { + 'captionId': cues.first['captionId'], + 'text': '改变了原文', + 'expectedVersion': await version(), + }); + await save(); + expect(jsonEncode((await check()).data), contains('sourceChanged')); + }); + test( + 'runtime repairs failed final verification through actual editor tools', + () async { + var repaired = false; + final model = _Model((request, step) async { + ModelResponse call(String name, Map args) => + ModelResponse( + calls: [ + ToolCall( + id: 'model-$step', + name: name, + arguments: {'workspaceId': 'timeline', ...args}, + ), + ], + ); + if (step == 0) { + return call('editor_expect_clips', { + 'clips': [ + { + 'clipId': 'clip', + 'parameters': [ + {'parameterId': 'cutdex.audio.gainDb', 'value': -12}, + ], + }, + ], + }); + } + if (step == 1) return ModelResponse(text: '完成'); + if (step == 2) { + expect(request.messages.last.runtimeNotice, true); + expect(request.messages.last.text, contains('cutdex.audio.gainDb')); + repaired = true; + return call('clip_setAudio', { + 'clipId': 'clip', + 'db': -12, + 'expectedVersion': await version(), + }); + } + if (step == 3) { + return call('project_save', {'expectedVersion': await version()}); + } + return ModelResponse(text: '已修正并核验'); + }); + final manager = SessionManager( + model: model, + store: FileSessionStore(Directory('${root.path}/sessions')), + contextBuilder: ContextBuilder(), + tools: tools.values, + completionCheck: acceptance.check, + ); + final s = await manager.create(id: 'agent'); + final end = await (await manager.prompt(s.id, 'set volume')).done; + expect(repaired, true); + expect(end.status, RunStatus.completed); + expect((end.completionEvidence!['result'] as Map)['isError'], false); + }, + ); + test( + 'live model verifies real persisted project through application tools', + () async { + final raw = Platform.environment['CUTDEX_ACCEPTANCE_LIVE']; + if (raw == null) return; + // This opt-in integration case uses the configured real provider. + final overrides = HttpOverrides.current; + HttpOverrides.global = null; + addTearDown(() => HttpOverrides.global = overrides); + final config = jsonDecode(raw) as Map; + final model = OpenAiResponsesAdapter( + baseUrl: Uri.parse(config['baseUrl'] as String), + model: config['model'] as String, + apiKey: config['key'] as String, + ); + final manager = SessionManager( + model: model, + store: FileSessionStore(Directory('${root.path}/live')), + contextBuilder: HarnessContextBuilder( + maxInputTokens: 32000, + directTools: const {'cutdex_workspaces'}, + summarizer: ModelContextSummarizer( + model: model, + budget: ContextBuilder(maxInputTokens: 32000), + ), + ), + tools: tools.values, + completionCheck: acceptance.check, + ); + final s = await manager.create(system: AgentPromptPolicy.editorAssistant); + final end = await (await manager.prompt( + s.id, + '在timeline工作区把clip片段音量设为-12 dB,保持顺序、时间和其他内容。', + maxTurns: 35, + )).done; + if (end.status != RunStatus.completed) { + stdout.writeln( + 'LIVE_FAILURE ${jsonEncode(end.history.map((m) => m.toJson()).toList())}', + ); + } + expect(end.status, RunStatus.completed, reason: end.error); + expect(end.completionEvidence, isNotNull); + final query = await invoke('timeline_query', {}, record: false); + final clip = ((query.data['data'] as Map)['clips'] as List).firstWhere( + (c) => c['clipId'] == 'clip', + ); + expect(clip['name'], 'Original'); + expect( + (clip['parameters'] as List).firstWhere( + (p) => p['id'] == 'cutdex.audio.gainDb', + )['defaultValue'], + -12, + ); + final persistedClip = (await project.loadTimeline('p')) + .sequences + .single + .elements + .singleWhere((e) => e.id == ElementId('clip')); + expect( + persistedClip.parameters + .singleWhere((p) => p.definition.id == 'cutdex.audio.gainDb') + .definition + .defaultValue, + -12, + ); + stdout.writeln( + 'LIVE_ACCEPTANCE_VERIFIED turns=${end.turns} evidence=${jsonEncode(end.completionEvidence)}', + ); + final sourceResult = await invoke('captionTrack_create', { + 'name': '日本語', + 'language': 'ja', + 'expectedVersion': await version(), + }); + final source = (sourceResult.data['data'] as Map)['roleId']; + const japanese = [ + 'こんにちは。', + 'ここで待ってください。', + '彼はまだ来ていません。', + '会議は午後三時に始まります。', + ]; + await invoke('caption_add', { + 'roleId': source, + 'cues': [ + for (var i = 0; i < japanese.length; i++) + { + 'text': japanese[i], + 'start': {'numerator': '$i', 'denominator': 1}, + 'duration': {'numerator': '1', 'denominator': 1}, + }, + ], + 'expectedVersion': await version(), + }); + await save(); + final translated = await (await manager.prompt( + s.id, + '把timeline工作区日本語轨道的全部字幕由你翻译成简体中文,新增中文轨道并保留原字幕和时间,完成后保存。', + maxTurns: 45, + )).done; + expect(translated.status, RunStatus.completed, reason: translated.error); + expect( + (translated.completionEvidence!['result'] as Map)['isError'], + false, + ); + final tracks = await invoke('caption_list', {}, record: false); + final target = ((tracks.data['data'] as Map)['tracks'] as List) + .singleWhere((t) => t['roleId'] != source); + final captions = await invoke('caption_list', { + 'roleId': target['roleId'], + }, record: false); + final cues = (captions.data['data'] as Map)['cues'] as List; + expect(cues.length, japanese.length); + stdout.writeln( + 'LIVE_TRANSLATION_VERIFIED turns=${translated.turns} cues=${jsonEncode(cues)} evidence=${jsonEncode(translated.completionEvidence)}', + ); + }, + timeout: const Timeout(Duration(minutes: 5)), + skip: Platform.environment['CUTDEX_ACCEPTANCE_LIVE'] == null, + ); +} diff --git a/test/editor_commands_test.dart b/test/editor_commands_test.dart new file mode 100644 index 0000000..352ede3 --- /dev/null +++ b/test/editor_commands_test.dart @@ -0,0 +1,1958 @@ +import 'support/creation_names.dart'; + +import 'package:cutdex/app/editor_theme.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex/workspace/project_assets_changed.dart'; +import 'package:cutdex/features/properties/animation_labels.dart'; +import 'package:cutdex/integrations/editor_command_host.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/timeline/engine.dart'; +import 'package:cutdex/workspace/media_import.dart'; + +import 'dart:convert'; +import 'dart:async'; + +import 'package:flutter/services.dart'; + +import 'dart:io'; + +import 'package:cutdex/integrations/editor_tools.dart'; +import 'package:cutdex/integrations/mcp/local_mcp_bridge.dart'; +import 'package:cutdex/integrations/mcp/mcp_settings.dart'; +import 'package:cutdex/persistence/app_settings_repositories.dart'; + +import 'support/memory_app_settings.dart'; +import 'support/project_write_lock.dart'; + +import 'package:cutdex/workspace/persistence/project_workspace.dart'; +import 'package:cutdex/workspace/timeline_session.dart'; +import 'package:cutdex/workspace/timeline_provider.dart'; +import 'package:cutdex/features/properties/picture_properties.dart'; +import 'package:cutdex/features/preview/preview_panel.dart'; +import 'package:cutdex_agent/cutdex_agent.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:cutdex_sdk/tools.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +TimelineDto _sequence(String id) => TimelineDto( + id: SequenceId(id), + format: TimelineFormat.fps30, + primaryStorylineId: StorylineId('primary'), + storylines: [ + StorylineDto( + id: StorylineId('primary'), + elementIds: [ElementId('a'), ElementId('b')], + ), + ], + elements: [ + for (final name in ['a', 'b']) + ElementDto( + id: ElementId(name), + name: name, + structure: ElementStructure.content, + duration: RationalTime.seconds(10), + sourceRange: TimeRange( + start: RationalTime.zero, + duration: RationalTime.seconds(10), + ), + mediaRange: TimeRange( + start: RationalTime.zero, + duration: RationalTime.seconds(20), + ), + ), + ], +); + +Map _request(String name, Map arguments) => { + 'jsonrpc': '2.0', + 'id': 1, + 'method': 'tools/call', + 'params': { + '_meta': { + 'io.modelcontextprotocol/protocolVersion': '2026-07-28', + 'io.modelcontextprotocol/clientCapabilities': {}, + }, + 'name': name, + 'arguments': arguments, + }, +}; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late Directory root; + late ProjectWorkspace workspace; + late EditorTimelineSession session; + late EditorToolAccess access; + final sequence = SequenceId('one'); + late String projectId; + + setUp(() async { + root = await Directory.systemTemp.createTemp('cutdex-commands-'); + workspace = ProjectWorkspace(creationNames: testCreationNames); + await workspace.open('${root.path}/Project.cutdex', name: 'Test'); + projectId = workspace.project!.info.id; + await workspace.project!.saveTimeline( + TimelineDocument( + id: 'project', + name: 'Commands', + sequences: [_sequence('one'), _sequence('two')], + defaultSequenceId: sequence, + ), + ); + session = await workspace.openTimelineSession( + projectId, + await workspace.loadTimeline(projectId, 'project'), + ); + access = EditorToolAccess(session); + }); + tearDown(() async { + await workspace.close(); + await root.delete(recursive: true); + }); + + test( + 'reopening the same session receives usable tools after access disposal', + () async { + await access.dispose(); + access = EditorToolAccess(session); + final tools = access.workspaces.values.first; + final result = await tools.invoke( + name: 'timeline.query', + arguments: const {}, + context: const CommandContext(operationId: 'reopened-query'), + ); + expect(result.isError, isFalse); + }, + ); + + ClipTransform transform([String clip = 'a']) { + final query = session.view(sequence).version.kernelVersion.query(); + return ClipTransform.fromRecord( + query.element(query.elementById(ElementId(clip))!), + ); + } + + Map position(double x, {String? version}) => { + 'clipId': 'a', + 'at': {'numerator': '0', 'denominator': 1}, + 'x': x, + 'y': 54, + 'expectedVersion': ?version, + }; + Future invoke( + String name, + String operation, + Map args, + ) => editorToolsFor(session, sequence).invoke( + name: name, + arguments: args, + context: CommandContext(operationId: operation), + ); + + test( + 'default SDK tool host exposes verification without Agent adapters', + () async { + final dispatcher = EditorToolDispatcher( + host: EditorSessionCommandHost(session, sequence), + ); + addTearDown(dispatcher.dispose); + Future verify(String name) => dispatcher.invoke( + name: 'editor.verify', + arguments: { + 'expectations': [ + { + 'kind': 'clip', + 'workspaceId': 'one', + 'expected': {'clipId': 'a', 'name': name}, + }, + ], + }, + context: const CommandContext(operationId: 'verification'), + ); + final good = await verify('a'); + expect(good.status, CommandStatus.succeeded); + expect(good.data['verified'], isTrue); + expect((await verify('wrong')).data['verified'], isFalse); + final invalid = await dispatcher.invoke( + name: 'editor.verify', + arguments: { + 'expectations': [ + {'kind': 'clip', 'workspaceId': 'one'}, + ], + }, + context: const CommandContext(operationId: 'invalid-verification'), + ); + expect(invalid.code, 'invalidArguments'); + expect(session.dirty, isFalse); + }, + ); + + test( + 'split receipt survives restart and deduplicates repeated invocation', + () async { + final dispatcher = editorToolsFor(session, sequence); + final args = { + 'clipId': 'a', + 'at': {'numerator': '5', 'denominator': 1}, + 'expectedVersion': session.version, + }; + final result = await dispatcher.invoke( + name: 'timeline.split', + arguments: args, + context: const CommandContext(operationId: 'durable-split'), + ); + expect(result.isError, isFalse); + final before = await workspace.project!.loadTimeline('project'); + expect(before.sequences.first.elements, hasLength(3)); + await access.dispose(); + await workspace.close(); + workspace = ProjectWorkspace(creationNames: testCreationNames); + await workspace.open('${root.path}/Project.cutdex'); + session = await workspace.openTimelineSession( + projectId, + await workspace.loadTimeline(projectId, 'project'), + ); + access = EditorToolAccess(session); + final fresh = editorToolsFor(session, sequence); + final recovered = await fresh.recoverInvocation( + operationId: 'durable-split', + name: 'timeline.split', + arguments: args, + ); + expect(recovered.state, OperationState.completed); + expect(recovered.result!.toJson(), result.toJson()); + for (var i = 0; i < 2; i++) { + final duplicate = await fresh.invoke( + name: 'timeline.split', + arguments: args, + context: const CommandContext(operationId: 'durable-split'), + ); + expect(duplicate.toJson(), result.toJson()); + } + final after = await workspace.project!.loadTimeline('project'); + expect(after.revision, before.revision); + expect( + after.sequences.first.elements.map((e) => e.id), + before.sequences.first.elements.map((e) => e.id), + ); + final conflict = await fresh.invoke( + name: 'timeline.split', + arguments: {...args, 'clipId': 'b'}, + context: const CommandContext(operationId: 'durable-split'), + ); + expect(conflict.code, 'operationIdConflict'); + }, + ); + + test('edit undo and redo receipts acknowledge persisted state', () async { + Future expectSaved(double expectedX) async { + expect(session.dirty, isFalse); + final stored = await workspace.project!.loadTimeline('project'); + final clip = stored.sequences.first.elements.first; + final curves = clip.parameters.where( + (curve) => curve.definition.id == 'canvas.position.x', + ); + final x = curves.isEmpty ? 0.0 : curves.first.definition.defaultValue; + expect(x, closeTo(expectedX, 1e-9)); + } + + final edit = await invoke( + 'clip.setTransform', + 'durable-edit', + position(192), + ); + expect(edit.edit, EditOutcome.committed); + expect(edit.data['saveState'], 'saved'); + await expectSaved(192 / session.canvas.width); + final undo = await invoke('timeline.undo', 'durable-undo', {}); + expect(undo.edit, EditOutcome.committed); + await expectSaved(0); + final redo = await invoke('timeline.redo', 'durable-redo', {}); + expect(redo.edit, EditOutcome.committed); + await expectSaved(192 / session.canvas.width); + }); + + test('selection tools share UI selection, validate atomically and keep history unchanged', () async { + final view = session.view(sequence); + final version = session.version; + final dirty = session.dirty; + final undo = session.canUndo(sequence); + var notifications = 0; + view.addListener(() => notifications++); + final result = await invoke('selection.set', 'select', { + 'clipIds': ['a', 'b'], + }); + expect(result.status, CommandStatus.succeeded); + expect(result.edit, EditOutcome.notApplicable); + expect(view.selectedIdentities, hasLength(2)); + expect(notifications, 1); + expect((await invoke('selection.query', 'query', {})).data['clipIds'], [ + 'a', + 'b', + ]); + expect( + (await invoke('selection.set', 'missing', { + 'clipIds': ['a', 'missing'], + })).status, + CommandStatus.rejected, + ); + expect(view.selectedIdentities, hasLength(2)); + expect( + (await invoke('selection.set', 'duplicate', { + 'clipIds': ['a', 'a'], + })).status, + CommandStatus.rejected, + ); + await invoke('selection.set', 'clear', {'clipIds': []}); + expect(view.selectedIdentities, isEmpty); + // Replaying a recorded selection must not override a newer UI selection. + await invoke('selection.set', 'select', { + 'clipIds': ['a', 'b'], + }); + expect(view.selectedIdentities, isEmpty); + view.setSelection([ + view.version.kernelVersion.query().elementById(ElementId('b'))!, + ]); + expect((await invoke('selection.query', 'query', {})).data['clipIds'], [ + 'b', + ]); + expect(session.version, version); + expect(session.dirty, dirty); + expect(session.canUndo(sequence), undo); + }); + + test('export tool reaches an isolated native session, journals receipt and closes it', () async { + const native = MethodChannel('cutdex_runtime'); + const events = MethodChannel('cutdex_runtime/sessions/export-test'); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + final calls = []; + messenger.setMockMethodCallHandler(events, (call) async { + if (call.method == 'listen') { + scheduleMicrotask( + () => messenger.handlePlatformMessage( + events.name, + const StandardMethodCodec().encodeSuccessEnvelope({ + 'type': 'attached', + }), + (_) {}, + ), + ); + } + return null; + }); + messenger.setMockMethodCallHandler(native, (call) async { + calls.add(call.method); + final args = call.arguments as Map; + switch (call.method) { + case 'capabilities': + return {'contractVersion': 1, 'features': {}}; + case 'createSession': + return {'sessionId': 'export-test'}; + case 'export': + expect(args['sessionId'], 'export-test'); + expect((args['plan'] as Map)['visualLayers'], isNotEmpty); + final uri = Uri.parse(args['destination'] as String); + await File.fromUri(uri).writeAsBytes([1, 2, 3]); + return uri.toString(); + case 'close': + return null; + default: + throw StateError('Unexpected native call: ${call.method}'); + } + }); + addTearDown(() { + messenger.setMockMethodCallHandler(native, null); + messenger.setMockMethodCallHandler(events, null); + }); + await invoke('timeline.deleteMany', 'clear-fixture', { + 'clipIds': ['a', 'b'], + }); + final image = Uri.file('${root.path}/image.png'); + await workspace.project!.saveAsset( + AssetDocument( + id: 'export-image', + name: 'Image', + storage: AssetStorage.external, + location: image.toString(), + ), + ); + session.insertAsset( + sequenceId: sequence, + assetId: 'export-image', + assetName: 'Image', + uri: image, + duration: RationalTime.seconds(1), + position: 0, + kind: 'image', + hasAudio: false, + ); + final before = session.version; + final destination = '${root.path}/result.mp4'; + final result = await invoke('project.export', 'encode', { + 'destination': destination, + }); + expect(result.status, CommandStatus.succeeded); + expect(result.edit, EditOutcome.notApplicable); + expect(result.data['exportedVersion'], before); + expect(await File(destination).exists(), true); + expect(calls, ['capabilities', 'createSession', 'export', 'close']); + expect(session.version, before); + await invoke('project.export', 'encode', {'destination': destination}); + expect(calls.where((value) => value == 'export'), hasLength(1)); + final collision = await invoke('project.export', 'other', { + 'destination': destination, + }); + expect(collision.code, 'destinationExists'); + expect(collision.edit, EditOutcome.notApplicable); + expect(await File(destination).readAsBytes(), [1, 2, 3]); + expect(calls.where((value) => value == 'createSession'), hasLength(1)); + }); + + test('grouped keys validate atomically, undo together and preserve other channels', () async { + final before = session.version; + final at = {'numerator': '1', 'denominator': 1}; + Map key(String id, double value) => { + 'parameterId': id, + 'action': 'set', + 'at': at, + 'value': value, + }; + for (final edits in [ + [key('canvas.position.x', .2), key('missing', .4)], + >[], + ]) { + final result = await invoke('keyframe.editMany', 'bad-group-$edits', { + 'clipId': 'a', + 'edits': edits, + }); + expect(result.status, CommandStatus.rejected); + expect(session.version, before); + } + final args = { + 'clipId': 'a', + 'edits': [key('canvas.position.x', .2), key('canvas.position.y', .4)], + }; + final result = await invoke('keyframe.editMany', 'group', args); + expect(result.edit, EditOutcome.committed, reason: '${result.toJson()}'); + final dto = session.persistence.timeline(sequence).exportDto(); + final curves = dto.elements.first.parameters; + expect( + curves + .firstWhere((c) => c.definition.id == 'canvas.position.x') + .keyframes + .single + .value, + .2, + ); + expect( + curves + .firstWhere((c) => c.definition.id == 'canvas.position.y') + .keyframes + .single + .value, + .4, + ); + await invoke('keyframe.editMany', 'group', args); + expect(session.version, result.version); + session.view(sequence).undo(); + expect( + session.persistence + .timeline(sequence) + .exportDto() + .elements + .first + .parameters, + isEmpty, + ); + expect( + (await invoke('keyframe.editMany', 'stale-group', { + ...args, + 'expectedVersion': result.version, + })).code, + 'staleVersion', + ); + }); + + test('MCP grouped editing and Agent saving use the shared session', () async { + final connection = access.server.connect(); + addTearDown(connection.close); + final response = await connection.handleJson( + jsonEncode( + _request('keyframe.editMany', { + 'workspaceId': access.workspaces.keys.first, + 'operationId': 'wire-group', + 'clipId': 'a', + 'edits': [ + for (final parameter in ['canvas.position.x', 'canvas.position.y']) + { + 'parameterId': parameter, + 'action': 'set', + 'at': {'numerator': '1', 'denominator': 1}, + }, + ], + }), + ), + ); + expect((response!['result'] as Map)['isError'], false, reason: '$response'); + final tool = access.agentTools.singleWhere( + (tool) => tool.name == 'project_save', + ); + final saved = await tool.execute( + ToolCall( + id: 'save', + name: tool.name, + arguments: {'workspaceId': access.workspaces.keys.first}, + ), + ToolContext( + sessionId: 's', + runId: 'r', + operationId: 'agent-save', + cancellation: CancellationToken(), + onProgress: (_) {}, + ), + ); + expect(saved.isError, false); + expect(session.dirty, false); + session.view(sequence).undo(); + expect( + session.persistence + .timeline(sequence) + .exportDto() + .elements + .first + .parameters, + isEmpty, + ); + expect(access.agentTools.map((tool) => tool.name), contains('clip_align')); + }); + + test( + 'save tool retries blocked persistence without changing edit history', + () async { + final release = blockProjectWrites(workspace.project!.directory.path); + addTearDown(release); + session.commands.setTransform( + sequence: sequence, + clip: ElementId('a'), + tick: 0, + change: (value) => value.copyWith(x: 100 / session.canvas.width), + ); + final version = session.version; + final failed = await invoke('project.save', 'failed-save', {}); + expect(failed.status, CommandStatus.unknown); + expect(failed.edit, EditOutcome.notApplicable); + expect(session.dirty, true); + expect( + (await invoke('timeline.query', 'failed-state', {})).data['saveState'], + 'failed', + ); + release(); + final replay = await invoke('project.save', 'failed-save', {}); + expect(replay.status, CommandStatus.unknown); + final saved = await invoke('project.save', 'retry-save', {}); + expect(saved.status, CommandStatus.succeeded); + expect(saved.edit, EditOutcome.notApplicable); + expect(saved.data['saveState'], 'saved'); + expect(session.saveError, isNull); + expect(session.version, version); + final stored = await workspace.project!.loadTimeline('project'); + expect(stored.sequences.first.elements.first.parameters, isNotEmpty); + session.view(sequence).undo(); + expect(transform().x, 0); + expect( + (await invoke('project.save', 'stale-save', { + 'expectedVersion': version, + })).code, + 'staleVersion', + ); + }, + ); + + test( + 'batch deletion validates all targets and creates one undo entry', + () async { + final before = session.commands.version; + for (final ids in [ + ['a', 'missing'], + ['a', 'a'], + [], + ]) { + final result = await invoke('timeline.deleteMany', 'invalid-$ids', { + 'clipIds': ids, + }); + expect(result.status, CommandStatus.rejected); + expect(session.commands.version, before); + } + final result = await invoke('timeline.deleteMany', 'batch-delete', { + 'clipIds': ['a', 'b'], + }); + expect(result.edit, EditOutcome.committed, reason: '${result.toJson()}'); + expect( + session.persistence.timeline(sequence).exportDto().elements, + isEmpty, + ); + final replay = await invoke('timeline.deleteMany', 'batch-delete', { + 'clipIds': ['a', 'b'], + }); + expect(replay.version, result.version); + await invoke('timeline.undo', 'undo-batch', {}); + expect( + session.persistence + .timeline(sequence) + .exportDto() + .elements + .map((e) => e.id.value), + ['a', 'b'], + ); + }, + ); + + test( + 'batch split rejects partial success and commits one split history', + () async { + final before = session.commands.version; + final invalid = await invoke('timeline.splitMany', 'bad-split', { + 'clipIds': ['a', 'b'], + 'at': {'numerator': '5', 'denominator': 1}, + }); + expect(invalid.status, CommandStatus.rejected); + expect(session.commands.version, before); + final result = await invoke('timeline.splitMany', 'split-batch', { + 'clipIds': ['a'], + 'at': {'numerator': '5', 'denominator': 1}, + }); + expect(result.edit, EditOutcome.committed, reason: '${result.toJson()}'); + expect( + session.persistence.timeline(sequence).exportDto().elements, + hasLength(3), + ); + await invoke('timeline.undo', 'undo-split-batch', {}); + expect( + session.persistence + .timeline(sequence) + .exportDto() + .elements + .map((e) => e.id.value), + ['a', 'b'], + ); + }, + ); + + test( + 'MCP splits overlapping clips atomically and Agent sees the same tools', + () async { + final placed = await invoke('timeline.place', 'batch-setup', { + 'clipId': 'b', + 'at': {'numerator': '1', 'denominator': 1}, + 'side': 'above', + }); + expect(placed.edit, EditOutcome.committed); + final connection = access.server.connect(); + addTearDown(connection.close); + final response = await connection.handleJson( + jsonEncode( + _request('timeline.splitMany', { + 'workspaceId': access.workspaces.keys.first, + 'operationId': 'mcp-batch', + 'clipIds': ['a', 'b'], + 'at': {'numerator': '5', 'denominator': 1}, + }), + ), + ); + expect( + (response!['result'] as Map)['isError'], + false, + reason: '$response', + ); + expect( + session.persistence.timeline(sequence).exportDto().elements, + hasLength(4), + ); + final undo = access.agentTools.singleWhere( + (tool) => tool.name == 'timeline_undo', + ); + final result = await undo.execute( + ToolCall( + id: 'batch-undo', + name: undo.name, + arguments: {'workspaceId': access.workspaces.keys.first}, + ), + ToolContext( + sessionId: 's', + runId: 'r', + operationId: 'agent-batch-undo', + cancellation: CancellationToken(), + onProgress: (_) {}, + ), + ); + expect(result.isError, false); + expect( + session.persistence.timeline(sequence).exportDto().elements, + hasLength(2), + ); + expect( + access.agentTools.map((t) => t.name), + containsAll([ + 'media_rename', + 'media_remove', + 'timeline_deleteMany', + 'timeline_splitMany', + 'preview_query', + 'preview_play', + 'preview_pause', + 'preview_seek', + 'preview_retry', + ]), + ); + }, + ); + + test( + 'catalog tools publish changes without removing files or timeline bindings', + () async { + final file = File('${root.path}/still.png'); + await file.writeAsBytes([0]); + await invoke('media.import', 'catalog-import', {'path': file.path}); + final media = + (await invoke('media.query', 'catalog-query', {})).data['media'] + as List; + final id = (media.single as Map)['mediaId']; + final inserted = await invoke('timeline.insert', 'catalog-insert', { + 'mediaId': id, + 'clipId': 'catalog-clip', + 'index': 1, + 'sourceStart': {'numerator': '0', 'denominator': 1}, + 'duration': {'numerator': '3', 'denominator': 1}, + }); + expect( + inserted.edit, + EditOutcome.committed, + reason: '${inserted.toJson()}', + ); + final before = session.commands.version; + final changes = []; + final subscription = workspace.assetChanges.listen(changes.add); + addTearDown(subscription.cancel); + final renamed = await invoke('media.rename', 'catalog-rename', { + 'mediaId': id, + 'name': 'Renamed', + }); + expect(renamed.edit, EditOutcome.committed); + final replay = await invoke('media.rename', 'catalog-rename', { + 'mediaId': id, + 'name': 'Renamed', + }); + expect(replay.edit, EditOutcome.committed); + final noop = await invoke('media.rename', 'catalog-noop', { + 'mediaId': id, + 'name': 'Renamed', + }); + expect(noop.edit, EditOutcome.notCommitted); + expect( + ((await invoke('media.query', 'renamed-query', {})).data['media'] + as List) + .single, + containsPair('name', 'Renamed'), + ); + final removed = await invoke('media.remove', 'catalog-remove', { + 'mediaId': id, + }); + expect(removed.edit, EditOutcome.committed); + expect( + (await invoke('media.query', 'removed-query', {})).data['media'], + isEmpty, + ); + expect(await file.exists(), isTrue); + expect(session.commands.version, before); + expect( + session.persistence + .timeline(sequence) + .exportDto() + .elements + .any((e) => e.id.value == 'catalog-clip'), + isTrue, + ); + await Future.delayed(Duration.zero); + expect(changes, hasLength(2)); + expect( + (await invoke('media.rename', 'missing-rename', { + 'mediaId': 'missing', + 'name': 'New', + })).status, + CommandStatus.rejected, + ); + expect( + (await invoke('media.rename', 'blank-rename', { + 'mediaId': id, + 'name': ' ', + })).status, + CommandStatus.rejected, + ); + }, + ); + + test('preview tools remain discoverable before a preview attaches', () async { + expect( + (await invoke('preview.query', 'preview-query', {})).data['available'], + false, + ); + final result = await invoke('preview.play', 'preview-play', {}); + expect(result.status, CommandStatus.rejected); + expect(result.edit, EditOutcome.notApplicable); + }); + + test( + 'mask switch preserves geometry and animation even with repeated fields', + () async { + await invoke('mask.edit', 'add-toggle-mask', { + 'clipId': 'a', + 'maskId': 'mask', + 'action': 'add', + 'at': {'numerator': '0', 'denominator': 1}, + }); + await invoke('keyframe.editMany', 'animate-toggle-mask', { + 'clipId': 'a', + 'edits': [ + for (final time in [0, 5]) + { + 'parameterId': 'mask.mask.center.x', + 'action': 'set', + 'at': {'numerator': '$time', 'denominator': 1}, + 'value': time == 0 ? .4 : .6, + }, + ], + }); + List geometry() => [ + for (final curve + in session.persistence + .timeline(sequence) + .exportDto() + .elements + .first + .parameters) + if (curve.definition.id != 'mask.mask.enabled') + [ + curve.definition.id, + curve.definition.defaultValue, + for (final key in curve.keyframes) + [key.sourceTime, key.value, key.interpolation], + ], + ]; + final before = geometry(); + for (final enabled in [false, true]) { + final result = await invoke('mask.edit', 'switch-$enabled', { + 'clipId': 'a', + 'maskId': 'mask', + 'action': 'setEnabled', + 'enabled': enabled, + 'x': .9, + 'y': .2, + 'width': .3, + 'at': {'numerator': '0', 'denominator': 1}, + }); + expect(result.edit, EditOutcome.committed); + expect(geometry(), before); + final stored = await workspace.project!.loadTimeline('project'); + expect( + stored.sequences.first.elements.first.parameters + .firstWhere((p) => p.definition.id == 'mask.mask.enabled') + .definition + .defaultValue, + enabled ? 1 : 0, + ); + } + }, + ); + + test('shared mask and grouped keyframe use cases interoperate with tools and undo atomically', () async { + final view = session.view(sequence); + final clip = ElementId('a'); + session.commands.addMask( + sequence: sequence, + clip: clip, + tick: 0, + maskId: 'mask', + shape: ClipMaskShape.rectangle, + ); + session.commands.editKeyframeChannel( + sequence: sequence, + clip: clip, + tick: 0, + parameterIds: ['mask.mask.center.x', 'mask.mask.center.y'], + ); + ElementRecord record() { + final query = view.version.kernelVersion.query(); + return query.element(query.elementById(clip)!); + } + + expect( + ClipMaskAnimation( + record(), + 0, + maskId: 'mask', + ).keyed(maskChannels['position']!), + isTrue, + ); + view.undo(); + expect( + ClipMaskAnimation( + record(), + 0, + maskId: 'mask', + ).keyed(maskChannels['position']!), + isFalse, + ); + view.redo(); + final edited = await invoke('mask.edit', 'shared-mask', { + 'clipId': 'a', + 'action': 'set', + 'maskId': 'mask', + 'at': {'numerator': '0', 'denominator': 1}, + 'x': .75, + }); + expect(edited.edit, EditOutcome.committed); + expect(ClipMaskAnimation(record(), 0, maskId: 'mask').value.x, .75); + final before = view.version; + expect( + () => session.commands.editKeyframeChannel( + sequence: sequence, + clip: clip, + tick: 0, + parameterIds: ['mask.mask.center.x', 'unsupported'], + ), + throwsA(isA()), + ); + expect( + view.version, + same(before), + reason: 'A bad second channel must not publish the first', + ); + await invoke('timeline.undo', 'undo-shared-mask', {}); + expect(ClipMaskAnimation(record(), 0, maskId: 'mask').value.x, .5); + }); + + test( + 'direct typed commands reject incomplete operands without publication', + () async { + final view = session.view(sequence); + final before = view.version; + for (final command in [ + EditKeyframe( + clipId: 'a', + parameterId: 'canvas.position.x', + at: CommandTime(0, 1), + action: KeyframeAction.move, + ), + EditKeyframe( + clipId: 'a', + parameterId: 'canvas.position.x', + at: CommandTime(0, 1), + action: KeyframeAction.set, + interpolation: KeyInterpolation.bezier, + ), + EditMask(clipId: 'a', at: CommandTime(0, 1), action: MaskAction.add), + const SetClipAudio(clipId: 'a', db: double.nan), + const SetProjectCanvas(width: double.infinity, height: 1080), + ]) { + expect( + () => session.commands.applyEdit(sequence, command), + throwsA(isA()), + ); + expect(view.version, same(before)); + } + expect(view.canUndo, isFalse); + }, + ); + + test( + 'UI and tools share history, atomic XY, versions, and persistent curves', + () async { + session.commands.setTransform( + sequence: sequence, + clip: ElementId('a'), + tick: 0, + change: (value) => value.copyWith(rotation: 25), + ); + final before = session.commands.version; + final result = await invoke( + 'clip.setTransform', + 'position', + position(192, version: before), + ); + expect(result.edit, EditOutcome.committed); + expect(result.version, isNot(before)); + expect(transform().x, closeTo(192 / session.canvas.width, 1e-9)); + expect(transform().y, closeTo(54 / session.canvas.height, 1e-9)); + expect(transform().rotation, 25); + session.view(sequence).undo(); + expect(transform().x, 0); + expect(transform().y, 0); + expect(transform().rotation, 25); + final undoVersion = session.commands.version; + final retried = await invoke( + 'clip.setTransform', + 'position', + position(192, version: before), + ); + expect(retried, same(result)); + expect(session.commands.version, undoVersion); + expect(transform().x, 0); + await invoke('timeline.redo', 'redo', {}); + await session.flush(); + final loaded = await workspace.project!.loadTimeline('project'); + final clip = loaded.sequences.first.elements.first; + expect( + clip.parameters + .firstWhere((curve) => curve.definition.id == 'canvas.position.x') + .definition + .defaultValue, + closeTo(192 / session.canvas.width, 1e-9), + ); + }, + ); + + test( + 'mask tools preserve identity, animation, undo and reject invalid edits', + () async { + Map args(String action, {String id = 'mask-one'}) => { + 'clipId': 'a', + 'maskId': id, + 'action': action, + 'at': {'numerator': '1', 'denominator': 1}, + }; + final add = await invoke('mask.edit', 'add-mask', { + ...args('add'), + 'shape': 'ellipse', + }); + expect(add.edit, EditOutcome.committed); + final version = session.commands.version; + expect( + (await invoke('mask.edit', 'add-mask', { + ...args('add'), + 'shape': 'ellipse', + })).version, + add.version, + ); + expect(session.commands.version, version); + expect( + (await invoke('mask.edit', 'bad-mask', { + ...args('set'), + 'width': 0, + })).status, + CommandStatus.rejected, + ); + expect(session.commands.version, version); + final key = await invoke('keyframe.edit', 'mask-key', { + 'clipId': 'a', + 'parameterId': 'mask.mask-one.center.x', + 'action': 'set', + 'at': {'numerator': '1', 'denominator': 1}, + 'value': .25, + }); + expect(key.edit, EditOutcome.committed); + expect( + (await invoke('mask.edit', 'set-mask', { + ...args('set'), + 'x': .75, + 'mode': 'subtract', + })).edit, + EditOutcome.committed, + ); + final query = await invoke('timeline.query', 'query-mask', {}); + expect( + query.status, + CommandStatus.succeeded, + reason: '${query.toJson()}', + ); + expect( + (await invoke('mask.edit', 'remove-mask', args('remove'))).edit, + EditOutcome.committed, + ); + expect( + (await invoke('timeline.undo', 'undo-mask', {})).edit, + EditOutcome.committed, + ); + await session.flush(); + final dto = session.persistence.timeline(sequence).exportDto(); + expect( + dto.elements.first.parameters.any( + (p) => p.definition.id == 'mask.mask-one.center.x', + ), + true, + ); + }, + ); + + test( + 'keyframe tools set move interpolate and clear without moving playhead', + () async { + final view = session.view(sequence); + final playhead = view.playheadTick; + final base = { + 'clipId': 'a', + 'parameterId': 'canvas.position.x', + 'at': {'numerator': '2', 'denominator': 1}, + }; + expect( + (await invoke('keyframe.edit', 'key-set', { + ...base, + 'action': 'set', + 'value': .3, + 'interpolation': 'easeInOut', + })).edit, + EditOutcome.committed, + ); + expect( + (await invoke('keyframe.edit', 'key-move', { + ...base, + 'action': 'move', + 'to': {'numerator': '3', 'denominator': 1}, + })).edit, + EditOutcome.committed, + ); + expect( + (await invoke('keyframe.edit', 'key-clear', { + ...base, + 'action': 'clear', + })).edit, + EditOutcome.committed, + ); + expect(transform().x, .3); + expect(view.playheadTick, playhead); + }, + ); + + test( + 'split leading trim and connected placement preserve shared history', + () async { + expect( + (await invoke('timeline.split', 'split-tool', { + 'clipId': 'a', + 'at': {'numerator': '3', 'denominator': 1}, + })).edit, + EditOutcome.committed, + ); + expect( + session.persistence.timeline(sequence).exportDto().elements.length, + 3, + ); + await invoke('timeline.undo', 'undo-split-tool', {}); + expect( + (await invoke('timeline.trim', 'leading-tool', { + 'clipId': 'a', + 'duration': {'numerator': '8', 'denominator': 1}, + 'leading': true, + })).edit, + EditOutcome.committed, + ); + await invoke('timeline.undo', 'undo-leading-tool', {}); + final placed = await invoke('timeline.place', 'place-tool', { + 'clipId': 'b', + 'at': {'numerator': '1', 'denominator': 1}, + 'side': 'above', + }); + expect(placed.edit, EditOutcome.committed, reason: '${placed.toJson()}'); + final moved = await invoke('timeline.place', 'move-connected-tool', { + 'clipId': 'b', + 'at': {'numerator': '2', 'denominator': 1}, + 'side': 'above', + }); + expect(moved.edit, EditOutcome.committed, reason: '${moved.toJson()}'); + await invoke('timeline.undo', 'undo-connected-tool', {}); + }, + ); + + test('canvas settings use version checks and persist', () async { + final old = session.commands.version; + expect( + (await invoke('project.setCanvas', 'canvas-tool', { + 'width': 1080, + 'height': 1920, + })).edit, + EditOutcome.committed, + ); + expect(session.canvas.width, 1080); + expect( + (await invoke('project.setCanvas', 'stale-canvas-tool', { + 'width': 1920, + 'height': 1080, + 'expectedVersion': old, + })).status, + CommandStatus.rejected, + ); + await session.flush(); + expect( + (await workspace.loadTimeline( + projectId, + 'project', + )).settings['renderSize'], + {'width': 1080.0, 'height': 1920.0}, + ); + }); + + test('MCP and Agent expose new tools and MCP mask edits reach the shared session', () async { + expect( + access.agentTools.map((tool) => tool.name), + containsAll([ + 'mask_edit', + 'keyframe_edit', + 'clip_setAudio', + 'timeline_split', + 'timeline_place', + 'media_import', + ]), + ); + final connection = access.server.connect(); + addTearDown(connection.close); + final response = await connection.handleJson( + jsonEncode( + _request('mask.edit', { + 'workspaceId': access.workspaces.keys.first, + 'operationId': 'wire-mask', + 'clipId': 'a', + 'maskId': 'wire-mask', + 'action': 'add', + 'at': {'numerator': '0', 'denominator': 1}, + 'feather': .2, + }), + ), + ); + expect((response!['result'] as Map)['isError'], false, reason: '$response'); + final dto = session.persistence.timeline(sequence).exportDto(); + expect( + dto.elements.first.parameters + .firstWhere( + (curve) => curve.definition.id == 'mask.wire-mask.feather', + ) + .definition + .defaultValue, + .2, + ); + final before = session.commands.version; + final canceledFile = File('${root.path}/canceled.png'); + await canceledFile.writeAsBytes([0]); + final result = await workspace.importExternalMedia(projectId, [ + ExternalMediaFile(path: canceledFile.path), + ], isCancelled: () => true); + expect(result.added, 0); + expect(result.failures, hasLength(1)); + expect(session.commands.version, before); + }); + + test('audio and color tools commit valid media properties and reject non-audio clips', () async { + expect( + (await invoke('clip.setAudio', 'invalid-audio', { + 'clipId': 'a', + 'db': -6, + })).status, + CommandStatus.rejected, + ); + final asset = AssetDocument( + id: 'av', + name: 'av.mov', + storage: AssetStorage.external, + location: 'file:///av.mov', + ); + await workspace.project!.saveAsset(asset); + session.insertAsset( + sequenceId: sequence, + assetId: asset.id, + assetName: asset.name, + uri: Uri.file('/av.mov'), + duration: RationalTime.seconds(5), + position: 0, + kind: 'video', + hasAudio: true, + clipId: ElementId('av-clip'), + ); + expect( + (await invoke('clip.setAudio', 'audio', { + 'clipId': 'av-clip', + 'db': -6, + 'muted': true, + })).edit, + EditOutcome.committed, + ); + final q = session.view(sequence).version.kernelVersion.query(); + final gain = ClipAudioGain.fromRecord( + q.element(q.elementById(ElementId('av-clip'))!), + ); + expect(gain.db, -6); + expect(gain.muted, true); + final colors = + (await invoke('timeline.query', 'colors', {})).data['colorSpaces'] + as List; + final color = await invoke('media.setColorInterpretation', 'color', { + 'mediaId': 'av', + 'trackIndex': 0, + 'colorSpace': colors[1], + }); + expect(color.edit, EditOutcome.committed); + expect(session.mediaColorInterpretation('av', 0)?.name, colors[1]); + }); + + test( + 'project tools import query and insert explicit IDs with source ranges', + () async { + final file = File('${root.path}/still.png'); + await file.writeAsBytes([0]); + expect( + (await invoke('media.import', 'import-image', { + 'path': file.path, + })).data['added'], + 1, + ); + final media = + (await invoke('media.query', 'query-media', {})).data['media'] + as List; + final arguments = { + 'clipId': 'new-image', + 'mediaId': (media.single as Map)['mediaId'], + 'index': 1, + 'sourceStart': {'numerator': '0', 'denominator': 1}, + 'duration': {'numerator': '3', 'denominator': 1}, + }; + final inserted = await invoke( + 'timeline.insert', + 'insert-image', + arguments, + ); + expect( + inserted.edit, + EditOutcome.committed, + reason: '${inserted.toJson()}', + ); + expect( + (await invoke('timeline.insert', 'insert-image', arguments)).version, + inserted.version, + ); + expect( + session.persistence + .timeline(sequence) + .exportDto() + .elements + .any((e) => e.id.value == 'new-image'), + true, + ); + await session.flush(); + }, + ); + + test( + 'review: wrong-sequence parameter timeline cannot publish either kernel', + () { + final other = SequenceId('two'); + final before = session.persistence.timeline(sequence).current; + final otherBefore = session.persistence.timeline(other).current; + final timeline = session.previewParameters( + sequence, + ElementId('a'), + const ClipTransform(x: .25).parameters, + ); + expect(() => session.commitParameters(other, timeline), throwsStateError); + expect(session.persistence.timeline(sequence).current, same(before)); + expect(session.persistence.timeline(other).current, same(otherBefore)); + expect(session.dirty, false); + timeline.cancel(); + }, + ); + + test( + 'review: publication listeners observe the version of the new state', + () { + final before = session.commands.version; + String? observed; + session.addListener(() { + observed = session.commands.version; + }); + session.commands.setTransform( + sequence: sequence, + clip: ElementId('a'), + tick: 0, + change: (value) => value.copyWith(x: .25), + ); + expect(observed, isNot(before)); + expect(observed, session.commands.version); + }, + ); + + test('session owns versions and rejects edits reentering publication', () { + final before = session.version; + Object? rejected; + void listener() { + expect(session.commands.version, session.version); + try { + session.commands.setTransform( + sequence: sequence, + clip: ElementId('a'), + tick: 0, + change: (value) => value.copyWith(x: .75), + ); + } catch (error) { + rejected = error; + } + } + + session.addListener(listener); + session.commands.setTransform( + sequence: sequence, + clip: ElementId('a'), + tick: 0, + change: (value) => value.copyWith(x: .25), + ); + session.removeListener(listener); + expect(rejected, isA()); + expect(session.version, isNot(before)); + expect(session.commands.version, session.version); + final committed = session.version; + session.commands.setTransform( + sequence: sequence, + clip: ElementId('a'), + tick: 0, + change: (value) => value.copyWith(x: .5), + ); + expect(session.version, isNot(committed)); + }); + + test('runtime MCP settings start, stop and restart the listener', () async { + final reserved = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); + final port = reserved.port; + await reserved.close(); + final ids = (projectId, 'project'); + final container = ProviderContainer( + overrides: [ + editorTimelineProvider( + ids.$1, + ids.$2, + ).overrideWith((ref) async => session), + mcpSettingsRepositoryProvider.overrideWithValue( + MemoryMcpSettingsRepository(), + ), + ], + ); + addTearDown(container.dispose); + final subscription = container.listen( + editorMcpConnectionProvider(ids.$1, ids.$2), + (_, _) {}, + ); + addTearDown(subscription.close); + await container.read(mcpSettingsProvider.future); + await container + .read(mcpSettingsProvider.notifier) + .saveSettings(enabled: true, port: port); + await container.read(editorMcpConnectionProvider(ids.$1, ids.$2).future); + final socket = await Socket.connect(InternetAddress.loopbackIPv4, port); + final disconnected = socket.drain().onError( + (_, _) {}, + ); + await container + .read(mcpSettingsProvider.notifier) + .saveSettings(enabled: false); + await container.read(editorMcpConnectionProvider(ids.$1, ids.$2).future); + await disconnected.timeout(const Duration(seconds: 2)); + await expectLater( + Socket.connect(InternetAddress.loopbackIPv4, port), + throwsA(isA()), + ); + await container + .read(mcpSettingsProvider.notifier) + .saveSettings(enabled: true); + await container.read(editorMcpConnectionProvider(ids.$1, ids.$2).future); + final reconnected = await Socket.connect( + InternetAddress.loopbackIPv4, + port, + ); + reconnected.destroy(); + await container + .read(mcpSettingsProvider.notifier) + .saveSettings(enabled: false); + await container.read(editorMcpConnectionProvider(ids.$1, ids.$2).future); + }); + + test( + 'review: an occupied MCP port must not disable built-in Agent tools', + () async { + final occupied = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); + addTearDown(occupied.close); + final ids = (projectId, 'project'); + final container = ProviderContainer( + retry: (_, _) => null, + overrides: [ + applicationToolAccessProvider.overrideWithValue(access), + editorTimelineProvider( + ids.$1, + ids.$2, + ).overrideWith((ref) async => session), + editorMcpConfigurationProvider.overrideWithValue( + EditorMcpConfiguration( + port: occupied.port, + token: 'review-token-01234567890123456789012345', + ), + ), + ], + ); + addTearDown(container.dispose); + final subscription = container.listen( + editorAgentToolsProvider(ids.$1, ids.$2), + (_, _) {}, + ); + addTearDown(subscription.close); + final binding = await container.read( + editorAgentToolsProvider(ids.$1, ids.$2).future, + ); + expect( + binding.tools.any((tool) => tool.name == 'clip_setTransform'), + true, + ); + final mcpSubscription = container.listen( + editorMcpConnectionProvider(ids.$1, ids.$2), + (_, _) {}, + ); + addTearDown(mcpSubscription.close); + await expectLater( + container.read(editorMcpConnectionProvider(ids.$1, ids.$2).future), + throwsA(anything), + ); + expect( + (await container.read(editorAgentToolsProvider(ids.$1, ids.$2).future)) + .owner, + same(session), + ); + final tool = binding.tools.singleWhere( + (tool) => tool.name == 'clip_setTransform', + ); + final result = await tool.execute( + ToolCall( + id: 'offline-mcp', + name: tool.name, + arguments: { + ...position(96), + 'workspaceId': access.workspaces.keys.first, + }, + ), + ToolContext( + sessionId: 's', + runId: 'r', + operationId: 'offline-mcp', + cancellation: CancellationToken(), + onProgress: (_) {}, + ), + ); + expect(result.isError, false); + expect(transform().x, closeTo(96 / session.canvas.width, 1e-9)); + }, + ); + + test('queued tools recheck versions after synchronous UI commit', () async { + final before = session.commands.version; + final pending = invoke( + 'clip.setTransform', + 'stale', + position(100, version: before), + ); + session.commands.setTransform( + sequence: sequence, + clip: ElementId('a'), + tick: 0, + change: (value) => value.copyWith(rotation: 10), + ); + expect((await pending).code, 'staleVersion'); + expect(transform().x, 0); + expect(transform().rotation, 10); + }); + + test('explicit tool time edits animated channels without following the UI playhead', () async { + final view = session.view(sequence); + final query = view.version.kernelVersion.query(); + final animation = ClipAnimation.at( + query, + query.elementById(ElementId('a'))!, + 0, + TimelineClock.ticksPerSecond ~/ 30, + ); + session.commitParameters( + sequence, + session.previewParameters( + sequence, + ElementId('a'), + animation.toggle(TransformChannel.position), + ), + parameterTargets: ClipTransform.targets, + ); + view.seekTo(8 * TimelineClock.ticksPerSecond); + final result = await invoke('clip.setTransform', 'key', { + ...position(192), + 'at': {'numerator': '5', 'denominator': 1}, + }); + expect(result.edit, EditOutcome.committed); + final updated = view.version.kernelVersion.query(); + final curve = updated + .element(updated.elementById(ElementId('a'))!) + .parameters!['canvas.position.x']!; + expect(curve.keyframeAt(0), isNotNull); + expect( + curve.keyframeAt(5 * TimelineClock.ticksPerSecond)!.value, + closeTo(192 / session.canvas.width, 1e-9), + ); + expect(curve.keyframeAt(8 * TimelineClock.ticksPerSecond), isNull); + expect(view.playheadTick, 8 * TimelineClock.ticksPerSecond); + }); + + test('toolbar cuts enter the project commit boundary', () async { + final view = session.view(sequence); + final query = view.version.kernelVersion.query(); + view.setSelection([query.elementById(ElementId('a'))!]); + view.seekTo(5 * TimelineClock.ticksPerSecond); + final version = session.commands.version; + expect(view.cutSelectionAtPlayhead(), true); + expect(session.commands.version, isNot(version)); + expect( + (await invoke('timeline.undo', 'undo-cut', {})).edit, + EditOutcome.committed, + ); + final current = view.version.kernelVersion.query(); + expect(current.storylineLength(current.primaryStoryline), 2); + }); + + test('a prepared UI edit cannot overwrite a tool commit', () async { + final timeline = session.previewParameters( + sequence, + ElementId('a'), + const ClipTransform(x: .8).parameters, + ); + await invoke('clip.setTransform', 'remote', position(100)); + expect( + () => session.commitParameters(sequence, timeline), + throwsA(anything), + ); + expect(transform().x, closeTo(100 / session.canvas.width, 1e-9)); + timeline.cancel(); + }); + + test( + 'move, trim and delete share UI undo history and publish views', + () async { + final view = session.view(sequence); + expect( + (await invoke('timeline.move', 'move', { + 'clipId': 'b', + 'index': 0, + })).edit, + EditOutcome.committed, + ); + var query = view.version.kernelVersion.query(); + expect( + query.element(query.storylineElements(query.primaryStoryline).first).id, + ElementId('b'), + ); + expect( + (await invoke('timeline.trim', 'trim', { + 'clipId': 'b', + 'duration': {'numerator': '4', 'denominator': 1}, + })).edit, + EditOutcome.committed, + ); + expect( + (await invoke('timeline.delete', 'delete', {'clipId': 'a'})).edit, + EditOutcome.committed, + ); + view.undo(); + query = view.version.kernelVersion.query(); + expect(query.elementById(ElementId('a')), isNotNull); + view.undo(); + view.undo(); + query = view.version.kernelVersion.query(); + expect( + query.element(query.storylineElements(query.primaryStoryline).first).id, + ElementId('a'), + ); + }, + ); + + test('MCP targets a fixed sequence independently of UI selection and deduplicates connections', () async { + final target = access.workspaces.keys.first; + session.selectSequence(SequenceId('two')); + final request = jsonEncode( + _request('clip.setTransform', { + ...position(250), + 'workspaceId': target, + 'operationId': 'mcp-position', + }), + ); + final first = access.server.connect(); + final response = await first.handleJson(request); + expect((response!['result'] as Map)['isError'], false); + first.close(); + final version = session.commands.version; + final second = access.server.connect(); + await second.handleJson(request); + second.close(); + expect(session.commands.version, version); + expect(session.activeSequenceId, SequenceId('two')); + expect(transform().x, closeTo(250 / session.canvas.width, 1e-9)); + final other = session.view(SequenceId('two')).version.kernelVersion.query(); + expect( + ClipTransform.fromRecord( + other.element(other.elementById(ElementId('a'))!), + ).x, + 0, + ); + }); + + test( + 'Agent adapter uses the same dispatcher and recovers original outcomes', + () async { + final tool = access.agentTools.singleWhere( + (tool) => tool.name == 'clip_setTransform', + ); + final call = ToolCall( + id: 'call', + name: tool.name, + arguments: { + ...position(42), + 'workspaceId': access.workspaces.keys.first, + }, + ); + final context = ToolContext( + sessionId: 's', + runId: 'r', + operationId: 'agent-edit', + cancellation: CancellationToken(), + onProgress: (_) {}, + ); + expect(tool.validate(call.arguments), isNull); + for (final declaration in access.agentTools) { + expect(declaration.name, matches(RegExp(r'^[a-zA-Z0-9_-]{1,64}$'))); + } + expect((await tool.execute(call, context)).isError, false); + expect( + (await tool.recover!(call, context)).status, + RecoveryStatus.completed, + ); + final conflicting = ToolCall( + id: call.id, + name: call.name, + arguments: {...call.arguments, 'x': 999}, + ); + expect( + (await tool.recover!(conflicting, context)).status, + RecoveryStatus.unknown, + ); + session.view(sequence).undo(); + expect(transform().x, 0); + }, + ); + + test('invalid time, cancellation, conflicting IDs and closed sessions do not edit', () async { + final initial = session.commands.version; + final bad = await invoke('clip.setTransform', 'bad-time', { + ...position(1), + 'at': {'numerator': '20', 'denominator': 1}, + }); + expect(bad.code, 'invalidTime'); + final tools = editorToolsFor(session, sequence); + final cancelled = await tools.invoke( + name: 'clip.setTransform', + arguments: position(1), + context: CommandContext( + operationId: 'cancelled', + isCancelled: () => true, + ), + ); + expect(cancelled.code, 'cancelled'); + expect(session.commands.version, initial); + await invoke('clip.setTransform', 'id', position(10)); + expect( + (await invoke('clip.setTransform', 'id', position(11))).code, + 'operationIdConflict', + ); + await session.close(); + expect( + (await tools.invoke( + name: 'timeline.query', + arguments: {}, + context: const CommandContext(operationId: 'closed'), + )).code, + 'closed', + ); + }); + + test('real stdio launcher edits the open app host through authenticated loopback', () async { + const token = 'cutdex-test-token-01234567890123456789'; + final bridge = await LocalMcpBridge.start( + access.server, + port: 0, + token: token, + ); + addTearDown(bridge.close); + final process = await Process.start( + 'dart', + ['run', 'tool/mcp_stdio.dart'], + runInShell: Platform.isWindows, + environment: { + 'CUTDEX_MCP_PORT': '${bridge.port}', + 'CUTDEX_MCP_TOKEN': token, + }, + ); + addTearDown(process.kill); + final errors = process.stderr.transform(utf8.decoder).join(); + process.stdin.writeln( + jsonEncode( + _request('clip.setTransform', { + ...position(320), + 'workspaceId': access.workspaces.keys.first, + 'operationId': 'stdio', + }), + ), + ); + final response = jsonDecode( + await process.stdout + .transform(utf8.decoder) + .transform(const LineSplitter()) + .first + .timeout(const Duration(seconds: 15)), + ) as Map; + expect((response['result'] as Map)['isError'], false, reason: '$response'); + expect(transform().x, closeTo(320 / session.canvas.width, 1e-9)); + await process.stdin.close(); + expect(await process.exitCode.timeout(const Duration(seconds: 5)), 0); + expect(await errors, isNot(contains('Could not connect'))); + }); + + test('wrong bridge credentials cannot reach the editor', () async { + final bridge = await LocalMcpBridge.start( + access.server, + port: 0, + token: 'cutdex-test-token-01234567890123456789', + ); + addTearDown(bridge.close); + final socket = await Socket.connect( + InternetAddress.loopbackIPv4, + bridge.port, + ); + final before = session.commands.version; + socket.write( + 'wrong\n${jsonEncode(_request('clip.setTransform', {...position(12), 'workspaceId': access.workspaces.keys.first, 'operationId': 'bad'}))}\n', + ); + expect( + await socket + .fold(0, (count, bytes) => count + bytes.length) + .timeout(const Duration(seconds: 5)), + 0, + ); + expect(session.commands.version, before); + socket.destroy(); + }); + + test('endpoint replacement releases the port and ignores old page cleanup', () async { + const token = 'cutdex-test-token-01234567890123456789'; + final endpoint = EditorMcpEndpoint(); + addTearDown(endpoint.close); + final first = await endpoint.open(access.server, port: 0, token: token); + final second = await endpoint.open( + access.server, + port: first.port, + token: token, + ); + await endpoint.release(first); + final socket = await Socket.connect( + InternetAddress.loopbackIPv4, + second.port, + ); + socket.write( + '$token\n${jsonEncode(_request('timeline.query', {'workspaceId': access.workspaces.keys.first}))}\n', + ); + final response = jsonDecode( + await socket + .cast>() + .transform(utf8.decoder) + .transform(const LineSplitter()) + .first, + ) as Map; + expect((response['result'] as Map)['isError'], false, reason: '$response'); + socket.destroy(); + }); + + testWidgets( + 'MCP refreshes inspector fields and invalidates an older input timeline', + (tester) async { + final query = session.view(sequence).version.kernelVersion.query(); + await tester.pumpWidget( + ProviderScope( + overrides: [ + editorPreviewProvider( + projectId, + 'project', + ).overrideWith((ref) async => throw StateError('No preview')), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + theme: EditorTheme.penLight, + home: Scaffold( + body: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 225, + child: SingleChildScrollView( + child: PictureProperties( + projectId: projectId, + timelineId: 'project', + session: session, + sequence: sequence, + clip: query.element(query.elementById(ElementId('a'))!), + ), + ), + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + Finder field(String key) => find.descendant( + of: find.byKey(ValueKey(key)), + matching: find.byType(TextField), + ); + await tester.enterText(field('picture-x'), '999'); + final connection = access.server.connect(); + await tester.runAsync(() async { + await connection.handleJson( + jsonEncode( + _request('clip.setTransform', { + ...position(192), + 'workspaceId': access.workspaces.keys.first, + 'operationId': 'inspector', + }), + ), + ); + await session.flush(); + }); + connection.close(); + await tester.pump(); + FocusManager.instance.primaryFocus?.unfocus(); + await tester.pumpAndSettle(); + expect( + double.parse( + tester.widget(field('picture-x')).controller!.text, + ), + 192, + ); + expect( + double.parse( + tester.widget(field('picture-y')).controller!.text, + ), + 54, + ); + expect(transform().x, closeTo(192 / session.canvas.width, 1e-9)); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + }, + ); +} diff --git a/test/editor_theme_test.dart b/test/editor_theme_test.dart new file mode 100644 index 0000000..836d1e3 --- /dev/null +++ b/test/editor_theme_test.dart @@ -0,0 +1,105 @@ +import 'dart:math' as math; + +import 'package:cutdex/app/editor_theme.dart'; +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex_sdk/timeline_ui.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + test( + 'Pen presets give timeline the same Codex surface and ink hierarchy', + () { + final light = EditorTheme.penLight; + final dark = EditorTheme.penDark; + expect(light.colorScheme.surface, const Color(0xFFF6F6F6)); + expect(light.colorScheme.surfaceContainerLow, const Color(0xFFFAFAFA)); + expect(light.colorScheme.onSurface, const Color(0xFF020202)); + expect(light.colorScheme.onSurfaceVariant, const Color(0xFF71717A)); + expect(dark.colorScheme.surface, const Color(0xFF111111)); + expect(dark.colorScheme.surfaceContainerLow, const Color(0xFF151515)); + expect(dark.colorScheme.onSurface, const Color(0xFFFCFCFC)); + expect(dark.colorScheme.outline, const Color(0xFF3B82F6)); + expect(dark.dividerColor, const Color(0xFF303030)); + expect(dark.dividerTheme.color, dark.dividerColor); + expect(light.dividerColor, light.colorScheme.outlineVariant); + expect(dark.colorScheme.outlineVariant, isNot(dark.dividerColor)); + + final inspector = AppTheme.propertiesPanelTheme(dark); + expect(inspector.colorScheme.surface, const Color(0xFF151515)); + expect(inspector.textTheme.bodyMedium?.fontSize, 13); + expect(inspector.textTheme.labelLarge?.fontSize, 13); + expect(inspector.textTheme.labelMedium?.fontSize, 12); + expect(inspector.textTheme.labelSmall?.fontSize, 12); + + final timeline = dark.extension()!; + expect(timeline.backgroundColor, dark.colorScheme.surface); + expect( + timeline.primaryLaneBackgroundColor, + dark.colorScheme.surfaceContainerLow, + ); + expect(timeline.rulerBackgroundColor, dark.colorScheme.surface); + expect(timeline.rulerHeight, 20); + expect(timeline.clipBorderColor, const Color(0xFF303030)); + expect(timeline.gapColor, const Color(0xFF303030)); + expect(timeline.clipBorderWidth, 1); + expect(timeline.visualClipColor, const Color(0xFF2F2F2F)); + expect(timeline.audioClipColor, const Color(0xFF242424)); + expect(timeline.connectionLineColor, const Color(0xFF303030)); + expect(timeline.connectionLineWidth, 3); + expect(timeline.selectionOutlineColor, dark.colorScheme.onSurface); + expect(timeline.selectionOutlineWidth, 2); + expect(timeline.clipCornerRadius, 4); + expect(timeline.clipNameTextStyle.color, dark.colorScheme.onSurface); + expect(timeline.rulerTextStyle.color, dark.colorScheme.onSurfaceVariant); + expect(timeline.playheadColor, dark.colorScheme.onSurface); + expect(AppTheme.timelinePanelTheme(dark).dividerColor, dark.dividerColor); + final lightTimeline = light.extension()!; + expect(lightTimeline.backgroundColor, light.colorScheme.surface); + expect( + lightTimeline.clipNameTextStyle.color, + light.colorScheme.onSurface, + ); + expect(lightTimeline.clipBorderColor, light.colorScheme.outlineVariant); + expect( + timeline.scrollbarThumbColor, + const Color(0xFFFCFCFC).withValues(alpha: .084), + ); + }, + ); + + test('Neutral text and timeline labels remain legible in both modes', () { + for (final theme in [EditorTheme.penLight, EditorTheme.penDark]) { + final colors = theme.colorScheme; + expect( + _contrast(colors.onSurface, colors.surface), + greaterThanOrEqualTo(7), + ); + if (colors.surface != const Color(0xFFF6F6F6)) { + for (final surface in [colors.surface, colors.surfaceContainerLow]) { + expect( + _contrast(colors.onSurfaceVariant, surface), + greaterThanOrEqualTo(4.5), + ); + } + } + expect( + _contrast(colors.onPrimary, colors.primary), + greaterThanOrEqualTo(7), + ); + final timeline = theme.extension()!; + for (final color in [timeline.visualClipColor, timeline.audioClipColor]) { + expect( + _contrast(timeline.clipNameTextStyle.color!, color), + greaterThanOrEqualTo(4.5), + ); + } + } + }); +} + +double _contrast(Color first, Color second) { + final a = first.computeLuminance(); + final b = second.computeLuminance(); + return (math.max(a, b) + .05) / (math.min(a, b) + .05); +} diff --git a/test/editor_window_chrome_test.dart b/test/editor_window_chrome_test.dart new file mode 100644 index 0000000..9664ee6 --- /dev/null +++ b/test/editor_window_chrome_test.dart @@ -0,0 +1,503 @@ +import 'package:cutdex_native/cutdex_native.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; + +import 'dart:async'; + +import 'package:cutdex/integrations/platform/editor_window_chrome.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + const channel = MethodChannel('cutdex_native/window'); + const controlsChannel = MethodChannel('cutdex_native/window_controls'); + final binding = TestWidgetsFlutterBinding.ensureInitialized(); + tearDown(() { + debugDefaultTargetPlatformOverride = null; + binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, null); + binding.defaultBinaryMessenger.setMockMethodCallHandler( + controlsChannel, + null, + ); + }); + + Widget app( + String id, { + VoidCallback? onCloseRequested, + TargetPlatform platform = TargetPlatform.macOS, + Widget Function(BuildContext, bool)? builder, + GlobalKey? navigatorKey, + }) { + debugDefaultTargetPlatformOverride = platform; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + return MaterialApp( + navigatorKey: navigatorKey, + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + home: EditorWindowChrome( + key: ValueKey(id), + headerHeight: 40, + onCloseRequested: onCloseRequested ?? () {}, + builder: + builder ?? + (context, integrated) => + Text(integrated ? 'integrated' : 'standard'), + ), + ); + } + + Future nativeCall(String method, Object arguments) async { + final reply = Completer(); + binding.defaultBinaryMessenger.handlePlatformMessage( + channel.name, + const StandardMethodCodec().encodeMethodCall( + MethodCall(method, arguments), + ), + reply.complete, + ); + expect( + const StandardMethodCodec().decodeEnvelope((await reply.future)!), + true, + ); + } + + testWidgets( + 'Windows buttons dispatch commands and follow native window state', + (tester) async { + final calls = []; + binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, ( + call, + ) async { + calls.add(call); + return call.method == 'configureChrome' + ? (call.arguments as Map)['enabled'] + : null; + }); + await tester.pumpWidget(app('windows', platform: TargetPlatform.windows)); + await tester.pumpAndSettle(); + expect(calls.first.arguments, { + 'enabled': true, + 'headerHeight': 40.0, + 'interceptClose': true, + 'headerInteractive': true, + }); + expect(EditorWindowChrome.leadingWidth, 0); + await tester.tap(find.byKey(const Key('window-minimize'))); + await tester.tap(find.byKey(const Key('window-maximize'))); + await tester.tap(find.byKey(const Key('window-close'))); + expect(calls.skip(1).map((c) => c.method), [ + 'minimize', + 'toggleMaximize', + 'close', + ]); + await nativeCall('windowState', { + 'maximized': true, + 'maximizeHovered': true, + }); + await tester.pump(); + expect(find.byTooltip('还原'), findsOneWidget); + expect(find.byIcon(Icons.filter_none), findsOneWidget); + await tester.pumpWidget(const SizedBox()); + await tester.pump(); + expect(calls.last.arguments, {'enabled': false}); + debugDefaultTargetPlatformOverride = null; + }, + ); + + testWidgets( + 'Windows headers reserve caption space only in the rightmost pane', + (tester) async { + binding.defaultBinaryMessenger.setMockMethodCallHandler( + channel, + (call) async => call.method == 'configureChrome' + ? (call.arguments as Map)['enabled'] + : null, + ); + final width = ValueNotifier(250.0); + addTearDown(width.dispose); + await tester.pumpWidget( + app( + 'layout', + platform: TargetPlatform.windows, + builder: (context, integrated) => ValueListenableBuilder( + valueListenable: width, + builder: (context, sidebarWidth, _) => Row( + children: [ + SizedBox( + width: sidebarWidth, + child: Column( + children: [ + WindowHeaderPadding( + child: SizedBox( + height: 40, + child: Row( + children: [ + const Spacer(), + TextButton( + key: const Key('left-action'), + onPressed: () {}, + child: const Text('Left'), + ), + ], + ), + ), + ), + ], + ), + ), + Expanded( + child: WindowHeaderPane( + offset: Offset(sidebarWidth, 0), + child: Column( + children: [ + WindowHeaderPadding( + child: SizedBox( + height: 40, + child: Row( + children: [ + const Spacer(), + TextButton( + key: const Key('right-action'), + onPressed: () {}, + child: const Text('Right'), + ), + ], + ), + ), + ), + ], + ), + ), + ), + ], + ), + ), + ), + ); + await tester.pumpAndSettle(); + final controlsLeft = tester + .getTopLeft(find.byKey(const Key('window-minimize'))) + .dx; + expect(tester.getTopRight(find.byKey(const Key('left-action'))).dx, 250); + expect( + tester.getTopRight(find.byKey(const Key('right-action'))).dx, + controlsLeft, + ); + width.value = 700; + await tester.pump(); + expect( + tester.getTopRight(find.byKey(const Key('left-action'))).dx, + controlsLeft, + ); + expect(tester.takeException(), isNull); + expect(find.byKey(const Key('right-action')), findsNothing); + await tester.pumpWidget(const SizedBox()); + await tester.pump(); + debugDefaultTargetPlatformOverride = null; + }, + ); + + testWidgets( + 'Windows reports actual maximize bounds without rebuilding the workspace', + (tester) async { + var builds = 0; + final regions = []; + binding.defaultBinaryMessenger.setMockMethodCallHandler( + channel, + (call) async => call.method == 'configureChrome' + ? (call.arguments as Map)['enabled'] + : null, + ); + binding.defaultBinaryMessenger.setMockMethodCallHandler(controlsChannel, ( + call, + ) async { + regions.add(call); + return null; + }); + await tester.pumpWidget( + app( + 'regions', + platform: TargetPlatform.windows, + builder: (context, integrated) { + builds++; + return const SizedBox.expand(); + }, + ), + ); + await tester.pumpAndSettle(); + final count = builds; + final rect = tester.getRect(find.byKey(const Key('window-maximize'))); + final report = regions + .map((c) => c.arguments as Map) + .singleWhere((args) => args['role'] == 'maximize'); + expect(report['rect'], { + 'x': rect.left, + 'y': rect.top, + 'width': rect.width, + 'height': rect.height, + }); + await nativeCall('windowState', { + 'maximized': true, + 'maximizeHovered': true, + }); + await tester.pump(); + expect(builds, count); + expect(find.byTooltip('还原'), findsOneWidget); + await tester.pumpWidget(const SizedBox()); + await tester.pump(); + expect( + regions.any( + (c) => + (c.arguments as Map)['role'] == 'maximize' && + (c.arguments as Map)['rect'] == null, + ), + true, + ); + debugDefaultTargetPlatformOverride = null; + }, + ); + + testWidgets( + 'nested pane offsets reserve caption space on the first integrated frame', + (tester) async { + binding.defaultBinaryMessenger.setMockMethodCallHandler( + channel, + (call) async => call.method == 'configureChrome' + ? (call.arguments as Map)['enabled'] + : null, + ); + await tester.pumpWidget( + app( + 'nested', + platform: TargetPlatform.windows, + builder: (context, integrated) => Row( + children: [ + const SizedBox(width: 200), + Expanded( + child: WindowHeaderPane( + offset: const Offset(200, 0), + child: Row( + children: [ + const SizedBox(width: 100), + Expanded( + child: WindowHeaderPane( + offset: const Offset(100, 0), + child: Column( + children: [ + WindowHeaderPadding( + child: SizedBox( + height: 40, + child: Row( + children: [ + const Spacer(), + TextButton( + key: const Key('nested-action'), + onPressed: () {}, + child: const Text('Action'), + ), + ], + ), + ), + ), + ], + ), + ), + ), + ], + ), + ), + ), + ], + ), + ), + ); + await tester.pump(); + expect( + tester.getTopRight(find.byKey(const Key('nested-action'))).dx, + tester.getTopLeft(find.byKey(const Key('window-minimize'))).dx, + ); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + await tester.pump(); + debugDefaultTargetPlatformOverride = null; + }, + ); + + testWidgets( + 'Windows modal routes suspend header hit testing until dismissed', + (tester) async { + final calls = []; + binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, ( + call, + ) async { + calls.add(call); + return call.method == 'configureChrome' + ? (call.arguments as Map)['enabled'] + : null; + }); + final navigatorKey = GlobalKey(); + await tester.pumpWidget( + app( + 'modal', + platform: TargetPlatform.windows, + navigatorKey: navigatorKey, + ), + ); + await tester.pumpAndSettle(); + unawaited( + showDialog( + context: tester.element(find.byType(EditorWindowChrome)), + builder: (_) => const AlertDialog(content: Text('Modal')), + ), + ); + await tester.pumpAndSettle(); + expect( + calls.where((c) => c.method == 'setHeaderInteractive').last.arguments, + false, + ); + navigatorKey.currentState!.pop(); + await tester.pumpAndSettle(); + expect( + calls.where((c) => c.method == 'setHeaderInteractive').last.arguments, + true, + ); + await tester.pumpWidget(const SizedBox()); + await tester.pump(); + debugDefaultTargetPlatformOverride = null; + }, + ); + + testWidgets( + 'Windows hosts without the native plugin retain the standard header', + (tester) async { + await tester.pumpWidget( + app('old-windows', platform: TargetPlatform.windows), + ); + await tester.pumpAndSettle(); + expect(find.text('standard'), findsOneWidget); + expect(find.byKey(const Key('window-close')), findsNothing); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + await tester.pump(); + debugDefaultTargetPlatformOverride = null; + }, + ); + + testWidgets('enables native chrome and restores it when leaving the editor', ( + tester, + ) async { + final calls = []; + binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, ( + call, + ) async { + calls.add(call); + return (call.arguments as Map)['enabled']; + }); + await tester.pumpWidget(app('one')); + await tester.pumpAndSettle(); + expect(find.text('integrated'), findsOneWidget); + expect(calls.single.method, 'configureChrome'); + expect(calls.single.arguments, { + 'enabled': true, + 'headerHeight': 40.0, + 'interceptClose': true, + }); + await tester.pumpWidget(const SizedBox()); + await tester.pump(); + expect(calls.last.arguments, {'enabled': false}); + debugDefaultTargetPlatformOverride = null; + }); + + testWidgets('forwards the native close request to the current editor', ( + tester, + ) async { + binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, ( + call, + ) async { + return (call.arguments as Map)['enabled']; + }); + var requests = 0; + await tester.pumpWidget(app('one', onCloseRequested: () => requests += 1)); + await tester.pumpAndSettle(); + + final reply = Completer(); + binding.defaultBinaryMessenger.handlePlatformMessage( + channel.name, + const StandardMethodCodec().encodeMethodCall( + const MethodCall('requestClose'), + ), + reply.complete, + ); + final result = const StandardMethodCodec().decodeEnvelope( + (await reply.future)!, + ); + await tester.pump(); + + expect(result, isTrue); + expect(requests, 1); + await tester.pumpWidget(const SizedBox()); + await tester.pump(); + debugDefaultTargetPlatformOverride = null; + }); + + testWidgets('late enable reply cannot re-enable a disposed editor', ( + tester, + ) async { + final enabled = Completer(); + final calls = []; + binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, ( + call, + ) async { + final enable = (call.arguments as Map)['enabled'] as bool; + calls.add(enable); + return enable ? enabled.future : false; + }); + await tester.pumpWidget(app('one')); + await tester.pumpWidget(const SizedBox()); + enabled.complete(true); + await tester.pumpAndSettle(); + expect(calls, [true, false]); + expect(tester.takeException(), isNull); + debugDefaultTargetPlatformOverride = null; + }); + + testWidgets( + 'replacing an editor does not let the old owner disable the new one', + (tester) async { + final calls = []; + binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, ( + call, + ) async { + final enable = (call.arguments as Map)['enabled'] as bool; + calls.add(enable); + return enable; + }); + await tester.pumpWidget(app('one')); + await tester.pumpAndSettle(); + await tester.pumpWidget(app('two')); + await tester.pumpAndSettle(); + expect(calls.last, isTrue); + expect(find.text('integrated'), findsOneWidget); + await tester.pumpWidget(const SizedBox()); + await tester.pump(); + expect(calls.last, isFalse); + debugDefaultTargetPlatformOverride = null; + }, + ); + + testWidgets( + 'an unregistered native plugin keeps the standard Flutter heading', + (tester) async { + await tester.pumpWidget(app('one')); + await tester.pumpAndSettle(); + expect(find.text('standard'), findsOneWidget); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + await tester.pump(); + debugDefaultTargetPlatformOverride = null; + }, + ); +} diff --git a/test/export_publication_test.dart b/test/export_publication_test.dart new file mode 100644 index 0000000..1c6b6e5 --- /dev/null +++ b/test/export_publication_test.dart @@ -0,0 +1,85 @@ +import 'dart:io'; +import 'dart:convert'; + +import 'package:crypto/crypto.dart'; +import 'package:cutdex/integrations/runtime/export_publication.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + late Directory root; + setUp( + () async => + root = await Directory.systemTemp.createTemp('export-recovery-'), + ); + tearDown(() => root.delete(recursive: true)); + test( + 'published output is recovered repeatedly without encoding again', + () async { + final destination = File('${root.path}/result.mp4').uri; + var calls = 0; + Future encode(Uri uri) async { + calls++; + await File.fromUri(uri).writeAsString('encoded movie'); + return uri; + } + + await ExportPublication(destination, 'op').run('snapshot', encode); + for (var i = 0; i < 3; i++) { + expect( + await ExportPublication(destination, 'op').run('snapshot', encode), + destination, + ); + } + expect(calls, 1); + await expectLater( + ExportPublication(destination, 'op').run('other', encode), + throwsA(isA()), + ); + }, + ); + test('ready staging receipt recovers the publication crash window', () async { + final destination = File('${root.path}/result.mp4').uri; + final job = ExportPublication(destination, 'op'); + await job.directory.create(); + final bytes = utf8.encode('complete movie'); + await job.staged.writeAsBytes(bytes); + await job.receipt.writeAsString( + jsonEncode({ + 'operationId': 'op', + 'destination': destination.toString(), + 'fingerprint': 'snapshot', + 'bytes': bytes.length, + 'sha256': sha256.convert(bytes).toString(), + }), + ); + expect(await ExportPublication(destination, 'op').recover(), destination); + expect(await job.staged.exists(), false); + expect(await File.fromUri(destination).readAsBytes(), bytes); + }); + test( + 'incomplete and externally changed output never silently overwrites', + () async { + final destination = File('${root.path}/result.mp4').uri; + final job = ExportPublication(destination, 'op'); + await expectLater( + job.run('snapshot', (_) async => throw StateError('killed encoder')), + throwsStateError, + ); + expect(await job.recover(), null); + await expectLater( + job.run('snapshot', (_) async => destination), + throwsA(isA()), + ); + expect(await File.fromUri(destination).exists(), false); + final next = ExportPublication(destination, 'explicit-retry'); + await next.run('snapshot', (uri) async { + await File.fromUri(uri).writeAsString('complete'); + return uri; + }); + await File.fromUri(destination).writeAsString('changed'); + await expectLater(next.recover(), throwsA(isA())); + expect(await File.fromUri(destination).readAsString(), 'changed'); + }, + ); +} diff --git a/test/features/assistant/agent_composer_controller_test.dart b/test/features/assistant/agent_composer_controller_test.dart new file mode 100644 index 0000000..6e9e984 --- /dev/null +++ b/test/features/assistant/agent_composer_controller_test.dart @@ -0,0 +1,184 @@ +import 'package:cutdex/errors/app_failure.dart'; + +import 'dart:async'; + +import 'package:cutdex/features/assistant/agent_composer_controller.dart'; +import 'package:cutdex/features/assistant/agent_composer_store.dart'; +import 'package:cutdex/workspace/external_media_import.dart'; +import 'package:cutdex/workspace/media_import.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:flutter_test/flutter_test.dart'; + +final _asset = AssetDocument( + id: 'asset', + name: 'Photo', + storage: AssetStorage.external, + location: 'file:///photo.png', + metadata: {'kind': 'image'}, +); + +void main() { + test( + 'deleting a conversation discards its pending attachment destination', + () async { + final completed = Completer(); + final started = Completer(); + final store = AgentComposerStore( + createComposer: (_) => AgentComposerController( + canImport: () => true, + pickFiles: () async => [], + importMedia: (_) { + started.complete(); + return completed.future; + }, + ), + ); + addTearDown(store.dispose); + final old = store.composer('project', 'chat'); + final pending = old.importAttachments([ + const ExternalMediaFile(path: '/photo.png'), + ]); + await started.future; + store.removeConversation('project', 'chat'); + final replacement = store.composer('project', 'chat'); + completed.complete(ExternalMediaSelection(selected: [_asset])); + await pending; + expect(old.attachments, isEmpty); + expect(replacement.attachments, isEmpty); + }, + ); + + test('promoting a draft preserves controllers and pending imports until deletion', () async { + final completed = Completer(); + final started = Completer(); + final store = AgentComposerStore( + createComposer: (_) => AgentComposerController( + canImport: () => true, + pickFiles: () async => [], + importMedia: (_) { + started.complete(); + return completed.future; + }, + ), + ); + addTearDown(store.dispose); + final input = store.input('project', null)..text = 'Follow-up'; + final composer = store.composer('project', 'draft'); + final pending = composer.importAttachments([ + const ExternalMediaFile(path: '/photo.png'), + ]); + await started.future; + store.promoteDraft('project', 'draft', 'chat'); + store.removeDraft('project', 'draft'); + expect(store.input('project', 'chat'), same(input)); + expect(store.composer('project', 'chat'), same(composer)); + expect(store.input('project', null), isNot(same(input))); + expect(store.input('project', null).text, isEmpty); + completed.complete(ExternalMediaSelection(selected: [_asset])); + await pending; + expect(composer.attachments.single.id, _asset.id); + expect(input.text, 'Follow-up'); + store.removeConversation('project', 'chat'); + expect(store.input('project', 'chat'), isNot(same(input))); + expect(store.composer('project', 'chat'), isNot(same(composer))); + }); + + test('partial import failures survive until consumed, successful imports add no notice', () async { + var fail = true; + final composer = AgentComposerController( + canImport: () => true, + pickFiles: () async => [const ExternalMediaFile(path: '/photo.png')], + importMedia: (_) async => fail + ? const ExternalMediaSelection( + selected: [], + result: MediaImportResult( + assets: [], + added: 0, + duplicates: 0, + failures: [ + MediaImportFailure( + name: 'photo.png', + failure: AppFailure( + AppErrorCode.diagnostic, + diagnostic: 'unreadable', + ), + ), + ], + ), + ) + : ExternalMediaSelection(selected: [_asset]), + ); + addTearDown(composer.dispose); + await composer.pickAttachments(); + expect(composer.feedback.hasPending, isTrue); + expect( + composer.feedback.takePending().single!.result!.failures.single.name, + 'photo.png', + ); + expect(composer.feedback.hasPending, isFalse); + fail = false; + await composer.pickAttachments(); + expect(composer.attachments.single.id, _asset.id); + expect(composer.feedback.hasPending, isFalse); + }); + + test( + 'changing projects while file picking does not import into another project', + () async { + var active = true; + var imports = 0; + final files = Completer>(); + final composer = AgentComposerController( + canImport: () => active, + pickFiles: () => files.future, + importMedia: (_) async { + imports++; + return ExternalMediaSelection(selected: [_asset]); + }, + ); + addTearDown(composer.dispose); + final pending = composer.pickAttachments(); + active = false; + files.complete([const ExternalMediaFile(path: '/photo.png')]); + await pending; + expect(imports, 0); + expect(composer.attachments, isEmpty); + expect(composer.busy, isFalse); + }, + ); + + test( + 'attachment commands serialize and recover after import failure', + () async { + final completed = Completer(); + var calls = 0; + final composer = AgentComposerController( + canImport: () => true, + pickFiles: () async => [], + importMedia: (_) { + calls++; + return completed.future; + }, + ); + addTearDown(composer.dispose); + final first = composer.importAttachments([ + const ExternalMediaFile(path: '/photo.png'), + ]); + await Future.delayed(Duration.zero); + expect(composer.busy, isTrue); + expect( + await composer.importAttachments([ + const ExternalMediaFile(path: '/second.png'), + ]), + isNull, + ); + completed.completeError(StateError('import failed')); + await expectLater(first, throwsStateError); + expect(calls, 1); + expect(composer.busy, isFalse); + expect(composer.feedback.hasPending, isTrue); + expect(composer.feedback.takePending(), [null]); + expect(composer.feedback.hasPending, isFalse); + }, + ); +} diff --git a/test/features/media/background_removal_controller_test.dart b/test/features/media/background_removal_controller_test.dart new file mode 100644 index 0000000..aa5edb8 --- /dev/null +++ b/test/features/media/background_removal_controller_test.dart @@ -0,0 +1,87 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:crypto/crypto.dart'; +import 'package:cutdex/features/media/background_removal_controller.dart'; +import 'package:cutdex/features/media/processing_targets.dart'; +import 'package:cutdex/integrations/runtime/processing_resource_repository.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../../support/preview_fixture.dart'; + +void main() { + test('closing the download view retains the operation until explicit cancellation', () async { + final fixture = await createPreviewFixture(Uri.file('/unused.mov')); + final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + final started = Completer(); + final release = Completer(); + const payload = [1, 2, 3]; + server.listen((request) async { + started.complete(); + await release.future; + try { + request.response.add(payload); + await request.response.close(); + } on SocketException { + // Cancellation closes the downloading client's socket. + } on HttpException { + // The cancelled request may already have closed. + } + }); + final repository = ProcessingResourceRepository( + root: Directory('${fixture.directory.path}/Processing'), + catalog: [ + ProcessingResourcePackage( + capability: ProcessingCapability.backgroundRemoval, + id: 'model', + version: '1', + name: 'Model', + description: '', + artifacts: [ + ProcessingResourceArtifact( + path: 'model.onnx', + url: Uri.parse('http://localhost:${server.port}/model'), + sha256: sha256.convert(payload).toString(), + bytes: payload.length, + ), + ], + ), + ], + ); + final container = ProviderContainer(); + addTearDown(() async { + if (!release.isCompleted) release.complete(); + container.dispose(); + await server.close(force: true); + repository.dispose(); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + }); + final provider = backgroundRemovalControllerProvider( + fixture.timeline, + BackgroundRemovalClipTarget( + sequence: fixture.timeline.activeSequenceId!, + clipId: 'clip', + mediaId: 'media', + name: 'Clip', + ), + ); + final subscription = container.listen(provider, (_, _) {}); + final controller = container.read(provider.notifier); + final operation = controller.start(repository, download: true); + await started.future.timeout(const Duration(seconds: 5)); + subscription.close(); + await container.pump(); + expect(container.exists(provider), isTrue); + expect(container.read(provider), isA()); + controller.cancel(repository); + release.complete(); + await operation.timeout(const Duration(seconds: 5)); + expect(fixture.timeline.backgroundRemovals.tasks, isEmpty); + expect( + repository.installFor(ProcessingCapability.backgroundRemoval).state, + ProcessingResourceState.notInstalled, + ); + }); +} diff --git a/test/features/projects/conversation_sidebar_test.dart b/test/features/projects/conversation_sidebar_test.dart new file mode 100644 index 0000000..2362d62 --- /dev/null +++ b/test/features/projects/conversation_sidebar_test.dart @@ -0,0 +1,302 @@ +import 'package:cutdex/features/assistant/agent_composer_store.dart'; + +import 'dart:async'; +import 'dart:io'; + +import 'package:cutdex/features/projects/conversation_sidebar.dart'; +import 'package:cutdex/integrations/agent/conversation_repository.dart'; +import 'package:cutdex/workspace/project_state.dart'; +import 'package:cutdex/workspace/projects.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +const _projects = [ + RecentProject(id: 'a', name: 'A', path: '/a'), + RecentProject(id: 'b', name: 'B', path: '/b'), +]; + +class _Projects extends Projects { + @override + Future build() async => + ProjectState(recent: _projects, activeProject: _projects[0]); + void selectProject(int index) => state = AsyncData( + state.requireValue.copyWith(activeProject: _projects[index]), + ); + void renameProjectLocally() => state = AsyncData( + state.requireValue.copyWith( + recent: [ + _projects[0].copyWith(name: 'Renamed'), + _projects[1], + ], + ), + ); +} + +class _SlowProjects extends _Projects { + _SlowProjects(this._loaded); + final Completer _loaded; + @override + Future build() async { + await _loaded.future; + return super.build(); + } +} + +ConversationMetadata _item(String projectId) => ConversationMetadata( + id: '$projectId-chat', + projectId: projectId, + title: projectId, + createdAt: DateTime.utc(2026), + updatedAt: DateTime.utc(2026), + providerId: 'provider', + modelId: 'model', + timelineId: 'timeline', + pending: false, + responseDurationsMs: const [], +); + +class _Repository extends ConversationRepository { + _Repository() : super(Directory('/unused')); + Completer>? blocked; + final started = Completer(); + bool fail = false; + bool failDelete = false; + final trashed = []; + final deleted = {}; + final selections = {}; + @override + Future> list( + String projectId, { + bool trash = false, + }) async { + if (trash) return List.of(trashed); + if (fail) throw StateError('read failed'); + if (projectId == 'a' && blocked != null) { + if (!started.isCompleted) started.complete(); + return blocked!.future; + } + return [if (!deleted.contains('$projectId-chat')) _item(projectId)]; + } + + @override + Future deletePermanently( + String projectId, + String conversationId, + ) async { + if (failDelete) throw StateError('delete failed'); + deleted.add(conversationId); + trashed.removeWhere((item) => item.id == conversationId); + if (selections[projectId] == conversationId) selections[projectId] = null; + } + + @override + Future select(String projectId, String? conversationId) async { + selections[projectId] = conversationId; + } + + @override + Future selected(String projectId) async => + selections.containsKey(projectId) + ? selections[projectId] + : '$projectId-chat'; +} + +void main() { + late _Repository repository; + late ProviderContainer container; + setUp(() async { + repository = _Repository(); + container = ProviderContainer( + overrides: [ + projectsProvider.overrideWith(_Projects.new), + conversationRepositoryProvider.overrideWith((ref) async => repository), + ], + ); + await container.read(projectsProvider.future); + await container.read(conversationSidebarProvider.future); + }); + tearDown(() => container.dispose()); + + test( + 'permanent deletion releases only the removed conversation cache', + () async { + final store = container.read(agentComposerStoreProvider); + final removedInput = store.input('a', 'a-chat')..text = 'removed draft'; + final keptInput = store.input('b', 'b-chat')..text = 'keep this draft'; + final removedComposer = store.composer('a', 'a-chat'); + await container + .read(conversationSidebarProvider.notifier) + .delete(_item('a')); + expect(store.input('a', 'a-chat'), isNot(same(removedInput))); + expect(store.composer('a', 'a-chat'), isNot(same(removedComposer))); + expect(store.input('b', 'b-chat'), same(keptInput)); + expect(keptInput.text, 'keep this draft'); + }, + ); + + test('failed permanent deletion preserves drafts', () async { + repository.failDelete = true; + final store = container.read(agentComposerStoreProvider); + final input = store.input('a', 'a-chat')..text = 'preserve'; + final composer = store.composer('a', 'a-chat'); + await expectLater( + container.read(conversationSidebarProvider.notifier).delete(_item('a')), + throwsStateError, + ); + expect(store.input('a', 'a-chat'), same(input)); + expect(store.composer('a', 'a-chat'), same(composer)); + expect(input.text, 'preserve'); + }); + + test('empty trash removes all trashed conversation caches', () async { + repository.trashed.addAll([ + _item('a'), + _item('a').copyWith(id: 'a-second'), + ]); + await container.read(conversationSidebarProvider.notifier).reload(); + final store = container.read(agentComposerStoreProvider); + final first = store.input('a', 'a-chat'); + final second = store.input('a', 'a-second'); + await container.read(conversationSidebarProvider.notifier).emptyTrash(); + expect(store.input('a', 'a-chat'), isNot(same(first))); + expect(store.input('a', 'a-second'), isNot(same(second))); + expect(repository.deleted, containsAll(['a-chat', 'a-second'])); + }); + + test('initial loading waits for workspace data without publishing an obsolete snapshot', () async { + final loaded = Completer(); + final cold = ProviderContainer( + overrides: [ + projectsProvider.overrideWith(() => _SlowProjects(loaded)), + conversationRepositoryProvider.overrideWith((ref) async => repository), + ], + ); + addTearDown(cold.dispose); + final snapshot = cold.read(conversationSidebarProvider.future); + loaded.complete(); + expect((await snapshot).projectId, 'a'); + }); + + test( + 'refresh and project rename preserve an explicitly opened draft', + () async { + container.read(conversationSidebarProvider.notifier).newConversation(); + final draft = container.read(conversationSelectionProvider('a')).draftKey; + repository.blocked = Completer(); + final refresh = container + .read(conversationSidebarProvider.notifier) + .reload(); + await repository.started.future; + repository.blocked!.complete([_item('a').copyWith(title: 'Updated')]); + await refresh; + (container.read(projectsProvider.notifier) as _Projects) + .renameProjectLocally(); + await container.pump(); + expect( + container.read(conversationSelectionProvider('a')).selectedId, + isNull, + ); + expect( + container.read(conversationSelectionProvider('a')).draftKey, + draft, + ); + expect( + container + .read(conversationSidebarProvider) + .requireValue + .groups['a']! + .single + .title, + 'Updated', + ); + }, + ); + + test( + 'late conversation creation does not promote a replaced draft', + () async { + final sidebar = container.read(conversationSidebarProvider.notifier); + sidebar.newConversation(); + final selection = conversationSelectionProvider('a'); + final firstKey = container.read(selection).draftKey; + final store = container.read(agentComposerStoreProvider); + store.composer('a', firstKey); + sidebar.newConversation(); + final secondKey = container.read(selection).draftKey; + final secondComposer = store.composer('a', secondKey); + final input = store.input('a', null)..text = 'New draft'; + await sidebar.updateListing( + _item('a').copyWith(id: 'created'), + selectIfDraftKey: firstKey, + ); + expect(container.read(selection).selectedId, isNull); + expect(container.read(selection).draftKey, secondKey); + expect(store.input('a', null), same(input)); + expect(input.text, 'New draft'); + expect(store.composer('a', secondKey), same(secondComposer)); + expect(store.input('a', 'created').text, isEmpty); + }, + ); + + test( + 'a late refresh from the prior project never replaces the active list', + () async { + repository.blocked = Completer(); + final refresh = container + .read(conversationSidebarProvider.notifier) + .reload(); + await repository.started.future; + final blocked = repository.blocked!; + repository.blocked = null; + (container.read(projectsProvider.notifier) as _Projects).selectProject(1); + await container.pump(); + expect( + (await container.read(conversationSidebarProvider.future)).projectId, + 'b', + ); + blocked.complete([_item('a')]); + await refresh; + expect( + container.read(conversationSidebarProvider).requireValue.projectId, + 'b', + ); + expect( + container.read(conversationSelectionProvider('b')).selectedId, + 'b-chat', + ); + }, + ); + + test('reopening a project reloads its saved selection', () async { + final provider = conversationSelectionProvider('a'); + container.listen(provider, (_, _) {}); + expect(container.read(provider).selectedId, 'a-chat'); + repository.selections['a'] = null; + final projects = container.read(projectsProvider.notifier) as _Projects; + projects.selectProject(1); + await container.pump(); + await container.read(conversationSidebarProvider.future); + projects.selectProject(0); + await container.pump(); + await container.read(conversationSidebarProvider.future); + expect(container.read(provider).selectedId, isNull); + expect(container.read(provider).initialized, isTrue); + }); + + test( + 'a failed refresh retains the current rows and reports the failure', + () async { + repository.fail = true; + await container.read(conversationSidebarProvider.notifier).reload(); + final value = container.read(conversationSidebarProvider).requireValue; + expect(value.groups['a']!.single.id, 'a-chat'); + expect(value.reloadFailed, isTrue); + repository.fail = false; + await container.read(conversationSidebarProvider.notifier).reload(); + expect( + container.read(conversationSidebarProvider).requireValue.reloadFailed, + isFalse, + ); + }, + ); +} diff --git a/test/features/timeline/timeline_drop_duration_test.dart b/test/features/timeline/timeline_drop_duration_test.dart new file mode 100644 index 0000000..342dbde --- /dev/null +++ b/test/features/timeline/timeline_drop_duration_test.dart @@ -0,0 +1,198 @@ +import 'dart:convert'; + +import 'package:cutdex/features/timeline/timeline_external_drop_target.dart'; +import 'package:cutdex/features/timeline/timeline_drop_preparation.dart'; +import 'package:cutdex/workspace/preview_target.dart'; +import 'package:cutdex/workspace/project_state.dart'; +import 'package:cutdex/workspace/projects.dart'; +import 'package:cutdex/workspace/timeline_session.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../../support/preview_fixture.dart'; + +class _Projects extends Projects { + _Projects(this.session); + final EditorTimelineSession session; + + @override + Future build() async => ProjectState( + activeProject: const RecentProject( + id: 'project', + name: 'Project', + path: '/project', + ), + timeline: session.document, + ); + + @override + Future withAssetMedia( + String? projectId, + AssetDocument asset, + Future Function(MediaReference) action, + ) => action(MediaReference(id: asset.id, uri: Uri.parse(asset.location))); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + testWidgets('releasing an MPG drag commits its precise source duration', ( + tester, + ) async { + // Actual native probe duration of VENU662C.mpg (100 ns source clock). + const numerator = 64737467444; + const denominator = 10000000; + const ticks = 9135751405697; + const channel = MethodChannel('drop-duration-test'); + debugDefaultTargetPlatformOverride = TargetPlatform.windows; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + const MethodChannel('cutdex_native/file_drop/timeline'), + (_) async => null, + ); + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, ( + call, + ) async { + final request = jsonDecode((call.arguments as Map)['request'] as String); + expect(request['method'], 'probe'); + return jsonEncode({ + 'value': { + 'duration': {'numerator': '$numerator', 'denominator': denominator}, + 'videoTrackCount': 1, + 'audioTrackCount': 0, + 'videoTrackIds': [0], + 'audioTrackIds': [], + 'isProtected': false, + 'audioTracks': [], + }, + }); + }); + final fixture = await tester.runAsync( + () => createPreviewFixture(Uri.file('/VENU662C.mpg')), + ); + final session = fixture!.timeline; + final container = ProviderContainer( + overrides: [ + projectsProvider.overrideWith(() => _Projects(session)), + runtimeConnectionProvider.overrideWithValue( + CutdexRuntime(channel: channel), + ), + ], + ); + final incoming = ValueNotifier(null); + addTearDown(() async { + debugDefaultTargetPlatformOverride = null; + incoming.dispose(); + container.dispose(); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + channel, + null, + ); + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + const MethodChannel('cutdex_native/file_drop/timeline'), + null, + ); + }); + await container.read(projectsProvider.future); + final sequence = SequenceId('empty'); + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: MaterialApp( + home: Scaffold( + body: TimelineExternalDropTarget( + projectId: 'project', + session: session, + sequenceId: sequence, + incoming: incoming, + child: const SizedBox(width: 600, height: 300), + ), + ), + ), + ), + ); + final finder = find.byType(TimelineExternalDropTarget); + incoming.value = ( + asset: AssetDocument( + id: 'media', + name: 'VENU662C.mpg', + storage: AssetStorage.external, + location: Uri.file('/VENU662C.mpg').toString(), + ), + globalPosition: tester.getCenter(finder), + ); + await tester.runAsync( + () => container + .read( + timelineDropPreparationProvider( + 'project', + session, + sequence, + ).notifier, + ) + .waitForPreparation(), + ); + await tester.pumpAndSettle(); + final drop = tester.state(finder); + final preparation = container + .read(timelineDropPreparationProvider('project', session, sequence)) + .preparation; + expect( + drop.preparedMedia, + isNotNull, + reason: '${preparation.error}\n${preparation.stackTrace}', + ); + expect( + session.persistence.timeline(sequence).exportDto().elements, + isEmpty, + ); + + // This is the same release entry point as the media-library drag target. + await drop.drop(); + await tester.pumpAndSettle(); + expect( + find.byType(SnackBar), + findsNothing, + reason: find + .descendant(of: find.byType(SnackBar), matching: find.byType(Text)) + .evaluate() + .map((element) => (element.widget as Text).data) + .join('\n'), + ); + final element = session.persistence + .timeline(sequence) + .exportDto() + .elements + .singleWhere((element) => element.payloadRef != null); + final clock = session.persistence.timeline(sequence).clock; + expect(clock.toTicks(element.duration), ticks); + expect(element.sourceRange.start, RationalTime.zero); + expect(element.sourceRange.duration, element.duration); + expect(element.mediaRange!.duration, element.duration); + final remainder = + BigInt.from(numerator) * BigInt.from(TimelineClock.ticksPerSecond) - + BigInt.from(ticks) * BigInt.from(denominator); + expect(remainder >= BigInt.zero, isTrue); + expect(remainder < BigInt.from(denominator), isTrue); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.runAsync(session.close); + final stored = await tester.runAsync( + () => fixture.workspace.project!.loadTimeline(session.document.id), + ); + final restored = stored!.sequences + .singleWhere((item) => item.id == sequence) + .elements + .singleWhere((item) => item.payloadRef != null); + expect(clock.toTicks(restored.duration), ticks); + expect(restored.sourceRange.duration, element.sourceRange.duration); + expect(restored.mediaRange!.duration, element.mediaRange!.duration); + debugDefaultTargetPlatformOverride = null; + }); +} diff --git a/test/features/timeline/timeline_drop_preparation_test.dart b/test/features/timeline/timeline_drop_preparation_test.dart new file mode 100644 index 0000000..38b8f72 --- /dev/null +++ b/test/features/timeline/timeline_drop_preparation_test.dart @@ -0,0 +1,308 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:cutdex/features/timeline/timeline_drop_preparation.dart'; +import 'package:cutdex/workspace/project_state.dart'; +import 'package:cutdex/workspace/preview_target.dart'; +import 'package:cutdex/workspace/projects.dart'; +import 'package:cutdex/workspace/timeline_session.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../../support/preview_fixture.dart'; + +AssetDocument _image(String id) => AssetDocument( + id: id, + name: id, + storage: AssetStorage.external, + location: Uri.file('/$id.png').toString(), + metadata: const {'kind': 'image'}, +); + +class _Projects extends Projects { + _Projects(this._session); + final EditorTimelineSession _session; + Completer? _gate; + Completer? _acquiring; + @override + Future build() async => ProjectState( + activeProject: const RecentProject( + id: 'project', + name: 'Project', + path: '/project', + ), + timeline: _session.document, + ); + @override + Future withAssetMedia( + String? projectId, + AssetDocument asset, + Future Function(MediaReference) action, + ) async { + if (_acquiring?.isCompleted == false) _acquiring!.complete(); + final media = _gate == null + ? MediaReference(id: asset.id, uri: Uri.parse(asset.location)) + : await _gate!.future; + return action(media); + } + + void leave() => + state = AsyncData(state.requireValue.copyWith(activeProject: null)); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + test( + 'probe prepares validated metadata before placement or commit', + () async { + final fixture = await createPreviewFixture(Uri.file('/source.mpg')); + final projects = _Projects(fixture.timeline); + const channel = MethodChannel('prepared-drop-test'); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + var probes = 0; + var response = { + 'duration': {'numerator': '64737467444', 'denominator': 10000000}, + 'videoTrackCount': 1, + 'audioTrackCount': 0, + 'videoTrackIds': [0], + 'audioTrackIds': [], + 'audioTracks': [], + 'isProtected': false, + }; + messenger.setMockMethodCallHandler(channel, (call) async { + if (call.method == 'request') { + final request = jsonDecode( + (call.arguments as Map)['request'] as String, + ); + expect(request['method'], 'probe'); + } else { + expect(call.method, 'probe'); + } + probes++; + return call.method == 'request' + ? jsonEncode({'value': response}) + : response; + }); + final container = ProviderContainer( + overrides: [ + projectsProvider.overrideWith(() => projects), + runtimeConnectionProvider.overrideWithValue( + CutdexRuntime(channel: channel), + ), + ], + ); + addTearDown(() async { + container.dispose(); + messenger.setMockMethodCallHandler(channel, null); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + }); + await container.read(projectsProvider.future); + final provider = timelineDropPreparationProvider( + 'project', + fixture.timeline, + fixture.timeline.activeSequenceId!, + ); + container.listen(provider, (_, _) {}); + final controller = container.read(provider.notifier); + final source = TimelineDropSource.asset( + AssetDocument( + id: 'source', + name: 'Source', + storage: AssetStorage.external, + location: Uri.file('/source.mpg').toString(), + ), + ); + await controller.probe(source); + final prepared = container.read(provider).preparation.requireValue!; + expect(prepared.metadata.kind, EditorMediaKind.video); + expect(prepared.metadata.hasAudio, isFalse); + expect( + TimelineClock.standard.toTicks(prepared.metadata.duration), + 9135751405697, + ); + await controller.commit((_, _) async {}, isCurrent: () => true); + expect(probes, 1); + + // Unusable metadata must never reach placement validation or insertion. + for (final changes in >[ + { + 'duration': {'numerator': '1', 'denominator': 0xffffffff}, + }, + { + 'duration': {'numerator': '9223372036854775807', 'denominator': 1}, + }, + {'isProtected': true}, + {'videoTrackCount': 0, 'videoTrackIds': []}, + ]) { + response = {...response, ...changes}; + await controller.probe(source); + expect(container.read(provider).preparation.hasError, isTrue); + expect(container.read(provider).preparation.value, isNull); + final preparationError = container.read(provider).preparation.error; + var validations = 0; + var inserts = 0; + await expectLater( + controller.commit( + (_, _) async { + inserts++; + }, + isCurrent: () => true, + validatePlacement: () { + validations++; + }, + ), + throwsA(same(preparationError)), + ); + expect(validations, 0); + expect(inserts, 0); + expect(fixture.timeline.dirty, isFalse); + response = { + ...response, + 'duration': {'numerator': '64737467444', 'denominator': 10000000}, + 'videoTrackCount': 1, + 'videoTrackIds': [0], + 'isProtected': false, + }; + } + }, + ); + + test( + 'a late probe cannot replace or delay a newer incoming source', + () async { + final fixture = await createPreviewFixture(Uri.file('/unused.mov')); + final projects = _Projects(fixture.timeline); + final container = ProviderContainer( + overrides: [projectsProvider.overrideWith(() => projects)], + ); + addTearDown(() async { + container.dispose(); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + }); + await container.read(projectsProvider.future); + final provider = timelineDropPreparationProvider( + 'project', + fixture.timeline, + fixture.timeline.activeSequenceId!, + ); + container.listen(provider, (_, _) {}); + final controller = container.read(provider.notifier); + final delayed = projects._gate = Completer(); + final old = controller.probe(TimelineDropSource.asset(_image('old'))); + var oldFinished = false; + final oldCompletion = controller.waitForCompletion().then((_) { + oldFinished = true; + }); + projects._gate = null; + await controller.probe(TimelineDropSource.asset(_image('new'))); + await controller.waitForCompletion(); + expect(oldFinished, isFalse); + delayed.complete(MediaReference(id: 'old', uri: Uri.file('/old.png'))); + await old; + await oldCompletion; + expect(oldFinished, isTrue); + expect( + container.read(provider).preparation.requireValue!.media.id, + 'new', + ); + }, + ); + + test('a drop waits for its probe and ignores a duplicate commit', () async { + final fixture = await createPreviewFixture(Uri.file('/unused.mov')); + final projects = _Projects(fixture.timeline); + final container = ProviderContainer( + overrides: [projectsProvider.overrideWith(() => projects)], + ); + addTearDown(() async { + container.dispose(); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + }); + await container.read(projectsProvider.future); + final provider = timelineDropPreparationProvider( + 'project', + fixture.timeline, + fixture.timeline.activeSequenceId!, + ); + container.listen(provider, (_, _) {}); + final controller = container.read(provider.notifier); + final delayed = projects._gate = Completer(); + final probe = controller.probe(TimelineDropSource.asset(_image('source'))); + var inserts = 0; + var validations = 0; + final commit = controller.commit( + (_, _) async { + inserts++; + }, + isCurrent: () => true, + validatePlacement: () { + validations++; + }, + ); + expect(container.read(provider).commit.isLoading, isTrue); + expect(inserts, 0); + await controller.commit((_, _) async { + inserts++; + }, isCurrent: () => true); + expect(inserts, 0); + projects._gate = null; + delayed.complete( + MediaReference(id: 'source', uri: Uri.file('/source.png')), + ); + await probe; + await commit; + expect(validations, 1); + expect(inserts, 1); + expect(container.read(provider).commit.hasValue, isTrue); + expect(container.read(provider).commit.isLoading, isFalse); + }); + + test( + 'a project switch during media acquisition prevents committing a drag', + () async { + final fixture = await createPreviewFixture(Uri.file('/unused.mov')); + final projects = _Projects(fixture.timeline); + final container = ProviderContainer( + overrides: [projectsProvider.overrideWith(() => projects)], + ); + addTearDown(() async { + container.dispose(); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + }); + await container.read(projectsProvider.future); + final provider = timelineDropPreparationProvider( + 'project', + fixture.timeline, + fixture.timeline.activeSequenceId!, + ); + container.listen(provider, (_, _) {}); + final controller = container.read(provider.notifier); + await controller.probe(TimelineDropSource.asset(_image('source'))); + final delayed = projects._gate = Completer(); + final acquiring = projects._acquiring = Completer(); + var inserted = false; + final pending = controller.commit((_, _) async { + inserted = true; + }, isCurrent: () => true); + await acquiring.future; + projects.leave(); + delayed.complete( + MediaReference(id: 'source', uri: Uri.file('/source.png')), + ); + await pending; + expect(inserted, isFalse); + expect(fixture.timeline.dirty, isFalse); + }, + ); +} diff --git a/test/fullscreen_playback_bar_test.dart b/test/fullscreen_playback_bar_test.dart new file mode 100644 index 0000000..bf5faac --- /dev/null +++ b/test/fullscreen_playback_bar_test.dart @@ -0,0 +1,115 @@ +import 'package:cutdex/app/editor_theme.dart'; +import 'package:cutdex/features/preview/fullscreen_playback_bar.dart'; +import 'package:cutdex/l10n/l10n.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets( + 'fullscreen transport previews during dragging and settles on release', + (tester) async { + final seeks = []; + final updates = []; + final ends = []; + var starts = 0; + var plays = 0; + var exits = 0; + const second = TimelineClock.ticksPerSecond; + await tester.pumpWidget( + MaterialApp( + theme: EditorTheme.penDark, + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('en'), + home: Scaffold( + body: Center( + child: SizedBox( + width: 560, + child: FullscreenPlaybackBar( + positionTick: second, + durationTick: 48 * 60 * second, + frameTick: second ~/ 30, + playing: false, + onPlayPause: () => plays++, + onSeek: seeks.add, + onExit: () => exits++, + onScrubStart: () => starts++, + onScrubUpdate: updates.add, + onScrubEnd: ends.add, + ), + ), + ), + ), + ), + ); + expect(find.text('00:01'), findsOneWidget); + expect(find.text('-47:59'), findsOneWidget); + await tester.tap(find.byTooltip('Play')); + await tester.tap(find.byTooltip('Exit fullscreen')); + expect(plays, 1); + expect(exits, 1); + await tester.tap(find.byTooltip('Previous frame')); + await tester.tap(find.byTooltip('Next frame')); + expect(seeks, [second - second ~/ 30, second + second ~/ 30]); + seeks.clear(); + final rect = tester.getRect(find.byKey(const Key('fullscreen-progress'))); + final gesture = await tester.startGesture( + Offset(rect.left + 20, rect.center.dy), + ); + await gesture.moveTo(rect.center); + await tester.pump(); + expect(seeks, isEmpty); + expect(starts, 1); + expect(updates, isNotEmpty); + expect(updates.last, closeTo(24 * 60 * second, second)); + expect(ends, isEmpty); + await gesture.up(); + await tester.pump(); + expect(ends, hasLength(1)); + expect(ends.single, closeTo(24 * 60 * second, second)); + await tester.tap(find.byTooltip('Go to start')); + expect(seeks.last, 0); + expect(tester.takeException(), isNull); + }, + ); + + testWidgets('empty fullscreen transport stays usable at narrow widths', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('en'), + home: Scaffold( + body: Center( + child: SizedBox( + width: 280, + child: FullscreenPlaybackBar( + positionTick: 0, + durationTick: 0, + frameTick: TimelineClock.ticksPerSecond ~/ 30, + playing: false, + onPlayPause: null, + onSeek: null, + onExit: () {}, + onScrubStart: null, + onScrubUpdate: null, + onScrubEnd: null, + ), + ), + ), + ), + ), + ); + expect(tester.widget(find.byType(Slider)).onChanged, isNull); + expect( + tester + .widget(find.byKey(const Key('preview-fullscreen'))) + .onPressed, + isNotNull, + ); + expect(tester.takeException(), isNull); + }); +} diff --git a/test/generated_code_test.dart b/test/generated_code_test.dart new file mode 100644 index 0000000..a2ab4f6 --- /dev/null +++ b/test/generated_code_test.dart @@ -0,0 +1,94 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:crypto/crypto.dart'; + +const _generatedFiles = [ + ':(glob)lib/**/*.g.dart', + ':(glob)lib/**/*.freezed.dart', + ':(glob)test/**/*.g.dart', + ':(glob)test/**/*.freezed.dart', +]; + +void main() { + test('workspace generated code is up to date', () async { + await _expectNoUntrackedGeneratedFiles(); + final before = await _generatedContents(); + final flutterRoot = Platform.environment['FLUTTER_ROOT']; + final dart = flutterRoot == null + ? (Platform.isWindows ? 'dart.exe' : 'dart') + : '$flutterRoot/bin/cache/dart-sdk/bin/${Platform.isWindows ? 'dart.exe' : 'dart'}'; + for (final directory in _generatorRoots()) { + final result = await Process.run(dart, [ + 'run', + 'build_runner', + 'build', + ], workingDirectory: directory); + expect( + result.exitCode, + 0, + reason: '$directory\n${result.stdout}\n${result.stderr}', + ); + } + expect( + await _generatedContents(), + before, + reason: 'Generated files changed. Run dart run build_runner build and review the output.', + ); + await _expectNoUntrackedGeneratedFiles(); + }, timeout: const Timeout(Duration(minutes: 5))); +} + +Future _expectNoUntrackedGeneratedFiles() async { + final result = await Process.run('git', [ + 'ls-files', + '--others', + '--', + ..._generatedFiles, + ]); + expect(result.exitCode, 0, reason: '${result.stderr}'); + expect( + (result.stdout as String).trim(), + isEmpty, + reason: 'Generate and track the .g.dart and .freezed.dart files in Git.', + ); +} + +Future> _generatedContents() async { + final contents = {}; + for (final root in [ + for (final directory in _generatorRoots()) ...[ + '$directory/lib', + '$directory/test', + ], + ]) { + if (!Directory(root).existsSync()) continue; + await for (final entity in Directory(root).list(recursive: true)) { + if (entity is File && + (entity.path.endsWith('.g.dart') || + entity.path.endsWith('.freezed.dart'))) { + contents[entity.path] = sha256 + .convert( + utf8.encode( + (await entity.readAsString()).replaceAll('\r\n', '\n'), + ), + ) + .toString(); + } + } + } + return contents; +} + +Iterable _generatorRoots() sync* { + yield '.'; + for (final directory in Directory( + 'packages', + ).listSync().whereType()) { + final manifest = File('${directory.path}/pubspec.yaml').readAsStringSync(); + if (RegExp(r'^ build_runner:', multiLine: true).hasMatch(manifest)) { + yield directory.path; + } + } +} diff --git a/test/integration_support/real_media_report_test.dart b/test/integration_support/real_media_report_test.dart new file mode 100644 index 0000000..ab17367 --- /dev/null +++ b/test/integration_support/real_media_report_test.dart @@ -0,0 +1,52 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; + +import '../../integration_test/support/real_media_report.dart'; + +void main() { + test( + 'incremental report saves preserve metadata and the latest failures', + () async { + final directory = await Directory.systemTemp.createTemp( + 'real-media-report-', + ); + addTearDown(() => directory.delete(recursive: true)); + final file = File('${directory.path}/results.json'); + final metadata = { + 'platform': 'android', + 'previewOnly': true, + }; + final report = RealMediaReport(file, metadata: metadata); + metadata['previewOnly'] = false; + final checks = >[]; + report.files.add({ + 'path': 'source.mp4', + 'checks': checks, + 'passed': false, + }); + report.save(); + expect( + (jsonDecode(await file.readAsString()) as Map)['previewOnly'], + isTrue, + ); + checks.add({'stage': 'probe', 'passed': true}); + checks.add({ + 'stage': 'preview', + 'passed': false, + 'error': 'frame timeout', + }); + report.save(); + final saved = jsonDecode(await file.readAsString()) as Map; + expect(saved['platform'], 'android'); + final recorded = (saved['files'] as List).single as Map; + expect(recorded['passed'], isFalse); + expect( + (recorded['checks'] as List).last, + containsPair('error', 'frame timeout'), + ); + expect(File('${file.path}.part').existsSync(), isFalse); + }, + ); +} diff --git a/test/integrations/platform/file_picker_test.dart b/test/integrations/platform/file_picker_test.dart new file mode 100644 index 0000000..d1f3f26 --- /dev/null +++ b/test/integrations/platform/file_picker_test.dart @@ -0,0 +1,103 @@ +import 'package:cutdex/integrations/platform/file_picker.dart'; +import 'package:flutter/services.dart'; +import 'package:cutdex/workspace/media_import.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + const picker = AppFilePicker(); + const channel = MethodChannel('filegate'); + Object? response; + MethodCall? lastCall; + + setUp(() { + response = null; + lastCall = null; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (call) async { + lastCall = call; + return response; + }); + }); + tearDown(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, null); + }); + + test( + 'selects an empty directory and preserves the initial location and label', + () async { + response = [ + {'path': '/tmp/empty', 'name': 'empty', 'kind': 'directory'}, + ]; + expect( + await picker.pickDirectory( + initialDirectory: '/tmp', + confirmButtonText: '选择', + ), + '/tmp/empty', + ); + expect(lastCall!.arguments, containsPair('enumerateDirectories', false)); + expect(lastCall!.arguments, containsPair('initialDirectory', '/tmp')); + expect(lastCall!.arguments, containsPair('confirmButtonText', '选择')); + }, + ); + + test('cancelled directory and file dialogs produce no selection', () async { + expect(await picker.pickDirectory(), isNull); + expect(await picker.pickFiles(allowedExtensions: ['mp4']), isEmpty); + }); + + test( + 'converts file URLs to local paths while retaining extension filtering', + () async { + response = [ + {'path': 'file:///tmp/a%20b.mp4', 'name': 'a b.mp4', 'kind': 'file'}, + {'path': '/tmp/c.wav', 'name': 'c.wav', 'kind': 'file'}, + ]; + expect(await picker.pickFiles(allowedExtensions: ['.MP4', 'wav']), [ + const ExternalMediaFile(path: '/tmp/a b.mp4'), + const ExternalMediaFile(path: '/tmp/c.wav'), + ]); + expect(lastCall!.arguments, containsPair('allowMultiple', true)); + expect( + lastCall!.arguments, + containsPair('allowedExtensions', ['mp4', 'wav']), + ); + }, + ); + + test( + 'preserves provider URI, display name and size for project import', + () async { + response = [ + { + 'path': 'content://provider/file/1', + 'name': 'a.mp4', + 'kind': 'file', + 'metadata': {'size': 42}, + }, + ]; + expect(await picker.pickFiles(allowedExtensions: ['mp4']), [ + ExternalMediaFile.content( + uri: Uri.parse('content://provider/file/1'), + name: 'a.mp4', + byteLength: 42, + ), + ]); + expect(lastCall!.arguments, containsPair('persistAccess', false)); + }, + ); + + test('propagates native picker failures', () async { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + channel, + (_) async => throw PlatformException(code: 'picker_active'), + ); + await expectLater( + picker.pickDirectory(), + throwsA(isA()), + ); + }); +} diff --git a/test/language_settings_test.dart b/test/language_settings_test.dart new file mode 100644 index 0000000..3eb226b --- /dev/null +++ b/test/language_settings_test.dart @@ -0,0 +1,325 @@ +import 'package:cutdex/app/app.dart'; +import 'package:cutdex/app/router/app_router.dart'; +import 'package:cutdex/features/settings/appearance_settings.dart'; +import 'package:cutdex/features/settings/language_settings.dart'; +import 'package:cutdex/persistence/settings/language_settings_repository.dart'; +import 'package:cutdex/features/settings/settings_dialog.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex/l10n/app_localizations_en.dart'; +import 'package:cutdex/l10n/app_messages.dart'; +import 'package:cutdex/errors/app_failure.dart'; +import 'package:cutdex/l10n/app_localizations_zh.dart'; +import 'package:cutdex_ui/widgets.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:go_router/go_router.dart'; + +void main() { + test('Agent errors use both Simplified and Traditional Chinese', () { + final simplified = AppLocalizationsZhHans(); + final traditional = AppLocalizationsZhHant(); + expect(simplified.agentContextBudgetExceeded, contains('输入预算不足')); + expect(traditional.agentContextBudgetExceeded, contains('輸入預算不足')); + expect(simplified.agentAuthenticationFailed, contains('鉴权失败')); + expect(traditional.agentAuthenticationFailed, contains('驗證失敗')); + }); + + test( + 'language choice is saved and restored by a new provider container', + () async { + final repository = _LanguageRepository(); + final container = ProviderContainer( + overrides: [ + languageSettingsRepositoryProvider.overrideWithValue(repository), + ], + ); + expect( + await container.read(languageSettingsProvider.future), + AppLanguage.system, + ); + await container + .read(languageSettingsProvider.notifier) + .setLanguage(AppLanguage.english); + container.dispose(); + + final reopened = ProviderContainer( + overrides: [ + languageSettingsRepositoryProvider.overrideWithValue(repository), + ], + ); + addTearDown(reopened.dispose); + expect( + await reopened.read(languageSettingsProvider.future), + AppLanguage.english, + ); + await reopened + .read(languageSettingsProvider.notifier) + .setLanguage(AppLanguage.system); + expect( + reopened.read(languageSettingsProvider).requireValue.locale, + isNull, + ); + }, + ); + + test('failed persistence preserves the current language', () async { + final repository = _LanguageRepository() + ..language = AppLanguage.simplifiedChinese; + final container = ProviderContainer( + overrides: [ + languageSettingsRepositoryProvider.overrideWithValue(repository), + ], + ); + addTearDown(container.dispose); + await container.read(languageSettingsProvider.future); + repository.failSave = true; + await expectLater( + container + .read(languageSettingsProvider.notifier) + .setLanguage(AppLanguage.english), + throwsStateError, + ); + expect( + container.read(languageSettingsProvider).requireValue, + AppLanguage.simplifiedChinese, + ); + }); + + testWidgets( + 'settings switch immediately and system choice follows device locale', + (tester) async { + tester.platformDispatcher.localesTestValue = const [Locale('zh')]; + addTearDown(tester.platformDispatcher.clearLocalesTestValue); + final repository = _LanguageRepository(); + final router = GoRouter( + routes: [ + GoRoute( + path: '/', + builder: (_, _) => const Scaffold(body: SettingsDialog()), + ), + ], + ); + final container = ProviderContainer( + overrides: [ + languageSettingsRepositoryProvider.overrideWithValue(repository), + appearanceSettingsProvider.overrideWith(_Appearance.new), + appRouterProvider.overrideWithValue(router), + ], + ); + addTearDown(container.dispose); + addTearDown(router.dispose); + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: const CutdexApp(), + ), + ); + await tester.pumpAndSettle(); + expect(find.text('通用'), findsNWidgets(3)); + + await tester.tap(find.byType(AppSelect)); + await tester.pumpAndSettle(); + await tester.tap(find.text('English')); + await tester.pumpAndSettle(); + expect(find.text('General'), findsNWidgets(3)); + expect(repository.language, AppLanguage.english); + + tester.platformDispatcher.localesTestValue = const [Locale('zh', 'CN')]; + await tester.pumpAndSettle(); + expect(find.text('General'), findsNWidgets(3)); + + await tester.tap(find.byType(AppSelect)); + await tester.pumpAndSettle(); + await tester.tap(find.text('System default').last); + await tester.pumpAndSettle(); + expect(find.text('通用'), findsNWidgets(3)); + expect(repository.language, AppLanguage.system); + + tester.platformDispatcher.localesTestValue = const [Locale('sw')]; + await tester.pumpAndSettle(); + expect(find.text('General'), findsNWidgets(3)); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + }, + ); + + test('Chinese scripts and regions resolve in device preference order', () { + final supported = AppLocalizations.supportedLocales; + const hans = Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hans'); + const hant = Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hant'); + for (final country in ['TW', 'HK', 'MO']) { + expect(resolveAppLocale([Locale('zh', country)], supported), hant); + } + expect(resolveAppLocale(const [Locale('zh', 'CN')], supported), hans); + expect(resolveAppLocale(const [Locale('zh', 'SG')], supported), hans); + expect(resolveAppLocale(const [Locale('zh')], supported), hans); + expect( + resolveAppLocale(const [ + Locale.fromSubtags( + languageCode: 'zh', + scriptCode: 'Hans', + countryCode: 'TW', + ), + ], supported), + hans, + ); + expect( + resolveAppLocale(const [ + Locale.fromSubtags( + languageCode: 'zh', + scriptCode: 'Hant', + countryCode: 'CN', + ), + ], supported), + hant, + ); + expect( + resolveAppLocale(const [Locale('sw'), Locale('pt', 'BR')], supported), + const Locale('pt'), + ); + expect( + resolveAppLocale(const [Locale('sw')], supported), + const Locale('en'), + ); + expect(resolveAppLocale(null, supported), const Locale('en')); + // Fallback stays English regardless of generator ordering. + expect( + resolveAppLocale(const [Locale('sw')], supported.reversed), + const Locale('en'), + ); + }); + + test('default timeline names follow every supported locale', () { + final expected = { + 'de': 'Timeline 2', + 'en': 'Timeline 2', + 'es': 'Línea de tiempo 2', + 'fr': 'Timeline 2', + 'it': 'Timeline 2', + 'ja': 'タイムライン 2', + 'ko': '타임라인 2', + 'pt': 'Linha do tempo 2', + 'ru': 'Таймлайн 2', + 'zh': '时间线 2', + 'zh-Hans': '时间线 2', + 'zh-Hant': '時間軸 2', + }; + for (final locale in AppLocalizations.supportedLocales) { + final key = [locale.languageCode, ?locale.scriptCode].join('-'); + expect( + lookupAppLocalizations(locale).defaultTimelineName(2), + expected[key], + reason: key, + ); + } + }); + + testWidgets( + 'every language is selectable and updates settings and direction', + (tester) async { + final repository = _LanguageRepository(); + final router = GoRouter( + routes: [ + GoRoute( + path: '/', + builder: (_, _) => const Scaffold(body: SettingsDialog()), + ), + ], + ); + final container = ProviderContainer( + overrides: [ + languageSettingsRepositoryProvider.overrideWithValue(repository), + appearanceSettingsProvider.overrideWith(_Appearance.new), + appRouterProvider.overrideWithValue(router), + ], + ); + addTearDown(container.dispose); + addTearDown(router.dispose); + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: const CutdexApp(), + ), + ); + await tester.pumpAndSettle(); + final choices = [ + (AppLanguage.english, 'Settings'), + (AppLanguage.simplifiedChinese, '设置'), + (AppLanguage.traditionalChinese, '設定'), + (AppLanguage.japanese, '設定'), + (AppLanguage.korean, '설정'), + (AppLanguage.french, 'Paramètres'), + (AppLanguage.german, 'Einstellungen'), + (AppLanguage.spanish, 'Ajustes'), + (AppLanguage.portuguese, 'Configurações'), + (AppLanguage.italian, 'Impostazioni'), + (AppLanguage.russian, 'Настройки'), + ]; + for (final (language, heading) in choices) { + final languageSelect = find.byType(AppSelect); + await tester.ensureVisible(languageSelect); + await tester.tap(languageSelect); + await tester.pumpAndSettle(); + final option = find.text(language.nativeName).last; + await tester.ensureVisible(option); + await tester.tap(option); + await tester.pumpAndSettle(); + expect(tester.widget(find.byType(AppDialog)).title, heading); + expect(find.text(heading), findsOneWidget); + final l10n = AppLocalizations.of( + tester.element(find.byType(SettingsDialog)), + )!; + expect(find.text(l10n.general), findsNWidgets(3)); + expect(repository.language, language); + final context = tester.element(find.byType(SettingsDialog)); + expect(Localizations.localeOf(context), language.locale); + expect(Directionality.of(context), TextDirection.ltr); + expect(tester.takeException(), isNull); + } + // Rebuild at a narrow size to exercise field wrapping and dialog layout. + tester.view.physicalSize = const Size(360, 400); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + await tester.pumpAndSettle(); + expect( + tester.widget(find.byType(AppDialog)).title, + 'Настройки', + ); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + }, + ); + + test('localized parameters and known domain errors preserve diagnostics', () { + final en = AppLocalizationsEn(); + final zh = AppLocalizationsZh(); + expect(en.removeMediaConfirmation('shot.mp4'), contains('shot.mp4')); + expect(zh.captionsImported('3'), '已导入 3 条字幕'); + expect( + en.failureMessage(const AppFailure(AppErrorCode.mediaNoLongerExists)), + 'Media no longer exists', + ); + expect(en.errorMessage('Native error 123'), 'Native error 123'); + }); +} + +class _Appearance extends AppearanceSettings { + @override + Future build() async => AppAppearance.system; +} + +class _LanguageRepository implements LanguageSettingsRepository { + AppLanguage language = AppLanguage.system; + bool failSave = false; + + @override + Future load() async => language; + + @override + Future save(AppLanguage value) async { + if (failSave) throw StateError('Storage unavailable'); + language = value; + } +} diff --git a/test/localization_resources_test.dart b/test/localization_resources_test.dart new file mode 100644 index 0000000..92f7e84 --- /dev/null +++ b/test/localization_resources_test.dart @@ -0,0 +1,93 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:cutdex/features/settings/language_settings.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + final template = _read('en'); + final keys = template.keys.where((key) => !key.startsWith('@')).toSet(); + final locales = [ + 'en', + 'zh', + 'zh_Hans', + 'zh_Hant', + 'ja', + 'ko', + 'fr', + 'de', + 'es', + 'pt', + 'it', + 'ru', + ]; + for (final locale in locales) { + test( + '$locale has complete nonempty translations and unchanged parameters', + () { + final translations = _read(locale); + expect(translations['@@locale'], locale); + expect( + translations.keys.where((key) => !key.startsWith('@')).toSet(), + keys, + ); + for (final key in keys) { + final value = translations[key] as String; + expect(value.trim(), isNotEmpty, reason: '$locale:$key'); + expect(value, isNot(contains('ZXQ')), reason: '$locale:$key'); + expect( + _parameters(value), + _parameters(template[key] as String), + reason: '$locale:$key', + ); + // Preserve the names of formats, models, and diagnostic codes. + for (final term in [ + 'MCP', + 'MP4', + 'SRT', + 'iTT', + 'CEA-608', + 'SCC', + 'SubRip', + 'Rec.709', + 'HDR', + 'SDR', + 'MelBand', + 'Whisper Turbo', + 'notConfigured', + 'noAudio', + 'invalidResult', + 'workerExited', + 'processingFailed', + ]) { + if ((template[key] as String).contains(term)) { + expect(value, contains(term), reason: '$locale:$key'); + } + } + } + }, + ); + } + + test('all eleven selectable locales have generated resource support', () { + final choices = AppLanguage.values.where( + (language) => language != AppLanguage.system, + ); + expect(choices.length, 11); + for (final choice in choices) { + expect(AppLocalizations.supportedLocales, contains(choice.locale)); + } + expect(AppLocalizations.supportedLocales.first.languageCode, 'en'); + }); +} + +Map _read(String locale) => + jsonDecode(File('lib/l10n/app_$locale.arb').readAsStringSync()) + as Map; + +Set _parameters(String value) => + RegExp(r'\{(\w+)(?:\}|,)') + .allMatches(value) + .map((match) => match[1]!) + .toSet(); diff --git a/test/localized_surfaces_test.dart b/test/localized_surfaces_test.dart new file mode 100644 index 0000000..0d5e835 --- /dev/null +++ b/test/localized_surfaces_test.dart @@ -0,0 +1,211 @@ +import 'package:cutdex/errors/app_failure.dart'; +import 'package:cutdex/workspace/persistence/timeline_creation_names.dart'; + +import 'dart:io'; + +import 'package:cutdex/app/shells/phone_workspace_shell.dart'; +import 'package:cutdex/app/shells/tablet_workspace_shell.dart'; +import 'package:cutdex/features/assistant/composer_document.dart'; +import 'package:cutdex/features/assistant/composer_suggestion_surface.dart'; +import 'package:cutdex/l10n/l10n.dart'; +import 'package:cutdex/workspace/media_color_interpretation.dart'; +import 'package:cutdex/workspace/persistence/project_workspace.dart'; +import 'package:cutdex/workspace/workspace_mode.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +Widget _localized(Locale locale, Widget child) => MaterialApp( + locale: locale, + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold(body: child), +); + +void main() { + for (final tablet in [false, true]) { + testWidgets( + '${tablet ? 'tablet' : 'phone'} navigation follows locale changes', + (tester) async { + Widget shell() => tablet + ? TabletWorkspaceShell( + mode: WorkspaceMode.agent, + onModeChanged: (_) {}, + navigation: const SizedBox(), + headerActions: const SizedBox(), + title: '', + integratedTitlebar: false, + agent: const SizedBox(), + editor: const SizedBox(), + ) + : PhoneWorkspaceShell( + mode: WorkspaceMode.agent, + onModeChanged: (_) {}, + navigation: const SizedBox(), + headerActions: const SizedBox(), + title: '', + integratedTitlebar: false, + agent: const SizedBox(), + editor: const SizedBox(), + ); + for (final (locale, agent, cut) in [ + (const Locale('en'), 'Agent', 'Cut'), + (const Locale('zh'), '助手', '剪辑'), + (const Locale('fr'), 'Assistant', 'Montage'), + ]) { + await tester.pumpWidget(_localized(locale, shell())); + await tester.pumpAndSettle(); + expect(find.text(agent), findsOneWidget); + expect(find.text(cut), findsOneWidget); + expect(tester.takeException(), isNull); + } + }, + ); + } + + testWidgets('open reference menu follows locale without changing the draft', ( + tester, + ) async { + final controller = ComposerDocumentController(); + addTearDown(controller.dispose); + Widget composer() => Center( + child: ComposerSuggestionSurface( + controller: controller, + projectId: 'project', + assets: const [], + timelines: const [], + width: 300, + onSend: () {}, + builder: (_, focus) => + TextField(controller: controller, focusNode: focus), + ), + ); + await tester.pumpWidget(_localized(const Locale('en'), composer())); + await tester.enterText(find.byType(TextField), '@missing'); + await tester.pumpAndSettle(); + expect(find.text('No options available'), findsOneWidget); + await tester.pumpWidget(_localized(const Locale('zh'), composer())); + await tester.pumpAndSettle(); + expect(find.text('暂无可用选项'), findsOneWidget); + expect(controller.text, '@missing'); + await tester.pumpWidget(const SizedBox()); + }); + + test('subtitle languages localize names while preserving protocol codes', () { + final expected = { + 'en': ['English', 'Japanese', 'Cantonese'], + 'zh': ['英语', '日语', '粤语'], + 'zh-Hant': ['英文', '日文', '粵語'], + 'fr': ['anglais', 'japonais', 'cantonais'], + }; + for (final locale in AppLocalizations.supportedLocales) { + final l10n = lookupAppLocalizations(locale); + final key = [locale.languageCode, ?locale.scriptCode].join('-'); + if (expected[key] case final names?) { + expect(['en', 'ja', 'yue'].map(l10n.subtitleLanguageName), names); + } + for (final code in { + ...m2m100LanguageNames.keys, + ...subtitleNativeLanguageNames.keys, + }) { + expect( + l10n.subtitleLanguageName(code), + isNot(code), + reason: '$key:$code', + ); + } + expect(l10n.subtitleLanguageName('auto'), l10n.autoDetect); + expect(l10n.subtitleLanguageName('none'), l10n.noTranslation); + expect(l10n.subtitleLanguageName('unknown-code'), 'unknown-code'); + } + }); + + test('known exceptions translate without losing unknown diagnostic text', () { + final en = lookupAppLocalizations(const Locale('en')); + final zh = lookupAppLocalizations(const Locale('zh')); + expect( + en.errorMessage( + AppException(AppErrorCode.mediaReadFailed, diagnostic: 'Any wording'), + ), + en.mediaReadFailed, + ); + expect( + en.errorMessage( + AppException( + AppErrorCode.timelineRequired, + diagnostic: 'Different punctuation!', + ), + ), + en.timelineRequired, + ); + expect( + en.errorMessage( + AppException( + AppErrorCode.resourceDownloadHttpFailed, + httpStatusCode: 503, + ), + ), + en.resourceDownloadHttpFailed('503'), + ); + expect( + en.errorMessage(AppException(AppErrorCode.resourceChecksumFailed)), + en.resourceChecksumFailed, + ); + expect( + zh.errorMessage(AppException(AppErrorCode.timelineMissing)), + zh.timelineMissing, + ); + expect(en.errorMessage('Native error 123'), 'Native error 123'); + final unknown = const FileSystemException( + 'Native error 123', + '/missing.mov', + ); + expect(en.errorMessage(unknown), unknown.toString()); + expect( + zh.errorMessage(AppException(AppErrorCode.mediaReadFailed)), + '无法读取素材', + ); + expect( + en.errorMessage('FormatException: diagnostic 123'), + 'FormatException: diagnostic 123', + ); + expect(RenderColorSpace.linearRec2020.label(zh), '线性 Rec.2020'); + }); + + test('new sequence names follow the current language and saved names stay intact', () async { + final root = await Directory.systemTemp.createTemp( + 'cutdex-localized-names-', + ); + var l10n = lookupAppLocalizations(const Locale('en')); + TimelineCreationNames names() => TimelineCreationNames( + timeline: l10n.defaultTimelineName(1), + sequence: l10n.primarySequence, + storyline: l10n.primaryStoryline, + ); + final workspace = ProjectWorkspace(creationNames: names()); + addTearDown(() async { + await workspace.close(); + await root.delete(recursive: true); + }); + await workspace.open('${root.path}/Project.cutdex', name: 'My project'); + final projectId = workspace.project!.info.id; + final originalId = (await workspace.project!.listTimelines()).first.id; + final original = await workspace.loadTimeline(projectId, originalId); + expect(original.name, 'Timeline 1'); + expect(original.sequences.single.name, 'Main sequence'); + expect(original.sequences.single.storylines.single.name, 'Main storyline'); + + l10n = lookupAppLocalizations(const Locale('zh')); + final timelines = await workspace.createTimeline( + 'User-chosen name', + creationNames: names(), + ); + final added = await workspace.loadTimeline(projectId, timelines.last.id); + expect(added.name, 'User-chosen name'); + expect(added.sequences.single.name, '主序列'); + expect(added.sequences.single.storylines.single.name, '主线'); + final retained = await workspace.loadTimeline(projectId, originalId); + expect(retained.name, 'Timeline 1'); + expect(retained.sequences.single.name, 'Main sequence'); + }); +} diff --git a/test/location_settings_test.dart b/test/location_settings_test.dart new file mode 100644 index 0000000..ab69520 --- /dev/null +++ b/test/location_settings_test.dart @@ -0,0 +1,329 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:cutdex/features/settings/location_settings.dart'; +import 'package:cutdex/integrations/runtime/processing_resource_repository.dart'; +import 'package:cutdex/persistence/app_settings_repositories.dart'; +import 'package:cutdex/workspace/persistence/project_location_directory.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_riverpod/misc.dart' show ProviderListenable; +import 'package:flutter_test/flutter_test.dart'; + +import 'support/memory_app_settings.dart'; + +void main() { + test( + 'project location load errors can be retried and re-inspected', + () async { + final repository = _ProjectRepository()..failLoads = true; + final inspector = _DirectoryInspector(ProjectLocationStatus.missing); + final container = ProviderContainer.test( + overrides: [ + projectLocationSettingsRepositoryProvider.overrideWithValue( + repository, + ), + projectLocationDirectoryProvider.overrideWithValue(inspector), + ], + ); + await _ready(container, projectLocationSettingsProvider); + expect( + container.read(projectLocationSettingsProvider).error, + LocationSettingsError.load, + ); + repository.failLoads = false; + final controller = container.read( + projectLocationSettingsProvider.notifier, + ); + await controller.reload(); + final loaded = container.read(projectLocationSettingsProvider); + expect(loaded.directory, '/projects'); + expect(loaded.status, ProjectLocationStatus.missing); + expect(loaded.error, isNull); + inspector.status = ProjectLocationStatus.ready; + await controller.reload(); + expect( + container.read(projectLocationSettingsProvider).status, + ProjectLocationStatus.ready, + ); + }, + ); + + test( + 'project saves keep the previous path on failure and reload on success', + () async { + final repository = _ProjectRepository(); + final inspector = _DirectoryInspector(ProjectLocationStatus.ready); + final container = ProviderContainer.test( + overrides: [ + projectLocationSettingsRepositoryProvider.overrideWithValue( + repository, + ), + projectLocationDirectoryProvider.overrideWithValue(inspector), + ], + ); + await _ready(container, projectLocationSettingsProvider); + final controller = container.read( + projectLocationSettingsProvider.notifier, + ); + repository.failWrites = true; + await controller.save('/other'); + final failed = container.read(projectLocationSettingsProvider); + expect(failed.directory, '/projects'); + expect(failed.error, LocationSettingsError.save); + expect(failed.saving, isFalse); + repository.failWrites = false; + inspector.status = ProjectLocationStatus.unavailable; + await controller.save('/other'); + final saved = container.read(projectLocationSettingsProvider); + expect(saved.directory, '/other'); + expect(saved.status, ProjectLocationStatus.unavailable); + expect(saved.error, isNull); + expect(inspector.paths, ['/projects', '/other']); + }, + ); + + test( + 'project saves and reloads run in order while storage is pending', + () async { + final repository = _ProjectRepository()..writeGate = Completer(); + final container = ProviderContainer.test( + overrides: [ + projectLocationSettingsRepositoryProvider.overrideWithValue( + repository, + ), + projectLocationDirectoryProvider.overrideWithValue( + _DirectoryInspector(ProjectLocationStatus.ready), + ), + ], + ); + await _ready(container, projectLocationSettingsProvider); + final controller = container.read( + projectLocationSettingsProvider.notifier, + ); + final first = controller.save('/first'); + await repository.started.future; + final second = controller.save('/second'); + final retry = controller.reload(); + await Future.delayed(Duration.zero); + expect(repository.writes, ['/first']); + expect(container.read(projectLocationSettingsProvider).saving, isTrue); + expect( + container.read(projectLocationSettingsProvider).directory, + '/projects', + ); + repository.writeGate!.complete(); + await Future.wait([first, second, retry]); + expect(repository.writes, ['/first', '/second']); + expect( + container.read(projectLocationSettingsProvider).directory, + '/second', + ); + expect(container.read(projectLocationSettingsProvider).saving, isFalse); + }, + ); + + test( + 'a resource save refreshes the repository even after the page closes', + () async { + final repository = _ResourceRepository()..writeGate = Completer(); + var resourceBuilds = 0; + final container = ProviderContainer.test( + overrides: [ + resourceLocationSettingsRepositoryProvider.overrideWithValue( + repository, + ), + processingResourceRepositoryProvider.overrideWith((ref) { + resourceBuilds++; + final resources = ProcessingResourceRepository( + root: Directory('${repository.value}/Processing'), + catalog: [], + ); + ref.onDispose(resources.dispose); + return resources; + }), + ], + ); + container.listen(processingResourceRepositoryProvider, (_, _) {}); + final oldResources = await container.read( + processingResourceRepositoryProvider.future, + ); + expect(oldResources.root.path, '/resources/Processing'); + final page = container.listen( + resourceLocationSettingsProvider, + (_, _) {}, + ); + await _ready( + container, + resourceLocationSettingsProvider, + closeAfterReady: true, + ); + final save = container + .read(resourceLocationSettingsProvider.notifier) + .save('/new'); + await repository.started.future; + page.close(); + await container.pump(); + expect(container.exists(resourceLocationSettingsProvider), isTrue); + repository.writeGate!.complete(); + await save; + await container.pump(); + final newResources = await container.read( + processingResourceRepositoryProvider.future, + ); + expect(newResources.root.path, '/new/Processing'); + expect(resourceBuilds, 2); + expect(container.exists(resourceLocationSettingsProvider), isFalse); + }, + ); + + test('resource location load errors are owned by the controller', () async { + final repository = _ResourceRepository()..failLoads = true; + final container = ProviderContainer.test( + overrides: [ + resourceLocationSettingsRepositoryProvider.overrideWithValue( + repository, + ), + ], + ); + await _ready(container, resourceLocationSettingsProvider); + final state = container.read(resourceLocationSettingsProvider); + expect(state.error, LocationSettingsError.load); + expect(state.loading, isFalse); + repository.failLoads = false; + await container + .read(resourceLocationSettingsProvider.notifier) + .save('/new'); + expect(container.read(resourceLocationSettingsProvider).directory, '/new'); + expect(container.read(resourceLocationSettingsProvider).error, isNull); + }); + + test( + 'resource save failures retain the path and allow a later save', + () async { + final repository = _ResourceRepository(); + final container = ProviderContainer.test( + overrides: [ + resourceLocationSettingsRepositoryProvider.overrideWithValue( + repository, + ), + ], + ); + await _ready(container, resourceLocationSettingsProvider); + final controller = container.read( + resourceLocationSettingsProvider.notifier, + ); + repository.failWrites = true; + await controller.save('/new'); + final failed = container.read(resourceLocationSettingsProvider); + expect(failed.directory, '/resources'); + expect(failed.error, LocationSettingsError.save); + expect(failed.saving, isFalse); + repository.failWrites = false; + await controller.save('/new'); + final saved = container.read(resourceLocationSettingsProvider); + expect(saved.directory, '/new'); + expect(saved.error, isNull); + expect(saved.saving, isFalse); + }, + ); + + test( + 'closing directory settings during a save skips queued writes safely', + () async { + final repository = _ResourceRepository()..writeGate = Completer(); + final container = ProviderContainer( + overrides: [ + resourceLocationSettingsRepositoryProvider.overrideWithValue( + repository, + ), + ], + ); + await _ready(container, resourceLocationSettingsProvider); + final controller = container.read( + resourceLocationSettingsProvider.notifier, + ); + final first = controller.save('/first'); + await repository.started.future; + final second = controller.save('/second'); + container.dispose(); + repository.writeGate!.complete(); + await Future.wait([first, second]); + expect(repository.value, '/first'); + expect(repository.writes, ['/first']); + }, + ); +} + +Future _ready( + ProviderContainer container, + ProviderListenable provider, { + bool closeAfterReady = false, +}) { + final completer = Completer(); + final subscription = container.listen(provider, (_, state) { + if (!state.loading && !completer.isCompleted) completer.complete(); + }, fireImmediately: true); + return completer.future.then((_) { + if (closeAfterReady) subscription.close(); + }); +} + +class _DirectoryInspector extends ProjectLocationDirectory { + _DirectoryInspector(this.status); + ProjectLocationStatus status; + final paths = []; + + @override + Future inspect(String path) async { + paths.add(path); + return status; + } +} + +class _ProjectRepository extends MemoryProjectLocationSettingsRepository { + _ProjectRepository() : super('/projects'); + bool failLoads = false; + bool failWrites = false; + final writes = []; + final started = Completer(); + Completer? writeGate; + + @override + Future load() async { + if (failLoads) throw StateError('read failed'); + return super.load(); + } + + @override + Future save(String directory) async { + writes.add(directory); + if (!started.isCompleted) started.complete(); + await writeGate?.future; + if (failWrites) throw StateError('write failed'); + await super.save(directory); + } +} + +class _ResourceRepository extends MemoryResourceLocationSettingsRepository { + _ResourceRepository() : super('/resources'); + bool failLoads = false; + bool failWrites = false; + final writes = []; + final started = Completer(); + Completer? writeGate; + + @override + Future load() async { + if (failLoads) throw StateError('read failed'); + return super.load(); + } + + @override + Future save(String directory) async { + writes.add(directory); + if (!started.isCompleted) started.complete(); + await writeGate?.future; + if (failWrites) throw StateError('write failed'); + await super.save(directory); + } +} diff --git a/test/macos_build_target_test.dart b/test/macos_build_target_test.dart new file mode 100644 index 0000000..19050ad --- /dev/null +++ b/test/macos_build_target_test.dart @@ -0,0 +1,29 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; + +void main() { + test('native build refuses only its running executable', () async { + final root = await Directory.systemTemp.createTemp('cutdex build guard '); + addTearDown(() => root.delete(recursive: true)); + final executable = await File('/bin/sleep').copy('${root.path}/cutdex'); + await Process.run('/bin/chmod', ['u+x', executable.path]); + Future check(String path) => Process.run('/bin/sh', [ + 'tool/macos/check_macos_build_target.sh', + path, + ]); + + expect((await check(executable.path)).exitCode, 0); + final process = await Process.start(executable.path, ['60']); + try { + final blocked = await check(executable.path); + expect(blocked.exitCode, 1); + expect(blocked.stderr, contains('Save your edits')); + expect((await check('${root.path}/other/cutdex')).exitCode, 0); + } finally { + process.kill(); + await process.exitCode; + } + expect((await check(executable.path)).exitCode, 0); + }, skip: !Platform.isMacOS); +} diff --git a/test/mcp_settings_test.dart b/test/mcp_settings_test.dart new file mode 100644 index 0000000..780939a --- /dev/null +++ b/test/mcp_settings_test.dart @@ -0,0 +1,170 @@ +import 'package:cutdex/app/editor_theme.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex/integrations/mcp/mcp_settings.dart'; +import 'package:cutdex/persistence/app_settings_repositories.dart'; +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex/features/settings/mcp_settings_panel.dart'; +import 'package:cutdex/features/settings/settings_dialog.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'support/memory_app_settings.dart'; + +void main() { + test('overlapping MCP updates retain enablement and port', () async { + final repository = MemoryMcpSettingsRepository(); + final container = ProviderContainer( + overrides: [mcpSettingsRepositoryProvider.overrideWithValue(repository)], + ); + addTearDown(container.dispose); + await container.read(mcpSettingsProvider.future); + final settings = container.read(mcpSettingsProvider.notifier); + await Future.wait([ + settings.saveSettings(enabled: true), + settings.saveSettings(port: 47832), + ]); + expect(repository.value!.enabled, isTrue); + expect(repository.value!.port, 47832); + await expectLater(settings.saveSettings(port: 0), throwsArgumentError); + await settings.saveSettings(port: 47833); + expect(repository.value!.port, 47833); + }); + + testWidgets('sidebar settings fit desktop and narrow windows', ( + tester, + ) async { + for (final size in [const Size(1280, 800), const Size(390, 640)]) { + await tester.binding.setSurfaceSize(size); + await tester.pumpWidget( + ProviderScope( + overrides: [ + appearanceSettingsRepositoryProvider.overrideWithValue( + MemoryAppearanceSettingsRepository(), + ), + mcpSettingsRepositoryProvider.overrideWithValue( + MemoryMcpSettingsRepository(), + ), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + theme: EditorTheme.penDark, + home: const Scaffold(body: SettingsDialog()), + ), + ), + ); + await tester.pumpAndSettle(); + final closeButton = find.byKey(const Key('app-dialog-close-button')); + final sidebar = find.byKey(const Key('settings-sidebar')); + final divider = find.byKey(const Key('settings-sidebar-divider')); + expect(sidebar, findsOneWidget); + expect(divider, findsOneWidget); + expect(closeButton, findsOneWidget); + expect(find.byKey(const Key('app-dialog-header-content')), findsNothing); + final frameSize = tester.getSize( + find.byKey(const Key('app-dialog-frame')), + ); + final viewport = MediaQuery.sizeOf( + tester.element(find.byType(SettingsDialog)), + ); + if (size.width == 1280) { + expect( + frameSize.width, + closeTo((viewport.width * .9).clamp(560, 1120), .001), + ); + expect( + frameSize.height, + closeTo((viewport.height * .88).clamp(520, 704), .001), + ); + } + expect(tester.getSize(closeButton), const Size.square(24)); + expect(tester.getRect(sidebar).right, tester.getRect(divider).left); + expect(tester.getRect(sidebar).height, frameSize.height); + expect( + tester.getRect(find.text('外观')).left, + greaterThan(tester.getRect(divider).right), + ); + expect( + tester.widget(find.text('外观')).style?.fontSize, + AppTheme.settingsContentTheme(EditorTheme.penDark) + .textTheme + .labelLarge + ?.fontSize, + ); + expect(find.text('外观'), findsOneWidget); + await tester.tap(find.text('MCP').first); + await tester.pumpAndSettle(); + expect(find.text('监听端口'), findsOneWidget); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + } + await tester.binding.setSurfaceSize(null); + }); + test('settings persist the token and enablement; invalid or failed writes retain state', () async { + final repository = MemoryMcpSettingsRepository(); + ProviderContainer create() => ProviderContainer( + overrides: [mcpSettingsRepositoryProvider.overrideWithValue(repository)], + ); + final container = create(); + addTearDown(container.dispose); + final initial = await container.read(mcpSettingsProvider.future); + expect(initial.enabled, false); + expect(initial.token.length, greaterThanOrEqualTo(32)); + await container + .read(mcpSettingsProvider.notifier) + .saveSettings(enabled: true, port: 47832); + final restored = create(); + addTearDown(restored.dispose); + final value = await restored.read(mcpSettingsProvider.future); + expect(value.enabled, true); + expect(value.port, 47832); + expect(value.token, initial.token); + await expectLater( + restored.read(mcpSettingsProvider.notifier).saveSettings(port: 0), + throwsArgumentError, + ); + repository.failWrites = true; + await expectLater( + restored.read(mcpSettingsProvider.notifier).saveSettings(enabled: false), + throwsStateError, + ); + expect(restored.read(mcpSettingsProvider).requireValue, same(value)); + }); + + testWidgets('settings switch enables and disables MCP and validates ports', ( + tester, + ) async { + await tester.pumpWidget( + ProviderScope( + overrides: [ + mcpSettingsRepositoryProvider.overrideWithValue( + MemoryMcpSettingsRepository(), + ), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + theme: EditorTheme.penLight, + home: const Scaffold(body: McpSettingsPanel()), + ), + ), + ); + await tester.pumpAndSettle(); + await tester.enterText(find.byType(TextFormField), '0'); + await tester.tap(find.byType(Switch)); + await tester.pumpAndSettle(); + expect(find.text('端口必须为 1–65535'), findsOneWidget); + await tester.enterText(find.byType(TextFormField), '47831'); + await tester.tap(find.byType(Switch)); + await tester.pumpAndSettle(); + expect(find.text('等待打开工程'), findsOneWidget); + await tester.tap(find.byType(Switch)); + await tester.pumpAndSettle(); + expect(find.text('已停用'), findsOneWidget); + }); +} diff --git a/test/media_availability_test.dart b/test/media_availability_test.dart new file mode 100644 index 0000000..edf3bec --- /dev/null +++ b/test/media_availability_test.dart @@ -0,0 +1,43 @@ +import 'dart:io'; + +import 'package:cutdex/workspace/media_availability.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + test( + 'detects missing originals and restoration independently of preview caches', + () async { + final directory = await Directory.systemTemp.createTemp( + 'cutdex-availability-', + ); + addTearDown(() => directory.delete(recursive: true)); + final file = File('${directory.path}/source.mp4'); + expect(await checkMediaAvailability(file.uri), MediaAvailability.missing); + await file.writeAsBytes([1, 2, 3]); + // A readable file is available even when it is not a decodable video. + expect( + await checkMediaAvailability(file.uri), + MediaAvailability.available, + ); + await file.delete(); + expect(await checkMediaAvailability(file.uri), MediaAvailability.missing); + await file.writeAsBytes([4]); + expect( + await checkMediaAvailability(file.uri), + MediaAvailability.available, + ); + }, + ); + + test( + 'unsupported locations are unavailable rather than reported missing', + () async { + expect( + await checkMediaAvailability( + Uri.parse('https://example.com/video.mp4'), + ), + MediaAvailability.inaccessible, + ); + }, + ); +} diff --git a/test/media_binding_test.dart b/test/media_binding_test.dart new file mode 100644 index 0000000..96eff83 --- /dev/null +++ b/test/media_binding_test.dart @@ -0,0 +1,105 @@ +import 'support/creation_names.dart'; + +import 'package:cutdex_sdk/editor.dart'; + +import 'dart:async'; +import 'dart:io'; + +import 'package:cutdex/workspace/persistence/project_workspace.dart'; +import 'package:cutdex/integrations/runtime/media_thumbnails.dart'; +import 'package:cutdex/integrations/runtime/media_waveforms.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + test( + 'binding preserves selected tracks, explicit disabled tracks and images', + () { + final uris = {'asset': Uri.file('/movie.mov')}; + EditorMediaBinding? binding(String type, Map data) => + EditorMediaBinding.resolve( + PayloadDocument( + id: 'payload', + type: type, + assetIds: ['asset'], + data: data, + ), + uris, + ); + expect( + binding('video', { + 'videoTrackIndex': 2, + 'audioTrackIndex': 1, + })!.videoTrackIndex, + 2, + ); + expect( + binding('video', { + 'videoTrackIndex': 2, + 'audioTrackIndex': 1, + })!.audioTrackIndex, + 1, + ); + expect( + binding('video', {'videoTrackIndex': null})!.videoTrackIndex, + isNull, + ); + expect(binding('audio', {'audioTrackIndex': 0})!.audioTrackIndex, 0); + expect(binding('audio', {}), isNull); + expect(binding('video', {}), isNull); + expect(binding('image', {})!.media.isImage, isTrue); + expect(binding('audio', {'audioTrackIndex': -1}), isNull); + expect(binding('video', {'videoTrackIndex': 'invalid'}), isNull); + }, + ); + + test('managed covers use resolved paths and generation survives a project switch', () async { + final root = await Directory.systemTemp.createTemp('cutdex-bindings-'); + final workspace = ProjectWorkspace(creationNames: testCreationNames); + addTearDown(() async { + await workspace.close(); + await root.delete(recursive: true); + }); + await workspace.open('${root.path}/one.cutdex', name: 'One'); + final project = workspace.project!; + final file = File('${root.path}/source.wav'); + await file.writeAsBytes([1, 2, 3, 4]); + final asset = await project.importFile(file); + expect(Uri.parse(asset.location).hasScheme, isFalse); + final resolved = await project.resolveAsset(asset); + final calls = []; + const channel = MethodChannel('cutdex_runtime'); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + messenger.setMockMethodCallHandler(channel, (call) async { + expect((call.arguments as Map)['media']['uri'], resolved.toString()); + calls.add(call.method); + throw PlatformException(code: 'testSource'); + }); + addTearDown(() => messenger.setMockMethodCallHandler(channel, null)); + Future load( + AssetDocument asset, + Future Function(MediaReference) action, + ) => workspace.withAssetMedia(project.info.id, asset, action); + await MediaThumbnails(loadMedia: load).load(asset); + await MediaWaveforms(loadMedia: load).load(asset); + expect(calls, ['thumbnail', 'waveform']); + + final started = Completer(), finish = Completer(); + final operation = load(asset, (media) async { + started.complete(); + await finish.future; + return File.fromUri(media.uri).readAsBytes(); + }); + await started.future; + await workspace.open('${root.path}/two.cutdex', name: 'Two'); + finish.complete(); + expect(await operation, [1, 2, 3, 4]); + expect((await load(asset, (media) async => media)).uri, resolved); + await workspace.close(); + await expectLater(load(asset, (media) async => media), throwsStateError); + }); +} diff --git a/test/media_color_interpretation_test.dart b/test/media_color_interpretation_test.dart new file mode 100644 index 0000000..c9bd4e3 --- /dev/null +++ b/test/media_color_interpretation_test.dart @@ -0,0 +1,139 @@ +import 'package:cutdex/app/editor_theme.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex/features/preview/preview_panel.dart'; +import 'package:cutdex/features/properties/color_interpretation_properties.dart'; +import 'package:cutdex_sdk/preview.dart'; +import 'package:cutdex/workspace/media_color_interpretation.dart'; +import 'package:cutdex/workspace/timeline_session.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'support/preview_fixture.dart'; + +class _ColorPreview extends PreviewController { + _ColorPreview(EditorTimelineSession timeline) + : super( + timeline: timeline, + runtime: CutdexRuntime(), + activeSequence: () => timeline.activeSequenceId, + viewForSequence: timeline.view, + ); + @override + List? videoColorSpaces(String assetId) => [null]; +} + +void main() { + test('only reported unknown inputs receive the display assumption', () { + for (final detected in [null, ...RenderColorSpace.values]) { + expect( + resolveMediaColor( + detected: detected, + override: null, + metadataReported: true, + ), + detected == null ? RenderColorSpace.rec709 : null, + ); + expect( + resolveMediaColor( + detected: detected, + override: RenderColorSpace.sRGB, + metadataReported: true, + ), + RenderColorSpace.sRGB, + ); + } + expect( + resolveMediaColor( + detected: null, + override: null, + metadataReported: false, + ), + isNull, + ); + }); + + for (final width in [240.0, 400.0]) { + testWidgets( + 'color inspector at $width saves source interpretation and restores automatic', + (tester) async { + await tester.runAsync(() async { + final f = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = _ColorPreview(f.timeline); + addTearDown( + () => tester.runAsync(() async { + await preview.close(); + await f.workspace.close(); + await f.directory.delete(recursive: true); + }), + ); + await tester.pumpWidget( + ProviderScope( + overrides: [ + editorPreviewProvider( + 'project', + 'project', + ).overrideWith((_) async => preview), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + theme: EditorTheme.penDark, + home: Scaffold( + body: Center( + child: SizedBox( + width: width, + child: ColorInterpretationProperties( + projectId: 'project', + timelineId: 'project', + session: f.timeline, + assetId: 'media', + trackIndex: 0, + ), + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect(find.text('色彩空间未知,暂按 Rec.709 显示'), findsOneWidget); + expect( + f.timeline.settings.containsKey('mediaColorInterpretations'), + isFalse, + ); + await tester.tap(find.byKey(const Key('media-color-menu'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('线性 Rec.2020')); + await tester.pumpAndSettle(); + expect(find.text('手动指定:线性 Rec.2020'), findsOneWidget); + expect(tester.takeException(), isNull); + { + await f.timeline.flush(); + final saved = await f.workspace.project!.loadTimeline('project'); + final reopened = EditorTimelineSession( + document: saved, + persistence: f.timeline.persistence, + assetUris: f.timeline.assetUris, + ); + expect( + reopened.mediaColorInterpretation('media', 0), + RenderColorSpace.linearRec2020, + ); + expect(reopened.mediaColorInterpretation('media', 1), isNull); + } + await tester.tap(find.byKey(const Key('media-color-menu'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('自动')); + await tester.pumpAndSettle(); + expect(find.text('色彩空间未知,暂按 Rec.709 显示'), findsOneWidget); + expect(f.timeline.mediaColorInterpretation('media', 0), isNull); + expect(tester.takeException(), isNull); + }); + }, + ); + } +} diff --git a/test/media_import_feedback_test.dart b/test/media_import_feedback_test.dart new file mode 100644 index 0000000..cbe89f6 --- /dev/null +++ b/test/media_import_feedback_test.dart @@ -0,0 +1,67 @@ +import 'package:cutdex/features/media/media_browser_feedback.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex/workspace/external_media_import.dart'; +import 'package:cutdex/workspace/media_import_feedback.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets( + 'offstage import feedback waits for visibility and is consumed once', + (tester) async { + final feedback = MediaImportFeedbackController(); + addTearDown(feedback.dispose); + var visible = false; + late StateSetter changeVisibility; + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: StatefulBuilder( + builder: (context, setState) { + changeVisibility = setState; + return Offstage( + offstage: !visible, + child: TickerMode( + enabled: visible, + child: MediaImportFeedbackListener( + feedback: feedback, + child: const Text('Browser'), + ), + ), + ); + }, + ), + ), + ), + ); + feedback.recordResult( + const ExternalMediaSelection(selected: [], failed: true), + ); + feedback.recordFailure(); + await tester.pumpAndSettle(); + expect(feedback.hasPending, isTrue); + expect(find.byType(SnackBar), findsNothing); + changeVisibility(() => visible = true); + await tester.pumpAndSettle(); + expect(feedback.hasPending, isFalse); + expect(find.byType(SnackBar), findsOneWidget); + final messenger = ScaffoldMessenger.of( + tester.element(find.text('Browser')), + ); + messenger.clearSnackBars(); + messenger.removeCurrentSnackBar(); + await tester.pumpAndSettle(); + changeVisibility(() => visible = false); + await tester.pumpAndSettle(); + changeVisibility(() => visible = true); + await tester.pumpAndSettle(); + expect(find.byType(SnackBar), findsNothing); + feedback.recordFailure(); + await tester.pumpAndSettle(); + expect(feedback.hasPending, isFalse); + expect(find.byType(SnackBar), findsOneWidget); + }, + ); +} diff --git a/test/media_import_test.dart b/test/media_import_test.dart new file mode 100644 index 0000000..ad08f4a --- /dev/null +++ b/test/media_import_test.dart @@ -0,0 +1,330 @@ +import 'support/creation_names.dart'; + +import 'dart:io'; + +import 'package:cutdex/workspace/media_import.dart'; +import 'package:cutdex/workspace/persistence/project_workspace.dart'; +import 'package:cutdex/integrations/platform/media_source_reader.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + late Directory root; + late ProjectWorkspace workspace; + late String projectId; + late String path; + late _ProviderReader reader; + + setUp(() async { + root = await Directory.systemTemp.createTemp('cutdex-media-test-'); + reader = _ProviderReader(); + workspace = ProjectWorkspace( + creationNames: testCreationNames, + mediaSourceReader: reader, + ); + path = '${root.path}/Project.cutdex'; + await workspace.open(path, name: '媒体库'); + projectId = workspace.project!.info.id; + }); + + test( + 'provider originals are managed, deduplicated and readable after reopen', + () async { + final source = ExternalMediaFile.content( + uri: Uri.parse('content://provider/document/42'), + name: '中文 空格 #.MP4', + byteLength: 3, + ); + final result = await workspace.importExternalMedia(projectId, [ + source, + source, + ]); + expect(result.added, 1); + expect(result.duplicates, 1); + expect(result.failures, isEmpty); + expect(reader.opens, 1); + expect(reader.closes, 1); + final asset = result.assets.single; + expect(asset.storage, AssetStorage.managed); + expect(asset.name, source.displayName); + expect(asset.metadata['kind'], 'video'); + expect(mediaSourceLocation(asset), source.sourceUri.toString()); + expect( + await workspace.withAssetMedia( + projectId, + asset, + (media) => File.fromUri(media.uri).readAsBytes(), + ), + [1, 2, 3], + ); + await workspace.close(); + workspace = ProjectWorkspace( + creationNames: testCreationNames, + mediaSourceReader: reader, + ); + await workspace.open(path); + final repeated = await workspace.importExternalMedia(projectId, [source]); + expect(repeated.added, 0); + expect(repeated.duplicates, 1); + expect(repeated.assets.single.id, asset.id); + expect(reader.opens, 1); + expect( + await workspace.withAssetMedia( + projectId, + repeated.assets.single, + (media) => File.fromUri(media.uri).readAsBytes(), + ), + [1, 2, 3], + ); + }, + ); + + test( + 'provider stream failure or size mismatch never registers a partial asset', + () async { + final source = ExternalMediaFile.content( + uri: Uri.parse('content://provider/document/42'), + name: 'a.wav', + byteLength: 4, + ); + var result = await workspace.importExternalMedia(projectId, [source]); + expect(result.failures, hasLength(1)); + expect(result.assets, isEmpty); + reader.fail = true; + result = await workspace.importExternalMedia(projectId, [source]); + expect(result.failures, hasLength(1)); + expect(result.assets, isEmpty); + expect(reader.closes, 2); + expect(await Directory('$path/media').exists(), isFalse); + }, + ); + + test( + 'cancelling a provider read closes the stream without registering media', + () async { + var cancelled = false; + reader.afterFirstChunk = () => cancelled = true; + final result = await workspace.importExternalMedia(projectId, [ + ExternalMediaFile.content( + uri: Uri.parse('content://provider/document/42'), + name: 'a.mp4', + ), + ], isCancelled: () => cancelled); + expect(result.failures, hasLength(1)); + expect(result.assets, isEmpty); + expect(reader.closes, 1); + expect(await Directory('$path/media').exists(), isFalse); + }, + ); + tearDown(() async { + await workspace.close(); + await root.delete(recursive: true); + }); + + test('video, audio and image drops persist only references across reopen', () async { + final files = []; + for (final name in ['中文 空格 #.MOV', 'sound.wav', 'photo.PNG']) { + files.add(await File('${root.path}/$name').writeAsBytes([1, 2, 3])); + } + final before = await workspace.createTimeline('剪辑'); + final result = await workspace.importExternalMedia( + projectId, + files.map((file) => ExternalMediaFile(path: file.path)), + ); + expect(result.added, 3); + expect(result.failures, isEmpty); + expect( + result.assets.map((asset) => asset.metadata['kind']), + unorderedEquals(['video', 'audio', 'image']), + ); + for (final asset in result.assets) { + expect(asset.storage, AssetStorage.external); + expect(asset.byteLength, 3); + expect(await File.fromUri(Uri.parse(asset.location)).readAsBytes(), [ + 1, + 2, + 3, + ]); + expect(asset.contentHash, isNull); + } + final after = await workspace.project!.listTimelines(); + expect( + after.map((timeline) => timeline.revision), + before.map((timeline) => timeline.revision), + ); + expect(await Directory('$path/media').exists(), isFalse); + await workspace.close(); + final reopened = await ProjectFile.open(Directory(path)); + try { + expect( + (await reopened.listAssets()).map((a) => a.location), + unorderedEquals(result.assets.map((a) => a.location)), + ); + // Losing a source does not delete its reference or prevent project open. + await files.first.delete(); + expect(await reopened.listAssets(), hasLength(3)); + } finally { + await reopened.close(); + } + }); + + test('large sparse file is registered without copying its bytes', () async { + final file = File('${root.path}/large.mp4'); + final handle = await file.open(mode: FileMode.write); + await handle.truncate(4 * 1024 * 1024 * 1024); + await handle.close(); + final result = await workspace.importExternalMedia(projectId, [ + ExternalMediaFile(path: file.path), + ]); + expect(result.added, 1); + expect(result.assets.single.byteLength, 4 * 1024 * 1024 * 1024); + expect(await Directory('$path/media').exists(), isFalse); + }); + + test( + 'FLV, RealMedia and TS drops persist video references with original names', + () async { + final files = []; + for (final name in [ + '中文 空格 [视频].flv', + '中文 空格 [视频].RMVB', + 'legacy.rm', + 'transport.ts', + '中文 空格 [视频].TS', + ]) { + files.add(await File('${root.path}/$name').writeAsString('fixture')); + } + final result = await workspace.importExternalMedia( + projectId, + files.map((file) => ExternalMediaFile(path: file.path)), + ); + expect(result.added, 5); + expect(result.failures, isEmpty); + expect( + result.assets.every((asset) => asset.metadata['kind'] == 'video'), + isTrue, + ); + expect( + result.assets.map((asset) => asset.name), + unorderedEquals([ + '中文 空格 [视频].flv', + '中文 空格 [视频].RMVB', + 'legacy.rm', + 'transport.ts', + '中文 空格 [视频].TS', + ]), + ); + await workspace.close(); + workspace = ProjectWorkspace(creationNames: testCreationNames); + await workspace.open(path); + expect( + (await workspace.project!.listAssets()).map((asset) => asset.location), + unorderedEquals(result.assets.map((asset) => asset.location)), + ); + expect(await Directory('$path/media').exists(), isFalse); + }, + ); + + test( + 'duplicates in a batch, queued drops and reopened projects reuse identity', + () async { + final file = await File('${root.path}/video.mp4') + .writeAsString('fixture'); + final source = ExternalMediaFile(path: file.path); + final results = await Future.wait([ + workspace.importExternalMedia(projectId, [source, source]), + workspace.importExternalMedia(projectId, [source]), + ]); + expect(results.first.added, 1); + expect(results.first.duplicates, 1); + expect(results.last.added, 0); + expect(results.last.duplicates, 1); + final id = results.first.assets.single.id; + await workspace.close(); + workspace = ProjectWorkspace(creationNames: testCreationNames); + await workspace.open(path); + expect( + (await workspace.importExternalMedia(projectId, [ + source, + ])).assets.single.id, + id, + ); + }, + ); + + test( + 'symlink aliases use the same external identity', + () async { + final file = await File('${root.path}/video.mp4') + .writeAsString('fixture'); + final alias = await Link('${root.path}/alias.mp4').create(file.path); + final result = await workspace.importExternalMedia(projectId, [ + ExternalMediaFile(path: file.path), + ExternalMediaFile(path: alias.path), + ]); + expect(result.added, 1); + expect(result.duplicates, 1); + }, + skip: Platform.isWindows + ? 'Symlink creation requires Windows privileges' + : false, + ); + + test('mixed drops report failures and still save valid files', () async { + final file = await File('${root.path}/ok.jpg').writeAsString('fixture'); + final unsupported = await File('${root.path}/notes.txt') + .writeAsString('not media'); + final directory = await Directory('${root.path}/folder.mp4').create(); + final result = await workspace.importExternalMedia(projectId, [ + ExternalMediaFile(path: '${root.path}/missing.wav'), + ExternalMediaFile(path: directory.path), + ExternalMediaFile(path: unsupported.path), + const ExternalMediaFile(path: 'relative.mp4'), + const ExternalMediaFile(path: 'https://example.com/video.mp4'), + ExternalMediaFile(path: file.path), + ]); + expect(result.added, 1); + expect(result.failures, hasLength(5)); + expect(result.assets.single.name, 'ok.jpg'); + }); + + test('queued drop cannot register files into a different project', () async { + final file = await File('${root.path}/video.mp4').writeAsString('fixture'); + final switchProject = workspace.open( + '${root.path}/Other.cutdex', + name: 'Other', + ); + final drop = workspace.importExternalMedia(projectId, [ + ExternalMediaFile(path: file.path), + ]); + final imported = await drop; + expect(imported.added, 1); + await switchProject; + expect(await workspace.project!.listAssets(), isEmpty); + await workspace.open(path); + expect( + (await workspace.project!.listAssets()).single.id, + imported.assets.single.id, + ); + }); +} + +class _ProviderReader extends MediaSourceReader { + int opens = 0; + int closes = 0; + bool fail = false; + void Function()? afterFirstChunk; + + @override + Stream> openRead(Uri uri) async* { + opens++; + try { + yield [1, 2]; + afterFirstChunk?.call(); + if (fail) throw const FileSystemException('Provider read failed'); + yield [3]; + } finally { + closes++; + } + } +} diff --git a/test/media_panel_test.dart b/test/media_panel_test.dart new file mode 100644 index 0000000..2d39bea --- /dev/null +++ b/test/media_panel_test.dart @@ -0,0 +1,810 @@ +import 'package:cutdex/app/editor_theme.dart'; +import 'package:cutdex/features/media/media_browser_page.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex_ui/widgets.dart'; + +import 'dart:async'; +import 'dart:ui' as ui; + +import 'package:cutdex/features/media/media_panel.dart'; +import 'package:cutdex/features/media/media_asset_strip.dart'; +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex/shared/widgets/drop_to_add_overlay.dart'; +import 'package:cutdex/workspace/projects.dart'; +import 'package:cutdex/workspace/project_state.dart'; +import 'package:cutdex/workspace/media_file_extensions.dart'; +import 'package:cutdex/workspace/media_import.dart'; +import 'package:cutdex/workspace/media_availability.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex/integrations/platform/native_project_drop_region.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + setUp(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('cutdex_native/file_drop/media-library'), + (_) async => null, + ); + }); + tearDown(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('cutdex_native/file_drop/media-library'), + null, + ); + }); + testWidgets( + 'list and grid share a context menu targeting the clicked asset', + (tester) async { + final container = ProviderContainer( + overrides: [ + projectsProvider.overrideWith(_Projects.new), + mediaAvailabilityProvider.overrideWith( + (ref, key) async => MediaAvailability.available, + ), + ], + ); + addTearDown(container.dispose); + await container.read(projectsProvider.future); + final projects = container.read(projectsProvider.notifier) as _Projects; + await projects.importExternalMedia('project', [ + const ExternalMediaFile(path: '/first.txt'), + const ExternalMediaFile(path: '/second.txt'), + ]); + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + theme: EditorTheme.penLight, + home: const Scaffold(body: MediaPanel(projectId: 'project')), + ), + ), + ); + await tester.pumpAndSettle(); + for (final layout in ['列表布局', '宫格布局']) { + await tester.tap(find.byTooltip(layout)); + await tester.pumpAndSettle(); + await tester.tap(find.text('first.txt')); + await tester.tap( + find.text('second.txt'), + buttons: kSecondaryMouseButton, + ); + await tester.pumpAndSettle(); + expect(find.text('添加到时间线'), findsOneWidget); + expect( + tester + .widget( + find.widgetWithText(MenuItemButton, '添加到时间线'), + ) + .onPressed, + isNull, + ); + await tester.tap(find.text('重命名')); + await tester.pumpAndSettle(); + expect( + tester.widget(find.byType(TextField)).controller!.text, + 'second.txt', + ); + await tester.tap(find.text('取消')); + await tester.pumpAndSettle(); + } + expect(tester.takeException(), isNull); + }, + ); + Future platformEvent( + WidgetTester tester, + String method, + Object? args, + ) async { + final done = Completer(); + final eventArgs = { + 'phase': method, + 'session': 1, + 'x': 0.0, + 'y': 0.0, + 'files': method == 'exit' + ? [] + : method == 'enter' + ? [ + {'path': '/originals/video.mp4'}, + ] + : [ + for (final f in args as List) + if (f is String) {'path': f} else {'path': (f as Map)['path']}, + ], + }; + tester.binding.defaultBinaryMessenger.handlePlatformMessage( + 'cutdex_native/file_drop/media-library', + const StandardMethodCodec().encodeMethodCall( + MethodCall('event', eventArgs), + ), + (_) => done.complete(), + ); + await done.future; + await tester.pump(); + } + + Future mount( + WidgetTester tester, { + MediaAvailability availability = MediaAvailability.available, + bool touch = false, + }) async { + final container = ProviderContainer( + overrides: [ + projectsProvider.overrideWith(_Projects.new), + mediaAvailabilityProvider.overrideWith( + (ref, key) async => availability, + ), + ], + ); + addTearDown(container.dispose); + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + theme: EditorTheme.penLight, + home: Scaffold( + body: touch + ? const MediaBrowserPage(projectId: 'project') + : const MediaPanel(projectId: 'project'), + ), + ), + ), + ); + await tester.pumpAndSettle(); + return container; + } + + testWidgets('list uses a filmstrip with real duration above its name', ( + tester, + ) async { + const channel = MethodChannel('cutdex_runtime'); + final times = []; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, ( + call, + ) async { + if (call.method == 'probe') { + return { + 'duration': {'numerator': '290', 'denominator': 1}, + 'videoTrackCount': 1, + 'videoTrackIds': [1], + 'audioTrackCount': 0, + 'audioTrackIds': [], + 'audioTracks': [], + 'isProtected': false, + }; + } + if (call.method == 'thumbnail') { + final args = call.arguments as Map; + final time = args['time'] as Map; + times.add(int.parse(time['numerator'].toString())); + } + throw PlatformException(code: 'no-preview'); + }); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + channel, + null, + ), + ); + final container = await mount(tester); + await (container.read(projectsProvider.notifier) as _Projects) + .importExternalMedia('project', [ + const ExternalMediaFile(path: '/movie.mp4'), + ]); + await tester.pumpAndSettle(); + await tester.tap(find.byTooltip('列表布局')); + await tester.pumpAndSettle(); + final strip = tester.getRect(find.byType(MediaAssetStrip)); + final name = tester.getRect(find.text('movie.mp4')); + final duration = tester.getRect(find.text('04:50')); + expect(strip.height, 46); + expect(name.top, greaterThanOrEqualTo(strip.bottom)); + expect(duration.right, lessThanOrEqualTo(strip.right)); + expect(duration.left, greaterThan(strip.center.dx)); + expect(duration.top, strip.top + 5); + expect(times.any((time) => time > 0), isTrue); + expect(tester.takeException(), isNull); + }); + + testWidgets( + 'missing assets stay named and marked in both layouts without dragging', + (tester) async { + final container = await mount( + tester, + availability: MediaAvailability.missing, + ); + final projects = container.read(projectsProvider.notifier) as _Projects; + await projects.importExternalMedia('project', [ + const ExternalMediaFile(path: '/missing.mov'), + ]); + await tester.pumpAndSettle(); + for (final layout in ['列表布局', '宫格布局']) { + await tester.tap(find.byTooltip(layout)); + await tester.pumpAndSettle(); + expect(find.text('素材缺失'), findsOneWidget); + expect(find.text('missing.mov'), findsOneWidget); + final drag = tester.widget( + find.byWidgetPredicate((widget) => widget is Draggable), + ); + expect(drag.maxSimultaneousDrags, 0); + expect(tester.takeException(), isNull); + } + }, + ); + + testWidgets( + 'category dropdown filters both layouts and restores all assets', + (tester) async { + final container = await mount(tester); + final projects = container.read(projectsProvider.notifier) as _Projects; + await projects.importExternalMedia('project', [ + const ExternalMediaFile(path: '/photo.png'), + const ExternalMediaFile(path: '/movie.mp4'), + const ExternalMediaFile(path: '/song.wav'), + const ExternalMediaFile(path: '/notes.txt'), + ]); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('media-import-button')), findsOneWidget); + expect( + tester.getSize(find.byKey(const Key('media-panel-header'))).height, + AppControlSize.panelToolbar, + ); + expect( + tester.getSize(find.byKey(const Key('media-import-button'))).height, + AppControlSize.headerButton, + ); + final header = tester.getRect( + find.byKey(const Key('media-panel-header')), + ); + expect( + tester.getRect(find.byKey(const Key('media-panel-body'))).top, + header.bottom, + ); + final importButton = tester.getRect( + find.byKey(const Key('media-import-button')), + ); + final layoutButton = tester.getRect( + find.byKey(const Key('media-layout-toggle')), + ); + final filter = find.byWidgetPredicate( + (widget) => widget is AppSelect && widget.label == '素材分类', + ); + final filterButton = tester.getRect( + find.descendant(of: filter, matching: find.byType(TextButton)), + ); + expect(importButton.left - header.left, AppSpacing.gap); + expect(importButton.top - header.top, AppSpacing.gap); + expect(header.right - layoutButton.right, AppSpacing.gap); + expect(layoutButton.left - filterButton.right, AppSpacing.tiny); + expect(tester.getSize(filter).height, AppControlSize.headerButton); + final importStyle = tester + .widget(find.byKey(const Key('media-import-button'))) + .style! + .textStyle! + .resolve({})!; + final filterStyle = tester.widget>(filter).textStyle!; + expect(importStyle.fontSize, 13); + expect(importStyle.height, 18 / 13); + expect(filterStyle.fontSize, importStyle.fontSize); + expect(filterStyle.height, importStyle.height); + expect(find.text('4 个素材'), findsNothing); + for (final entry in { + '图片': 'photo.png', + '视频': 'movie.mp4', + '音频': 'song.wav', + }.entries) { + await tester.tap( + find.descendant( + of: find.byWidgetPredicate( + (widget) => widget is AppSelect && widget.label == '素材分类', + ), + matching: find.byType(TextButton), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.widgetWithText(MenuItemButton, entry.key)); + await tester.pumpAndSettle(); + expect(find.text('1 个素材'), findsNothing); + expect(find.text(entry.value), findsOneWidget); + expect(find.text('notes.txt'), findsNothing); + } + await tester.tap(find.byTooltip('列表布局')); + await tester.pumpAndSettle(); + expect(find.text('song.wav'), findsOneWidget); + expect(find.text('movie.mp4'), findsNothing); + await tester.tap( + find.descendant( + of: find.byWidgetPredicate( + (widget) => widget is AppSelect && widget.label == '素材分类', + ), + matching: find.byType(TextButton), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.widgetWithText(MenuItemButton, '全部')); + await tester.pumpAndSettle(); + expect(find.text('4 个素材'), findsNothing); + expect(find.text('notes.txt'), findsOneWidget); + expect(tester.takeException(), isNull); + }, + ); + + testWidgets( + 'media layouts resize columns and retain selection and dragging', + (tester) async { + await tester.binding.setSurfaceSize(const Size(280, 600)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + final container = await mount(tester); + final controller = container.read(projectsProvider.notifier) as _Projects; + await controller.importExternalMedia('project', [ + for (var i = 0; i < 8; i++) + ExternalMediaFile(path: '/originals/very-long-asset-name-$i.png'), + ]); + await tester.pumpAndSettle(); + int columns() => + (tester.widget(find.byType(GridView)).gridDelegate + as SliverGridDelegateWithFixedCrossAxisCount) + .crossAxisCount; + expect(columns(), 2); + expect( + find.ancestor( + of: find.byType(GridView), + matching: find.byType(ShaderMask), + ), + findsOneWidget, + ); + expect( + find.ancestor( + of: find.byKey(const Key('media-panel-header')), + matching: find.byType(ShaderMask), + ), + findsNothing, + ); + final first = find.text('very-long-asset-name-0.png'); + await tester.tap(first); + await tester.tap(find.byTooltip('列表布局')); + await tester.pumpAndSettle(); + expect(find.byType(GridView), findsNothing); + expect(find.byType(ListView), findsOneWidget); + expect( + find.ancestor( + of: find.byType(ListView), + matching: find.byType(ShaderMask), + ), + findsOneWidget, + ); + expect( + find.ancestor( + of: first, + matching: find.byWidgetPredicate( + (w) => w is Semantics && w.properties.selected == true, + ), + ), + findsOneWidget, + ); + expect( + find.ancestor( + of: first, + matching: find.byWidgetPredicate((w) => w is Draggable), + ), + findsOneWidget, + ); + await tester.tap(find.byTooltip('宫格布局')); + await tester.pumpAndSettle(); + for (final (width, count) in [ + (180.0, 1), + (280.0, 2), + (520.0, 3), + (560.0, 4), + (900.0, 6), + ]) { + await tester.binding.setSurfaceSize(Size(width, 600)); + await tester.pumpAndSettle(); + expect(columns(), count); + expect(tester.takeException(), isNull); + } + expect( + find.ancestor( + of: first, + matching: find.byWidgetPredicate( + (w) => w is Semantics && w.properties.selected == true, + ), + ), + findsOneWidget, + ); + }, + ); + + testWidgets('native file event imports real paths without a success prompt', ( + tester, + ) async { + final container = await mount(tester); + final target = tester.getCenter(find.byType(NativeProjectDropRegion)); + await platformEvent(tester, 'enter', [target.dx, target.dy]); + expect(find.byKey(const Key('media-drop-highlight')), findsOneWidget); + expect( + tester.widget(find.byKey(const Key('media-drop-highlight'))), + isA(), + ); + expect(find.text('松手即可添加'), findsOneWidget); + await platformEvent(tester, 'drop', [ + {'path': '/originals/video.mp4'}, + {'path': '/originals/audio.wav'}, + {'path': '/originals/image.png'}, + {'path': '/originals/中文 视频.RMVB'}, + {'path': '/originals/中文 视频.flv'}, + ]); + await tester.pumpAndSettle(); + final controller = container.read(projectsProvider.notifier) as _Projects; + expect(controller.received.map((f) => f.localPath!), [ + '/originals/video.mp4', + '/originals/audio.wav', + '/originals/image.png', + '/originals/中文 视频.RMVB', + '/originals/中文 视频.flv', + ]); + expect(find.text('video.mp4'), findsOneWidget); + expect(find.text('中文 视频.RMVB'), findsOneWidget); + expect(find.text('中文 视频.flv'), findsOneWidget); + expect(find.byType(SnackBar), findsNothing); + expect(find.byKey(const Key('media-drop-highlight')), findsNothing); + expect(tester.takeException(), isNull); + }, variant: TargetPlatformVariant.only(TargetPlatform.macOS)); + + testWidgets( + 'duplicate native drop selects the existing asset without a prompt', + (tester) async { + final container = await mount(tester); + final controller = container.read(projectsProvider.notifier) as _Projects; + await controller.importExternalMedia('project', [ + const ExternalMediaFile(path: '/originals/first.mp4'), + const ExternalMediaFile(path: '/originals/second.wav'), + ]); + await tester.pumpAndSettle(); + await tester.tap(find.text('second.wav')); + await platformEvent(tester, 'enter', [0.0, 0.0]); + await platformEvent(tester, 'drop', ['/originals/first.mp4']); + await tester.pumpAndSettle(); + expect(controller.received.map((file) => file.localPath!), [ + '/originals/first.mp4', + '/originals/second.wav', + ]); + expect( + container.read(projectsProvider).requireValue.assets, + hasLength(2), + ); + expect( + find.ancestor( + of: find.text('first.mp4'), + matching: find.byWidgetPredicate( + (w) => w is Semantics && w.properties.selected == true, + ), + ), + findsOneWidget, + ); + expect(find.byType(SnackBar), findsNothing); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + }, + variant: TargetPlatformVariant.only(TargetPlatform.macOS), + ); + + testWidgets('native drop without an entered session is ignored', ( + tester, + ) async { + final container = await mount(tester); + await platformEvent(tester, 'drop', ['/originals/video.mp4']); + await tester.pumpAndSettle(); + final controller = container.read(projectsProvider.notifier) as _Projects; + expect(controller.received, isEmpty); + expect(find.byType(SnackBar), findsNothing); + }, variant: TargetPlatformVariant.only(TargetPlatform.windows)); + + testWidgets('busy project ignores drops and clears active hover', ( + tester, + ) async { + final container = await mount(tester); + final target = tester.getCenter(find.byType(NativeProjectDropRegion)); + await platformEvent(tester, 'enter', [target.dx, target.dy]); + final controller = container.read(projectsProvider.notifier) as _Projects; + controller.setBusy(true); + await tester.pump(); + expect(find.byKey(const Key('media-drop-highlight')), findsNothing); + await platformEvent(tester, 'drop', ['/originals/video.mp4']); + expect(controller.received, isEmpty); + expect(tester.takeException(), isNull); + }, variant: TargetPlatformVariant.only(TargetPlatform.macOS)); + + testWidgets( + 'audio assets display a cached full-source single-sided waveform', + (tester) async { + const channel = MethodChannel('cutdex_runtime'); + final messenger = tester.binding.defaultBinaryMessenger; + var requests = 0; + messenger.setMockMethodCallHandler(channel, (call) async { + expect(call.method, 'waveform'); + requests++; + return { + 'sampleRate': 4.0, + 'sourceStartSeconds': 2.0, + 'frameCount': 4, + 'trackId': 1, + 'channelCount': 2, + 'levels': [ + { + 'samplesPerBucket': 2, + 'channels': [ + [-0.25, 0.0, 0.1, -0.75, 0.0, 0.4], + [0.0, 0.25, 0.1, 0.0, 0.75, 0.4], + ], + }, + ], + }; + }); + addTearDown(() => messenger.setMockMethodCallHandler(channel, null)); + final container = await mount(tester); + final controller = container.read(projectsProvider.notifier) as _Projects; + await controller.importExternalMedia('project', [ + const ExternalMediaFile(path: '/originals/song.wav'), + ]); + await tester.pumpAndSettle(); + final finder = find.byKey( + const ValueKey('audio-waveform-/originals/song.wav'), + ); + expect(finder, findsOneWidget); + expect(find.text('song.wav'), findsOneWidget); + final painter = tester.widget(finder).painter!; + final recorder = ui.PictureRecorder(); + painter.paint(Canvas(recorder), const Size(100, 40)); + final picture = recorder.endRecording(); + final alpha = await tester.runAsync(() async { + final image = await picture.toImage(100, 40); + try { + final data = (await image.toByteData())!; + return [ + for (final (x, y) in [(11, 35), (11, 15), (71, 15), (71, 5)]) + data.getUint8((y * 100 + x) * 4 + 3), + ]; + } finally { + image.dispose(); + picture.dispose(); + } + }); + expect(alpha, [255, 0, 255, 0]); + final pixelRecorder = ui.PictureRecorder(); + final pixelCanvas = Canvas(pixelRecorder)..scale(2); + painter.paint(pixelCanvas, const Size(101, 40)); + final pixelPicture = pixelRecorder.endRecording(); + final barAlphas = await tester.runAsync(() async { + final image = await pixelPicture.toImage(202, 80); + try { + final data = (await image.toByteData())!; + return { + for (var x = 0; x < 202; x++) + if (data.getUint8((78 * 202 + x) * 4 + 3) > 0) + data.getUint8((78 * 202 + x) * 4 + 3), + }; + } finally { + image.dispose(); + pixelPicture.dispose(); + } + }); + expect(barAlphas, {255}); + controller.setBusy(true); + await tester.pumpAndSettle(); + expect(requests, 1); + }, + ); + + testWidgets( + 'audio cover failures retain a stable fallback without retry loops', + (tester) async { + const channel = MethodChannel('cutdex_runtime'); + final messenger = tester.binding.defaultBinaryMessenger; + var requests = 0; + messenger.setMockMethodCallHandler(channel, (call) async { + requests++; + throw PlatformException(code: 'unsupported'); + }); + addTearDown(() => messenger.setMockMethodCallHandler(channel, null)); + final container = await mount(tester); + final controller = container.read(projectsProvider.notifier) as _Projects; + await controller.importExternalMedia('project', [ + const ExternalMediaFile(path: '/originals/bad.wav'), + ]); + await tester.pumpAndSettle(); + expect(find.byIcon(Icons.audio_file_outlined), findsOneWidget); + final before = tester.getSize( + find.byKey(const ValueKey('audio-cover-/originals/bad.wav')), + ); + controller.setBusy(true); + await tester.pumpAndSettle(); + expect( + tester.getSize( + find.byKey(const ValueKey('audio-cover-/originals/bad.wav')), + ), + before, + ); + expect(requests, 2); + expect(tester.takeException(), isNull); + }, + ); + + testWidgets('touch can open media actions without a mouse', (tester) async { + final container = await mount(tester, touch: true); + final projects = container.read(projectsProvider.notifier) as _Projects; + await projects.importExternalMedia('project', [ + const ExternalMediaFile(path: '/originals/notes.txt'), + ]); + await tester.pumpAndSettle(); + await tester.longPress(find.text('notes.txt')); + await tester.pumpAndSettle(); + expect(find.text('重命名'), findsOneWidget); + expect(find.widgetWithText(MenuItemButton, '添加到时间线'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('mobile file selection imports without native desktop drop', ( + tester, + ) async { + final channel = const MethodChannel('filegate'); + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + channel, + (_) async => [ + {'path': '/originals/phone.mp4', 'name': 'phone.mp4', 'kind': 'file'}, + ], + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + channel, + null, + ), + ); + final container = await mount(tester); + await tester.tap(find.byKey(const Key('media-import-button'))); + await tester.pumpAndSettle(); + expect( + (container.read( + projectsProvider.notifier, + ) as _Projects).received.single.localPath, + '/originals/phone.mp4', + ); + expect(find.byType(NativeProjectDropRegion), findsNothing); + expect(find.text('phone.mp4'), findsOneWidget); + expect(tester.takeException(), isNull); + }, variant: TargetPlatformVariant.only(TargetPlatform.android)); + + testWidgets('mobile shows assets without a desktop drop target', ( + tester, + ) async { + await mount(tester); + expect(find.byType(NativeProjectDropRegion), findsNothing); + expect(find.text('暂无素材'), findsOneWidget); + }, variant: TargetPlatformVariant.only(TargetPlatform.android)); + + testWidgets('imported still images request and display native covers', ( + tester, + ) async { + final recorder = ui.PictureRecorder(); + Canvas(recorder).drawColor(Colors.green, BlendMode.src); + final picture = recorder.endRecording(); + final bytes = await tester.runAsync(() async { + final image = await picture.toImage(12, 16); + try { + return (await image.toByteData(format: ui.ImageByteFormat.png))!.buffer + .asUint8List(); + } finally { + image.dispose(); + picture.dispose(); + } + }); + const channel = MethodChannel('cutdex_runtime'); + final messenger = tester.binding.defaultBinaryMessenger; + final requested = []; + messenger.setMockMethodCallHandler(channel, (call) async { + expect(call.method, 'thumbnail'); + final args = call.arguments as Map; + final media = args['media'] as Map; + expect(media['isImage'], isTrue); + requested.add(media['uri'] as String); + return { + 'requestedTime': args['time'], + 'actualTime': args['time'], + 'width': 12, + 'height': 16, + 'format': args['format'], + 'data': bytes, + }; + }); + addTearDown(() => messenger.setMockMethodCallHandler(channel, null)); + final container = await mount(tester); + final controller = container.read(projectsProvider.notifier) as _Projects; + await controller.importExternalMedia('project', [ + for (final ext in ['heic', 'png', 'jpg']) + ExternalMediaFile(path: '/originals/photo.$ext'), + ]); + await tester.pumpAndSettle(); + expect(requested, hasLength(3)); + expect(find.byType(Image), findsNWidgets(3)); + for (final ext in ['heic', 'png', 'jpg']) { + expect(find.text('photo.$ext'), findsOneWidget); + } + expect(tester.takeException(), isNull); + }); +} + +class _Projects extends Projects { + @override + Future withAssetMedia( + String? projectId, + AssetDocument asset, + Future Function(MediaReference media) action, + ) => action( + MediaReference( + id: asset.id, + uri: Uri.parse(asset.location), + isImage: asset.metadata['kind'] == 'image', + ), + ); + @visibleForTesting + List received = []; + @override + Future build() async => const ProjectState( + activeProject: RecentProject( + id: 'project', + name: 'Project', + path: '/Project.cutdex', + ), + ); + + void setBusy(bool busy) { + state = AsyncData(state.requireValue.copyWith(projectBusy: busy)); + } + + @override + Future importExternalMedia( + String projectId, + List files, { + bool Function()? isCancelled, + }) async { + received = files; + final previous = state.requireValue.assets; + final previousIds = {for (final asset in previous) asset.id}; + final assets = [ + ...previous, + for (final file in files) + if (!previousIds.contains(file.localPath!)) + AssetDocument( + id: file.localPath!, + name: file.localPath!.split('/').last, + storage: AssetStorage.external, + location: Uri.file(file.localPath!).toString(), + metadata: {'kind': mediaKindForPath(file.localPath!)}, + ), + ]; + state = AsyncData(state.requireValue.copyWith(assets: assets)); + return MediaImportResult( + assets: assets, + added: assets.length - previous.length, + duplicates: files + .where((file) => previousIds.contains(file.localPath!)) + .length, + failures: [], + ); + } +} diff --git a/test/name_dialog_test.dart b/test/name_dialog_test.dart new file mode 100644 index 0000000..efe71ab --- /dev/null +++ b/test/name_dialog_test.dart @@ -0,0 +1,70 @@ +import 'package:cutdex/app/editor_theme.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex/features/projects/widgets/name_dialog.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets('rename chat uses the same dialog and compact input', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + theme: EditorTheme.penDark, + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + home: Scaffold( + body: Builder( + builder: (context) => TextButton( + onPressed: () => askName( + context, + title: '重命名聊天', + description: '保持简短且易于识别', + label: '名称', + initialValue: '实现图片页面并添加跳转', + submitLabel: '保存', + ), + child: const Text('Open'), + ), + ), + ), + ), + ); + await tester.tap(find.text('Open')); + await tester.pumpAndSettle(); + + final frame = tester.getRect(find.byKey(const Key('app-dialog-frame'))); + final field = tester.getRect(find.byType(TextFormField)); + final save = tester.getRect(find.widgetWithText(FilledButton, '保存')); + expect(frame.width, 420); + expect(find.text('重命名聊天'), findsOneWidget); + expect(find.text('保持简短且易于识别'), findsOneWidget); + expect(field.left - frame.left, AppSpacing.large); + expect(frame.right - field.right, AppSpacing.large); + expect(field.height, 36); + expect(save.top - field.bottom, AppSpacing.compact); + expect( + tester + .widget( + find.descendant( + of: find.byType(TextFormField), + matching: find.byType(EditableText), + ), + ) + .style + .fontSize, + 14, + ); + expect( + (Theme.of(tester.element(find.byType(TextFormField))) + .inputDecorationTheme + .focusedBorder! + as OutlineInputBorder) + .borderSide + .color, + const Color(0xFF6084AF), + ); + }); +} diff --git a/test/native_project_drop_region_test.dart b/test/native_project_drop_region_test.dart new file mode 100644 index 0000000..a6d227f --- /dev/null +++ b/test/native_project_drop_region_test.dart @@ -0,0 +1,276 @@ +import 'package:cutdex/integrations/platform/native_project_drop_region.dart'; +import 'package:cutdex/integrations/platform/native_file_drop_policy.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + const manager = MethodChannel('cutdex_native/file_drop'); + setUp(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(manager, (_) async => null); + }); + tearDown(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(manager, null); + }); + for (final name in [ + 'cutdex_native/file_drop/media-library', + 'cutdex_native/file_drop/attachments', + ]) { + testWidgets('$name receives events after replacement', (tester) async { + final channel = MethodChannel(name); + final messenger = tester.binding.defaultBinaryMessenger; + messenger.setMockMethodCallHandler(channel, (_) async => null); + addTearDown(() => messenger.setMockMethodCallHandler(channel, null)); + var entered = 0; + Widget target(String key) => MaterialApp( + home: NativeProjectDropRegion( + key: ValueKey(key), + regionId: name.split('/').last, + policy: name == 'cutdex_native/file_drop/attachments' + ? NativeFileDropPolicy.attachments + : NativeFileDropPolicy.mediaLibrary, + enabled: true, + onEnter: (_) => entered++, + onExit: () {}, + onDrop: (_) async {}, + child: const SizedBox.expand(), + ), + ); + await tester.pumpWidget(target('old')); + await tester.pumpAndSettle(); + await tester.pumpWidget(target('new')); + await tester.pumpAndSettle(); + await messenger.handlePlatformMessage( + name, + const StandardMethodCodec().encodeMethodCall( + const MethodCall('event', { + 'phase': 'enter', + 'session': 1, + 'files': [ + {'path': '/sample.mp4'}, + ], + }), + ), + (_) {}, + ); + await tester.pump(); + expect(entered, 1); + await tester.pumpWidget(const SizedBox()); + await tester.pumpAndSettle(); + }); + } + testWidgets('policy changes at fixed bounds update native acceptance', ( + tester, + ) async { + const channel = MethodChannel('cutdex_native/file_drop/media-library'); + final messenger = tester.binding.defaultBinaryMessenger; + final calls = []; + messenger.setMockMethodCallHandler(channel, (call) async { + calls.add(call); + return null; + }); + addTearDown(() => messenger.setMockMethodCallHandler(channel, null)); + Widget target(NativeFileDropPolicy policy) => MaterialApp( + home: NativeProjectDropRegion( + policy: policy, + enabled: true, + onEnter: (_) {}, + onExit: () {}, + onDrop: (_) async {}, + child: const SizedBox.expand(), + ), + ); + await tester.pumpWidget(target(NativeFileDropPolicy.mediaLibrary)); + await tester.pumpAndSettle(); + final library = calls.last.arguments as Map; + // The importer handles failures per file, preserving valid mixed batches. + expect(library['allowedExtensions'], isNull); + calls.clear(); + await tester.pumpWidget(target(NativeFileDropPolicy.timeline)); + await tester.pumpAndSettle(); + final timeline = calls.single.arguments as Map; + expect(timeline['width'], library['width']); + expect(timeline['allowedExtensions'], contains('wav')); + expect(timeline['allowedExtensions'], isNot(contains('png'))); + expect(timeline['maximumFileCount'], 1); + calls.clear(); + await tester.pumpWidget(target(NativeFileDropPolicy.attachments)); + await tester.pumpAndSettle(); + final attachments = calls.single.arguments as Map; + expect(attachments['allowedExtensions'], isNull); + expect(attachments['maximumFileCount'], isNull); + await tester.pumpWidget(const SizedBox()); + await tester.pumpAndSettle(); + }); + testWidgets( + 'timeline rejects images and batches while attachments accept documents', + (tester) async { + const name = 'cutdex_native/file_drop/media-library'; + const channel = MethodChannel(name); + final messenger = tester.binding.defaultBinaryMessenger; + final released = []; + messenger.setMockMethodCallHandler(channel, (call) async { + if (call.method == 'release') { + released.add((call.arguments as Map)['session'] as int); + } + return null; + }); + addTearDown(() => messenger.setMockMethodCallHandler(channel, null)); + var entered = 0, dropped = 0, exited = 0; + Widget target(NativeFileDropPolicy policy) => MaterialApp( + home: NativeProjectDropRegion( + policy: policy, + enabled: true, + onEnter: (_) => entered++, + onExit: () => exited++, + onDrop: (_) async { + dropped++; + }, + child: const SizedBox.expand(), + ), + ); + Future event(String phase, int id, List paths) async { + await messenger.handlePlatformMessage( + name, + const StandardMethodCodec().encodeMethodCall( + MethodCall('event', { + 'phase': phase, + 'session': id, + 'files': [ + for (final path in paths) {'path': path}, + ], + }), + ), + (_) {}, + ); + await tester.pump(); + } + + await tester.pumpWidget(target(NativeFileDropPolicy.timeline)); + await tester.pumpAndSettle(); + await event('enter', 1, ['/image.png']); + await event('enter', 2, ['/a.wav', '/b.mov']); + expect(entered, 0); + expect(released, [1, 2]); + await event('enter', 3, ['/a.WAV']); + await event('drop', 3, ['/a.WAV']); + expect(entered, 1); + expect(dropped, 1); + // A changed drop payload must not commit now-rejected paths. + await event('enter', 4, ['/a.wav']); + await event('drop', 4, ['/image.png']); + expect(dropped, 1); + expect(exited, 1); + expect(released, [1, 2, 3, 4]); + await tester.pumpWidget(target(NativeFileDropPolicy.attachments)); + await tester.pumpAndSettle(); + await event('enter', 5, ['/notes.pdf', '/README']); + await event('drop', 5, ['/notes.pdf', '/README']); + expect(entered, 3); + expect(dropped, 2); + expect(released, [1, 2, 3, 4, 5]); + await tester.pumpWidget(target(NativeFileDropPolicy.timeline)); + await tester.pumpAndSettle(); + await event('enter', 6, ['/素材/transport stream.TS']); + await event('drop', 6, ['/素材/transport stream.TS']); + expect(entered, 4); + expect(dropped, 3); + expect(released, [1, 2, 3, 4, 5, 6]); + await tester.pumpWidget(const SizedBox()); + await tester.pumpAndSettle(); + }, + ); + testWidgets('disabled drop region activates without a geometry change', ( + tester, + ) async { + const channel = MethodChannel('cutdex_native/file_drop/media-library'); + final messenger = tester.binding.defaultBinaryMessenger; + final calls = []; + messenger.setMockMethodCallHandler(channel, (call) async { + calls.add(call); + return null; + }); + addTearDown(() => messenger.setMockMethodCallHandler(channel, null)); + final enabled = ValueNotifier(false); + addTearDown(enabled.dispose); + await tester.pumpWidget( + MaterialApp( + home: ValueListenableBuilder( + valueListenable: enabled, + child: const SizedBox.expand(), + builder: (_, value, child) => NativeProjectDropRegion( + enabled: value, + onEnter: (_) {}, + onExit: () {}, + onDrop: (_) async {}, + child: child!, + ), + ), + ), + ); + await tester.pumpAndSettle(); + calls.clear(); + enabled.value = true; + await tester.pumpAndSettle(); + expect( + calls.where((c) => c.method == 'setRegion' && c.arguments != null), + isNotEmpty, + ); + calls.clear(); + enabled.value = false; + await tester.pumpAndSettle(); + expect(calls.last.arguments, isNull); + calls.clear(); + enabled.value = true; + await tester.pumpAndSettle(); + expect(calls.single.arguments, isNotNull); + await tester.pumpWidget(const SizedBox()); + await tester.pumpAndSettle(); + expect(calls.last.arguments, isNull); + }); + testWidgets('TickerMode restores the drop region without changing layout', ( + tester, + ) async { + const channel = MethodChannel('cutdex_native/file_drop/media-library'); + final messenger = tester.binding.defaultBinaryMessenger; + final calls = []; + messenger.setMockMethodCallHandler(channel, (call) async { + calls.add(call); + return null; + }); + addTearDown(() => messenger.setMockMethodCallHandler(channel, null)); + final active = ValueNotifier(false); + addTearDown(active.dispose); + await tester.pumpWidget( + MaterialApp( + home: ValueListenableBuilder( + valueListenable: active, + child: NativeProjectDropRegion( + enabled: true, + onEnter: (_) {}, + onExit: () {}, + onDrop: (_) async {}, + child: const SizedBox.expand(), + ), + builder: (_, value, child) => + TickerMode(enabled: value, child: child!), + ), + ), + ); + await tester.pumpAndSettle(); + for (final value in [true, false, true]) { + calls.clear(); + active.value = value; + await tester.pumpAndSettle(); + final region = calls + .lastWhere((call) => call.method == 'setRegion') + .arguments; + expect(region, value ? isNotNull : isNull); + } + await tester.pumpWidget(const SizedBox()); + await tester.pumpAndSettle(); + }); +} diff --git a/test/picture_keyframes_test.dart b/test/picture_keyframes_test.dart new file mode 100644 index 0000000..3142f84 --- /dev/null +++ b/test/picture_keyframes_test.dart @@ -0,0 +1,156 @@ +import 'package:cutdex/app/editor_theme.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex/features/preview/preview_panel.dart'; +import 'package:cutdex/features/properties/picture_properties.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'support/preview_fixture.dart'; + +void main() { + testWidgets( + 'compact keyframe inspector authors, seeks, interpolates and clears', + (tester) async { + final f = (await tester.runAsync( + () => createPreviewFixture( + Uri.file('/test/video.mov'), + clipDuration: RationalTime.seconds(5), + ), + ))!; + final view = f.timeline.view(SequenceId('one')); + final project = f.workspace.project!.info.id; + ClipAnimation current() { + final q = view.version.kernelVersion.query(); + return ClipAnimation.at( + q, + q.elementById(ElementId('clip'))!, + view.playheadTick, + TimelineClock.ticksPerSecond ~/ 30, + ); + } + + await tester.pumpWidget( + ProviderScope( + overrides: [ + editorPreviewProvider(project, 'project').overrideWith( + (ref) async => throw StateError('No native preview'), + ), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + theme: EditorTheme.penLight, + home: Scaffold( + body: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 225, + child: SingleChildScrollView( + child: PictureProperties( + projectId: project, + timelineId: 'project', + session: f.timeline, + sequence: SequenceId('one'), + clip: current().record, + animationView: true, + ), + ), + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + Future settleEdit() async { + await tester.pump(); + await tester.runAsync(f.timeline.flush); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + } + + Future tap(String key) async { + await tester.ensureVisible(find.byKey(ValueKey(key))); + await tester.tap(find.byKey(ValueKey(key))); + await settleEdit(); + } + + Finder input(String key) => find.descendant( + of: find.byKey(ValueKey(key)), + matching: find.byType(TextField), + ); + await tap('picture-key-position'); + expect(current().keyed(TransformChannel.position), isTrue); + view.seekTo(2 * TimelineClock.ticksPerSecond); + await tester.pump(); + await tester.enterText(input('picture-x'), '216'); + await tester.testTextInput.receiveAction(TextInputAction.done); + await settleEdit(); + expect(current().value.x, .2); + expect(current().keyTimes(TransformChannel.position).length, 2); + view.seekTo(TimelineClock.ticksPerSecond); + await tester.pump(); + expect( + tester.widget(input('picture-x')).controller!.text, + '108', + ); + await tap('picture-key-previous-position'); + expect(view.playheadTick, 0); + await tap('picture-key-menu-position'); + await tester.tap(find.widgetWithText(MenuItemButton, '保持')); + await settleEdit(); + view.seekTo(TimelineClock.ticksPerSecond); + await tester.pump(); + expect(current().value.x, 0); + await tap('picture-key-next-position'); + expect(view.playheadTick, 2 * TimelineClock.ticksPerSecond); + await tap('picture-key-position'); + expect(current().keyTimes(TransformChannel.position), [0]); + await tap('picture-key-marker-position-0'); + expect(view.playheadTick, 0); + await tap('picture-key-position'); + expect(current().animated(TransformChannel.position), isFalse); + await tap('picture-key-scale'); + await tap('picture-lock'); + view.seekTo(2 * TimelineClock.ticksPerSecond); + await tester.pump(); + await tester.enterText(input('picture-scale-y'), '200'); + await tester.testTextInput.receiveAction(TextInputAction.done); + await settleEdit(); + expect(current().value.scale, 1); + expect(current().value.scaleY, 2); + view.seekTo(TimelineClock.ticksPerSecond); + await tester.pump(); + expect( + tester.widget(input('picture-scale-y')).controller!.text, + '150', + ); + await tap('picture-key-menu-scale'); + await tester.tap(find.text('移除全部关键帧')); + await settleEdit(); + expect(current().animated(TransformChannel.scale), isFalse); + expect(current().value.scaleY, 1.5); + // Unsubmitted text cannot leak into a different playhead position. + await tester.enterText(input('picture-x'), '999'); + view.seekTo(3 * TimelineClock.ticksPerSecond); + await tester.pump(); + await tester.testTextInput.receiveAction(TextInputAction.done); + await settleEdit(); + expect(current().value.x, 0); + await tester.enterText(input('picture-rotation'), '25'); + await tap('picture-key-rotation'); + expect(current().value.rotation, 25); + expect(current().keyed(TransformChannel.rotation), isTrue); + await tester.pumpWidget(const SizedBox()); + await tester.runAsync(() async { + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + }, + ); +} diff --git a/test/preview_controller_test.dart b/test/preview_controller_test.dart new file mode 100644 index 0000000..5a3d7f6 --- /dev/null +++ b/test/preview_controller_test.dart @@ -0,0 +1,3810 @@ +import 'package:cutdex/app/editor_theme.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex/l10n/app_localizations_zh.dart'; +import 'package:cutdex/integrations/editor_command_host.dart'; +import 'package:cutdex_sdk/tools.dart'; +import 'package:cutdex/features/preview/preview_messages.dart'; +import 'package:cutdex/features/properties/animation_labels.dart'; +import 'package:cutdex/features/properties/canvas_presets.dart'; +import 'package:cutdex_sdk/editor.dart'; + +import 'dart:async'; + +import 'package:cutdex_sdk/preview.dart'; +import 'package:cutdex/features/preview/preview_panel.dart'; +import 'package:cutdex/features/properties/mask_properties.dart'; +import 'package:cutdex/features/properties/property_number_input.dart'; +import 'package:cutdex_ui/theme.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:cutdex_sdk/timeline/layout.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'support/preview_fixture.dart'; + +Future until(bool Function() check) async { + for (var i = 0; i < 200; i++) { + if (check()) return; + await Future.delayed(const Duration(milliseconds: 5)); + } + fail('Preview did not reach expected state'); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + const channel = MethodChannel('cutdex_runtime'); + const events = MethodChannel('cutdex_runtime/sessions/test'); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + final calls = []; + String revision = '1'; + bool failPatch = false; + bool toneMappingAvailable = true; + String? detectedColor = 'rec709'; + String? stateBeforeLoadReply; + PlatformException? loadError; + PlatformException? sourceLoadError; + int sourceLoadErrorsRemaining = 0; + final missingMedia = {}; + Completer? blockedProbe; + Completer? blockedSeek; + Completer? blockedTransform; + int cancelledTransforms = 0; + int cancelledRenders = 0; + Completer? blockedPause; + Completer? blockedPlay; + Completer? blockedPatch; + Completer? blockedRender; + void emit(Object data) => messenger.handlePlatformMessage( + events.name, + const StandardMethodCodec().encodeSuccessEnvelope(data), + (_) {}, + ); + setUp(() { + calls.clear(); + blockedProbe = null; + missingMedia.clear(); + failPatch = false; + toneMappingAvailable = true; + detectedColor = 'rec709'; + stateBeforeLoadReply = null; + loadError = null; + sourceLoadError = null; + sourceLoadErrorsRemaining = 0; + blockedSeek = null; + blockedTransform = null; + cancelledTransforms = 0; + cancelledRenders = 0; + blockedPause = null; + blockedPlay = null; + blockedPatch = null; + blockedRender = null; + messenger.setMockMethodCallHandler(events, (call) async { + if (call.method == 'listen') { + scheduleMicrotask(() => emit({'type': 'attached'})); + } + return null; + }); + messenger.setMockMethodCallHandler(channel, (call) async { + calls.add(call); + if (call.method == 'capabilities') { + return { + 'contractVersion': 1, + 'features': { + 'playback.preview': 'available', + 'plan.generatedText': 'available', + 'media.imageProbe': 'available', + 'render.toneMapping': toneMappingAvailable + ? 'available' + : 'notImplemented', + }, + }; + } + if (call.method == 'probe') { + await blockedProbe?.future; + if (missingMedia.contains((call.arguments as Map)['media']['id'])) { + throw PlatformException( + code: 'resourceMissing', + message: 'Source was deleted', + ); + } + return { + 'duration': MediaTime(22199, 600).toMap(), + 'videoTrackCount': 1, + 'videoTrackIds': [1], + 'videoColorSpaces': [detectedColor], + 'videoDisplaySizes': [ + {'width': 1080.0, 'height': 1920.0}, + ], + 'audioTrackCount': 1, + 'audioTrackIds': [1], + 'audioTracks': [ + { + 'start': MediaTime(0, 1).toMap(), + 'duration': MediaTime(1775840, 48000).toMap(), + }, + ], + 'isProtected': false, + }; + } + if (call.method == 'snapshot') { + return { + 'state': 'paused', + 'revision': revision, + 'position': MediaTime(0, 1).toMap(), + 'rate': 0.0, + }; + } + if (call.method == 'recover') { + emit({ + 'state': 'paused', + 'revision': revision, + 'position': MediaTime(0, 1).toMap(), + 'rate': 0.0, + }); + return null; + } + if (call.method == 'createSession') return {'sessionId': 'test'}; + if (call.method == 'load') { + if (sourceLoadError case final failure? + when sourceLoadErrorsRemaining > 0) { + sourceLoadErrorsRemaining--; + throw failure; + } + if (loadError != null) throw loadError!; + revision = (call.arguments as Map)['plan']['revision'] as String; + if (stateBeforeLoadReply case final state?) { + emit({ + 'state': state, + 'revision': revision, + 'position': MediaTime(0, 1).toMap(), + 'rate': state == 'playing' ? 1.0 : 0.0, + }); + await Future.delayed(const Duration(milliseconds: 5)); + } + return revision; + } + if (call.method == 'applyPatch') { + await blockedPatch?.future; + if (loadError != null) throw loadError!; + if (failPatch) throw PlatformException(code: 'testFailure'); + return revision = + (call.arguments as Map)['patch']['revision'] as String; + } + if (call.method == 'seek') await blockedSeek?.future; + if (call.method == 'pause') await blockedPause?.future; + if (call.method == 'play') await blockedPlay?.future; + if (call.method == 'updateInteractiveTransform') { + await blockedRender?.future; + if (cancelledRenders > 0) { + cancelledRenders--; + throw PlatformException( + code: 'cancelled', + message: 'The operation was cancelled', + details: {'domain': 'render'}, + ); + } + } + if (call.method == 'beginInteractiveTransform') { + await blockedTransform?.future; + if (cancelledTransforms > 0) { + cancelledTransforms--; + throw PlatformException( + code: 'cancelled', + message: 'The operation was cancelled', + details: {'domain': 'render'}, + ); + } + } + return null; + }); + }); + tearDown(() { + messenger.setMockMethodCallHandler(channel, null); + messenger.setMockMethodCallHandler(events, null); + }); + + test('alignment tools share geometry, preserve rotation and undo, and never seek', () async { + final fixture = await createPreviewFixture(Uri.file('/align.mov')); + final timeline = fixture.timeline; + final sequence = SequenceId('one'); + final clip = ElementId('clip'); + timeline.commands.setTransform( + sequence: sequence, + clip: clip, + tick: 0, + change: (_) => const ClipTransform( + x: .1, + y: .1, + scale: .5, + scaleY: .4, + rotation: 25, + ), + ); + final preview = PreviewController( + timeline: timeline, + activeSequence: () => timeline.activeSequenceId, + viewForSequence: timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + }); + final tools = editorToolsFor(timeline, sequence); + Future align( + String id, + String alignment, { + int seconds = 1, + }) => tools.invoke( + name: 'clip.align', + arguments: { + 'clipId': 'clip', + 'alignment': alignment, + 'at': {'numerator': '$seconds', 'denominator': 1}, + }, + context: CommandContext(operationId: id), + ); + expect((await align('no-preview', 'left')).status, CommandStatus.rejected); + await preview.initialize(); + await until(() => calls.any((c) => c.method == 'seek')); + final seeks = calls.where((c) => c.method == 'seek').length; + final initial = timeline.persistence.timeline(sequence).exportDto(); + for (final alignment in CanvasAlignment.values) { + final result = await align(alignment.name, alignment.name); + expect(result.edit, EditOutcome.committed, reason: '${result.toJson()}'); + await preview.alignedTransform( + sequence, + AlignClip(clipId: 'clip', at: CommandTime(1, 1), alignment: alignment), + ); + final visual = preview.visualForProperties(clip)!; + final bounds = visual.geometry.bounds; + final coordinate = switch (alignment) { + CanvasAlignment.left => bounds.left, + CanvasAlignment.right => bounds.right - timeline.canvas.width, + CanvasAlignment.horizontalCenter => + bounds.center.dx - timeline.canvas.width / 2, + CanvasAlignment.top => bounds.top, + CanvasAlignment.bottom => bounds.bottom - timeline.canvas.height, + CanvasAlignment.verticalCenter => + bounds.center.dy - timeline.canvas.height / 2, + }; + expect(coordinate, closeTo(0, 1e-6)); + expect(visual.transform.rotation, 25); + expect(visual.transform.scale, .5); + expect(visual.transform.scaleY, .4); + expect(timeline.view(sequence).playheadTick, 0); + timeline.view(sequence).undo(); + expect( + timeline.persistence + .timeline(sequence) + .exportDto() + .elements + .first + .parameters + .map((p) => p.definition.defaultValue), + initial.elements.first.parameters.map((p) => p.definition.defaultValue), + ); + } + expect( + (await align('outside', 'left', seconds: 10)).status, + CommandStatus.rejected, + ); + expect(calls.where((c) => c.method == 'seek'), hasLength(seeks)); + expect(calls.where((c) => c.method == 'createSession'), hasLength(1)); + }); + + test( + 'generated captions participate in canvas selection and transforms', + () async { + final duration = RationalTime.seconds(2); + final fixture = await createPreviewFixture( + Uri.file('/caption.mov'), + timelineOverride: TimelineDto( + id: SequenceId('one'), + name: 'one', + format: TimelineFormat.fps30, + primaryStorylineId: StorylineId('primary'), + storylines: [ + StorylineDto( + id: StorylineId('primary'), + elementIds: [ElementId('clip')], + ), + StorylineDto( + id: StorylineId('captions'), + timeDomain: TimeDomain.parallel, + elementIds: [ElementId('caption-gap'), ElementId('caption')], + ), + ], + elements: [ + ElementDto( + id: ElementId('clip'), + structure: ElementStructure.content, + payloadRef: PayloadRef('source'), + duration: duration, + sourceRange: TimeRange( + start: RationalTime.zero, + duration: duration, + ), + mediaRange: TimeRange( + start: RationalTime.zero, + duration: duration, + ), + ), + ElementDto( + id: ElementId('caption-gap'), + structure: ElementStructure.gap, + duration: duration, + sourceRange: TimeRange( + start: RationalTime.zero, + duration: duration, + ), + ), + ElementDto( + id: ElementId('caption'), + name: 'Canvas caption', + structure: ElementStructure.content, + payloadRef: PayloadRef('caption-payload'), + duration: RationalTime.seconds(1), + sourceRange: TimeRange( + start: RationalTime.zero, + duration: RationalTime.seconds(1), + ), + sourceExtendable: true, + parallelOffset: RationalTime(1, 5), + ), + ElementDto( + id: ElementId('caption-role'), + name: 'Captions', + structure: ElementStructure.container, + payloadRef: PayloadRef('caption-role-payload'), + duration: duration, + sourceRange: TimeRange( + start: RationalTime.zero, + duration: duration, + ), + containerStorylineId: StorylineId('captions'), + ), + ], + connections: [ + ConnectionDto( + id: ConnectionId('caption-connection'), + anchorId: ElementId('clip'), + targetId: ElementId('caption-role'), + anchorTime: RationalTime.zero, + targetTime: RationalTime.zero, + side: ConnectionSide.above, + ), + ], + ), + payloads: [ + PayloadDocument( + id: 'source', + type: 'video', + assetIds: ['media'], + data: {'videoTrackIndex': 0}, + ), + PayloadDocument( + id: 'caption-payload', + type: 'caption', + data: EditorCaption(text: 'Canvas caption').toJson(), + ), + PayloadDocument( + id: 'caption-role-payload', + type: 'caption-role', + data: const EditorCaptionRole().toJson(), + ), + ], + ); + final timeline = fixture.timeline; + final sequence = SequenceId('one'); + final clip = ElementId('caption'); + final preview = PreviewController( + timeline: timeline, + activeSequence: () => timeline.activeSequenceId, + viewForSequence: timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + }); + await preview.initialize(); + await until(() => !preview.busy); + final visual = preview.visualForProperties(clip)!; + expect( + visual.geometry.center.dy, + greaterThan(timeline.canvas.height / 2), + ); + expect(visual.geometry.size.width, lessThan(800)); + expect(visual.geometry.size.height, lessThan(100)); + expect(visual.geometry.size.height, greaterThanOrEqualTo(48)); + preview.selectVisual(clip); + expect(preview.selectedVisualIds, {clip}); + final selected = timeline.view(sequence).selectedIdentities.single; + expect(selected, isA()); + expect((selected as LayoutBodyId).kind, 'caption-cue'); + final edit = preview.transforms.begin(visual)!; + edit.update( + visual.transform.copyWith(x: .1, y: .05, scale: 1.2, rotation: 20), + ); + await edit.end(); + final record = timeline.persistence + .timeline(sequence) + .current + .query() + .elementById(clip)!; + final value = ClipTransform.fromRecord( + timeline.persistence.timeline(sequence).current.query().element(record), + ); + expect(value.x, .1); + expect(value.y, .05); + expect(value.scale, 1.2); + expect(value.rotation, 20); + }, + ); + + test( + 'tools control native preview without changing authored state', + () async { + final fixture = await createPreviewFixture(Uri.file('/tools.mov')); + final timeline = fixture.timeline; + final sequence = SequenceId('one'); + final preview = PreviewController( + timeline: timeline, + activeSequence: () => timeline.activeSequenceId, + viewForSequence: timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + }); + Future invoke( + String name, + String id, [ + Map args = const {}, + SequenceId? target, + ]) => editorToolsFor(timeline, target ?? sequence).invoke( + name: name, + arguments: args, + context: CommandContext(operationId: id), + ); + expect( + (await invoke('preview.query', 'before')).data['available'], + false, + ); + await preview.initialize(); + final version = timeline.commands.version; + final dirty = timeline.dirty; + expect((await invoke('preview.query', 'ready')).data['ready'], true); + final seek = await invoke('preview.seek', 'seek', { + 'at': {'numerator': '1', 'denominator': 1}, + }); + expect(seek.status, CommandStatus.succeeded, reason: '${seek.toJson()}'); + expect(seek.edit, EditOutcome.notApplicable); + expect( + timeline.view(sequence).playheadTick, + TimelineClock.ticksPerSecond, + ); + final seeks = calls.where((c) => c.method == 'seek').length; + await invoke('preview.seek', 'seek', { + 'at': {'numerator': '1', 'denominator': 1}, + }); + expect(calls.where((c) => c.method == 'seek'), hasLength(seeks)); + expect( + (await invoke('preview.play', 'play')).status, + CommandStatus.succeeded, + ); + expect(calls.any((c) => c.method == 'play'), true); + expect( + (await invoke('preview.pause', 'pause')).status, + CommandStatus.succeeded, + ); + expect(calls.any((c) => c.method == 'pause'), true); + expect( + (await invoke('preview.retry', 'retry')).status, + CommandStatus.succeeded, + ); + final wrong = await invoke('preview.seek', 'other', { + 'at': {'numerator': '0', 'denominator': 1}, + }, SequenceId('empty')); + expect(wrong.status, CommandStatus.rejected); + expect(wrong.edit, EditOutcome.notApplicable); + expect(timeline.commands.version, version); + expect(timeline.dirty, dirty); + await preview.close(); + expect( + (await invoke('preview.query', 'closed')).data['available'], + false, + ); + }, + ); + + test('round 2: closed preview cannot publish a late probe failure', () async { + final fixture = await createPreviewFixture(Uri.file('/late.mov')); + final preview = PreviewController( + timeline: fixture.timeline, + activeSequence: () => fixture.timeline.activeSequenceId, + viewForSequence: fixture.timeline.view, + runtime: CutdexRuntime(), + ); + blockedProbe = Completer(); + missingMedia.add('media'); + final initialized = preview.initialize(); + await until(() => calls.any((call) => call.method == 'probe')); + final closing = preview.close(); + blockedProbe!.complete(); + await initialized; + await closing; + expect(fixture.timeline.unavailableAssets, isEmpty); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + }); + + for (final mediaType in ['video', 'image']) { + test( + 'offline $mediaType preserves timing and other clips remain playable, retry restores it', + () async { + final fixture = await createPreviewFixture( + Uri.file('/missing.$mediaType'), + mediaType: mediaType, + ); + final timeline = fixture.timeline; + await fixture.workspace.project!.saveAsset( + AssetDocument( + id: 'available', + name: 'Available', + storage: AssetStorage.external, + location: 'file:///available.mov', + ), + ); + timeline.insertAsset( + sequenceId: SequenceId('one'), + assetId: 'available', + assetName: 'Available', + uri: Uri.file('/available.mov'), + duration: RationalTime.seconds(1), + position: 2 * TimelineClock.ticksPerSecond, + kind: 'video', + hasAudio: false, + ); + final original = timeline.view(SequenceId('one')).version.kernelVersion; + missingMedia.add('media'); + final preview = PreviewController( + timeline: timeline, + activeSequence: () => timeline.activeSequenceId, + viewForSequence: timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + }); + await preview.initialize(); + expect(preview.error, isNull); + expect(preview.canPlay, isTrue); + expect(preview.durationTick, 3 * TimelineClock.ticksPerSecond); + final plan = + (calls.firstWhere((c) => c.method == 'load').arguments + as Map)['plan'] + as Map; + expect((plan['media'] as List).map((m) => m['id']), ['available']); + expect( + (plan['visualLayers'] as List).single['timelineRange']['start'], + MediaTime(2, 1).toMap(), + ); + expect(preview.unavailableAtPlayhead, contains('Preview clip')); + expect(timeline.unavailableAssets, {'media': 'resourceMissing'}); + expect( + timeline.view(SequenceId('one')).version.kernelVersion, + same(original), + ); + await preview.togglePlayback(); + expect(calls.any((c) => c.method == 'play'), isTrue); + timeline + .view(SequenceId('one')) + .seekTo(2 * TimelineClock.ticksPerSecond); + expect(preview.unavailableAtPlayhead, isEmpty); + missingMedia.clear(); + await preview.retry(); + expect(preview.error, isNull); + expect(timeline.unavailableAssets, isEmpty); + expect( + timeline.view(SequenceId('one')).version.kernelVersion, + same(original), + ); + }, + ); + } + + test( + 'transient source decode failure retries the complete media plan', + () async { + final fixture = await createPreviewFixture(Uri.file('/broken.mov')); + final preview = PreviewController( + timeline: fixture.timeline, + activeSequence: () => fixture.timeline.activeSequenceId, + viewForSequence: fixture.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + }); + sourceLoadError = PlatformException( + code: 'malformedData', + message: 'Decode failed', + details: { + 'domain': 'media', + 'platformDetails': {'mediaID': 'media', 'sourceFailure': 'true'}, + }, + ); + sourceLoadErrorsRemaining = 1; + await preview.initialize(); + expect(preview.error, isNull); + expect(preview.canPlay, isTrue); + expect(preview.durationTick, 2 * TimelineClock.ticksPerSecond); + expect(fixture.timeline.unavailableAssets, isEmpty); + final loads = calls.where((call) => call.method == 'load').toList(); + expect(loads, hasLength(2)); + expect((loads.last.arguments as Map)['plan']['media'], isNotEmpty); + }, + ); + + test( + 'persistent source decode failure retries once then omits that media', + () async { + final fixture = await createPreviewFixture(Uri.file('/broken.mov')); + final preview = PreviewController( + timeline: fixture.timeline, + activeSequence: () => fixture.timeline.activeSequenceId, + viewForSequence: fixture.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + }); + sourceLoadError = PlatformException( + code: 'malformedData', + message: 'Decode failed', + details: { + 'domain': 'media', + 'platformDetails': {'mediaID': 'media', 'sourceFailure': 'true'}, + }, + ); + sourceLoadErrorsRemaining = 2; + await preview.initialize(); + expect(preview.error, isNull); + expect(fixture.timeline.unavailableAssets, {'media': 'malformedData'}); + final loads = calls.where((call) => call.method == 'load').toList(); + expect(loads, hasLength(3)); + expect((loads.last.arguments as Map)['plan']['media'], isEmpty); + }, + ); + + for (final detected in [null, 'rec709', 'rec2020HLG', 'rec2020PQ']) { + test( + 'input color $detected defaults, overrides and resets without a timeline edit', + () async { + detectedColor = detected; + final f = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: f.timeline, + activeSequence: () => f.timeline.activeSequenceId, + viewForSequence: f.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + await preview.initialize(); + final initial = + (calls.lastWhere((c) => c.method == 'load').arguments + as Map)['plan'] + as Map; + expect( + initial['inputColorOverrides'], + detected == null ? {'video:clip': 'rec709'} : isEmpty, + ); + final version = f.timeline + .view(SequenceId('one')) + .version + .kernelVersion; + f.timeline.commands.setMediaColor('media', 0, MediaColorSpace.sRGB); + await until(() => !preview.busy); + expect(preview.ready, isTrue); + final changed = + (calls.lastWhere((c) => c.method == 'applyPatch').arguments + as Map)['patch'] + as Map; + expect(changed['inputColorOverrides'], {'video:clip': 'sRGB'}); + expect(changed['toneMapping'], initial['toneMapping']); + expect( + f.timeline.view(SequenceId('one')).version.kernelVersion, + same(version), + ); + await f.timeline.flush(); + final saved = await f.workspace.project!.loadTimeline('project'); + expect(saved.settings['mediaColorInterpretations'], { + 'media': {'0': 'sRGB'}, + }); + f.timeline.commands.setMediaColor('media', 0, null); + await until(() => !preview.busy); + final reset = + (calls.lastWhere((c) => c.method == 'applyPatch').arguments + as Map)['patch'] + as Map; + expect(reset['inputColorOverrides'], initial['inputColorOverrides']); + expect(calls.where((c) => c.method == 'probe'), hasLength(1)); + }, + ); + } + + testWidgets('mask inspector adds a shape and grouped keys at compact width', ( + tester, + ) async { + final selected = ValueNotifier((ElementId('clip'), 0)); + addTearDown(selected.dispose); + await tester.binding.setSurfaceSize(const Size(320, 760)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + final f = (await tester.runAsync( + () => createPreviewFixture(Uri.file('/test/video.mov')), + ))!; + final preview = PreviewController( + timeline: f.timeline, + activeSequence: () => f.timeline.activeSequenceId, + viewForSequence: f.timeline.view, + runtime: CutdexRuntime(), + ); + await tester.runAsync(preview.initialize); + await tester.pumpWidget( + ProviderScope( + overrides: [ + editorPreviewProvider( + 'project', + 'project', + ).overrideWith((ref) async => preview), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + theme: EditorTheme.penDark, + home: Scaffold( + body: SingleChildScrollView( + child: Padding( + padding: const EdgeInsets.all(16), + child: ValueListenableBuilder( + valueListenable: selected, + builder: (context, element, _) => MaskProperties( + key: ValueKey(element.$2), + projectId: 'project', + timelineId: 'project', + element: element.$1, + ), + ), + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect(find.byKey(const ValueKey('mask-shape-ellipse')), findsNothing); + expect(find.byTooltip('重置蒙版'), findsNothing); + await tester.tap(find.byTooltip('添加蒙版')); + await tester.pumpAndSettle(); + await tester.tap(find.text('椭圆')); + await tester.pump(); + await tester.runAsync(f.timeline.flush); + await tester.pumpAndSettle(); + expect(preview.maskFor(ElementId('clip'))!.shape, ClipMaskShape.ellipse); + final originalMask = preview.maskFor(ElementId('clip'))!; + await tester.runAsync(() async { + preview.applyMask(originalMask.copyWith(x: 2.5, y: -2)); + await until(() => !preview.busy); + }); + await tester.pumpAndSettle(); + for (final label in ['X', 'Y']) { + final input = tester.widget( + find.byWidgetPredicate( + (widget) => widget is PropertyNumberInput && widget.label == label, + ), + ); + expect(input.onScrubStart!(), isTrue); + input.onScrubUpdate(1); + expect(preview.maskFor(ElementId('clip'))!.x, label == 'X' ? 2.51 : 2.5); + expect(preview.maskFor(ElementId('clip'))!.y, label == 'Y' ? -1.99 : -2); + input.onScrubCancel(); + await tester.pumpAndSettle(); + } + await tester.runAsync(() async { + preview.applyMask(originalMask); + await until(() => !preview.busy); + }); + await tester.pumpAndSettle(); + + await tester.runAsync(() async { + preview.applyMask(originalMask.copyWith(width: 5, height: 4)); + await until(() => !preview.busy); + }); + await tester.pumpAndSettle(); + final widthField = find.byWidgetPredicate( + (widget) => widget is PropertyNumberInput && widget.label == 'W', + ); + final widthLabel = find.descendant( + of: widthField, + matching: find.text('W'), + ); + await tester.ensureVisible(widthLabel); + final scrub = await tester.startGesture(tester.getCenter(widthLabel)); + await scrub.moveBy(const Offset(20, 0)); + await tester.pump(); + expect(preview.maskFor(ElementId('clip'))!.width, closeTo(5.2, 1e-6)); + expect(preview.maskFor(ElementId('clip'))!.height, 4); + await scrub.moveBy(const Offset(20000, 0)); + await tester.pump(); + expect(preview.maskFor(ElementId('clip'))!.width, ClipMask.maxExtent); + await scrub.moveBy(const Offset(-20000, 0)); + await tester.pump(); + expect(preview.maskFor(ElementId('clip'))!.width, closeTo(5.2, 1e-6)); + await scrub.up(); + await tester.runAsync(f.timeline.flush); + await tester.pumpAndSettle(); + expect(preview.maskFor(ElementId('clip'))!.width, closeTo(5.2, 1e-6)); + await tester.runAsync(() async { + f.timeline.view(SequenceId('one')).undo(); + await until(() => !preview.busy); + }); + await tester.pumpAndSettle(); + expect(preview.maskFor(ElementId('clip'))!.width, 5); + await tester.runAsync(() async { + preview.applyMask(originalMask); + await until(() => !preview.busy); + }); + await tester.pumpAndSettle(); + await tester.ensureVisible(find.byKey(const ValueKey('mask-key-位置'))); + + for (final (channel, input) in [ + ('位置', 'Y'), + ('尺寸', 'H'), + ('旋转', '旋转'), + ('羽化', '羽化'), + ]) { + expect( + tester.getRect(find.byKey(ValueKey('mask-key-$channel'))).left - + tester + .getRect( + find.byWidgetPredicate( + (widget) => + widget is PropertyNumberInput && widget.label == input, + ), + ) + .right, + AppSpacing.small, + ); + } + expect(find.byTooltip('羽化关键帧'), findsOneWidget); + final xDraft = find.byWidgetPredicate( + (widget) => widget is PropertyNumberInput && widget.label == 'X', + ); + await tester.ensureVisible(xDraft); + await tester.enterText( + find.descendant(of: xDraft, matching: find.byType(TextField)), + '75', + ); + await tester.tap(find.byKey(const ValueKey('mask-key-位置'))); + await tester.pump(); + await tester.runAsync(f.timeline.flush); + await tester.pumpAndSettle(); + expect( + preview + .maskAnimation(ElementId('clip'))! + .keyed(maskChannels['position']!), + isTrue, + ); + expect(preview.maskFor(ElementId('clip'))!.x, .75); + await tester.runAsync(() async { + f.timeline.view(SequenceId('one')).undo(); + await until(() => !preview.busy); + }); + await tester.pumpAndSettle(); + expect( + preview + .maskAnimation(ElementId('clip'))! + .keyed(maskChannels['position']!), + isFalse, + ); + expect(preview.maskFor(ElementId('clip'))!.x, .75); + await tester.runAsync(() async { + f.timeline.view(SequenceId('one')).undo(); + await until(() => !preview.busy); + }); + await tester.pumpAndSettle(); + expect(preview.maskFor(ElementId('clip'))!.x, originalMask.x); + final firstMaskId = preview.selectedMaskId!; + await tester.tap(find.byTooltip('添加蒙版')); + await tester.pumpAndSettle(); + await tester.tap(find.text('矩形').last); + await tester.pump(); + await tester.runAsync(f.timeline.flush); + await tester.pumpAndSettle(); + final added = preview.selectedMaskId!; + expect(preview.maskStackFor(ElementId('clip'))!.layers, hasLength(2)); + await tester.tap(find.byTooltip('组合方式:相加')); + await tester.pumpAndSettle(); + await tester.tap(find.text('相减')); + await tester.pump(); + await tester.runAsync(f.timeline.flush); + await tester.pumpAndSettle(); + expect( + preview.maskStackFor(ElementId('clip'))!.layers.last.mode, + ClipMaskMode.subtract, + ); + await tester.tap(find.byTooltip('上移蒙版')); + await tester.pump(); + await tester.runAsync(f.timeline.flush); + await tester.pumpAndSettle(); + expect(preview.maskStackFor(ElementId('clip'))!.layers.first.id, added); + await tester.tap(find.byTooltip('删除蒙版').first); + await tester.pump(); + await tester.runAsync(f.timeline.flush); + await tester.pumpAndSettle(); + expect( + preview.maskStackFor(ElementId('clip'))!.layers.single.id, + firstMaskId, + ); + expect(find.byKey(const ValueKey('mask-shape-none')), findsNothing); + await tester.tap(find.byTooltip('删除蒙版')); + await tester.pump(); + await tester.runAsync(f.timeline.flush); + await tester.pumpAndSettle(); + expect(preview.maskFor(ElementId('clip')), isNull); + expect(find.byTooltip('添加蒙版'), findsOneWidget); + expect(find.byTooltip('重置蒙版'), findsNothing); + expect(find.byKey(const ValueKey('mask-key-位置')), findsNothing); + expect(tester.takeException(), isNull); + selected.value = (ElementId('clip'), 1); + await tester.pumpAndSettle(); + final replacementElement = preview.maskEditingElement; + selected.value = (ElementId('other'), 1); + await tester.pumpAndSettle(); + final boundElement = preview.maskEditingElement; + await tester.pumpWidget(const SizedBox()); + final closing = preview.close(); + var closed = false; + unawaited(closing.then((_) => closed = true)); + for (var i = 0; i < 40 && !closed; i++) { + await tester.pump(); + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 10)), + ); + } + expect(closed, isTrue); + await tester.runAsync(() async { + await closing; + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + expect(boundElement, ElementId('other')); + expect(replacementElement, ElementId('clip')); + }); + + testWidgets('large mask corner resize preserves SDK-valid extents', ( + tester, + ) async { + await tester.binding.setSurfaceSize(const Size(900, 800)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + final f = (await tester.runAsync( + () => createPreviewFixture(Uri.file('/test/video.mov')), + ))!; + final preview = PreviewController( + timeline: f.timeline, + activeSequence: () => f.timeline.activeSequenceId, + viewForSequence: f.timeline.view, + runtime: CutdexRuntime(), + ); + await tester.runAsync(preview.initialize); + final id = ElementId('clip'); + await tester.runAsync(() async { + preview.setMaskEditing(id); + preview.addMask(ClipMaskShape.rectangle); + await until(() => !preview.busy); + preview.applyMask(preview.maskFor(id)!.copyWith(width: 5, height: 3)); + await until(() => !preview.busy); + }); + const rect = Rect.fromLTWH(350, 240, 100, 178); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: MaskInteractionOverlay(controller: preview, canvasRect: rect), + ), + ), + ); + final mask = preview.maskFor(id)!; + final g = preview.visuals.single.geometry; + final scale = rect.width / preview.canvas.width; + final origin = rect.topLeft + g.corners[0] * scale; + final xAxis = (g.corners[1] - g.corners[0]) * scale; + final yAxis = (g.corners[3] - g.corners[0]) * scale; + final corner = + origin + + xAxis * (mask.x + mask.width / 2) + + yAxis * (mask.y + mask.height / 2); + final gesture = await tester.startGesture(corner); + await gesture.moveBy(const Offset(20, 20)); + await tester.pump(); + expect(preview.maskFor(id)!.width, greaterThan(5)); + expect(preview.maskFor(id)!.height, greaterThan(3)); + await gesture.up(); + await tester.runAsync(f.timeline.flush); + await tester.pumpAndSettle(); + expect(preview.maskFor(id)!.width, greaterThan(5)); + await tester.runAsync(() async { + f.timeline.view(SequenceId('one')).undo(); + await until(() => !preview.busy); + }); + await tester.pumpAndSettle(); + expect(preview.maskFor(id)!.width, 5); + expect(preview.maskFor(id)!.height, 3); + await tester.pumpWidget(const SizedBox()); + await tester.runAsync(() async { + await preview.close(); + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + }); + + testWidgets('mask canvas movement preserves SDK-valid positions', ( + tester, + ) async { + await tester.binding.setSurfaceSize(const Size(900, 800)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + final f = (await tester.runAsync( + () => createPreviewFixture(Uri.file('/test/video.mov')), + ))!; + final preview = PreviewController( + timeline: f.timeline, + activeSequence: () => f.timeline.activeSequenceId, + viewForSequence: f.timeline.view, + runtime: CutdexRuntime(), + ); + await tester.runAsync(preview.initialize); + final id = ElementId('clip'); + await tester.runAsync(() async { + preview.setMaskEditing(id); + preview.addMask(ClipMaskShape.rectangle); + await until(() => !preview.busy); + preview.applyMask(preview.maskFor(id)!.copyWith(x: 2.5, y: -2)); + await until(() => !preview.busy); + }); + const rect = Rect.fromLTWH(250, 450, 100, 178); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: MaskInteractionOverlay(controller: preview, canvasRect: rect), + ), + ), + ); + final mask = preview.maskFor(id)!; + final g = preview.visuals.single.geometry; + final scale = rect.width / preview.canvas.width; + final origin = rect.topLeft + g.corners[0] * scale; + final xAxis = (g.corners[1] - g.corners[0]) * scale; + final yAxis = (g.corners[3] - g.corners[0]) * scale; + final center = origin + xAxis * mask.x + yAxis * mask.y; + final gesture = await tester.startGesture(center); + await gesture.moveBy(const Offset(20, 20)); + await tester.pump(); + await gesture.moveBy(const Offset(10, 10)); + await tester.pump(); + expect(preview.maskFor(id)!.x, greaterThan(2.5)); + expect(preview.maskFor(id)!.y, greaterThan(-2)); + expect(preview.maskFor(id)!.y, lessThan(-1)); + await gesture.up(); + await tester.runAsync(f.timeline.flush); + await tester.pumpAndSettle(); + expect(preview.maskFor(id)!.x, greaterThan(2.5)); + await tester.runAsync(() async { + f.timeline.view(SequenceId('one')).undo(); + await until(() => !preview.busy); + }); + await tester.pumpAndSettle(); + expect(preview.maskFor(id)!.x, 2.5); + expect(preview.maskFor(id)!.y, -2); + await tester.pumpWidget(const SizedBox()); + await tester.runAsync(() async { + await preview.close(); + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + }); + + for (var corner = 0; corner < 4; corner++) { + testWidgets( + 'mask exterior corner $corner rotates and preserves dimensions', + (tester) async { + final f = (await tester.runAsync( + () => createPreviewFixture(Uri.file('/test/video.mov')), + ))!; + final preview = PreviewController( + timeline: f.timeline, + activeSequence: () => f.timeline.activeSequenceId, + viewForSequence: f.timeline.view, + runtime: CutdexRuntime(), + ); + await tester.runAsync(preview.initialize); + final id = ElementId('clip'); + await tester.runAsync(() async { + preview.setMaskEditing(id); + preview.addMask(ClipMaskShape.rectangle); + await until(() => !preview.busy); + }); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: MaskInteractionOverlay( + controller: preview, + canvasRect: const Rect.fromLTWH(100, 100, 320, 568), + ), + ), + ), + ); + final mask = preview.maskFor(id)!; + final g = preview.visuals.single.geometry; + final scale = 320 / preview.canvas.width; + final origin = const Offset(100, 100) + g.corners[0] * scale; + final xAxis = (g.corners[1] - g.corners[0]) * scale; + final yAxis = (g.corners[3] - g.corners[0]) * scale; + final center = origin + xAxis * mask.x + yAxis * mask.y; + final signs = [ + const Offset(-1, -1), + const Offset(1, -1), + const Offset(1, 1), + const Offset(-1, 1), + ]; + final direction = + xAxis * (mask.width / 2 * signs[corner].dx) + + yAxis * (mask.height / 2 * signs[corner].dy); + final radial = direction + direction / direction.distance * 16; + final gesture = await tester.startGesture(center + radial); + await gesture.moveTo(center + Offset(-radial.dy, radial.dx)); + await tester.pump(); + expect(preview.maskFor(id)!.rotation, closeTo(90, .01)); + expect(preview.maskFor(id)!.width, mask.width); + expect(preview.maskFor(id)!.height, mask.height); + await gesture.up(); + await tester.runAsync(f.timeline.flush); + await tester.pumpAndSettle(); + expect(preview.maskFor(id)!.rotation, closeTo(90, .01)); + await tester.pumpWidget(const SizedBox()); + await tester.runAsync(() async { + await preview.close(); + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + }, + ); + } + + for (final obscure in [false, true]) { + testWidgets( + 'region canvas movement commits once and Escape restores timeline obscure=$obscure', + (tester) async { + final f = (await tester.runAsync( + () => createPreviewFixture(Uri.file('/test/video.mov')), + ))!; + final preview = PreviewController( + timeline: f.timeline, + activeSequence: () => f.timeline.activeSequenceId, + viewForSequence: f.timeline.view, + runtime: CutdexRuntime(), + ); + await tester.runAsync(preview.initialize); + final id = ElementId('clip'); + ClipMask? region() => + obscure ? preview.obscureFor(id) : preview.maskFor(id); + await tester.runAsync(() async { + if (obscure) { + f.timeline.publishParameters(SequenceId('one'), id, [ + maskConstant('obscure.enabled', 1), + maskConstant('obscure.width', .5), + maskConstant('obscure.height', .5), + ]); + preview.setObscureEditing(id); + } else { + preview.setMaskEditing(id); + preview.addMask(ClipMaskShape.rectangle); + } + await until(() => !preview.busy); + }); + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + theme: EditorTheme.penDark, + home: Scaffold( + body: MaskInteractionOverlay( + obscure: obscure, + controller: preview, + canvasRect: const Rect.fromLTWH(0, 0, 320, 568), + ), + ), + ), + ); + final base = f.timeline.view(SequenceId('one')).version; + final gesture = await tester.startGesture(const Offset(160, 284)); + await gesture.moveTo(const Offset(185, 284)); + await tester.pump(); + await gesture.moveTo(const Offset(205, 284)); + await tester.pump(); + expect(region()!.x, greaterThan(.5)); + expect(f.timeline.view(SequenceId('one')).version, same(base)); + await gesture.up(); + await tester.pump(); + await tester.runAsync(f.timeline.flush); + await tester.pumpAndSettle(); + final committed = region()!.x; + final patches = calls.where((c) => c.method == 'applyPatch').length; + final second = await tester.startGesture(Offset(committed * 320, 284)); + await second.moveBy(const Offset(25, 0)); + await tester.pump(); + await second.moveBy(const Offset(20, 0)); + await tester.pump(); + expect(region()!.x, greaterThan(committed)); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await second.up(); + await tester.pumpAndSettle(); + expect(region()!.x, committed); + final retainedAfterCancel = preview.transforms.hasContext; + final patchesAfterCancel = calls + .where((c) => c.method == 'applyPatch') + .length; + final endedAfterCancel = calls + .where((c) => c.method == 'endInteractiveTransform') + .length; + if (obscure) { + final beforeResize = f.timeline.view(SequenceId('one')).version; + final resize = await tester.startGesture( + Offset((committed + .25) * 320, .75 * 568), + ); + await resize.moveBy(const Offset(20, 20)); + await tester.pump(); + await resize.moveBy(const Offset(10, 10)); + await tester.pump(); + expect(region()!.width, greaterThan(.5)); + expect(region()!.height, greaterThan(.5)); + expect( + f.timeline.view(SequenceId('one')).version, + same(beforeResize), + ); + await resize.up(); + await tester.pump(); + await tester.runAsync(f.timeline.flush); + await tester.pumpAndSettle(); + f.timeline.view(SequenceId('one')).undo(); + await tester.pump(); + await tester.runAsync(f.timeline.flush); + await tester.pumpAndSettle(); + expect(region()!.width, .5); + expect(region()!.x, committed); + } + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + final closing = preview.close(); + var closed = false; + unawaited(closing.then((_) => closed = true)); + for (var i = 0; i < 40 && !closed; i++) { + await tester.pump(); + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 10)), + ); + } + expect(closed, isTrue); + await tester.runAsync(() async { + await closing.timeout(const Duration(seconds: 5)); + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + expect(patchesAfterCancel, patches); + expect(endedAfterCancel, 0); + expect(retainedAfterCancel, isTrue); + }, + ); + } + test('cold mask key edits retain the interactive frame', () async { + final f = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: f.timeline, + activeSequence: () => f.timeline.activeSequenceId, + viewForSequence: f.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + await preview.initialize(); + final id = ElementId('clip'); + preview.setMaskEditing(id); + preview.addMask(ClipMaskShape.rectangle); + preview.cancelTransform(); + await until(() => !preview.busy); + final patches = calls.where((c) => c.method == 'applyPatch').length; + preview.toggleMaskKeys(maskChannels['position']!); + await until(() => !preview.busy); + expect(calls.where((c) => c.method == 'applyPatch'), hasLength(patches)); + await until( + () => calls.any((c) => c.method == 'updateInteractiveTransform'), + ); + expect(preview.maskAnimation(id)!.keyed(maskChannels['position']!), isTrue); + }); + + test('multiple masks preserve identities, keys, order and history through save and playback', () async { + final f = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: f.timeline, + activeSequence: () => f.timeline.activeSequenceId, + viewForSequence: f.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + await preview.initialize(); + final id = ElementId('clip'); + final view = f.timeline.view(SequenceId('one')); + preview.setMaskEditing(id); + final emptyVersion = view.version; + expect(preview.maskAnimation(id), isNull); + expect(await preview.beginMaskEdit(), isFalse); + preview.applyMask(const ClipMask(shape: ClipMaskShape.ellipse)); + preview.updateMask(const ClipMask(x: .9)); + preview.endMaskEdit(); + preview.toggleMaskKeys(maskChannels['position']!); + expect(view.version, same(emptyVersion)); + expect(preview.maskStackFor(id)!.layers, isEmpty); + preview.addMask(ClipMaskShape.rectangle); + preview.applyMask(const ClipMask(shape: ClipMaskShape.rectangle, x: .25)); + preview.toggleMaskKeys(maskChannels['position']!); + final firstMaskId = preview.selectedMaskId!; + final original = preview + .maskStackFor(id)! + .record + .parameters!['mask.$firstMaskId.center.x']; + preview.addMask(ClipMaskShape.rectangle); + final second = preview.selectedMaskId!; + expect(second, isNot(firstMaskId)); + preview.applyMask(preview.maskFor(id)!.copyWith(x: .75)); + preview.toggleMaskKeys(maskChannels['position']!); + preview.configureMask(second, mode: ClipMaskMode.subtract); + preview.reorderMasks([second, firstMaskId]); + expect(preview.maskStackFor(id)!.layers.map((e) => e.id), [ + second, + firstMaskId, + ]); + expect( + preview + .maskStackFor(id)! + .record + .parameters!['mask.$firstMaskId.center.x'], + same(original), + ); + expect(preview.maskAnimation(id)!.keyed(maskChannels['position']!), isTrue); + expect(preview.maskFor(id)!.x, .75); + await until( + () => calls.any((c) => c.method == 'updateInteractiveTransform'), + ); + expect(calls.where((c) => c.method == 'applyPatch'), isEmpty); + preview.configureMask(second, enabled: false); + expect(preview.maskStackFor(id)!.layers.first.enabled, isFalse); + preview.removeMask(second); + expect(preview.maskStackFor(id)!.parametersFor(second), isEmpty); + expect(preview.maskStackFor(id)!.layers.single.id, firstMaskId); + view.undo(); + await until(() => !preview.busy); + expect(preview.maskStackFor(id)!.layers.first.id, second); + expect(preview.maskStackFor(id)!.layers.first.enabled, isFalse); + preview.selectMask(second); + expect(preview.maskAnimation(id)!.keyed(maskChannels['position']!), isTrue); + await f.timeline.flush(); + final saved = await f.workspace.project!.loadTimeline('project'); + final parameters = saved.sequences.first.elements.first.parameters; + expect( + parameters.any( + (p) => + p.definition.id == 'mask.$second.center.x' && + p.keyframes.isNotEmpty, + ), + isTrue, + ); + preview.removeMask(second); + preview.removeMask(firstMaskId); + expect(preview.maskStackFor(id)!.layers, isEmpty); + preview.setMaskEditing(null); + await until(() => !preview.busy && !preview.transforms.hasContext); + expect(preview.error, isNull); + }); + + test('obscuration timelines commit once, preserve masks and cancel stale gestures', () async { + final f = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: f.timeline, + activeSequence: () => f.timeline.activeSequenceId, + viewForSequence: f.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + final id = ElementId('clip'), sequence = SequenceId('one'); + final view = f.timeline.view(sequence); + f.timeline.publishParameters(sequence, id, [ + maskConstant('obscure.enabled', 1), + maskConstant('obscure.width', .3), + maskConstant('obscure.height', .4), + maskConstant('mask.test.enabled', 1), + maskConstant('mask.test.width', .8), + ]); + await preview.initialize(); + preview.setObscureEditing(id); + final base = view.version; + expect(await preview.beginObscureEdit(), isTrue); + preview.updateObscure(preview.obscureFor(id)!.copyWith(x: .7, width: .6)); + await until( + () => calls.where((c) => c.method == 'updateInteractiveTransform').any(( + call, + ) { + final transform = + ((call.arguments as Map)['transforms'] as List).single as Map; + return transform['obscure']?['obscure.center.x'] == .7 && + transform['mask']?['mask.test.width'] == .8; + }), + ); + expect(view.version, same(base)); + preview.endObscureEdit(); + expect(preview.obscureFor(id)!.width, .6); + view.undo(); + await until(() => !preview.busy); + expect(view.version.kernelVersion, same(base.kernelVersion)); + view.redo(); + await until(() => !preview.busy); + expect(preview.obscureFor(id)!.x, .7); + expect(await preview.beginObscureEdit(), isTrue); + preview.updateObscure(preview.obscureFor(id)!.copyWith(width: .9)); + preview.cancelObscureEdit(); + expect(preview.obscureFor(id)!.width, .6); + expect(await preview.beginObscureEdit(), isTrue); + preview.updateObscure(preview.obscureFor(id)!.copyWith(x: .1)); + view.seekTo(1000000); + preview.endObscureEdit(); + await until(() => !preview.busy); + expect(preview.obscureFor(id)!.x, .7); + await f.timeline.flush(); + final saved = await f.workspace.project!.loadTimeline('project'); + expect( + saved.sequences.first.elements.first.parameters + .firstWhere((p) => p.definition.id == 'obscure.width') + .keyframes + .single + .value, + .6, + ); + expect(preview.error, isNull); + }); + + test('mask edits render privately, commit once, persist and undo', () async { + final f = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: f.timeline, + activeSequence: () => f.timeline.activeSequenceId, + viewForSequence: f.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + await preview.initialize(); + final id = ElementId('clip'); + final view = f.timeline.view(SequenceId('one')); + preview.setMaskEditing(id); + preview.addMask(ClipMaskShape.ellipse); + await until(() => !preview.busy); + final patches = calls.where((c) => c.method == 'applyPatch').length; + final base = view.version; + expect(await preview.beginMaskEdit(), isTrue); + preview.updateMask(preview.maskFor(id)!.copyWith(x: .7, feather: .1)); + await until( + () => calls.where((c) => c.method == 'updateInteractiveTransform').any(( + call, + ) { + final transforms = (call.arguments as Map)['transforms'] as List; + return transforms.any( + (t) => + (t as Map)['mask']['mask.${preview.selectedMaskId}.center.x'] == + .7, + ); + }), + ); + expect(preview.ready, isTrue); + expect(view.version, same(base)); + expect(calls.where((c) => c.method == 'applyPatch'), hasLength(patches)); + preview.endMaskEdit(); + await until(() => !preview.busy); + expect(calls.where((c) => c.method == 'applyPatch'), hasLength(patches)); + expect(preview.maskFor(id)!.x, .7); + await f.timeline.flush(); + final saved = await f.workspace.project!.loadTimeline('project'); + expect( + saved.sequences.first.elements.first.parameters.any( + (p) => p.definition.id == 'mask.${preview.selectedMaskId}.center.x', + ), + isTrue, + ); + view.undo(); + await until(() => !preview.busy); + expect(preview.maskFor(id)!.x, .5); + expect(await preview.beginMaskEdit(), isTrue); + preview.updateMask(preview.maskFor(id)!.copyWith(width: .8)); + preview.cancelTransform(); + expect(preview.maskFor(id)!.width, .5); + expect(preview.error, isNull); + }); + + test( + 'mask clicks share a frozen frame and retain it through playback handoff', + () async { + final f = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: f.timeline, + activeSequence: () => f.timeline.activeSequenceId, + viewForSequence: f.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + await preview.initialize(); + final id = ElementId('clip'); + preview.setMaskEditing(id); + blockedTransform = Completer(); + final patches = calls.where((c) => c.method == 'applyPatch').length; + preview.addMask(ClipMaskShape.rectangle); + preview.applyMask(const ClipMask(shape: ClipMaskShape.ellipse)); + preview.applyMask( + const ClipMask(shape: ClipMaskShape.ellipse, inverted: true), + ); + expect(preview.ready, isTrue); + expect(preview.busy, isFalse); + expect(calls.where((c) => c.method == 'applyPatch'), hasLength(patches)); + await until( + () => calls.any((c) => c.method == 'beginInteractiveTransform'), + ); + blockedTransform!.complete(); + await until( + () => calls.any((c) => c.method == 'updateInteractiveTransform'), + ); + Map mask() => + ((calls + .lastWhere( + (c) => c.method == 'updateInteractiveTransform', + ) + .arguments + as Map)['transforms'] + as List) + .single['mask'] + as Map; + expect(mask()['mask.${preview.selectedMaskId}.shape'], 2); + expect(mask()['mask.${preview.selectedMaskId}.inverted'], 1); + preview.applyMask(const ClipMask()); + await until( + () => + mask()['mask.${preview.selectedMaskId}.shape'] == 1 && + mask()['mask.${preview.selectedMaskId}.inverted'] == 0, + ); + expect( + calls.where((c) => c.method == 'beginInteractiveTransform'), + hasLength(1), + ); + expect( + calls.where((c) => c.method == 'endInteractiveTransform'), + isEmpty, + ); + expect(calls.where((c) => c.method == 'applyPatch'), hasLength(patches)); + await f.timeline.flush(); + final saved = await f.workspace.project!.loadTimeline('project'); + expect( + saved.sequences.first.elements.first.parameters + .singleWhere( + (p) => p.definition.id == 'mask.${preview.selectedMaskId}.shape', + ) + .definition + .defaultValue, + 1, + ); + blockedPatch = Completer(); + preview.setMaskEditing(null); + await until( + () => + calls.where((c) => c.method == 'applyPatch').length == patches + 1, + ); + expect( + calls.where((c) => c.method == 'endInteractiveTransform'), + isEmpty, + ); + blockedPatch!.complete(); + await until( + () => calls.any((c) => c.method == 'endInteractiveTransform'), + ); + final view = f.timeline.view(SequenceId('one')); + for (final expected in [(2, true), (2, false), (1, false)]) { + view.undo(); + await until(() => !preview.busy); + expect(preview.maskFor(id)!.shape.code, expected.$1); + expect(preview.maskFor(id)!.inverted, expected.$2); + } + view.undo(); + await until(() => !preview.busy); + expect(preview.maskFor(id), isNull); + expect(view.canUndo, isFalse); + }, + ); + + test('keyframe dragging previews video parameters without publishing and restores on cancel', () async { + const second = TimelineClock.ticksPerSecond; + final f = await createPreviewFixture( + Uri.file('/test/video.mov'), + clipDuration: RationalTime.seconds(5), + ); + final preview = PreviewController( + timeline: f.timeline, + activeSequence: () => f.timeline.activeSequenceId, + viewForSequence: f.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + await preview.initialize(); + final sequence = SequenceId('one'); + final clip = ElementId('clip'); + final view = f.timeline.view(sequence); + f.timeline.commitParameters( + sequence, + f.timeline.previewParameters(sequence, clip, [ + ParameterCurveDto( + definition: TimelineParameterDefinition( + id: 'canvas.rotation', + defaultValue: 0, + minimum: -360, + maximum: 360, + ), + keyframes: [ + const ParameterKeyframeDto(sourceTime: RationalTime.zero, value: 0), + ParameterKeyframeDto( + sourceTime: RationalTime.seconds(2), + value: 90, + ), + ], + ), + ]), + parameterTargets: ClipTransform.targets, + ); + await until(() => !preview.busy); + final base = view.version; + final viewport = TimelineViewportRect(width: 600, height: 200); + view.setCamera(TimelineCamera(baseTick: 0, pixelsPerTick: 60 / second)); + final centerY = view.geometry.primaryTop + view.geometry.primaryHeight / 2; + final patchCount = calls.where((c) => c.method == 'applyPatch').length; + final loadCount = calls.where((c) => c.method == 'load').length; + expect( + view.beginDrag( + viewport: viewport, + position: Offset(120, centerY), + keyframes: true, + ), + isTrue, + ); + view.updateDrag(viewport: viewport, position: Offset(180, centerY)); + expect( + preview.ready, + isTrue, + reason: 'keyframe movement must retain the ready frame', + ); + await until( + () => calls.any((c) => c.method == 'updateInteractiveTransform'), + ); + expect(view.version, same(base)); + expect(view.playheadTick, 2 * second); + expect( + preview.visualForProperties(clip)!.transform.rotation, + closeTo(60, 1e-6), + ); + expect(calls.where((c) => c.method == 'applyPatch'), hasLength(patchCount)); + expect(calls.where((c) => c.method == 'load'), hasLength(loadCount)); + expect( + calls.where((c) => c.method == 'beginInteractiveTransform'), + hasLength(1), + ); + await until( + () => preview.transforms.displayedValueFor(clip)?.rotation == 60, + ); + blockedRender = Completer(); + final renders = calls + .where((c) => c.method == 'updateInteractiveTransform') + .length; + view.updateDrag(viewport: viewport, position: Offset(210, centerY)); + await until( + () => + calls.where((c) => c.method == 'updateInteractiveTransform').length == + renders + 1, + ); + view.updateDrag(viewport: viewport, position: Offset(240, centerY)); + view.updateDrag(viewport: viewport, position: Offset(270, centerY)); + expect(preview.ready, isTrue); + expect( + calls.where((c) => c.method == 'updateInteractiveTransform'), + hasLength(renders + 1), + ); + blockedRender!.complete(); + await until( + () => preview.transforms.displayedValueFor(clip)?.rotation == 40, + ); + expect( + calls.where((c) => c.method == 'updateInteractiveTransform'), + hasLength(renders + 2), + ); + expect(calls.where((c) => c.method == 'applyPatch'), hasLength(patchCount)); + view.cancelDrag(); + await until(() => !preview.busy); + view.seekTo(second); + expect( + preview.visualForProperties(clip)!.transform.rotation, + closeTo(45, 1e-6), + ); + expect(view.version, same(base)); + + expect( + view.beginDrag( + viewport: viewport, + position: Offset(120, centerY), + keyframes: true, + ), + isTrue, + ); + view.updateDrag(viewport: viewport, position: Offset(180, centerY)); + expect(preview.ready, isTrue); + view.finishDrag(viewport: viewport, position: Offset(180, centerY)); + await until(() => !preview.busy); + expect( + calls.where((c) => c.method == 'applyPatch'), + hasLength(patchCount + 1), + ); + expect( + preview.visualForProperties(clip)!.transform.rotation, + closeTo(60, 1e-6), + ); + + await preview.transforms.settled; + final begins = calls + .where((c) => c.method == 'beginInteractiveTransform') + .length; + blockedSeek = Completer(); + expect( + view.beginDrag( + viewport: viewport, + position: Offset(180, centerY), + keyframes: true, + ), + isTrue, + ); + view.updateDrag(viewport: viewport, position: Offset(240, centerY)); + view.cancelDrag(); + blockedSeek!.complete(); + await Future.delayed(const Duration(milliseconds: 150)); + expect( + calls.where((c) => c.method == 'beginInteractiveTransform'), + hasLength(begins), + ); + expect(preview.transforms.valueFor(clip), isNull); + expect(preview.error, isNull); + }); + + test( + 'animated properties compile and canvas edits retain keys at other times', + () async { + final f = await createPreviewFixture( + Uri.file('/test/video.mov'), + clipDuration: RationalTime.seconds(4), + ); + final preview = PreviewController( + timeline: f.timeline, + activeSequence: () => f.timeline.activeSequenceId, + viewForSequence: f.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + await preview.initialize(); + final sequence = SequenceId('one'); + final clip = ElementId('clip'); + final view = f.timeline.view(sequence); + ClipAnimation at(int tick) { + final q = view.version.kernelVersion.query(); + return ClipAnimation.at( + q, + q.elementById(clip)!, + tick, + TimelineClock.ticksPerSecond ~/ 30, + ); + } + + void commit(List curves) => + f.timeline.commitParameters( + sequence, + f.timeline.previewParameters(sequence, clip, curves), + parameterTargets: ClipTransform.targets, + ); + commit([ + for (final channel in TransformChannel.values) ...at(0).toggle(channel), + ]); + await until(() => !preview.busy); + commit( + at(2 * TimelineClock.ticksPerSecond).edit( + const ClipTransform(x: .4, y: .2, scale: 2, scaleY: 3, rotation: 90), + ), + ); + await until(() => !preview.busy); + view.seekTo(TimelineClock.ticksPerSecond); + final visual = preview.visualForProperties(clip)!; + expect(visual.transform.x, closeTo(.2, 1e-9)); + expect(visual.transform.y, closeTo(.1, 1e-9)); + expect(visual.transform.scale, closeTo(1.5, 1e-9)); + expect(visual.transform.scaleY, closeTo(2, 1e-9)); + expect(visual.transform.rotation, closeTo(45, 1e-9)); + final before = view.version.kernelVersion; + final edit = preview.transforms.begin(visual)!; + expect(await edit.prepared, isTrue); + edit.update(edit.value.copyWith(scaleY: 2.5)); + await edit.end(); + expect( + at(TimelineClock.ticksPerSecond).keyed(TransformChannel.scale), + isTrue, + ); + expect(at(0).value.scaleY, 1); + expect(at(2 * TimelineClock.ticksPerSecond).value.scaleY, 3); + expect(at(0).keyTimes(TransformChannel.position).length, 2); + final update = + calls + .lastWhere((c) => c.method == 'updateInteractiveTransform') + .arguments + as Map; + expect( + ((update['transforms'] as List).single as Map)['scaleY'], + closeTo(1.25, 1e-9), + ); + preview.cancelTransform(); + await until(() => !preview.busy); + expect( + preview.visualForProperties(clip)!.transform.scaleY, + closeTo(2.5, 1e-9), + ); + view.undo(); + expect(view.version.kernelVersion, same(before)); + await until(() => !preview.busy); + expect( + preview.visualForProperties(clip)!.transform.scaleY, + closeTo(2, 1e-9), + ); + view.seekTo(preview.durationTick); + final lastFrame = preview.transforms.begin(preview.visuals.single)!; + expect(await lastFrame.prepared, isTrue); + lastFrame.update(lastFrame.value.copyWith(scaleY: 3.5)); + await lastFrame.end(); + expect(preview.error, isNull); + expect(at(2 * TimelineClock.ticksPerSecond).value.scaleY, 3); + expect( + at(preview.durationTick - TimelineClock.ticksPerSecond ~/ 30) + .value + .scaleY, + 3.5, + ); + }, + ); + + test( + 'Flutter selection retains all selected occurrences across a cut', + () async { + final duration = RationalTime.seconds(2); + final f = await createPreviewFixture( + Uri.file('/test/video.mov'), + timelineOverride: TimelineDto( + id: SequenceId('one'), + name: 'one', + format: TimelineFormat.fps30, + primaryStorylineId: StorylineId('primary'), + storylines: [ + StorylineDto( + id: StorylineId('primary'), + elementIds: [ElementId('a'), ElementId('b')], + ), + ], + elements: [ + for (final id in ['a', 'b']) + ElementDto( + id: ElementId(id), + structure: ElementStructure.content, + payloadRef: PayloadRef('source'), + duration: duration, + sourceRange: TimeRange( + start: RationalTime.zero, + duration: duration, + ), + mediaRange: TimeRange( + start: RationalTime.zero, + duration: duration, + ), + ), + ], + ), + ); + final preview = PreviewController( + timeline: f.timeline, + activeSequence: () => f.timeline.activeSequenceId, + viewForSequence: f.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + await preview.initialize(); + final view = f.timeline.view(SequenceId('one')); + final q = view.version.kernelVersion.query(); + view.setSelection([ + q.elementById(ElementId('a'))!, + q.elementById(ElementId('b'))!, + ]); + await Future.delayed(const Duration(milliseconds: 20)); + expect(preview.selectedVisualIds, {ElementId('a'), ElementId('b')}); + expect( + calls.where((c) => c.method == 'beginInteractiveTransform'), + isEmpty, + ); + }, + ); + + test('Flutter selection never freezes playback or a pending seek', () async { + final f = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: f.timeline, + activeSequence: () => f.timeline.activeSequenceId, + viewForSequence: f.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + blockedRender?.complete(); + blockedSeek?.complete(); + await preview.close(); + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + await preview.initialize(); + preview.selectVisual(ElementId('clip')); + await Future.delayed(const Duration(milliseconds: 20)); + expect( + calls.where((c) => c.method == 'updateInteractiveTransform'), + isEmpty, + ); + + final playback = preview.togglePlayback(); + await playback; + // Windows acknowledges play before the event-channel snapshot arrives. + // A rebuild in that gap must not acquire another paused-frame token. + calls.clear(); + await Future.delayed(const Duration(milliseconds: 20)); + expect(preview.playing, isTrue); + expect( + calls.where((c) => c.method == 'beginInteractiveTransform'), + isEmpty, + ); + emit({ + 'state': 'playing', + 'revision': revision, + 'position': MediaTime(1, 2).toMap(), + 'rate': 1.0, + }); + await until(() => preview.playing); + calls.clear(); + await Future.delayed(const Duration(milliseconds: 20)); + expect( + calls.where( + (c) => c.method == 'beginInteractiveTransform' || c.method == 'pause', + ), + isEmpty, + ); + expect(preview.selectedVisualIds, {ElementId('clip')}); + expect(preview.visuals, isNotEmpty); + + await preview.pauseForCanvasInteraction(); + blockedSeek = Completer(); + f.timeline.view(SequenceId('one')).seekTo(TimelineClock.ticksPerSecond); + await until(() => calls.any((c) => c.method == 'seek')); + calls.clear(); + await Future.delayed(const Duration(milliseconds: 120)); + expect( + calls.where((c) => c.method == 'beginInteractiveTransform'), + isEmpty, + ); + blockedSeek!.complete(); + blockedSeek = null; + await until(() => !preview.busy); + expect(preview.selectedVisualIds, {ElementId('clip')}); + expect(preview.error, isNull); + preview.selectVisual(null); + await Future.delayed(const Duration(milliseconds: 20)); + }); + + test( + 'Flutter selection opens a native frame only for an actual edit', + () async { + final f = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: f.timeline, + activeSequence: () => f.timeline.activeSequenceId, + viewForSequence: f.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + await preview.initialize(); + final view = f.timeline.view(SequenceId('one')); + preview.selectVisual(ElementId('clip')); + final version = view.version.kernelVersion; + await Future.delayed(const Duration(milliseconds: 20)); + expect(view.version.kernelVersion, same(version)); + expect(preview.transforms.hasPending, isFalse); + expect( + calls.where((c) => c.method == 'beginInteractiveTransform'), + isEmpty, + ); + final edit = preview.transforms.begin(preview.visuals.single)!; + expect(await edit.prepared, isTrue); + edit.update(const ClipTransform(x: .1)); + await edit.end(); + await until( + () => calls.any((c) => c.method == 'updateInteractiveTransform'), + ); + final last = + calls + .lastWhere((c) => c.method == 'updateInteractiveTransform') + .arguments + as Map; + expect((last['transforms'] as List).single['x'], .1); + expect(last['overlay'], isNull); + preview.selectVisual(null); + expect( + calls.where((c) => c.method == 'beginInteractiveTransform'), + hasLength(1), + ); + }, + ); + + test('cut refreshes Flutter geometry without freezing the frame', () async { + final f = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: f.timeline, + activeSequence: () => f.timeline.activeSequenceId, + viewForSequence: f.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + await preview.initialize(); + final view = f.timeline.view(SequenceId('one')); + preview.selectVisual(ElementId('clip')); + view.seekTo(TimelineClock.ticksPerSecond); + await until(() => calls.any((c) => c.method == 'seek')); + final oldLayer = preview.visuals.single.layerId; + expect(view.cutSelectionAtPlayhead(), isTrue); + await until( + () => + !preview.busy && + preview.visuals.isNotEmpty && + preview.visuals.single.layerId != oldLayer, + ); + expect( + calls.where((c) => c.method == 'beginInteractiveTransform'), + isEmpty, + ); + expect( + calls.where((c) => c.method == 'updateInteractiveTransform'), + isEmpty, + ); + expect(preview.error, isNull); + }); + + test('cut requires no frame preparation even when native transforms would cancel', () async { + final f = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: f.timeline, + activeSequence: () => f.timeline.activeSequenceId, + viewForSequence: f.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + await preview.initialize(); + final view = f.timeline.view(SequenceId('one')); + preview.selectVisual(ElementId('clip')); + view.seekTo(TimelineClock.ticksPerSecond); + await until(() => calls.any((c) => c.method == 'seek')); + await Future.delayed(const Duration(milliseconds: 20)); + cancelledTransforms = 1; + expect(view.cutSelectionAtPlayhead(), isTrue); + await until(() => !preview.busy); + expect( + calls.where((c) => c.method == 'beginInteractiveTransform'), + isEmpty, + ); + expect(preview.error, isNull); + }); + + test( + 'playhead scrubbing never acquires a frozen canvas between skim replies', + () async { + final f = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: f.timeline, + activeSequence: () => f.timeline.activeSequenceId, + viewForSequence: f.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + await preview.initialize(); + final view = f.timeline.view(SequenceId('one')); + preview.selectVisual(ElementId('clip')); + calls.clear(); + cancelledTransforms = 3; + view.beginScrubbing(); + for (final tick in [100, 200, 300]) { + view.seekTo(tick); + await Future.delayed(const Duration(milliseconds: 30)); + expect(preview.error, isNull); + expect( + calls.where((c) => c.method == 'beginInteractiveTransform'), + isEmpty, + ); + } + expect(calls.where((c) => c.method == 'skim'), isNotEmpty); + expect(calls.where((c) => c.method == 'beginSkimming'), hasLength(1)); + cancelledTransforms = 0; + view.endScrubbing(); + await until(() => calls.any((c) => c.method == 'endSkimming')); + expect( + calls.where((c) => c.method == 'beginInteractiveTransform'), + isEmpty, + ); + expect(preview.ready, isTrue); + expect(preview.error, isNull); + expect(view.canUndo, isFalse); + }, + ); + + test('reselection requires no native overlay render', () async { + final f = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: f.timeline, + activeSequence: () => f.timeline.activeSequenceId, + viewForSequence: f.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + await preview.initialize(); + final view = f.timeline.view(SequenceId('one')); + preview.selectVisual(ElementId('clip')); + cancelledRenders = 1; + preview.selectVisual(null); + preview.selectVisual(ElementId('clip')); + await Future.delayed(const Duration(milliseconds: 20)); + expect( + calls.where((c) => c.method == 'beginInteractiveTransform'), + isEmpty, + ); + expect( + calls.where((c) => c.method == 'updateInteractiveTransform'), + isEmpty, + ); + expect(view.canUndo, isFalse); + expect(preview.error, isNull); + }); + + test( + 'independent property scale survives native handoff, next drag and undo', + () async { + final f = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: f.timeline, + activeSequence: () => f.timeline.activeSequenceId, + viewForSequence: f.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + await preview.initialize(); + final sequence = SequenceId('one'); + final id = ElementId('clip'); + final view = f.timeline.view(sequence); + final first = preview.transforms.begin(preview.visuals.single)!; + expect(await first.prepared, isTrue); + first.update(const ClipTransform(x: .1)); + await first.end(); + final edit = f.timeline.previewParameters( + sequence, + id, + const ClipTransform( + x: .1, + scale: 2, + scaleY: .5, + rotation: 37, + ).parameters, + ); + f.timeline.commitParameters( + sequence, + edit, + parameterTargets: ClipTransform.targets, + ); + await until(() => !preview.busy && !preview.transforming); + final visual = preview.visuals.single; + expect(visual.geometry.size, const Size(2160, 960)); + expect(visual.transform.scaleY, .5); + final drag = preview.transforms.begin(visual)!; + expect(await drag.prepared, isTrue); + drag.update(visual.transform.copyWith(scaleY: .25)); + await until( + () => calls.any((call) { + if (call.method != 'updateInteractiveTransform') return false; + final transform = + ((call.arguments as Map)['transforms'] as List).single as Map; + return transform['scale'] == 1.0 && transform['scaleY'] == .5; + }), + ); + final points = visual.geometry.selectionCorners; + drag.update( + scaleFromCorner( + visual, + 0, + points[2] + (points[0] - points[2]) * 1.5, + Size(preview.canvas.width, preview.canvas.height), + ), + ); + await drag.end(); + expect(preview.visuals.single.transform.scaleY, closeTo(.75, 1e-9)); + expect(preview.visuals.single.transform.scale, closeTo(3, 1e-9)); + preview.cancelTransform(); + await until(() => !preview.busy); + view.undo(); + await until(() => !preview.busy); + expect(preview.visuals.single.transform.scaleY, .5); + expect(preview.visuals.single.geometry.size, const Size(2160, 960)); + view.seekTo(5 * TimelineClock.ticksPerSecond); + expect(preview.visualForProperties(id)?.transform.scaleY, .5); + }, + ); + + test('canvas press pauses immediately and drag shares the pending acknowledgement', () async { + final f = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: f.timeline, + activeSequence: () => f.timeline.activeSequenceId, + viewForSequence: f.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + await preview.initialize(); + // Opening a sequence restores its playhead independently of canvas interaction. + await until(() => calls.any((c) => c.method == 'seek')); + calls.clear(); + await preview.pauseForCanvasInteraction(); + expect(calls, isEmpty); + emit({ + 'state': 'playing', + 'revision': revision, + 'position': MediaTime(0, 1).toMap(), + 'rate': 1.0, + }); + await until(() => preview.playing); + blockedPause = Completer(); + final paused = preview.pauseForCanvasInteraction(); + expect(preview.playing, isFalse); + expect(preview.pauseForCanvasInteraction(), same(paused)); + await until(() => calls.any((c) => c.method == 'pause')); + final started = preview.transforms.begin(preview.visuals.single)!.prepared; + emit({ + 'state': 'playing', + 'revision': revision, + 'position': MediaTime(0, 1).toMap(), + 'rate': 1.0, + }); + await Future.delayed(const Duration(milliseconds: 20)); + expect(preview.playing, isFalse); + expect( + calls.where((c) => c.method == 'beginInteractiveTransform'), + isEmpty, + ); + blockedPause!.complete(); + await paused; + expect(await started, isTrue); + expect( + (calls + .singleWhere((c) => c.method == 'beginInteractiveTransform') + .arguments + as Map) + .containsKey('time'), + isFalse, + ); // Pausing may advance beyond the last observed editor position. + expect(calls.where((c) => c.method == 'pause').length, 1); + expect( + calls.where( + (c) => ['seek', 'load', 'applyPatch', 'play'].contains(c.method), + ), + isEmpty, + ); + preview.cancelTransform(); + expect(f.timeline.dirty, isFalse); + await preview.pauseForCanvasInteraction(); + expect(calls.where((c) => c.method == 'pause').length, 1); + }); + + test( + 'canvas gesture does not compile or patch until its single commit', + () async { + final f = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: f.timeline, + activeSequence: () => f.timeline.activeSequenceId, + viewForSequence: f.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + await preview.initialize(); + await until(() => !preview.busy); + final view = f.timeline.view(SequenceId('one')); + final base = view.version.kernelVersion; + expect( + preview.visuals.single.geometry.size.aspectRatio, + closeTo(1080 / 1920, 1e-9), + ); + preview.selectVisual(ElementId('clip')); + expect(preview.selectedVisualIds, {ElementId('clip')}); + final gesture = preview.transforms.begin(preview.visuals.single)!; + expect(await gesture.prepared, isTrue); + calls.clear(); + for (var i = 1; i <= 100; i++) { + gesture.update( + ClipTransform(x: i / 250, y: .2, scale: .6, rotation: 35), + ); + expect(view.version.kernelVersion, same(base)); + expect(f.timeline.dirty, isFalse); + expect(preview.busy, isFalse); + } + await Future.delayed(Duration.zero); + expect( + calls.where( + (c) => ['load', 'applyPatch', 'seek', 'probe'].contains(c.method), + ), + isEmpty, + ); + await gesture.end(); + expect(calls.where((c) => c.method == 'applyPatch'), isEmpty); + expect( + calls.where((c) => c.method == 'endInteractiveTransform'), + isEmpty, + ); + preview.cancelTransform(); + await until( + () => + !preview.busy && + calls.any((c) => c.method == 'endInteractiveTransform'), + ); + expect(calls.where((c) => c.method == 'applyPatch').length, 1); + expect(calls.last.method, 'endInteractiveTransform'); + expect(preview.error, isNull); + expect(preview.visuals.single.transform.x, .4); + expect(preview.visuals.single.transform.y, .2); + expect(preview.visuals.single.transform.rotation, 35); + view.undo(); + await until(() => !preview.busy); + expect(view.version.kernelVersion, same(base)); + expect(preview.visuals.single.transform.scale, 1); + view.redo(); + await until(() => !preview.busy); + expect(preview.visuals.single.transform.scale, .6); + await f.timeline.flush(); + final saved = await f.workspace.loadTimeline( + f.workspace.project!.info.id, + 'project', + ); + final clip = saved.sequences.first.elements.single; + expect( + clip.parameters + .singleWhere((p) => p.definition.id == 'canvas.rotation') + .definition + .defaultValue, + 35, + ); + expect( + (saved.settings['parameterTargets'] as Map)['canvas.rotation'], + 'rotation', + ); + }, + ); + + test('repeated releases keep one native frame and skip obsolete renders while preserving history', () async { + final f = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: f.timeline, + activeSequence: () => f.timeline.activeSequenceId, + viewForSequence: f.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + if (blockedRender != null && !blockedRender!.isCompleted) { + blockedRender!.complete(); + } + await preview.close(); + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + await preview.initialize(); + final first = preview.transforms.begin(preview.visuals.single)!; + expect(await first.prepared, isTrue); + calls.clear(); + blockedRender = Completer(); + first.update(const ClipTransform(x: .1)); + await until( + () => calls.any((c) => c.method == 'updateInteractiveTransform'), + ); + await first.end(); + for (final x in [.2, .3]) { + final edit = preview.transforms.begin(preview.visuals.single)!; + expect(await edit.prepared, isTrue); + edit.update(ClipTransform(x: x)); + await edit.end(); + } + expect(preview.visuals.single.transform.x, .3); + expect(preview.busy, isFalse); + await f.timeline.flush(); + final saved = await f.workspace.project!.loadTimeline('project'); + expect( + saved.sequences.first.elements.single.parameters + .singleWhere((p) => p.definition.id == 'canvas.position.x') + .definition + .defaultValue, + .3, + ); + expect( + calls.where( + (c) => [ + 'beginInteractiveTransform', + 'endInteractiveTransform', + 'applyPatch', + 'load', + ].contains(c.method), + ), + isEmpty, + ); + blockedRender!.complete(); + await until( + () => + calls.where((c) => c.method == 'updateInteractiveTransform').length == + 2, + ); + final rendered = calls + .where((c) => c.method == 'updateInteractiveTransform') + .map((c) => ((c.arguments as Map)['transforms'] as List).single['x']) + .toList(); + expect(rendered, [.1, .3]); + final view = f.timeline.view(SequenceId('one')); + for (final x in [.2, .1, 0]) { + view.undo(); + await until(() => !preview.busy); + expect(preview.visuals.single.transform.x, x); + } + }); + + test('releases before preparation finishes commit history but only render the latest state', () async { + final f = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: f.timeline, + activeSequence: () => f.timeline.activeSequenceId, + viewForSequence: f.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + if (blockedTransform != null && !blockedTransform!.isCompleted) { + blockedTransform!.complete(); + } + await preview.close(); + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + await preview.initialize(); + blockedTransform = Completer(); + for (final x in [.1, .2, .3]) { + final edit = preview.transforms.begin(preview.visuals.single)!; + edit.update(ClipTransform(x: x)); + await edit.end(); + } + await until( + () => calls.any((c) => c.method == 'beginInteractiveTransform'), + ); + expect(calls.where((c) => c.method == 'applyPatch'), isEmpty); + expect(preview.visuals.single.transform.x, .3); + blockedTransform!.complete(); + await until( + () => calls.any((c) => c.method == 'updateInteractiveTransform'), + ); + final updates = calls.where( + (c) => c.method == 'updateInteractiveTransform', + ); + expect(updates.length, 1); + expect( + ((updates.single.arguments as Map)['transforms'] as List).single['x'], + .3, + ); + }); + + test('cancelling the next drag restores the last commit without rebuilding its frame', () async { + final f = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: f.timeline, + activeSequence: () => f.timeline.activeSequenceId, + viewForSequence: f.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + await preview.initialize(); + final first = preview.transforms.begin(preview.visuals.single)!; + await first.prepared; + first.update(const ClipTransform(x: .12)); + await first.end(); + calls.clear(); + final second = preview.transforms.begin(preview.visuals.single)!; + second.update(const ClipTransform(x: .18)); + second.cancel(); + await Future.delayed(Duration.zero); + expect(preview.visuals.single.transform.x, .12); + expect( + calls.where( + (c) => [ + 'beginInteractiveTransform', + 'endInteractiveTransform', + 'applyPatch', + ].contains(c.method), + ), + isEmpty, + ); + final updates = calls.where( + (c) => c.method == 'updateInteractiveTransform', + ); + expect( + ((updates.last.arguments as Map)['transforms'] as List).single['x'], + .12, + ); + }); + + test('play synchronizes committed edits once before releasing the frame and resuming', () async { + final f = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: f.timeline, + activeSequence: () => f.timeline.activeSequenceId, + viewForSequence: f.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + await preview.initialize(); + final edit = preview.transforms.begin(preview.visuals.single)!; + await edit.prepared; + edit.update(const ClipTransform(x: .12)); + await edit.end(); + calls.clear(); + await preview.togglePlayback(); + final methods = calls.map((c) => c.method).toList(); + expect(methods.where((m) => m == 'applyPatch').length, 1); + expect( + methods.indexOf('applyPatch'), + lessThan(methods.indexOf('endInteractiveTransform')), + ); + expect( + methods.indexOf('endInteractiveTransform'), + lessThan(methods.indexOf('play')), + ); + expect(preview.visuals.single.transform.x, .12); + }); + + test( + 'failed playback handoff preserves authored history for retry', + () async { + final f = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: f.timeline, + activeSequence: () => f.timeline.activeSequenceId, + viewForSequence: f.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + await preview.initialize(); + final edit = preview.transforms.begin(preview.visuals.single)!; + await edit.prepared; + edit.update(const ClipTransform(x: .12)); + await edit.end(); + loadError = PlatformException(code: 'testFailure'); + preview.cancelTransform(); + await until(() => !preview.busy); + expect(preview.error, isNotNull); + loadError = null; + await preview.retry(); + expect(preview.visuals.single.transform.x, .12); + }, + ); + + for (final change in ['seek', 'sequence', 'canvas', 'undo']) { + test( + 'a $change invalidates the active pointer and synchronizes committed history', + () async { + final f = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: f.timeline, + activeSequence: () => f.timeline.activeSequenceId, + viewForSequence: f.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + await preview.initialize(); + final first = preview.transforms.begin(preview.visuals.single)!; + await first.prepared; + first.update(const ClipTransform(x: .12)); + await first.end(); + final second = preview.transforms.begin(preview.visuals.single)!; + second.update(const ClipTransform(x: .18)); + switch (change) { + case 'seek': + f.timeline + .view(SequenceId('one')) + .seekTo(TimelineClock.ticksPerSecond); + case 'sequence': + f.timeline.selectSequence(SequenceId('empty')); + case 'canvas': + preview.setCanvas(ProjectCanvasPresets.values['4:3']!); + case 'undo': + f.timeline.view(SequenceId('one')).undo(); + } + expect(second.cancelled, isTrue); + await second.done; + await until(() => !preview.busy); + expect(preview.transforms.hasContext, isFalse); + if (change != 'sequence') { + expect( + preview.visuals.single.transform.x, + change == 'undo' ? 0 : .12, + ); + } + }, + ); + } + + test( + 'starting a canvas drag cancels the delayed timeline refinement seek', + () async { + final f = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: f.timeline, + activeSequence: () => f.timeline.activeSequenceId, + viewForSequence: f.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + await preview.initialize(); + await until(() => calls.any((c) => c.method == 'seek')); + calls.clear(); + f.timeline.view(SequenceId('one')).seekTo(TimelineClock.ticksPerSecond); + expect( + await preview.transforms.begin(preview.visuals.single)!.prepared, + isTrue, + ); + expect(calls.where((c) => c.method == 'seek').length, 1); + calls.clear(); + await Future.delayed(const Duration(milliseconds: 150)); + expect(calls.where((c) => c.method == 'seek'), isEmpty); + expect(preview.transforming, isTrue); + preview.cancelTransform(); + }, + ); + + test( + 'cancelling while source frames prepare rejects the late gesture', + () async { + final f = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: f.timeline, + activeSequence: () => f.timeline.activeSequenceId, + viewForSequence: f.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + await preview.initialize(); + blockedTransform = Completer(); + final beginning = preview.transforms + .begin(preview.visuals.single)! + .prepared; + await until( + () => calls.any((c) => c.method == 'beginInteractiveTransform'), + ); + preview.cancelTransform(); + blockedTransform!.complete(); + expect(await beginning, isFalse); + await until( + () => calls.any((c) => c.method == 'endInteractiveTransform'), + ); + expect(f.timeline.dirty, isFalse); + expect(preview.transforming, isFalse); + expect( + await preview.transforms.begin(preview.visuals.single)!.prepared, + isTrue, + ); + preview.cancelTransform(); + }, + ); + + test( + 'canvas pause supersedes a resume still waiting for a timeline seek', + () async { + final f = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: f.timeline, + activeSequence: () => f.timeline.activeSequenceId, + viewForSequence: f.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + await preview.initialize(); + await until(() => calls.any((c) => c.method == 'seek')); + calls.clear(); + blockedSeek = Completer(); + f.timeline.view(SequenceId('one')).seekTo(TimelineClock.ticksPerSecond); + await until(() => calls.any((c) => c.method == 'seek')); + final resume = preview.togglePlayback(); + await preview.pauseForCanvasInteraction(); + blockedSeek!.complete(); + await resume; + expect(calls.where((c) => c.method == 'play'), isEmpty); + expect(preview.playing, isFalse); + }, + ); + + test( + 'canvas press pauses a play command before its acknowledgement arrives', + () async { + final f = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: f.timeline, + activeSequence: () => f.timeline.activeSequenceId, + viewForSequence: f.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + await preview.initialize(); + await until(() => calls.any((c) => c.method == 'seek')); + calls.clear(); + blockedPlay = Completer(); + final resume = preview.togglePlayback(); + await until(() => calls.any((c) => c.method == 'play')); + await preview.pauseForCanvasInteraction(); + blockedPlay!.complete(); + await resume; + expect(calls.where((c) => c.method == 'pause').length, 1); + }, + ); + + test( + 'cancelled canvas gesture and sequence switch never publish a transform', + () async { + final f = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: f.timeline, + activeSequence: () => f.timeline.activeSequenceId, + viewForSequence: f.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + await preview.initialize(); + await until(() => !preview.busy); + final view = f.timeline.view(SequenceId('one')); + final base = view.version.kernelVersion; + final first = preview.transforms.begin(preview.visuals.single)!; + expect(await first.prepared, isTrue); + first.update(const ClipTransform(x: .2)); + preview.cancelTransform(); + await until(() => !preview.busy); + expect(preview.visuals.single.transform.x, 0); + expect(view.version.kernelVersion, same(base)); + final second = preview.transforms.begin(preview.visuals.single)!; + expect(await second.prepared, isTrue); + second.update(const ClipTransform(scale: 2)); + f.timeline.selectSequence(SequenceId('empty')); + await second.end(); + expect(view.version.kernelVersion, same(base)); + expect(f.timeline.dirty, isFalse); + }, + ); + + test( + 'canvas changes patch native output without changing clips or the session', + () async { + final fixture = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: fixture.timeline, + activeSequence: () => fixture.timeline.activeSequenceId, + viewForSequence: fixture.timeline.view, + runtime: CutdexRuntime(), + ); + try { + await preview.initialize(); + final session = preview.session; + final view = fixture.timeline.view(SequenceId('one')); + final version = view.version.kernelVersion; + calls.clear(); + preview.setCanvas(ProjectCanvasPresets.values['4:3']!); + await until(() => !preview.busy); + expect(preview.error, isNull); + expect(preview.session, same(session)); + expect(view.version.kernelVersion, same(version)); + final patch = + (calls.singleWhere((call) => call.method == 'applyPatch').arguments + as Map)['patch'] + as Map; + expect(patch['renderSize'], {'width': 1440.0, 'height': 1080.0}); + expect(calls.where((call) => call.method == 'createSession'), isEmpty); + calls.clear(); + preview.setCanvas(ProjectCanvasPresets.values['4:3']!); + await fixture.timeline.flush(); + expect(calls.where((call) => call.method == 'applyPatch'), isEmpty); + } finally { + await preview.close(); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + } + }, + ); + + test( + 'current native state arriving before load acknowledgement is retained', + () async { + for (final state in ['failed', 'playing']) { + stateBeforeLoadReply = state; + final fixture = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: fixture.timeline, + activeSequence: () => fixture.timeline.activeSequenceId, + viewForSequence: fixture.timeline.view, + runtime: CutdexRuntime(), + ); + try { + await preview.initialize(); + if (state == 'failed') { + expect(preview.error, isNotNull); + expect(preview.canPlay, isFalse); + } else { + expect(preview.error, isNull); + expect(preview.playing, isTrue); + } + } finally { + await preview.close(); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + } + } + }, + ); + + test( + 'obsolete execution events cannot change current playback or fail it', + () async { + final fixture = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: fixture.timeline, + activeSequence: () => fixture.timeline.activeSequenceId, + viewForSequence: fixture.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + }); + await preview.initialize(); + await Future.delayed(const Duration(milliseconds: 20)); + final oldRevision = revision; + fixture.timeline.selectSequence(SequenceId('empty')); + await until( + () => preview.ready && !preview.busy && revision != oldRevision, + ); + fixture.timeline.selectSequence(SequenceId('one')); + await until(() => preview.canPlay); + await Future.delayed(const Duration(milliseconds: 20)); + calls.clear(); + for (final state in ['playing', 'failed']) { + emit({ + 'state': state, + 'revision': oldRevision, + 'position': MediaTime(1, 1).toMap(), + 'rate': state == 'playing' ? 1.0 : 0.0, + }); + await Future.delayed(const Duration(milliseconds: 5)); + expect(preview.playing, isFalse, reason: 'Obsolete $state event'); + expect(preview.canPlay, isTrue, reason: 'Obsolete $state event'); + expect(preview.error, isNull); + expect(preview.positionTick, 0); + } + expect(calls, isEmpty); + emit({ + 'state': 'failed', + 'revision': revision, + 'position': MediaTime(0, 1).toMap(), + 'rate': 0.0, + }); + await until(() => preview.error != null); + expect(preview.canPlay, isFalse); + }, + ); + + test( + 'native failure for a split revision retains the split operation ID', + () async { + final fixture = await createPreviewFixture(Uri.file('/test/video.mov')); + final diagnostics = []; + final preview = PreviewController( + timeline: fixture.timeline, + activeSequence: () => fixture.timeline.activeSequenceId, + viewForSequence: fixture.timeline.view, + runtime: CutdexRuntime(diagnostics: diagnostics.add), + ); + addTearDown(() async { + if (blockedPatch != null && !blockedPatch!.isCompleted) { + blockedPatch!.complete(); + } + await preview.close(); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + }); + await preview.initialize(); + final sequence = fixture.timeline.activeSequenceId!; + final view = fixture.timeline.view(sequence); + view.seekTo(TimelineClock.ticksPerSecond); + expect(view.cutSelectionAtPlayhead(), isTrue); + final splitId = fixture.timeline.editDiagnosticContext['operationId']; + await until(() => preview.ready && !preview.busy); + final installedRevision = revision; + // A new edit is being prepared, but this failure belongs to the split revision. + blockedPatch = Completer(); + await fixture.timeline.executeCommand( + sequence, + SetClipTransform(clipId: 'clip', at: CommandTime(0, 1), scaleX: .75), + operationId: 'later-transform-edit', + ); + await until( + () => + calls.any( + (call) => + call.method == 'applyPatch' && + (call.arguments as Map)['patch'] != null, + ) && + preview.busy, + ); + emit({ + 'state': 'failed', + 'revision': installedRevision, + 'position': MediaTime(0, 1).toMap(), + 'rate': 0.0, + 'message': 'split decoder failed', + }); + await until(() => preview.error != null); + final event = diagnostics.singleWhere((e) => e.component == 'preview'); + expect(event.context['editOperation'], 'split'); + expect(event.context['operationId'], splitId); + expect(event.context['operationId'], isNot('later-transform-edit')); + blockedPatch!.complete(); + blockedPatch = null; + }, + ); + + test('current failed snapshots are logged once while obsolete failures are ignored', () async { + final fixture = await createPreviewFixture(Uri.file('/test/video.mov')); + final diagnostics = []; + final preview = PreviewController( + timeline: fixture.timeline, + activeSequence: () => fixture.timeline.activeSequenceId, + viewForSequence: fixture.timeline.view, + runtime: CutdexRuntime(diagnostics: diagnostics.add), + ); + addTearDown(() async { + await preview.close(); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + }); + await preview.initialize(); + emit({ + 'state': 'failed', + 'revision': '0', + 'position': MediaTime(0, 1).toMap(), + 'rate': 0.0, + }); + await Future.delayed(const Duration(milliseconds: 10)); + expect(diagnostics, isEmpty); + for (var i = 0; i < 3; i++) { + emit({ + 'state': 'failed', + 'revision': revision, + 'position': MediaTime(0, 1).toMap(), + 'rate': 0.0, + 'message': 'decoder failed', + }); + } + await until(() => preview.error != null); + await Future.delayed(const Duration(milliseconds: 10)); + expect(diagnostics, hasLength(1)); + expect(diagnostics.single.component, 'preview'); + expect(diagnostics.single.error.toString(), contains('decoder failed')); + expect(diagnostics.single.context['nativeSessionId'], 'test'); + }); + + test( + 'pause and resume do not seek; reaching the end still restarts at zero', + () async { + final fixture = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: fixture.timeline, + activeSequence: () => fixture.timeline.activeSequenceId, + viewForSequence: fixture.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + }); + await preview.initialize(); + await Future.delayed(const Duration(milliseconds: 20)); + for (var i = 0; i < 3; i++) { + emit({ + 'state': 'paused', + 'revision': revision, + 'position': MediaTime(1, 1).toMap(), + 'rate': 0.0, + }); + await until( + () => + !preview.playing && + preview.positionTick == TimelineClock.ticksPerSecond, + ); + calls.clear(); + await preview.togglePlayback(); + expect(calls.map((c) => c.method), ['play']); + emit({ + 'state': 'playing', + 'revision': revision, + 'position': MediaTime(3, 2).toMap(), + 'rate': 1.0, + }); + await until(() => preview.playing); + calls.clear(); + await preview.togglePlayback(); + expect(calls.map((c) => c.method), ['pause']); + } + emit({ + 'state': 'paused', + 'revision': revision, + 'position': MediaTime(2, 1).toMap(), + 'rate': 0.0, + }); + await until( + () => !preview.playing && preview.positionTick == preview.durationTick, + ); + calls.clear(); + await preview.togglePlayback(); + expect(calls.map((c) => c.method), ['seek', 'play']); + expect( + MediaTime.fromMap( + (calls.first.arguments as Map)['time'] as Map, + ).numerator, + 0, + ); + }, + ); + + test( + 'buffering playback can be paused instead of issuing another play', + () async { + final fixture = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: fixture.timeline, + activeSequence: () => fixture.timeline.activeSequenceId, + viewForSequence: fixture.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + }); + await preview.initialize(); + await Future.delayed(const Duration(milliseconds: 20)); + emit({ + 'state': 'waiting', + 'revision': revision, + 'position': MediaTime(1, 1).toMap(), + 'rate': 0.0, + }); + await Future.delayed(const Duration(milliseconds: 5)); + calls.clear(); + await preview.togglePlayback(); + expect(calls.map((c) => c.method), ['pause']); + }, + ); + + for (final (state, beforeClick) in [ + ('preparing', true), + ('ready', true), + ('preparing', false), + ('ready', false), + ('paused', false), + ]) { + test( + 'pause intent survives $state ${beforeClick ? 'before' : 'after'} clicking during seek', + () async { + final fixture = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: fixture.timeline, + activeSequence: () => fixture.timeline.activeSequenceId, + viewForSequence: fixture.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + blockedSeek?.complete(); + await preview.close(); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + }); + await preview.initialize(); + await Future.delayed(const Duration(milliseconds: 20)); + emit({ + 'state': 'playing', + 'revision': revision, + 'position': MediaTime(0, 1).toMap(), + 'rate': 1.0, + }); + await until(() => preview.playing); + calls.clear(); + blockedSeek = Completer(); + fixture.timeline + .view(SequenceId('one')) + .seekTo(TimelineClock.ticksPerSecond); + await until(() => calls.any((c) => c.method == 'seek')); + final pause = beforeClick ? null : preview.togglePlayback(); + emit({ + 'state': state, + 'revision': revision, + 'position': MediaTime(1, 1).toMap(), + 'rate': 0.0, + }); + await Future.delayed(const Duration(milliseconds: 5)); + final latePause = beforeClick ? preview.togglePlayback() : null; + blockedSeek!.complete(); + blockedSeek = null; + await pause; + await latePause; + expect(calls.map((c) => c.method), ['seek', 'pause']); + }, + ); + } + + test('resume waits for the pending user seek without repeating it', () async { + final fixture = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: fixture.timeline, + activeSequence: () => fixture.timeline.activeSequenceId, + viewForSequence: fixture.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + }); + await preview.initialize(); + await Future.delayed(const Duration(milliseconds: 20)); + calls.clear(); + blockedSeek = Completer(); + fixture.timeline + .view(SequenceId('one')) + .seekTo(TimelineClock.ticksPerSecond); + await until(() => calls.any((c) => c.method == 'seek')); + final resume = preview.togglePlayback(); + await Future.delayed(const Duration(milliseconds: 5)); + expect(calls.map((c) => c.method), ['seek']); + blockedSeek!.complete(); + blockedSeek = null; + await resume; + await Future.delayed(const Duration(milliseconds: 120)); + expect(calls.map((c) => c.method), ['seek', 'play']); + }); + + test( + 'seeking to the end previews the last frame, including subframe clips', + () async { + for (final (duration, expected) in [ + (RationalTime.seconds(2), 59 / 30), + (RationalTime(1, 60), 0.0), + (RationalTime(21, 20), 31 / 30), + (RationalTime(22199, 600), 1109 / 30), + ]) { + final fixture = await createPreviewFixture( + Uri.file('/test/video.mov'), + clipDuration: duration, + ); + final preview = PreviewController( + timeline: fixture.timeline, + activeSequence: () => fixture.timeline.activeSequenceId, + viewForSequence: fixture.timeline.view, + runtime: CutdexRuntime(), + ); + try { + await preview.initialize(); + await Future.delayed(const Duration(milliseconds: 20)); + calls.clear(); + fixture.timeline.view(SequenceId('one')).seekTo(preview.durationTick); + await Future.delayed(const Duration(milliseconds: 150)); + final seeks = calls.where((c) => c.method == 'seek'); + expect(seeks, isNotEmpty); + for (final seek in seeks) { + final time = MediaTime.fromMap( + (seek.arguments as Map)['time'] as Map, + ); + expect(time.seconds, closeTo(expected, 0.000000001)); + expect(time.seconds, greaterThanOrEqualTo(0)); + expect( + time.seconds, + lessThan(preview.durationTick / TimelineClock.ticksPerSecond), + ); + } + expect(preview.error, isNull); + } finally { + await preview.close(); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + } + } + }, + ); + + test('cut, undo and redo retain the clock; returning to a sequence restores its playhead', () async { + final fixture = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: fixture.timeline, + activeSequence: () => fixture.timeline.activeSequenceId, + viewForSequence: fixture.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + }); + await preview.initialize(); + final view = fixture.timeline.view(SequenceId('one')); + view.setSelection([ + view.version.kernelVersion.query().elementById(ElementId('clip'))!, + ]); + view.seekTo(TimelineClock.ticksPerSecond); + await Future.delayed(const Duration(milliseconds: 150)); + for (final edit in [view.cutSelectionAtPlayhead, view.undo, view.redo]) { + calls.clear(); + edit(); + await until( + () => !preview.busy && calls.any((c) => c.method == 'applyPatch'), + ); + await Future.delayed(const Duration(milliseconds: 120)); + expect(preview.error, isNull); + expect(calls.where((c) => c.method == 'seek'), isEmpty); + } + fixture.timeline.selectSequence(SequenceId('empty')); + await until(() => !preview.busy); + calls.clear(); + fixture.timeline.selectSequence(SequenceId('one')); + await until(() => !preview.busy && calls.any((c) => c.method == 'seek')); + final seek = calls.lastWhere((c) => c.method == 'seek'); + expect( + MediaTime.fromMap( + (seek.arguments as Map)['time'] as Map, + ).seconds, + 1, + ); + }); + + test( + 'nanosecond playback stays accurate past six seconds without issuing seeks', + () async { + final fixture = await createPreviewFixture( + Uri.file('/test/long.mov'), + clipDuration: RationalTime.seconds(7200), + ); + final preview = PreviewController( + timeline: fixture.timeline, + activeSequence: () => fixture.timeline.activeSequenceId, + viewForSequence: fixture.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + }); + await preview.initialize(); + await Future.delayed(const Duration(milliseconds: 20)); + final view = fixture.timeline.view(SequenceId('one')); + calls.clear(); + final positions = <(MediaTime, int)>[ + (MediaTime(6500000001, 1000000000), 9172800001), + (MediaTime(6600000001, 1000000000), 9313920001), + (MediaTime(7, 1), TimelineClock.ticksPerSecond * 7), + (MediaTime(7100000001, 1000000000), 10019520001), + ( + MediaTime(37000000001, 1000000000), + TimelineClock.ticksPerSecond * 37 + 1, + ), + ( + MediaTime(3600000000001, 1000000000), + TimelineClock.ticksPerSecond * 3600 + 1, + ), + (MediaTime(7200000000001, 1000000000), preview.durationTick), + // A real backward seek is still allowed; observations are not forced monotonic. + (MediaTime(2, 1), TimelineClock.ticksPerSecond * 2), + (MediaTime(-1, 1000000000), 0), + (MediaTime(0x7fffffffffffffff, 1), preview.durationTick), + (MediaTime(-0x7fffffffffffffff, 1), 0), + ]; + for (final (time, expected) in positions) { + emit({ + 'state': 'playing', + 'revision': revision, + 'position': time.toMap(), + 'rate': 1.0, + }); + await Future.delayed(const Duration(milliseconds: 5)); + expect( + view.playheadTick, + expected, + reason: 'native position ${time.numerator}/${time.denominator}', + ); + expect(preview.positionTick, expected); + } + await Future.delayed(const Duration(milliseconds: 120)); + expect(calls.where((c) => c.method == 'seek'), isEmpty); + expect(fixture.timeline.dirty, isFalse); + }, + ); + + test( + 'saved video with shorter audio previews, edits and reuses metadata', + () async { + final fixture = await createPreviewFixture( + Uri.file('/test/phone.mov'), + hasAudio: true, + clipDuration: RationalTime(22199, 600), + ); + final preview = PreviewController( + timeline: fixture.timeline, + activeSequence: () => fixture.timeline.activeSequenceId, + viewForSequence: fixture.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + }); + await preview.initialize(); + final plan = + (calls.firstWhere((c) => c.method == 'load').arguments + as Map)['plan']; + final audio = (plan['audioLayers'] as List).single; + final duration = MediaTime.fromMap( + audio['sourceRange']['duration'] as Map, + ); + expect(duration.seconds, closeTo(36.9966666667, 1e-9)); + expect( + preview.durationTick, + TimelineClock.standard.toTicks(RationalTime(22199, 600)), + ); + expect(preview.canPlay, isTrue); + expect(fixture.timeline.dirty, isFalse); + final view = fixture.timeline.view(SequenceId('one')); + view.setSelection([ + view.version.kernelVersion.query().elementById(ElementId('clip'))!, + ]); + view.seekTo(TimelineClock.ticksPerSecond); + view.cutSelectionAtPlayhead(); + await until( + () => !preview.busy && calls.any((c) => c.method == 'applyPatch'), + ); + expect(preview.error, isNull); + view.undo(); + await until(() => !preview.busy); + expect(preview.error, isNull); + expect(calls.where((c) => c.method == 'probe'), hasLength(1)); + }, + ); + + test( + 'native plan, coalesced seek and playback observations share the timeline', + () async { + final fixture = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: fixture.timeline, + activeSequence: () => fixture.timeline.activeSequenceId, + viewForSequence: fixture.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + }); + await preview.initialize(); + await Future.delayed(const Duration(milliseconds: 20)); + expect(preview.canPlay, isTrue); + expect( + (calls.firstWhere((c) => c.method == 'load').arguments + as Map)['plan']['visualLayers'], + hasLength(1), + ); + final view = fixture.timeline.view(SequenceId('one')); + calls.clear(); + blockedSeek = Completer(); + view.seekTo(TimelineClock.ticksPerSecond ~/ 4); + await until(() => calls.any((c) => c.method == 'seek')); + view.seekTo(TimelineClock.ticksPerSecond ~/ 2); + view.seekTo(TimelineClock.ticksPerSecond); + expect(calls.where((c) => c.method == 'seek'), hasLength(1)); + blockedSeek!.complete(); + blockedSeek = null; + await Future.delayed(const Duration(milliseconds: 150)); + final seeks = calls.where((c) => c.method == 'seek').toList(); + expect( + MediaTime.fromMap( + (seeks.last.arguments as Map)['time'] as Map, + ).seconds, + 1, + ); + expect((seeks.last.arguments as Map)['policy'], 'exact'); + expect((seeks.last.arguments as Map).containsKey('exact'), isFalse); + expect( + calls.where((c) => c.method == 'load' || c.method == 'applyPatch'), + isEmpty, + ); + calls.clear(); + emit({ + 'state': 'playing', + 'revision': revision, + 'position': MediaTime(3, 2).toMap(), + 'rate': 1.0, + }); + await until( + () => view.playheadTick == TimelineClock.ticksPerSecond * 3 ~/ 2, + ); + expect(calls.where((c) => c.method == 'seek'), isEmpty); + expect(fixture.timeline.dirty, isFalse); + await preview.togglePlayback(); + expect(calls.any((c) => c.method == 'pause'), isTrue); + }, + ); + + test( + 'retry recovers failed native playback before reloading the plan', + () async { + final fixture = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: fixture.timeline, + activeSequence: () => fixture.timeline.activeSequenceId, + viewForSequence: fixture.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + }); + await preview.initialize(); + calls.clear(); + emit({ + 'state': 'failed', + 'revision': revision, + 'position': MediaTime(0, 1).toMap(), + 'rate': 0.0, + 'message': 'Playback failed', + }); + await until(() => preview.error != null); + await preview.retry(); + final methods = calls.map((call) => call.method).toList(); + expect(methods, contains('recover')); + expect(methods.indexOf('recover'), lessThan(methods.lastIndexOf('load'))); + expect(preview.error, isNull); + }, + ); + + test( + 'edits patch plans, retry reloads and empty sequence clears preview', + () async { + final fixture = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: fixture.timeline, + activeSequence: () => fixture.timeline.activeSequenceId, + viewForSequence: fixture.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + }); + await preview.initialize(); + final view = fixture.timeline.view(SequenceId('one')); + view.setSelection([ + view.version.kernelVersion.query().elementById(ElementId('clip'))!, + ]); + view.seekTo(TimelineClock.ticksPerSecond); + failPatch = true; + view.cutSelectionAtPlayhead(); + await until(() => preview.error != null); + expect(view.canUndo, isTrue); + expect(preview.canPlay, isFalse); + failPatch = false; + await preview.retry(); + expect(preview.error, isNull); + expect(calls.where((c) => c.method == 'load'), hasLength(2)); + fixture.timeline.selectSequence(SequenceId('empty')); + await until(() => preview.ready && !preview.busy); + expect(preview.durationTick, 0); + final plan = + (calls.lastWhere((c) => c.method == 'load').arguments as Map)['plan'] + as Map; + expect(plan['visualLayers'], isEmpty); + await preview.close(); + await preview.close(); + expect(calls.where((c) => c.method == 'close'), hasLength(1)); + }, + ); + test('default preview tone mapping is explicit and does not change project settings', () async { + final fixture = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: fixture.timeline, + activeSequence: () => fixture.timeline.activeSequenceId, + viewForSequence: fixture.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + }); + await preview.initialize(); + final plan = + (calls.firstWhere((c) => c.method == 'load').arguments as Map)['plan']; + expect(plan['toneMapping'], { + 'mode': 'headroom', + 'source': 4.0, + 'target': 1.0, + }); + expect( + fixture.timeline.document.settings.containsKey('toneMapping'), + isFalse, + ); + expect(fixture.timeline.dirty, isFalse); + expect(preview.canPlay, isTrue); + }); + + test('project tone mapping overrides preview default', () async { + final fixture = await createPreviewFixture( + Uri.file('/test/video.mov'), + toneMapping: {'sourceHeadroom': 8, 'targetHeadroom': 2}, + ); + final preview = PreviewController( + timeline: fixture.timeline, + activeSequence: () => fixture.timeline.activeSequenceId, + viewForSequence: fixture.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + }); + await preview.initialize(); + final plan = + (calls.firstWhere((c) => c.method == 'load').arguments as Map)['plan']; + expect(plan['toneMapping'], { + 'mode': 'headroom', + 'source': 8.0, + 'target': 2.0, + }); + }); + + test( + 'older systems keep SDR preview and report HDR configuration accurately', + () async { + toneMappingAvailable = false; + final fixture = await createPreviewFixture(Uri.file('/test/video.mov')); + final preview = PreviewController( + timeline: fixture.timeline, + activeSequence: () => fixture.timeline.activeSequenceId, + viewForSequence: fixture.timeline.view, + runtime: CutdexRuntime(), + ); + addTearDown(() async { + await preview.close(); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + }); + await preview.initialize(); + final plan = + (calls.firstWhere((c) => c.method == 'load').arguments + as Map)['plan']; + expect(plan['toneMapping'], {'mode': 'none'}); + expect(preview.canPlay, isTrue); + loadError = PlatformException( + code: 'invalidArgument', + message: + 'Invalid media request: HDR to SDR requires explicit tone mapping', + ); + final view = fixture.timeline.view(SequenceId('one')); + view.setSelection([ + view.version.kernelVersion.query().elementById(ElementId('clip'))!, + ]); + view.seekTo(TimelineClock.ticksPerSecond); + view.cutSelectionAtPlayhead(); + await until(() => preview.error != null); + expect( + previewErrorMessage(preview.error!, AppLocalizationsZh()), + contains('HDR 素材需要色调映射'), + ); + expect( + previewErrorMessage(preview.error!, AppLocalizationsZh()), + isNot(contains('素材是否可访问')), + ); + }, + ); + + test('invalid native video composition has an accurate preview message', () { + const error = RuntimeException( + code: 'playback/failed', + message: 'The operation could not be completed.', + domain: 'playback', + details: { + 'nativeDomain': 'AVFoundationErrorDomain', + 'nativeCode': '-11841', + }, + ); + + expect( + previewErrorMessage(error, AppLocalizationsZh()), + '视频合成配置无效,无法创建预览。', + ); + expect( + previewErrorMessage(error, AppLocalizationsZh()), + isNot(contains('素材是否可访问')), + ); + }); + + test('invalid preview data is not reported as inaccessible media', () { + final message = previewErrorMessage(TypeError(), AppLocalizationsZh()); + expect(message, '预览数据无效,请重试。'); + expect(message, isNot(contains('素材是否可访问'))); + }); +} diff --git a/test/preview_fullscreen_test.dart b/test/preview_fullscreen_test.dart new file mode 100644 index 0000000..4b8d055 --- /dev/null +++ b/test/preview_fullscreen_test.dart @@ -0,0 +1,295 @@ +import 'dart:async'; + +import 'package:cutdex/app/editor_theme.dart'; +import 'package:cutdex/features/preview/preview_fullscreen.dart'; +import 'package:cutdex_ui/theme.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets( + 'disposal waits for native fullscreen entry before restoring the window', + (tester) async { + const channel = MethodChannel('cutdex_native/fullscreen'); + final messenger = tester.binding.defaultBinaryMessenger; + final entered = Completer(); + final requests = []; + messenger.setMockMethodCallHandler(channel, (call) async { + final entering = call.arguments as bool; + requests.add(entering); + if (entering) await entered.future; + if (!entering && !entered.isCompleted) { + throw PlatformException(code: 'busy'); + } + return null; + }); + addTearDown(() => messenger.setMockMethodCallHandler(channel, null)); + await tester.pumpWidget( + const MaterialApp( + home: Scaffold(body: PreviewFullscreenHost(child: _Toggle('enter'))), + ), + ); + await tester.tap(find.text('enter')); + await tester.pump(); + await tester.pumpWidget(const SizedBox()); + await tester.pump(); + expect(requests, [true]); + entered.complete(); + await tester.pump(); + expect(requests, [true, false]); + }, + variant: TargetPlatformVariant.only(TargetPlatform.macOS), + ); + + testWidgets( + 'native fullscreen exit restores the panel and disposal restores the window', + (tester) async { + const channel = MethodChannel('cutdex_native/fullscreen'); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + final requests = []; + messenger.setMockMethodCallHandler(channel, (call) async { + requests.add(call.arguments as bool); + return null; + }); + addTearDown(() => messenger.setMockMethodCallHandler(channel, null)); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: Center( + child: SizedBox( + width: 320, + height: 200, + child: PreviewFullscreenHost( + child: _Preview(onInit: () {}, onDispose: () {}), + ), + ), + ), + ), + ), + ); + await tester.tap(find.byType(TextButton)); + await tester.pumpAndSettle(); + expect(requests, [true]); + messenger.handlePlatformMessage( + channel.name, + const StandardMethodCodec().encodeMethodCall( + const MethodCall('exited'), + ), + (_) {}, + ); + await tester.pumpAndSettle(); + expect(tester.getSize(find.byType(_Preview)), const Size(320, 200)); + await tester.tap(find.byType(TextButton)); + await tester.pumpAndSettle(); + await tester.pumpWidget(const SizedBox()); + await tester.pumpAndSettle(); + expect(requests, [true, true, false]); + }, + variant: const TargetPlatformVariant({TargetPlatform.macOS}), + ); + + testWidgets( + 'fullscreen reparents the same preview and Escape restores its size', + (tester) async { + var initialized = 0; + var disposed = 0; + await tester.pumpWidget( + MaterialApp( + theme: EditorTheme.penLight, + home: Scaffold( + body: Center( + child: SizedBox( + width: 320, + height: 200, + child: PreviewFullscreenHost( + child: _Preview( + onInit: () => initialized++, + onDispose: () => disposed++, + ), + ), + ), + ), + ), + ), + ); + final preview = find.byType(_Preview); + final initialState = tester.state(preview); + expect(tester.getSize(preview), const Size(320, 200)); + expect(Theme.of(tester.element(preview)).brightness, Brightness.light); + await tester.tap(find.byType(TextButton)); + await tester.pumpAndSettle(); + expect(tester.getSize(preview), const Size(800, 600)); + expect(tester.state(preview), same(initialState)); + final fullscreenTheme = Theme.of(tester.element(preview)); + expect(fullscreenTheme.brightness, Brightness.dark); + expect(fullscreenTheme.colorScheme.surface, Colors.black); + expect( + fullscreenTheme.extension()!.previewBackground, + Colors.black, + ); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pumpAndSettle(); + expect(tester.getSize(preview), const Size(320, 200)); + expect(Theme.of(tester.element(preview)).brightness, Brightness.light); + expect(initialized, 1); + expect(disposed, 0); + await tester.tap(find.byType(TextButton)); + await tester.pumpAndSettle(); + await tester.tap(find.byType(TextButton)); + await tester.pumpAndSettle(); + expect(tester.getSize(preview), const Size(320, 200)); + expect(disposed, 0); + }, + ); + testWidgets( + 'old fullscreen host disposal preserves the active exit listener', + (tester) async { + const channel = MethodChannel('cutdex_native/fullscreen'); + final messenger = tester.binding.defaultBinaryMessenger; + messenger.setMockMethodCallHandler(channel, (_) async => null); + addTearDown(() => messenger.setMockMethodCallHandler(channel, null)); + Widget page({required bool old, required bool next}) => MaterialApp( + home: Scaffold( + body: Row( + children: [ + if (old) + const Expanded( + key: ValueKey('old'), + child: PreviewFullscreenHost(child: _Toggle('old')), + ), + if (next) + const Expanded( + key: ValueKey('new'), + child: PreviewFullscreenHost(child: _Toggle('new')), + ), + ], + ), + ), + ); + await tester.pumpWidget(page(old: true, next: false)); + await tester.tap(find.text('old')); + await tester.pumpAndSettle(); + await tester.tap(find.text('old')); + await tester.pumpAndSettle(); + await tester.pumpWidget(page(old: true, next: true)); + await tester.pumpAndSettle(); + await tester.tap(find.text('new')); + await tester.pumpAndSettle(); + await tester.pumpWidget(page(old: false, next: true)); + await tester.pumpAndSettle(); + await messenger.handlePlatformMessage( + channel.name, + const StandardMethodCodec().encodeMethodCall( + const MethodCall('exited'), + ), + (_) {}, + ); + await tester.pumpAndSettle(); + expect( + PreviewFullscreenScope.of(tester.element(find.text('new')))!.fullscreen, + isFalse, + ); + }, + variant: TargetPlatformVariant.only(TargetPlatform.macOS), + ); + testWidgets( + 'disposing a superseded fullscreen host does not exit the active window', + (tester) async { + const channel = MethodChannel('cutdex_native/fullscreen'); + final messenger = tester.binding.defaultBinaryMessenger; + final requests = []; + messenger.setMockMethodCallHandler(channel, (call) async { + requests.add(call.arguments as bool); + return null; + }); + addTearDown(() => messenger.setMockMethodCallHandler(channel, null)); + Widget page(bool old) => MaterialApp( + home: Scaffold( + body: Row( + children: [ + if (old) + const Expanded( + key: ValueKey('old'), + child: PreviewFullscreenHost(child: _Toggle('old')), + ), + const Expanded( + key: ValueKey('new'), + child: PreviewFullscreenHost(child: _Toggle('new')), + ), + ], + ), + ), + ); + await tester.pumpWidget(page(true)); + await tester.tap(find.text('old')); + await tester.pumpAndSettle(); + // A newly mounted route can take ownership while the old route is retiring. + tester + .widget(find.widgetWithText(TextButton, 'new')) + .onPressed!(); + await tester.pumpAndSettle(); + await tester.pumpWidget(page(false)); + await tester.pumpAndSettle(); + expect(requests, [true, true]); + await messenger.handlePlatformMessage( + channel.name, + const StandardMethodCodec().encodeMethodCall( + const MethodCall('exited'), + ), + (_) {}, + ); + await tester.pumpAndSettle(); + expect( + PreviewFullscreenScope.of(tester.element(find.text('new')))!.fullscreen, + isFalse, + ); + await tester.pumpWidget(const SizedBox()); + await tester.pumpAndSettle(); + }, + variant: TargetPlatformVariant.only(TargetPlatform.macOS), + ); +} + +class _Preview extends StatefulWidget { + const _Preview({required this.onInit, required this.onDispose}); + final VoidCallback onInit; + final VoidCallback onDispose; + @override + State<_Preview> createState() => _PreviewState(); +} + +class _PreviewState extends State<_Preview> { + @override + void initState() { + super.initState(); + widget.onInit(); + } + + @override + void dispose() { + widget.onDispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => Center( + child: TextButton( + onPressed: PreviewFullscreenScope.of(context)!.toggle, + child: const Text('Fullscreen'), + ), + ); +} + +class _Toggle extends StatelessWidget { + const _Toggle(this.label); + final String label; + @override + Widget build(BuildContext context) => Center( + child: TextButton( + onPressed: PreviewFullscreenScope.of(context)!.toggle, + child: Text(label), + ), + ); +} diff --git a/test/preview_interaction_test.dart b/test/preview_interaction_test.dart new file mode 100644 index 0000000..16b1cef --- /dev/null +++ b/test/preview_interaction_test.dart @@ -0,0 +1,1005 @@ +import 'package:cutdex/l10n/app_localizations.dart'; + +import 'dart:async'; +import 'dart:math' as math; + +import 'package:cutdex_sdk/preview.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + Future mount( + WidgetTester tester, + _Preview preview, { + Rect canvasRect = const Rect.fromLTWH(40, 40, 500, 300), + }) => tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + home: Scaffold( + body: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: canvasRect.right + 60, + height: canvasRect.bottom + 60, + child: ListenableBuilder( + listenable: preview, + builder: (_, _) => PreviewInteractionOverlay( + controller: preview, + canvasRect: canvasRect, + ), + ), + ), + ), + ), + ), + ); + void expectGuides(WidgetTester tester, bool visible) { + final paint = tester.renderObject( + find.descendant( + of: find.byType(PreviewInteractionOverlay), + matching: find.byType(CustomPaint), + ), + ); + final matcher = paints..line(color: const Color(0xFFFF55C8)); + expect(paint, visible ? matcher : isNot(matcher)); + } + + for (final (width, entry) in [ + (250.0, 1.5), + (500.0, 3.0), + (1000.0, 6.0), + (1500.0, 6.0), + ]) { + testWidgets('move snap entry and release follow a $width-wide canvas', ( + tester, + ) async { + tester.view.physicalSize = const Size(1800, 1100); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final preview = _Preview()..selectVisual(ElementId('upper')); + final canvasRect = Rect.fromLTWH(40, 40, width, width * .6); + final scale = width / 1000; + await mount(tester, preview, canvasRect: canvasRect); + final gesture = await tester.startGesture(canvasRect.center); + await gesture.moveBy(const Offset(30, 0)); + await tester.pump(); + + Future move(double distance, {required bool snapped}) async { + await gesture.moveTo(canvasRect.center + Offset(distance, 0)); + await tester.pump(); + expect( + preview.visuals.last.geometry.center.dx, + closeTo(500 + (snapped ? 0 : distance / scale), 1e-6), + ); + } + + await move(entry * 1.2, snapped: false); + await move(entry * .8, snapped: true); + await move(entry * 1.4, snapped: true); + await move(entry * 1.8, snapped: false); + await gesture.up(); + await tester.pumpAndSettle(); + await tester.pumpWidget(const SizedBox()); + preview.dispose(); + }); + } + + for (var corner = 0; corner < 4; corner++) { + testWidgets('exterior corner $corner rotates without resizing', ( + tester, + ) async { + final preview = _Preview()..selectVisual(ElementId('upper')); + await mount(tester, preview); + final geometry = preview.visuals.last.geometry; + final center = const Offset(40, 40) + geometry.center * .5; + final point = const Offset(40, 40) + geometry.corners[corner] * .5; + final direction = point - center; + final radial = direction + direction / direction.distance * 16; + final gesture = await tester.startGesture(center + radial); + await gesture.moveTo(center + Offset(-radial.dy, radial.dx)); + await gesture.up(); + await tester.pumpAndSettle(); + expect(preview.value.rotation, closeTo(90, .01)); + expect(preview.value.scale, 1); + expect(preview.value.scaleY, 1); + expect(preview.commits, 1); + await tester.pumpWidget(const SizedBox()); + preview.dispose(); + }); + } + + testWidgets('unlocked corner drag changes dimensions independently', ( + tester, + ) async { + final preview = _Preview()..aspectRatioLocked = false; + preview.selectVisual(ElementId('upper')); + await mount(tester, preview); + final gesture = await tester.startGesture(const Offset(365, 240)); + await gesture.moveBy(const Offset(45, 10)); + await tester.pump(); + await gesture.up(); + await tester.pumpAndSettle(); + expect(preview.value.scale, closeTo(1.3, 1e-9)); + expect(preview.value.scaleY, closeTo(1.1, 1e-9)); + expect(preview.visuals.last.geometry.corners[0], const Offset(350, 200)); + await tester.pumpWidget(const SizedBox()); + preview.dispose(); + }); + testWidgets( + 'corner scaling paints Flutter guides and Alt temporarily disables snapping', + (tester) async { + final preview = _Preview(); + preview.selectVisual(ElementId('upper')); + await mount(tester, preview); + final gesture = await tester.startGesture(const Offset(365, 240)); + await gesture.moveTo(const Offset(538.5, 355.6666666666667)); + await tester.pump(); + expectGuides(tester, true); + expect(preview.visuals.last.geometry.bounds.right, closeTo(1000, 1e-6)); + await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); + await tester.pump(); + expectGuides(tester, false); + expect(preview.visuals.last.geometry.bounds.right, closeTo(997, 1e-6)); + await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); + await tester.pump(); + expectGuides(tester, true); + await gesture.up(); + await tester.pumpAndSettle(); + expectGuides(tester, false); + await tester.pumpWidget(const SizedBox()); + preview.dispose(); + }, + ); + testWidgets('canvas receives input with Flutter selection', (tester) async { + final preview = _Preview(); + await mount(tester, preview); + expect( + find.descendant( + of: find.byType(PreviewInteractionOverlay), + matching: find.byType(CustomPaint), + ), + findsOneWidget, + ); + final gesture = await tester.startGesture(const Offset(290, 190)); + await gesture.moveBy(const Offset(60, 0)); + await gesture.up(); + await tester.pumpAndSettle(); + expect(preview.value.x, closeTo(.12, 1e-9)); + expect(preview.commits, 1); + await tester.pumpWidget(const SizedBox()); + preview.dispose(); + }); + + testWidgets('playback and seeking retain the Flutter decoration', ( + tester, + ) async { + final preview = _Preview() + ..playing = true + ..selectedVisualIds = {ElementId('upper')}; + await mount(tester, preview); + final selection = find.descendant( + of: find.byType(PreviewInteractionOverlay), + matching: find.byType(CustomPaint), + ); + expect(selection, findsOneWidget); + expect(preview.pauses, 0); + + preview.value = const ClipTransform(x: .1, scaleY: 1.5, rotation: 30); + preview.notifyListeners(); + await tester.pump(); + expect(selection, findsOneWidget); + + preview.playing = false; + preview.notifyListeners(); + await tester.pump(); + expect(selection, findsOneWidget); + preview.selectVisual(null); + await tester.pump(); + expect(selection, findsOneWidget); + expect(preview.pauses, 0); + await tester.pumpWidget(const SizedBox()); + preview.dispose(); + }); + + testWidgets( + 'a visible corner stays hittable while the previous drag render is pending', + (tester) async { + final preview = _Preview()..delayUpdates = true; + await mount(tester, preview); + final move = await tester.startGesture(const Offset(290, 190)); + await move.moveBy(const Offset(60, 0)); + await move.up(); + await tester.pumpAndSettle(); + final scale = await tester.startGesture(const Offset(365, 240)); + await scale.moveBy(const Offset(30, 20)); + await scale.up(); + await tester.pumpAndSettle(); + expect( + preview.value.scale, + greaterThan(1), + reason: 'Hit testing must use the same geometry as the visible handles', + ); + expect(preview.commits, 2); + await tester.pumpWidget(const SizedBox()); + preview.dispose(); + }, + ); + + testWidgets( + 'selection does not outrun a delayed native render during a drag', + (tester) async { + final preview = _Preview()..delayUpdates = true; + await mount(tester, preview); + final gesture = await tester.startGesture(const Offset(290, 190)); + await gesture.moveBy(const Offset(60, 0)); + await tester.pumpAndSettle(); + final paint = tester.widget( + find.descendant( + of: find.byType(PreviewInteractionOverlay), + matching: find.byType(CustomPaint), + ), + ); + final geometry = (paint.painter as dynamic).geometry as PreviewGeometry; + expect( + geometry.center, + const Offset(500, 300), + reason: 'The video has not rendered the requested displacement yet', + ); + expect( + preview.transforms.valueFor(ElementId('upper'))!.x, + closeTo(.12, 1e-9), + ); + await gesture.moveBy(const Offset(40, 0)); + await tester.pump(); + preview.delayedUpdates.first(); + await tester.pump(); + PreviewGeometry painted() => + (tester + .widget( + find.descendant( + of: find.byType(PreviewInteractionOverlay), + matching: find.byType(CustomPaint), + ), + ) + .painter + as dynamic) + .geometry + as PreviewGeometry; + expect(painted().center, const Offset(620, 300)); + expect( + preview.transforms.valueFor(ElementId('upper'))!.x, + closeTo(.2, 1e-9), + ); + await gesture.up(); + await tester.pump(); + expect( + painted().center, + const Offset(620, 300), + reason: 'Release must not jump the box ahead of the last frame', + ); + preview.delayedUpdates.last(); + await tester.pump(); + expect(painted().center, const Offset(700, 300)); + await tester.pumpWidget(const SizedBox()); + preview.dispose(); + }, + ); + + testWidgets( + 'selection uses workspace bounds and old top rotation handle is inactive', + (tester) async { + final preview = _Preview() + ..value = const ClipTransform(scale: 3) + ..selectVisual(ElementId('upper')); + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + home: Scaffold( + body: Align( + alignment: Alignment.topLeft, + child: SizedBox( + width: 600, + height: 400, + child: PreviewInteractionOverlay( + controller: preview, + canvasRect: const Rect.fromLTWH(40, 16, 500, 300), + ), + ), + ), + ), + ), + ); + final paint = tester.renderObject( + find.descendant( + of: find.byType(PreviewInteractionOverlay), + matching: find.byType(CustomPaint), + ), + ); + expect( + paint, + paints..clipRect(rect: const Rect.fromLTWH(0, 0, 600, 400)), + ); + final gesture = await tester.startGesture(const Offset(290, 8)); + await gesture.moveTo(const Offset(448, 166)); + await gesture.up(); + await tester.pumpAndSettle(); + expect(preview.value.rotation, 0); + expect(preview.commits, 0); + await tester.pumpWidget(const SizedBox()); + preview.dispose(); + }, + ); + + testWidgets( + 'corners outside video remain visible and resizable in workspace', + (tester) async { + final preview = _Preview(size: const Size(300, 160)) + ..selectVisual(ElementId('upper')); + await mount(tester, preview); + final gesture = await tester.startGesture(const Offset(290, 190)); + await gesture.moveTo(const Offset(290, 350)); + await gesture.up(); + await tester.pumpAndSettle(); + expect(preview.value.y, closeTo(160 / 300, 1e-9)); + expect(preview.commits, 1); + final corner = + const Offset(40, 40) + preview.visuals.last.geometry.corners[2] * .5; + expect(corner.dy, greaterThan(340)); + expect(corner.dy, lessThan(400)); + final hidden = await tester.startGesture(corner); + await hidden.moveBy(const Offset(-30, -40)); + await hidden.up(); + await tester.pumpAndSettle(); + expect(preview.commits, 2); + expect(preview.value.scale, lessThan(1)); + await tester.pumpWidget(const SizedBox()); + preview.dispose(); + }, + ); + + testWidgets( + 'one mouse move before release still applies its full displacement', + (tester) async { + final preview = _Preview(); + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + home: Scaffold( + body: SizedBox( + width: 600, + height: 400, + child: PreviewInteractionOverlay( + controller: preview, + canvasRect: const Rect.fromLTWH(40, 40, 500, 300), + ), + ), + ), + ), + ); + final gesture = await tester.startGesture(const Offset(290, 190)); + await gesture.moveTo(const Offset(350, 190)); + await gesture.up(); + await tester.pumpAndSettle(); + expect(preview.value.x, closeTo(.12, 1e-9)); + expect(preview.commits, 1); + await tester.pumpWidget(const SizedBox()); + preview.dispose(); + }, + ); + + testWidgets( + 'a second drag is retained while the released gesture is still preparing', + (tester) async { + final preview = _Preview()..blockedBegin = Completer(); + await mount(tester, preview); + final first = await tester.startGesture(const Offset(290, 190)); + await first.moveBy(const Offset(60, 0)); + await first.up(); + await tester.pump(); + final second = await tester.startGesture(const Offset(350, 190)); + await second.moveBy(const Offset(30, 0)); + await second.up(); + preview.blockedBegin!.complete(); + await tester.pumpAndSettle(); + expect(preview.commits, 2); + expect(preview.value.x, closeTo(.18, 1e-9)); + expect(preview.transforms.hasPending, isFalse); + await tester.pumpWidget(const SizedBox()); + preview.dispose(); + }, + ); + + testWidgets( + 'a second drag immediately moves the selection using the previous commit', + (tester) async { + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetDevicePixelRatio); + final preview = _Preview(); + await mount(tester, preview); + final first = await tester.startGesture(const Offset(290, 190)); + await first.moveBy(const Offset(60, 0)); + await tester.pump(); + await first.up(); + await tester.pump(); + final second = await tester.startGesture(const Offset(350, 190)); + await second.moveBy(const Offset(30, 0)); + await tester.pump(); + final paint = tester.renderObject( + find.descendant( + of: find.byType(PreviewInteractionOverlay), + matching: find.byType(CustomPaint), + ), + ); + expect( + paint, + paints + ..path(color: const Color(0xFF0099FF), style: PaintingStyle.stroke) + ..rect( + rect: const Rect.fromLTWH(301, 136, 8, 8), + color: Colors.white, + ), + ); + expect(preview.visuals.last.transform.x, closeTo(.18, 1e-9)); + expect(preview.commits, 1); + await second.up(); + await tester.pumpAndSettle(); + expect(preview.commits, 2); + expect(preview.value.x, closeTo(.18, 1e-9)); + await tester.pumpWidget(const SizedBox()); + preview.dispose(); + }, + ); + + testWidgets( + 'Escape cancels only the new pointer edit and preserves the previous commit', + (tester) async { + final preview = _Preview(); + await mount(tester, preview); + final first = await tester.startGesture(const Offset(290, 190)); + await first.moveBy(const Offset(60, 0)); + await tester.pump(); + await first.up(); + final second = await tester.startGesture(const Offset(350, 190)); + await second.moveBy(const Offset(30, 0)); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await second.up(); + await tester.pumpAndSettle(); + expect(preview.commits, 1); + expect(preview.value.x, closeTo(.12, 1e-9)); + await tester.pumpWidget(const SizedBox()); + preview.dispose(); + }, + ); + + for (final operation in ['scale', 'rotate']) { + testWidgets( + 'consecutive $operation uses the previous drag final geometry', + (tester) async { + final preview = _Preview(); + await mount(tester, preview); + final first = await tester.startGesture(const Offset(290, 190)); + await first.moveBy(const Offset(60, 0)); + await tester.pump(); + await first.up(); + final second = await tester.startGesture( + operation == 'scale' + ? const Offset(425, 240) + : const Offset(265, 130), + ); + await second.moveTo( + operation == 'scale' + ? const Offset(455, 260) + : const Offset(410, 105), + ); + await second.up(); + await tester.pumpAndSettle(); + expect(preview.commits, 2); + if (operation == 'scale') { + expect(preview.value.scale, greaterThan(1)); + expect(preview.value.x, greaterThan(.12)); + } else { + expect(preview.value.rotation, closeTo(90, .01)); + expect(preview.value.x, closeTo(.12, 1e-9)); + } + await tester.pumpWidget(const SizedBox()); + preview.dispose(); + }, + ); + } + + testWidgets( + 'a tap after release preserves the committed edit and accepts the next drag', + (tester) async { + final preview = _Preview(); + await mount(tester, preview); + final gesture = await tester.startGesture(const Offset(290, 190)); + await gesture.moveBy(const Offset(60, 0)); + await tester.pump(); + await gesture.up(); + await tester.pump(); + await tester.tapAt(const Offset(290, 190)); + await tester.pump(); + expect(preview.transforming, isTrue); + await tester.pumpAndSettle(); + expect(preview.commits, 1); + expect(preview.value.x, closeTo(.12, 1e-9)); + final next = await tester.startGesture(const Offset(350, 190)); + await next.moveBy(const Offset(30, 0)); + await next.up(); + await tester.pumpAndSettle(); + expect(preview.commits, 2); + expect(preview.value.x, closeTo(.18, 1e-9)); + await tester.pumpWidget(const SizedBox()); + preview.dispose(); + }, + ); + + testWidgets('switching controllers cancels only the old pending gesture', ( + tester, + ) async { + final old = _Preview()..blockedBegin = Completer(); + final replacement = _Preview(); + await mount(tester, old); + final first = await tester.startGesture(const Offset(290, 190)); + await first.moveBy(const Offset(60, 0)); + await first.up(); + await tester.pump(); + await mount(tester, replacement); + final second = await tester.startGesture(const Offset(290, 190)); + await second.moveBy(const Offset(30, 0)); + await tester.pump(); + old.blockedBegin!.complete(); + await tester.pump(); + expect(replacement.transforming, isTrue); + expect(old.transforming, isFalse); + await second.up(); + await tester.pumpAndSettle(); + expect(replacement.commits, 1); + expect(old.commits, 1); + await tester.pumpWidget(const SizedBox()); + old.dispose(); + replacement.dispose(); + }); + + testWidgets( + 'selection follows video rotation and its visible corners resize', + (tester) async { + final preview = _Preview() + ..value = const ClipTransform(rotation: 45) + ..selectVisual(ElementId('upper')); + await mount(tester, preview); + final geometry = preview.visuals.last.geometry; + final points = geometry.corners + .map((p) => const Offset(40, 40) + p * .5) + .toList(); + final paint = tester.renderObject( + find.descendant( + of: find.byType(PreviewInteractionOverlay), + matching: find.byType(CustomPaint), + ), + ); + final expected = paints; + expected.something((method, arguments) => method == #drawVertices); + for (final p in points) { + const handle = Rect.fromLTWH(-4, -4, 8, 8); + expected + ..save() + ..translate(x: p.dx, y: p.dy) + ..rotate( + angle: math.atan2( + (points[1] - points[0]).dy, + (points[1] - points[0]).dx, + ), + ) + ..rect(rect: handle, color: Colors.white) + ..something((method, arguments) => method == #drawVertices) + ..restore(); + } + expect(paint, expected); + final pointer = points[0] + (points[2] - points[0]) * 1.5; + final gesture = await tester.startGesture(points[2]); + await gesture.moveTo(pointer); + await gesture.up(); + await tester.pumpAndSettle(); + expect(preview.commits, 1); + expect(preview.value.scale, closeTo(1.5, 1e-9)); + expect(preview.value.rotation, 45); + expect( + (preview.visuals.last.geometry.corners[0] - geometry.corners[0]) + .distance, + lessThan(1e-8), + ); + await tester.pumpWidget(const SizedBox()); + preview.dispose(); + }, + ); + + testWidgets('outer corner rotation follows the rotated video', ( + tester, + ) async { + final preview = _Preview() + ..value = const ClipTransform(rotation: 37) + ..selectVisual(ElementId('upper')); + await mount(tester, preview); + final geometry = preview.visuals.last.geometry; + final center = const Offset(40, 40) + geometry.center * .5; + final radial = geometry.rotate( + Offset(-geometry.size.width * .25 - 12, -geometry.size.height * .25 - 12), + ); + final gesture = await tester.startGesture(center + radial); + await gesture.moveTo(center + Offset(-radial.dy, radial.dx)); + await tester.pump(); + expect(preview.pending!.rotation, closeTo(127, 1e-8)); + // Verify the live overlay, not only the geometry after committing. + final paint = tester.renderObject( + find.descendant( + of: find.byType(PreviewInteractionOverlay), + matching: find.byType(CustomPaint), + ), + ); + final expected = paints; + expected.something((method, arguments) => method == #drawVertices); + expect(paint, expected); + await gesture.up(); + await tester.pumpAndSettle(); + expect(preview.value.rotation, closeTo(127, 1e-8)); + expect(preview.value.scale, 1); + expect(preview.value.x, 0); + expect(preview.value.y, 0); + await tester.pumpWidget(const SizedBox()); + preview.dispose(); + }); + + testWidgets('empty space inside a rotated selection does not hit the video', ( + tester, + ) async { + final preview = _Preview() + ..value = const ClipTransform(rotation: 45) + ..selectVisual(ElementId('upper')); + await mount(tester, preview); + final geometry = preview.visuals.last.geometry; + final point = geometry.bounds.topLeft + const Offset(30, 30); + expect(geometry.contains(point), isFalse); + await tester.tapAt(const Offset(40, 40) + point * .5); + await tester.pump(); + expect(preview.selectedVisualIds, isEmpty); + expect(preview.commits, 0); + await tester.pumpWidget(const SizedBox()); + preview.dispose(); + }); + + testWidgets( + 'overlap selects top timeline layer; click blank clears selection', + (tester) async { + final preview = _Preview(); + await mount(tester, preview); + await tester.tapAt(const Offset(290, 190)); + await tester.pump(); + expect(preview.selectedVisualIds, {ElementId('upper')}); + await tester.tapAt(const Offset(45, 45)); + await tester.pump(); + expect(preview.selectedVisualIds, isEmpty); + await tester.pumpWidget(const SizedBox()); + preview.dispose(); + }, + ); + + testWidgets( + 'pressing video or blank canvas pauses before release or drag recognition', + (tester) async { + final preview = _Preview(); + await mount(tester, preview); + for (final point in [const Offset(290, 190), const Offset(45, 45)]) { + preview.playing = true; + final down = await tester.startGesture(point); + expect( + preview.playing, + isFalse, + ); // No pump, movement, or pointer-up required. + expect(preview.transforming, isFalse); + expect(preview.commits, 0); + await down.up(); + await tester.pumpAndSettle(); + } + expect(preview.pauses, 2); + await tester.tapAt(const Offset(290, 190)); + await tester.pump(); + expect(preview.playing, isFalse); + expect( + preview.pauses, + 2, + ); // A paused canvas click never toggles playback on. + await tester.pumpWidget(const SizedBox()); + preview.dispose(); + }, + ); + + testWidgets( + 'drag holds its target, Option clears it immediately, and new drags start fresh', + (tester) async { + final preview = _Preview(); + await mount(tester, preview); + final gesture = await tester.startGesture(const Offset(290, 190)); + await gesture.moveTo(const Offset(330, 190)); + await tester.pump(); + await gesture.moveTo(const Offset(292, 190)); + await tester.pump(); + expect(preview.pending!.x, 0); + await gesture.moveTo(const Offset(294, 190)); + await tester.pump(); + expect( + preview.pending!.x, + 0, + ); // Retains the lock outside the 3px entry radius. + await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); + await tester.pump(); + expect(preview.pending!.x, closeTo(.008, 1e-9)); + await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); + await tester.pump(); + expect( + preview.pending!.x, + closeTo(.008, 1e-9), + ); // No old lock to restore. + await gesture.moveTo(const Offset(292.5, 190)); + await tester.pump(); + expect(preview.pending!.x, 0); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await gesture.up(); + await tester.pumpAndSettle(); + expect(preview.commits, 0); + final next = await tester.startGesture(const Offset(290, 190)); + await next.moveTo(const Offset(330, 190)); + await tester.pump(); + await next.moveTo(const Offset(294, 190)); + await tester.pump(); + expect(preview.pending!.x, closeTo(.008, 1e-9)); + await next.up(); + await tester.pumpAndSettle(); + expect(preview.commits, 1); + await tester.pumpWidget(const SizedBox()); + preview.dispose(); + }, + ); + + testWidgets( + 'all six simultaneous guides are painted above the selection outline', + (tester) async { + final preview = _Preview(size: const Size(1000, 600)); + await mount(tester, preview); + final gesture = await tester.startGesture(const Offset(290, 190)); + await gesture.moveTo(const Offset(330, 190)); + await tester.pump(); + await gesture.moveTo(const Offset(292, 192)); + await tester.pump(); + final paint = tester.renderObject( + find.descendant( + of: find.byType(PreviewInteractionOverlay), + matching: find.byType(CustomPaint), + ), + ); + const color = Color(0xFFFF55C8); + expect( + paint, + paints + ..path(color: const Color(0xFF0099FF), style: PaintingStyle.stroke) + ..line( + p1: const Offset(40, 40), + p2: const Offset(40, 340), + color: color, + ) + ..line( + p1: const Offset(290, 40), + p2: const Offset(290, 340), + color: color, + ) + ..line( + p1: const Offset(540, 40), + p2: const Offset(540, 340), + color: color, + ) + ..line( + p1: const Offset(40, 40), + p2: const Offset(540, 40), + color: color, + ) + ..line( + p1: const Offset(40, 190), + p2: const Offset(540, 190), + color: color, + ) + ..line( + p1: const Offset(40, 340), + p2: const Offset(540, 340), + color: color, + ), + ); + await gesture.up(); + await tester.pumpAndSettle(); + await tester.pumpWidget(const SizedBox()); + preview.dispose(); + }, + ); + + testWidgets('drag previews then commits once; escape restores original', ( + tester, + ) async { + final preview = _Preview(); + await mount(tester, preview); + final gesture = await tester.startGesture(const Offset(290, 190)); + await gesture.moveBy(const Offset(20, 0)); + await tester.pump(); + await gesture.moveBy(const Offset(40, 20)); + await tester.pump(const Duration(milliseconds: 40)); + expect(preview.transforming, isTrue); + expect(preview.commits, 0); + expect(preview.pending!.x, greaterThan(.05)); + await gesture.up(); + await tester.pumpAndSettle(); + expect(preview.commits, 1); + final committed = preview.value; + final center = + const Offset(290, 190) + Offset(committed.x * 500, committed.y * 300); + final cancelled = await tester.startGesture(center); + await cancelled.moveBy(const Offset(20, 0)); + await tester.pump(); + await cancelled.moveBy(const Offset(50, 0)); + await tester.pump(const Duration(milliseconds: 40)); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pump(); + await cancelled.up(); + await tester.pumpAndSettle(); + expect(preview.commits, 1); + expect(preview.value, same(committed)); + expect(preview.transforms.hasPending, isFalse); + await tester.pumpWidget(const SizedBox()); + preview.dispose(); + }); + + testWidgets('corner resizes video and exterior corner drag rotates', ( + tester, + ) async { + final preview = _Preview()..selectVisual(ElementId('upper')); + await mount(tester, preview); + final scale = await tester.startGesture(const Offset(365, 240)); + await scale.moveBy(const Offset(20, 20)); + await tester.pump(); + await scale.moveBy(const Offset(25, 10)); + await tester.pump(const Duration(milliseconds: 40)); + await scale.up(); + await tester.pumpAndSettle(); + expect(preview.value.scale, greaterThan(1)); + expect(preview.value.rotation, 0); + final visual = preview.visuals.last; + final center = const Offset(40, 40) + visual.geometry.center * .5; + final radial = Offset( + -visual.geometry.size.width * .25 - 12, + -visual.geometry.size.height * .25 - 12, + ); + final rotate = await tester.startGesture(center + radial); + await rotate.moveBy(const Offset(20, 0)); + await tester.pump(); + await rotate.moveTo(center + Offset(-radial.dy, radial.dx)); + await tester.pump(const Duration(milliseconds: 40)); + await rotate.up(); + await tester.pumpAndSettle(); + expect(preview.value.rotation, closeTo(90, .01)); + expect(preview.commits, 2); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + preview.dispose(); + }); +} + +class _Preview extends ChangeNotifier implements PreviewController { + @override + bool aspectRatioLocked = true; + _Preview({this.size = const Size(300, 200)}); + final Size size; + @override + final canvas = const ProjectCanvas(1000, 600); + ClipTransform value = const ClipTransform(); + ClipTransform? pending; + int commits = 0; + bool delayUpdates = false; + final delayedUpdates = []; + Completer? blockedBegin; + int _epoch = 0; + @override + late final transforms = PreviewTransformSession( + canBegin: () => true, + select: selectVisual, + prepareNative: () => beginTransform(ElementId('upper')), + updateNative: (_, value, rendered) { + if (delayUpdates) { + delayedUpdates.add(() { + updateTransform(value); + rendered(); + }); + } else { + updateTransform(value); + rendered(); + } + }, + commit: (_, next) { + value = next; + pending = null; + commits++; + notifyListeners(); + }, + cancelNative: cancelTransform, + failed: (error) => throw error, + changed: notifyListeners, + ); + @override + bool playing = false; + int pauses = 0; + @override + Future pauseForCanvasInteraction() async { + if (playing) { + playing = false; + pauses++; + } + } + + @override + bool transforming = false; + @override + Set selectedVisualIds = {}; + @override + List get visuals => transforms.project([ + for (final (id, lane) in [('lower', 0), ('upper', 1)]) + PreviewVisual( + layerId: id, + elementId: ElementId(id), + lane: lane, + transform: value, + geometry: PreviewGeometry( + center: const Offset(500, 300), + size: size, + ).changed(const ClipTransform(), value, const Size(1000, 600)), + ), + ], const Size(1000, 600)); + @override + void selectVisual(ElementId? id) { + selectedVisualIds = {?id}; + notifyListeners(); + } + + Future beginTransform(ElementId id) async { + if (transforming) return false; + final epoch = ++_epoch; + transforming = true; + await blockedBegin?.future; + return epoch == _epoch; + } + + void updateTransform(ClipTransform value) { + pending = value; + } + + @override + void cancelTransform() { + _epoch++; + pending = null; + transforming = false; + notifyListeners(); + } + + @override + dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} diff --git a/test/preview_panel_test.dart b/test/preview_panel_test.dart new file mode 100644 index 0000000..97686d7 --- /dev/null +++ b/test/preview_panel_test.dart @@ -0,0 +1,508 @@ +import 'package:cutdex/app/editor_theme.dart'; +import 'package:cutdex_ui/widgets.dart'; +import 'package:cutdex/workspace/timeline_provider.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex/features/properties/canvas_presets.dart'; + +import 'dart:async'; + +import 'package:cutdex/features/preview/preview_panel.dart'; +import 'package:cutdex_sdk/preview.dart'; +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex/workspace/media_availability.dart'; +import 'package:cutdex/workspace/preview_target.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'support/preview_fixture.dart'; + +void main() { + final surface = find.byKey(const Key('preview-surface')); + final toolbar = find.byKey(const Key('preview-toolbar')); + final canvas = find.byKey(const Key('preview-canvas')); + final playButton = find.byWidgetPredicate( + (widget) => widget is IconButton && widget.tooltip == '播放', + ); + + Future mount( + WidgetTester tester, + Future Function() load, { + ThemeData? theme, + MediaAvailability availability = MediaAvailability.available, + }) => tester.pumpWidget( + ProviderScope( + overrides: [ + mediaAvailabilityProvider.overrideWith( + (ref, key) async => availability, + ), + editorPreviewProvider( + 'project', + 'project', + ).overrideWith((ref) => load()), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + theme: theme ?? EditorTheme.penLight, + home: const Scaffold( + body: EditorPreviewPanel(projectId: 'project', timelineId: 'project'), + ), + ), + ), + ); + + testWidgets( + 'missing source shows the project placeholder and disables playback', + (tester) async { + final preview = _Preview(); + addTearDown(preview.dispose); + await mount( + tester, + () async => preview, + availability: MediaAvailability.missing, + ); + await tester.pumpAndSettle(); + final container = ProviderScope.containerOf( + tester.element(find.byType(EditorPreviewPanel)), + ); + container + .read(previewTargetProvider('project', 'project')) + .showAsset( + AssetDocument( + id: 'missing', + name: 'missing.mov', + storage: AssetStorage.external, + location: 'file:///missing.mov', + ), + ); + await tester.pumpAndSettle(); + expect(find.text('素材缺失'), findsOneWidget); + expect(find.byIcon(Icons.broken_image_outlined), findsOneWidget); + expect(find.textContaining('RuntimeException'), findsNothing); + expect(tester.widget(playButton).onPressed, isNull); + expect(find.byTooltip('画布比例'), findsNothing); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + }, + ); + + testWidgets('workspace follows theme while canvas content stays dark', ( + tester, + ) async { + final preview = _Preview()..error = 'Preview error'; + addTearDown(preview.dispose); + for (final theme in [EditorTheme.penLight, EditorTheme.penDark]) { + await mount(tester, () async => preview, theme: theme); + await tester.pumpAndSettle(); + expect( + tester.widget(surface).color, + theme.colorScheme.surface, + ); + expect(tester.widget(canvas).color, Colors.black); + expect(Theme.of(tester.element(toolbar)).brightness, theme.brightness); + expect( + Theme.of(tester.element(find.text('Preview error'))).brightness, + Brightness.dark, + ); + } + }); + + testWidgets('preview has a fixed toolbar below flexible video', ( + tester, + ) async { + final preview = _Preview(); + addTearDown(preview.dispose); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetDevicePixelRatio); + addTearDown(tester.view.resetPhysicalSize); + await mount(tester, () async => preview); + await tester.pumpAndSettle(); + + for (final size in [const Size(640, 400), const Size(240, 180)]) { + tester.view.physicalSize = size; + await tester.pumpAndSettle(); + final videoRect = tester.getRect(surface); + final canvasRect = tester.getRect(canvas); + final toolbarRect = tester.getRect(toolbar); + expect(find.text('视频预览'), findsNothing); + expect(videoRect.left, AppSpacing.panelContentHorizontal); + expect(videoRect.right, size.width - AppSpacing.panelContentHorizontal); + expect(videoRect.top, AppSpacing.small); + expect(videoRect.bottom, toolbarRect.top - AppSpacing.small); + expect(canvasRect.center.dx, closeTo(videoRect.center.dx, 0.01)); + expect(canvasRect.center.dy, closeTo(videoRect.center.dy, 0.01)); + expect(toolbarRect.bottom, size.height); + expect(toolbarRect.height, AppControlSize.panelHeader); + expect(tester.getCenter(find.byTooltip('播放')).dx, size.width / 2); + expect( + find.descendant( + of: toolbar, + matching: find.text('00:00:00:00 / 02:00:00:00'), + ), + findsOneWidget, + ); + expect(Theme.of(tester.element(surface)).brightness, Brightness.light); + expect(Theme.of(tester.element(toolbar)).brightness, Brightness.light); + expect(tester.takeException(), isNull); + } + + await tester.tap(find.byTooltip('播放')); + await tester.pump(); + expect(preview.playing, isTrue); + expect(find.byTooltip('暂停播放'), findsOneWidget); + preview.moveTo(3661 * TimelineClock.ticksPerSecond); + await tester.pump(); + expect(find.text('01:01:01:00 / 02:00:00:00'), findsOneWidget); + await tester.tap(find.byTooltip('暂停播放')); + await tester.pump(); + expect(preview.playing, isFalse); + await tester.pumpWidget(const SizedBox()); + }); + + testWidgets('empty timeline does not render a video canvas', (tester) async { + final preview = _Preview()..durationTick = 0; + addTearDown(preview.dispose); + await mount(tester, () async => preview); + await tester.pumpAndSettle(); + + expect(canvas, findsNothing); + expect(find.byKey(const Key('empty-preview-area')), findsOneWidget); + expect(find.text('暂无可预览内容'), findsNothing); + expect(toolbar, findsOneWidget); + expect(tester.takeException(), isNull); + + preview.durationTick = TimelineClock.ticksPerSecond; + preview.notifyListeners(); + await tester.pump(); + expect(canvas, findsOneWidget); + expect(find.byKey(const Key('empty-preview-area')), findsNothing); + + preview.durationTick = 0; + preview.notifyListeners(); + await tester.pump(); + expect(canvas, findsNothing); + expect(find.byKey(const Key('empty-preview-area')), findsOneWidget); + await tester.pumpWidget(const SizedBox()); + }); + + testWidgets('empty timeline skips native preview initialization', ( + tester, + ) async { + final empty = TimelineDto( + id: SequenceId('one'), + name: 'Empty', + format: TimelineFormat.fps30, + primaryStorylineId: StorylineId('primary'), + storylines: [ + StorylineDto(id: StorylineId('primary'), elementIds: const []), + ], + elements: const [], + ); + final fixture = (await tester.runAsync( + () => createPreviewFixture( + Uri.file('/unused.mov'), + timelineOverride: empty, + ), + ))!; + addTearDown(() async { + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + }); + final calls = []; + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + const runtimeChannel = MethodChannel('cutdex_runtime'); + messenger.setMockMethodCallHandler(runtimeChannel, (call) async { + calls.add(call); + return null; + }); + addTearDown(() => messenger.setMockMethodCallHandler(runtimeChannel, null)); + final ids = (fixture.workspace.project!.info.id, 'project'); + + await tester.pumpWidget( + ProviderScope( + overrides: [ + editorTimelineProvider( + ids.$1, + ids.$2, + ).overrideWith((ref) async => fixture.timeline), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + theme: EditorTheme.penLight, + home: Scaffold( + body: EditorPreviewPanel(projectId: ids.$1, timelineId: ids.$2), + ), + ), + ), + ); + await tester.pumpAndSettle(); + + expect(find.byKey(const Key('empty-preview-area')), findsOneWidget); + expect(canvas, findsNothing); + expect(find.byType(CircularProgressIndicator), findsNothing); + expect(calls, isEmpty); + expect(tester.takeException(), isNull); + }); + + testWidgets('time display follows project frames and duration changes', ( + tester, + ) async { + final preview = _Preview() + ..frameDuration = TimelineFormat.fps25.frameDuration; + addTearDown(preview.dispose); + final frame = TimelineClock.standard.toTicks(preview.frameDuration); + preview.durationTick = 129 * frame; + preview.positionTick = 15 * frame; + await mount(tester, () async => preview); + await tester.pumpAndSettle(); + expect(find.text('00:00:00:15 / 00:00:05:04'), findsOneWidget); + preview.durationTick = 150 * frame; + preview.moveTo(25 * frame); + await tester.pump(); + expect(find.text('00:00:01:00 / 00:00:06:00'), findsOneWidget); + await tester.pumpWidget(const SizedBox()); + }); + + testWidgets('editor failure retry recreates the editor provider', ( + tester, + ) async { + var attempts = 0; + await tester.pumpWidget( + ProviderScope( + overrides: [ + editorTimelineProvider('project', 'project').overrideWith(( + ref, + ) async { + attempts++; + throw StateError('checkpoint failed'); + }), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + theme: EditorTheme.penLight, + home: const Scaffold( + body: EditorPreviewPanel( + projectId: 'project', + timelineId: 'project', + ), + ), + ), + ), + ); + for (var i = 0; i < 20 && find.text('无法打开时间线编辑器').evaluate().isEmpty; i++) { + await tester.pump(const Duration(milliseconds: 10)); + } + await tester.pumpAndSettle(); + expect(find.text('无法打开时间线编辑器'), findsOneWidget); + expect(attempts, 1); + await tester.tap(find.text('重试')); + await tester.pumpAndSettle(); + expect(attempts, 2); + expect(find.text('无法启动原生预览'), findsNothing); + await tester.pumpWidget(const SizedBox()); + }); + + testWidgets( + 'editor startup failure is distinct from native preview failure', + (tester) async { + await mount( + tester, + () async => + throw EditorSessionStartupException(StateError('checkpoint')), + ); + for ( + var i = 0; + i < 20 && find.text('无法打开时间线编辑器').evaluate().isEmpty; + i++ + ) { + await tester.pump(const Duration(milliseconds: 10)); + } + await tester.pumpAndSettle(); + expect(find.text('无法打开时间线编辑器'), findsOneWidget); + expect(find.text('无法启动原生预览'), findsNothing); + expect(find.text('重试'), findsOneWidget); + expect(tester.widget(playButton).onPressed, isNull); + await tester.pumpWidget(const SizedBox()); + }, + ); + + testWidgets('loading and initialization failure keep the toolbar disabled', ( + tester, + ) async { + final pending = Completer(); + var loads = 0; + await mount(tester, () { + loads++; + return pending.future; + }); + final loadingRect = tester.getRect(toolbar); + expect(find.text('00:00:00:00 / 00:00:00:00'), findsOneWidget); + expect(tester.widget(playButton).onPressed, isNull); + pending.completeError(StateError('unavailable')); + await tester.pumpAndSettle(); + expect(find.text('无法启动原生预览'), findsOneWidget); + expect(tester.getRect(toolbar), loadingRect); + expect(tester.widget(playButton).onPressed, isNull); + await tester.tap(find.text('重试')); + await tester.pumpAndSettle(); + expect(loads, 2); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + }); + + testWidgets( + 'canvas ratio changes independently of the workspace and toolbar', + (tester) async { + final preview = _Preview(); + addTearDown(preview.dispose); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetDevicePixelRatio); + addTearDown(tester.view.resetPhysicalSize); + await mount(tester, () async => preview); + await tester.pumpAndSettle(); + for (final size in [const Size(640, 400), const Size(240, 180)]) { + tester.view.physicalSize = size; + await tester.pumpAndSettle(); + final toolbarRect = tester.getRect(toolbar); + final surfaceRect = tester.getRect(surface); + for (final entry in ProjectCanvasPresets.values.entries) { + await tester.tap(find.byType(AppSelect)); + await tester.pumpAndSettle(); + final item = find.text(entry.key).last; + await tester.ensureVisible(item); + await tester.pumpAndSettle(); + await tester.tap(item); + await tester.pumpAndSettle(); + final rect = tester.getRect(canvas); + expect( + rect.width / rect.height, + closeTo(entry.value.aspectRatio, 0.000001), + ); + expect(rect.center.dx, closeTo(surfaceRect.center.dx, 0.000001)); + expect(rect.top, closeTo(surfaceRect.top, 0.000001)); + expect(rect.left, greaterThan(surfaceRect.left)); + expect(rect.right, lessThan(surfaceRect.right)); + expect(rect.bottom, lessThanOrEqualTo(surfaceRect.bottom + 0.000001)); + expect(tester.getRect(toolbar), toolbarRect); + expect( + tester.widget(canvas).color, + isNot(tester.widget(surface).color), + ); + expect(tester.takeException(), isNull); + } + } + await tester.pumpWidget(const SizedBox()); + }, + ); + + testWidgets('offline media keeps playback available with a local notice', ( + tester, + ) async { + final preview = _Preview() + ..hasUnavailableMedia = true + ..unavailableAtPlayhead = ['image']; + addTearDown(preview.dispose); + await mount(tester, () async => preview); + await tester.pumpAndSettle(); + expect(find.text('素材离线或不可用:image'), findsOneWidget); + expect(tester.widget(playButton).onPressed, isNotNull); + expect(find.byTooltip('重试预览'), findsOneWidget); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + }); + + testWidgets('playback failure offers retry in the bottom toolbar', ( + tester, + ) async { + final preview = _Preview()..error = '预览失败'; + addTearDown(preview.dispose); + await mount(tester, () async => preview); + await tester.pumpAndSettle(); + expect(tester.widget(playButton).onPressed, isNull); + expect( + find.descendant(of: toolbar, matching: find.byTooltip('重试预览')), + findsOneWidget, + ); + await tester.tap(find.byTooltip('重试预览')); + await tester.pump(); + expect(preview.retries, 1); + expect(find.byTooltip('重试预览'), findsNothing); + expect(tester.widget(playButton).onPressed, isNotNull); + await tester.pumpWidget(const SizedBox()); + }); +} + +class _Preview extends ChangeNotifier implements PreviewController { + @override + Listenable get positionChanges => this; + + @override + bool hasUnavailableMedia = false; + @override + List unavailableAtPlayhead = []; + @override + ProjectCanvas canvas = ProjectCanvas.widescreen; + + @override + void setCanvas(ProjectCanvas value) { + canvas = value; + notifyListeners(); + } + + @override + RuntimeSession? get session => null; + @override + bool playing = false; + @override + bool busy = false; + @override + Object? error; + @override + int positionTick = 0; + @override + int durationTick = 7200 * TimelineClock.ticksPerSecond; + @override + RationalTime frameDuration = TimelineFormat.fps30.frameDuration; + @override + bool get canPlay => !busy && error == null; + int retries = 0; + + void moveTo(int tick) { + positionTick = tick; + notifyListeners(); + } + + @override + Future togglePlayback() async { + playing = !playing; + notifyListeners(); + } + + @override + Future pauseForCanvasInteraction() async { + playing = false; + } + + @override + Future retry() async { + retries++; + error = null; + notifyListeners(); + } + + @override + dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); +} diff --git a/test/processing_configuration_test.dart b/test/processing_configuration_test.dart new file mode 100644 index 0000000..c7faab3 --- /dev/null +++ b/test/processing_configuration_test.dart @@ -0,0 +1,100 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; + +import 'support/processing_fixture.dart'; + +import 'package:cutdex/integrations/runtime/processing_configuration.dart'; + +void main() { + for (var mask = 0; mask < 16; mask++) { + test('processing capabilities are independent: $mask', () async { + final root = await Directory.systemTemp.createTemp('processing-matrix-'); + addTearDown(() => root.delete(recursive: true)); + final config = await processingFixture(root, mask); + expect(config.transcriptionModel != null, mask & 1 != 0); + expect(config.translationModel != null, mask & 2 != 0); + expect(config.vocalSeparationModel != null, mask & 4 != 0); + expect(config.backgroundRemovalModel != null, mask & 8 != 0); + }); + } + test( + 'stale model paths and missing runtime disable optional capabilities', + () async { + final root = await Directory.systemTemp.createTemp('processing-stale-'); + addTearDown(() => root.delete(recursive: true)); + final config = await processingFixture(root, 7, stale: true); + expect(config.transcriptionModel, isNull); + expect(config.translationModel, isNull); + expect(config.vocalSeparationModel, isNull); + expect(config.backgroundRemovalModel, isNull); + expect( + ProcessingConfiguration.fromPaths( + root: '${root.path}/missing', + transcriptionPath: '${root.path}/asr', + translationPath: '${root.path}/translation', + vocalPath: '${root.path}/audio/melband.pt', + ), + isNull, + ); + }, + ); + + test('translation configuration is independent of ASR, audio models and FFmpeg', () async { + final suffix = Platform.isWindows ? '.exe' : ''; + final root = await Directory.systemTemp.createTemp('cutdex configuration '); + try { + for (final path in [ + 'runtime/bin/cutdex-processing-worker$suffix', + 'runtime/workers/translation/cutdex-m2m100-worker$suffix', + 'Documents/Cutdex/Resources/Processing/Translation/m2m100-418m/1/model.bin', + 'Documents/Cutdex/Resources/Processing/Translation/m2m100-418m/1/config.json', + 'Documents/Cutdex/Resources/Processing/Translation/m2m100-418m/1/shared_vocabulary.json', + 'Documents/Cutdex/Resources/Processing/Translation/m2m100-418m/1/sentencepiece.bpe.model', + ]) { + final file = File('${root.path}/$path'); + await file.parent.create(recursive: true); + await file.writeAsString('fixture'); + } + final script = File('${root.path}/configuration.dart'); + await script.writeAsString(''' +import 'dart:convert'; +import 'package:cutdex/integrations/runtime/processing_configuration.dart'; +void main() { + final config = ProcessingConfiguration.configured()!; + print(jsonEncode({ + 'translation': config.translationModel != null, + 'transcription': config.transcriptionModel != null, + 'vocals': config.vocalSeparationModel != null, + 'inheritsEnvironment': config.backend.includeParentEnvironment, + 'provider': config.backend.environment['CUTDEX_ORT_PROVIDER'], + })); +} +'''); + final result = await Process.run( + 'dart', + [ + '--packages=${File('.dart_tool/package_config.json').absolute.path}', + script.path, + ], + runInShell: Platform.isWindows, + environment: { + 'HOME': root.path, + 'USERPROFILE': root.path, + 'CUTDEX_PROCESSING_ROOT': '${root.path}/runtime', + }, + ); + expect(result.exitCode, 0, reason: result.stderr.toString()); + expect(jsonDecode(result.stdout as String), { + 'translation': true, + 'transcription': false, + 'vocals': false, + 'inheritsEnvironment': false, + 'provider': 'cpu', + }); + } finally { + await root.delete(recursive: true); + } + }, skip: !(Platform.isMacOS || Platform.isWindows)); +} diff --git a/test/processing_resource_download_dialog_test.dart b/test/processing_resource_download_dialog_test.dart new file mode 100644 index 0000000..7f9863d --- /dev/null +++ b/test/processing_resource_download_dialog_test.dart @@ -0,0 +1,69 @@ +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex/shared/widgets/processing_resource_download_dialog.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets('resource download keeps the same actions across phases', ( + tester, + ) async { + var cancelled = 0; + var downloaded = 0; + var paused = 0; + var backgrounded = 0; + + Future show({bool downloading = false, bool isPaused = false}) => + tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + home: Scaffold( + body: ProcessingResourceDownloadDialog( + title: '下载抠像资源', + description: '下载完成后自动开始抠像。', + resourceName: '抠像模型', + downloadSize: '需下载 973 MB', + downloading: downloading, + paused: isPaused, + downloadedBytes: 250, + totalBytes: 1000, + bytesPerSecond: 100, + onCancel: () => cancelled++, + onDownload: () => downloaded++, + onTogglePause: () => paused++, + onBackground: () => backgrounded++, + ), + ), + ), + ); + + await show(); + expect(find.text('下载抠像资源'), findsOneWidget); + expect(find.text('下载完成后自动开始抠像。'), findsOneWidget); + expect(find.text('需下载 973 MB'), findsOneWidget); + expect(find.text('取消'), findsOneWidget); + expect(find.text('下载'), findsOneWidget); + expect(find.text('后台下载'), findsNothing); + await tester.tap(find.text('下载')); + expect(downloaded, 1); + + await show(downloading: true); + expect(find.text('需下载 973 MB'), findsNothing); + expect(find.text('抠像模型'), findsOneWidget); + expect(find.text('25%'), findsOneWidget); + expect(find.text('取消下载'), findsOneWidget); + expect(find.text('暂停'), findsOneWidget); + expect(find.text('后台下载'), findsOneWidget); + await tester.tap(find.text('暂停')); + await tester.tap(find.text('后台下载')); + expect(paused, 1); + expect(backgrounded, 1); + + await show(downloading: true, isPaused: true); + expect(find.text('已暂停'), findsOneWidget); + expect(find.text('继续'), findsOneWidget); + await tester.tap(find.text('取消下载')); + expect(cancelled, 1); + }); +} diff --git a/test/processing_resource_repository_test.dart b/test/processing_resource_repository_test.dart new file mode 100644 index 0000000..aa4b87a --- /dev/null +++ b/test/processing_resource_repository_test.dart @@ -0,0 +1,604 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:crypto/crypto.dart'; +import 'package:cutdex/errors/app_failure.dart'; +import 'package:cutdex/integrations/runtime/processing_resource_repository.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:cutdex/integrations/runtime/processing_resource_state.dart'; + +void main() { + test('disposing the resource owner cancels a pending subtitle bundle without late notifications', () async { + final fixture = await _subtitleFixture(); + var disposed = false; + await expectLater( + fixture.repository.ensureSubtitleResources( + onProgress: (_, _) { + if (!disposed) { + disposed = true; + fixture.repository.dispose(); + } + }, + ), + throwsA(isA()), + ); + expect(fixture.requests, isEmpty); + }); + + test( + 'resource snapshots freeze installed states and observe bundle completion', + () async { + final fixture = await _subtitleFixture(); + final container = ProviderContainer(); + addTearDown(container.dispose); + final provider = processingResourcesProvider(fixture.repository); + final updates = []; + container.listen( + provider, + (_, next) => updates.add(next), + fireImmediately: true, + ); + final before = container.read(provider); + await fixture.repository.ensureSubtitleResources(onProgress: (_, _) {}); + final after = container.read(provider); + expect(updates.any((value) => value.subtitleDownloading), isTrue); + expect(after.subtitleDownloading, isFalse); + expect(after.subtitleDownloadedBytes, after.subtitleTotalBytes); + expect( + after.installs.every( + (value) => value.state == ProcessingResourceState.installed, + ), + isTrue, + ); + expect( + before.installs.any( + (value) => value.state == ProcessingResourceState.installed, + ), + isFalse, + ); + }, + ); + + test( + 'subtitle bundle downloads both models with one monotonic byte progress', + () async { + final fixture = await _subtitleFixture(); + final reports = <(ProcessingCapability, double)>[]; + expect(fixture.repository.subtitleTotalBytes, 80); + await fixture.repository.ensureSubtitleResources( + onProgress: (stage, progress) { + reports.add((stage, progress)); + if (stage == ProcessingCapability.translation && progress == .25) { + expect(fixture.repository.subtitleDownloadedBytes, 20); + expect(fixture.repository.subtitleDownloading, isTrue); + } + }, + ); + expect(fixture.repository.subtitleDownloading, isFalse); + expect(fixture.requests, ['transcription', 'translation']); + expect(reports.first.$2, 0); + expect(reports.last.$2, 1); + expect( + reports + .where((entry) => entry.$1 == ProcessingCapability.translation) + .first + .$2, + 0.25, + ); + for (var i = 1; i < reports.length; i++) { + expect(reports[i].$2, greaterThanOrEqualTo(reports[i - 1].$2)); + } + expect( + fixture.repository.installs.every( + (install) => install.state == ProcessingResourceState.installed, + ), + isTrue, + ); + await fixture.repository.ensureSubtitleResources(onProgress: (_, _) {}); + expect(fixture.requests, ['transcription', 'translation']); + }, + ); + + test( + 'subtitle bundle skips configured speech and still installs translation', + () async { + final fixture = await _subtitleFixture(); + final reports = <(ProcessingCapability, double)>[]; + await fixture.repository.ensureSubtitleResources( + available: {ProcessingCapability.transcription}, + onProgress: (stage, progress) => reports.add((stage, progress)), + ); + expect(fixture.requests, ['translation']); + expect(reports.first, (ProcessingCapability.translation, 0.25)); + expect(reports.last.$2, 1); + }, + ); + + test('pausing a subtitle download keeps its bytes and resumes the same request', () async { + final root = await Directory.systemTemp.createTemp('subtitle-pause-'); + final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + final firstChunk = List.filled(10, 1); + final secondChunk = List.filled(10, 2); + final speech = [...firstChunk, ...secondChunk]; + final translation = List.filled(5, 3); + final requests = []; + final releaseSecondChunk = Completer(); + final secondChunkSent = Completer(); + server.listen((request) async { + final name = request.uri.pathSegments.single; + requests.add(name); + if (name == 'transcription') { + request.response.bufferOutput = false; + request.response.contentLength = speech.length; + request.response.add(firstChunk); + await request.response.flush(); + await releaseSecondChunk.future; + request.response.add(secondChunk); + await request.response.flush(); + secondChunkSent.complete(); + } else { + request.response.contentLength = translation.length; + request.response.add(translation); + } + await request.response.close(); + }); + final repository = ProcessingResourceRepository( + root: root, + catalog: [ + for (final (capability, payload) in [ + (ProcessingCapability.transcription, speech), + (ProcessingCapability.translation, translation), + ]) + ProcessingResourcePackage( + capability: capability, + id: capability.name, + version: '1', + name: capability.name, + description: '', + artifacts: [ + ProcessingResourceArtifact( + path: 'model.bin', + url: Uri.parse( + 'http://127.0.0.1:${server.port}/${capability.name}', + ), + sha256: sha256.convert(payload).toString(), + bytes: payload.length, + ), + ], + ), + ], + ); + addTearDown(() async { + if (!releaseSecondChunk.isCompleted) releaseSecondChunk.complete(); + repository.dispose(); + await server.close(force: true); + await root.delete(recursive: true); + }); + final paused = Completer(); + final progress = []; + final download = repository.ensureSubtitleResources( + onProgress: (stage, value) { + progress.add(value); + if (stage == ProcessingCapability.transcription && + repository.installFor(stage).downloadedBytes == firstChunk.length && + !paused.isCompleted) { + paused.complete(); + repository.pauseSubtitleResources(); + } + }, + ); + await paused.future.timeout( + const Duration(seconds: 5), + onTimeout: () => throw StateError( + 'first chunk was not observed: requests=$requests progress=$progress ' + 'install=${repository.installFor(ProcessingCapability.transcription).downloadedBytes}', + ), + ); + expect(repository.subtitlePaused, isTrue); + final atPause = progress.last; + releaseSecondChunk.complete(); + await secondChunkSent.future.timeout( + const Duration(seconds: 5), + onTimeout: () => throw StateError('server did not send the second chunk'), + ); + await Future.delayed(const Duration(milliseconds: 30)); + expect(progress.last, atPause); + expect( + repository.installFor(ProcessingCapability.transcription).downloadedBytes, + firstChunk.length, + ); + repository.resumeSubtitleResources(); + await download.timeout( + const Duration(seconds: 5), + onTimeout: () => throw StateError('download did not resume'), + ); + expect(repository.subtitlePaused, isFalse); + expect(requests, ['transcription', 'translation']); + expect(progress.last, 1); + }); + + test('download speed remains available without a progress widget', () async { + final root = await Directory.systemTemp.createTemp('resource-speed-'); + final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + final releaseLastChunk = Completer(); + final payload = [ + ...List.filled(10, 1), + ...List.filled(10, 2), + ...List.filled(10, 3), + ]; + server.listen((request) async { + request.response.bufferOutput = false; + request.response.contentLength = payload.length; + request.response.add(payload.sublist(0, 10)); + await request.response.flush(); + await Future.delayed(const Duration(milliseconds: 550)); + request.response.add(payload.sublist(10, 20)); + await request.response.flush(); + await releaseLastChunk.future; + request.response.add(payload.sublist(20)); + await request.response.close(); + }); + final repository = ProcessingResourceRepository( + root: root, + catalog: [ + ProcessingResourcePackage( + capability: ProcessingCapability.backgroundRemoval, + id: 'speed-test', + version: '1', + name: 'Speed test', + description: '', + artifacts: [ + ProcessingResourceArtifact( + path: 'model.bin', + url: Uri.parse('http://127.0.0.1:${server.port}/model'), + sha256: sha256.convert(payload).toString(), + bytes: payload.length, + ), + ], + ), + ], + ); + addTearDown(() async { + if (!releaseLastChunk.isCompleted) releaseLastChunk.complete(); + repository.dispose(); + await server.close(force: true); + await root.delete(recursive: true); + }); + final secondChunk = Completer(); + repository.addListener(() { + if (repository + .installFor(ProcessingCapability.backgroundRemoval) + .downloadedBytes == + 20 && + !secondChunk.isCompleted) { + secondChunk.complete(); + } + }); + final download = repository.ensureAvailable( + ProcessingCapability.backgroundRemoval, + ); + await secondChunk.future.timeout(const Duration(seconds: 5)); + expect( + repository.downloadBytesPerSecondFor( + ProcessingCapability.backgroundRemoval, + ), + greaterThan(0), + ); + repository.pauseDownload(ProcessingCapability.backgroundRemoval); + expect( + repository.downloadPausedFor(ProcessingCapability.backgroundRemoval), + isTrue, + ); + expect( + repository.downloadBytesPerSecondFor( + ProcessingCapability.backgroundRemoval, + ), + 0, + ); + releaseLastChunk.complete(); + await Future.delayed(const Duration(milliseconds: 30)); + expect( + repository + .installFor(ProcessingCapability.backgroundRemoval) + .downloadedBytes, + 20, + ); + repository.resumeDownload(ProcessingCapability.backgroundRemoval); + await download.timeout(const Duration(seconds: 5)); + expect( + repository.downloadPausedFor(ProcessingCapability.backgroundRemoval), + isFalse, + ); + expect( + repository.downloadBytesPerSecondFor( + ProcessingCapability.backgroundRemoval, + ), + 0, + ); + }); + + test( + 'cancelling between models stops translation and retry reuses speech', + () async { + final fixture = await _subtitleFixture(); + await expectLater( + fixture.repository.ensureSubtitleResources( + onProgress: (stage, progress) { + if (stage == ProcessingCapability.transcription && + fixture.repository.installFor(stage).state == + ProcessingResourceState.installed) { + fixture.repository.cancelSubtitleResources(); + } + }, + ), + throwsA(isA()), + ); + expect(fixture.requests, ['transcription']); + await fixture.repository.ensureSubtitleResources(onProgress: (_, _) {}); + expect(fixture.requests, ['transcription', 'translation']); + }, + ); + + test( + 'cancelling a paused subtitle download releases the pause gate', + () async { + final fixture = await _subtitleFixture(); + final paused = Completer(); + final download = fixture.repository.ensureSubtitleResources( + onProgress: (stage, progress) { + if (stage == ProcessingCapability.transcription && + progress == 0 && + !paused.isCompleted) { + paused.complete(); + fixture.repository.pauseSubtitleResources(); + } + }, + ); + await paused.future.timeout(const Duration(seconds: 5)); + fixture.repository.cancel(ProcessingCapability.transcription); + await expectLater( + download.timeout(const Duration(seconds: 5)), + throwsA(isA()), + ); + expect(fixture.repository.subtitlePaused, isFalse); + }, + ); + + test( + 'translation verification failure keeps speech and can be retried', + () async { + final fixture = await _subtitleFixture(corruptTranslationOnce: true); + await expectLater( + fixture.repository.ensureSubtitleResources(onProgress: (_, _) {}), + throwsA( + isA().having( + (error) => error.failure.code, + 'code', + AppErrorCode.resourceChecksumFailed, + ), + ), + ); + expect( + fixture.repository.installFor(ProcessingCapability.transcription).state, + ProcessingResourceState.installed, + ); + expect( + fixture.repository.installFor(ProcessingCapability.translation).state, + ProcessingResourceState.failed, + ); + await fixture.repository.ensureSubtitleResources(onProgress: (_, _) {}); + expect(fixture.requests, ['transcription', 'translation', 'translation']); + }, + ); + + test( + 'downloads, verifies and atomically publishes a processing resource', + () async { + final root = await Directory.systemTemp.createTemp('cutdex-models-'); + final payload = utf8.encode('verified model'); + final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + server.listen((request) async { + request.response.add(payload); + await request.response.close(); + }); + addTearDown(() async { + await server.close(force: true); + await root.delete(recursive: true); + }); + final package = ProcessingResourcePackage( + capability: ProcessingCapability.transcription, + id: 'test-model', + version: '7', + name: 'Test', + description: 'Test model', + artifacts: [ + ProcessingResourceArtifact( + path: 'model.bin', + url: Uri.parse('http://127.0.0.1:${server.port}/model'), + sha256: sha256.convert(payload).toString(), + bytes: payload.length, + ), + ], + ); + final repository = ProcessingResourceRepository( + root: root, + catalog: [package], + ); + + await repository.ensureAvailable(ProcessingCapability.transcription); + + expect( + repository.installs.single.state, + ProcessingResourceState.installed, + ); + expect( + File('${root.path}/Transcription/test-model/7/model.bin') + .readAsBytesSync(), + payload, + ); + expect( + Directory('${root.path}/Transcription/test-model/7.download') + .existsSync(), + false, + ); + }, + ); + + test( + 'HTTP download failure retains its status code in the install state', + () async { + final root = await Directory.systemTemp.createTemp('cutdex-http-error-'); + final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + server.listen((request) async { + request.response.statusCode = 503; + await request.response.close(); + }); + final repository = ProcessingResourceRepository( + root: root, + catalog: [ + ProcessingResourcePackage( + capability: ProcessingCapability.transcription, + id: 'http-test', + version: '1', + name: 'Test', + description: 'Test', + artifacts: [ + ProcessingResourceArtifact( + path: 'model.bin', + url: Uri.parse('http://127.0.0.1:${server.port}/model'), + sha256: List.filled(64, '0').join(), + bytes: 1, + ), + ], + ), + ], + ); + addTearDown(() async { + repository.dispose(); + await server.close(force: true); + await root.delete(recursive: true); + }); + await expectLater( + repository.ensureAvailable(ProcessingCapability.transcription), + throwsA(isA()), + ); + final install = repository.installs.single; + expect(install.state, ProcessingResourceState.failed); + expect(install.error?.code, AppErrorCode.resourceDownloadHttpFailed); + expect(install.error?.httpStatusCode, 503); + expect(await repository.directoryFor(install.package).exists(), isFalse); + }, + ); + + test('does not publish a resource with a mismatched checksum', () async { + final root = await Directory.systemTemp.createTemp('cutdex-models-'); + final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + server.listen((request) async { + request.response.write('corrupt'); + await request.response.close(); + }); + addTearDown(() async { + await server.close(force: true); + await root.delete(recursive: true); + }); + final package = ProcessingResourcePackage( + capability: ProcessingCapability.transcription, + id: 'test-model', + version: '1', + name: 'Test', + description: 'Test model', + artifacts: [ + ProcessingResourceArtifact( + path: 'model.bin', + url: Uri.parse('http://127.0.0.1:${server.port}/model'), + sha256: List.filled(64, '0').join(), + bytes: 7, + ), + ], + ); + final repository = ProcessingResourceRepository( + root: root, + catalog: [package], + ); + + await expectLater( + repository.ensureAvailable(ProcessingCapability.transcription), + throwsA( + isA().having( + (error) => error.failure.code, + 'code', + AppErrorCode.resourceChecksumFailed, + ), + ), + ); + + expect(repository.installs.single.state, ProcessingResourceState.failed); + expect( + repository.installs.single.error?.code, + AppErrorCode.resourceChecksumFailed, + ); + expect( + Directory('${root.path}/Transcription/test-model/1').existsSync(), + false, + ); + expect( + Directory('${root.path}/Transcription/test-model/1.download') + .existsSync(), + false, + ); + }); +} + +Future<({ProcessingResourceRepository repository, List requests})> +_subtitleFixture({bool corruptTranslationOnce = false}) async { + final root = await Directory.systemTemp.createTemp('subtitle-bundle-'); + final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + final requests = []; + final data = { + ProcessingCapability.transcription: List.filled(20, 1), + ProcessingCapability.translation: List.filled(60, 2), + }; + final repository = ProcessingResourceRepository( + root: root, + catalog: [ + for (final entry in data.entries) + ProcessingResourcePackage( + capability: entry.key, + id: entry.key.name, + version: '1', + name: entry.key.name, + description: '', + artifacts: [ + ProcessingResourceArtifact( + path: 'model.bin', + url: Uri.parse( + 'http://127.0.0.1:${server.port}/${entry.key.name}', + ), + sha256: sha256.convert(entry.value).toString(), + bytes: entry.value.length, + ), + ], + ), + ], + ); + server.listen((request) async { + final name = request.uri.pathSegments.single; + requests.add(name); + final payload = data[ProcessingCapability.values.byName(name)]!; + if (name == 'translation' && corruptTranslationOnce) { + corruptTranslationOnce = false; + request.response.add(List.filled(payload.length, 0)); + } else { + request.response.add(payload); + } + await request.response.close(); + }); + addTearDown(() async { + repository.dispose(); + await server.close(force: true); + await root.delete(recursive: true); + }); + return (repository: repository, requests: requests); +} diff --git a/test/project_creation_localization_test.dart b/test/project_creation_localization_test.dart new file mode 100644 index 0000000..b5a625f --- /dev/null +++ b/test/project_creation_localization_test.dart @@ -0,0 +1,90 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:cutdex/features/settings/language_settings.dart'; +import 'package:cutdex/persistence/app_settings_repositories.dart'; +import 'package:cutdex/workspace/persistence/recent_projects.dart'; +import 'package:cutdex/workspace/projects.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'support/memory_app_settings.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + test( + 'creation waits for saved language and later changes only new names', + () async { + final root = await Directory.systemTemp.createTemp( + 'cutdex-creation-locale-', + ); + final repository = _DelayedLanguageRepository(); + final container = ProviderContainer( + overrides: [ + languageSettingsRepositoryProvider.overrideWithValue(repository), + recentProjectsProvider.overrideWithValue( + MemoryRecentProjectsRepository(), + ), + resourceLocationSettingsRepositoryProvider.overrideWithValue( + MemoryResourceLocationSettingsRepository(root.path), + ), + ], + ); + final projects = container.read(projectsProvider.notifier); + addTearDown(() async { + await projects.prepareToQuit(); + container.dispose(); + await root.delete(recursive: true); + }); + + final opening = projects.open('${root.path}/My.cutdex', name: 'My name'); + await repository.loadStarted.future; + expect(await Directory('${root.path}/My.cutdex').exists(), isFalse); + repository.loaded.complete(AppLanguage.traditionalChinese); + expect(await opening, isTrue); + final initial = container.read(projectsProvider).requireValue; + expect(initial.activeProject!.name, 'My name'); + expect(initial.timeline!.name, '時間軸 1'); + expect(initial.timeline!.sequences.single.name, '主序列'); + expect(initial.timeline!.sequences.single.storylines.single.name, '主線'); + + await container + .read(languageSettingsProvider.notifier) + .setLanguage(AppLanguage.english); + expect(await projects.createTimeline(name: 'User title'), isTrue); + final added = container.read(projectsProvider).requireValue; + expect(added.timeline!.name, 'User title'); + expect(added.timeline!.sequences.single.name, 'Main sequence'); + expect( + added.timeline!.sequences.single.storylines.single.name, + 'Main storyline', + ); + expect( + await projects.openTimeline( + initial.activeProject!.id, + initial.timeline!.id, + ), + isTrue, + ); + final retained = container.read(projectsProvider).requireValue; + expect(retained.activeProject!.name, 'My name'); + expect(retained.timeline!.name, '時間軸 1'); + expect(retained.timeline!.sequences.single.name, '主序列'); + }, + ); +} + +class _DelayedLanguageRepository implements LanguageSettingsRepository { + final loaded = Completer(); + final loadStarted = Completer(); + + @override + Future load() { + loadStarted.complete(); + return loaded.future; + } + + @override + Future save(AppLanguage language) async {} +} diff --git a/test/project_entry_test.dart b/test/project_entry_test.dart new file mode 100644 index 0000000..46cd1b4 --- /dev/null +++ b/test/project_entry_test.dart @@ -0,0 +1,739 @@ +import 'package:cutdex/errors/app_failure.dart'; + +import 'package:cutdex/app/editor_theme.dart'; +import 'package:cutdex/integrations/platform/device_experience.dart'; + +import 'support/empty_conversation_repository.dart'; + +import 'package:cutdex/integrations/agent/conversation_repository.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex/integrations/editor_command_host.dart'; +import 'package:cutdex_sdk/tools.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; + +import 'dart:io'; + +import 'package:cutdex/app/router/app_router.dart'; +import 'package:cutdex/features/editor/editor_page.dart'; +import 'package:cutdex/features/preview/preview_panel.dart'; +import 'package:cutdex/persistence/app_settings_repositories.dart'; +import 'package:cutdex/workspace/projects.dart'; +import 'package:cutdex/workspace/timeline_provider.dart'; +import 'package:cutdex/workspace/project_state.dart'; +import 'package:cutdex/workspace/persistence/recent_projects.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'support/memory_app_settings.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + test('superseded prepared project never publishes and restores the prior workspace', () async { + final root = await Directory.systemTemp.createTemp( + 'cutdex-stale-selection-', + ); + final container = ProviderContainer( + overrides: [ + deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop), + recentProjectsProvider.overrideWithValue( + MemoryRecentProjectsRepository(), + ), + resourceLocationSettingsRepositoryProvider.overrideWithValue( + MemoryResourceLocationSettingsRepository(root.path), + ), + ], + ); + try { + final projects = container.read(projectsProvider.notifier); + await projects.open('${root.path}/One.cutdex', name: 'One'); + final initial = container.read(projectsProvider).requireValue; + final firstSession = await projects.openTimelineSession( + initial.activeProject!.id, + initial.timeline!.id, + ); + var checks = 0; + final publishedIds = []; + final subscription = container.listen(projectsProvider, (_, next) { + publishedIds.add(next.value?.activeProject?.id); + }); + final opened = await projects.open( + '${root.path}/Two.cutdex', + name: 'Two', + isCurrent: () => ++checks < 6, + ); + expect(opened, isFalse); + expect( + publishedIds.every((id) => id == initial.activeProject!.id), + isTrue, + ); + expect(container.read(projectsProvider).requireValue.error, isNull); + expect( + await projects.openTimelineSession( + initial.activeProject!.id, + initial.timeline!.id, + ), + same(firstSession), + ); + subscription.close(); + } finally { + await container.read(projectsProvider.notifier).prepareToQuit(); + container.dispose(); + await root.delete(recursive: true); + } + }); + + test('creating a project rebuilds a deleted local save directory', () async { + final root = await Directory.systemTemp.createTemp( + 'cutdex-recreate-projects-', + ); + final location = Directory('${root.path}/deleted/projects'); + await location.create(recursive: true); + await location.parent.delete(recursive: true); + final container = ProviderContainer( + overrides: [ + deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop), + recentProjectsProvider.overrideWithValue( + MemoryRecentProjectsRepository(), + ), + projectLocationSettingsRepositoryProvider.overrideWithValue( + DefaultingProjectLocationSettingsRepository( + MemoryProjectLocationSettingsRepository(location.path), + ), + ), + resourceLocationSettingsRepositoryProvider.overrideWithValue( + MemoryResourceLocationSettingsRepository(root.path), + ), + ], + ); + try { + expect( + await container + .read(projectsProvider.notifier) + .createProject('Recovered', initialTimelineName: 'Timeline'), + isTrue, + ); + expect(await location.exists(), isTrue); + expect( + container.read(projectsProvider).requireValue.activeProject?.name, + 'Recovered', + ); + } finally { + await container.read(projectsProvider.notifier).prepareToQuit(); + container.dispose(); + await root.delete(recursive: true); + } + }); + + test('selecting an existing project keeps its sidebar position', () async { + final root = await Directory.systemTemp.createTemp('cutdex-project-order-'); + final container = ProviderContainer( + overrides: [ + deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop), + recentProjectsProvider.overrideWithValue( + MemoryRecentProjectsRepository(), + ), + resourceLocationSettingsRepositoryProvider.overrideWithValue( + MemoryResourceLocationSettingsRepository(root.path), + ), + ], + ); + try { + final projects = container.read(projectsProvider.notifier); + final firstPath = '${root.path}/First.cutdex'; + final secondPath = '${root.path}/Second.cutdex'; + expect(await projects.open(firstPath, name: 'First'), isTrue); + expect(await projects.open(secondPath, name: 'Second'), isTrue); + final before = container.read(projectsProvider).requireValue.recent; + expect(before.map((project) => project.name), ['Second', 'First']); + + expect( + await projects.open(firstPath, expectedId: before.last.id), + isTrue, + ); + final after = container.read(projectsProvider).requireValue.recent; + expect( + after.map((project) => project.id), + before.map((project) => project.id), + ); + expect( + container.read(projectsProvider).requireValue.activeProject?.id, + before.last.id, + ); + } finally { + await container.read(projectsProvider.notifier).prepareToQuit(); + container.dispose(); + await root.delete(recursive: true); + } + }); + + test( + 'removing a project preserves files and undo restores its position', + () async { + final root = await Directory.systemTemp.createTemp( + 'cutdex-remove-project-', + ); + final repository = MemoryRecentProjectsRepository(); + final container = ProviderContainer( + overrides: [ + deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop), + recentProjectsProvider.overrideWithValue(repository), + resourceLocationSettingsRepositoryProvider.overrideWithValue( + MemoryResourceLocationSettingsRepository(root.path), + ), + ], + ); + try { + final projects = container.read(projectsProvider.notifier); + expect( + await projects.open('${root.path}/First.cutdex', name: 'First'), + isTrue, + ); + expect( + await projects.open('${root.path}/Second.cutdex', name: 'Second'), + isTrue, + ); + final before = container.read(projectsProvider).requireValue; + final removed = before.recent.first; + expect(await projects.removeRecentProject(removed.id), isTrue); + expect((await repository.load()).map((item) => item.id), [ + before.recent.last.id, + ]); + expect(await Directory(removed.path).exists(), isTrue); + expect( + container.read(projectsProvider).requireValue.activeProject?.id, + removed.id, + ); + expect(await projects.restoreRecentProject(removed, 0), isTrue); + expect( + (await repository.load()).map((item) => item.id), + before.recent.map((item) => item.id), + ); + } finally { + await container.read(projectsProvider.notifier).prepareToQuit(); + container.dispose(); + await root.delete(recursive: true); + } + }, + ); + + test( + 'deleting the selected timeline selects its previous neighbor', + () async { + final root = await Directory.systemTemp.createTemp( + 'cutdex-delete-timeline-', + ); + final container = ProviderContainer( + overrides: [ + deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop), + recentProjectsProvider.overrideWithValue( + MemoryRecentProjectsRepository(), + ), + resourceLocationSettingsRepositoryProvider.overrideWithValue( + MemoryResourceLocationSettingsRepository(root.path), + ), + ], + ); + try { + final projects = container.read(projectsProvider.notifier); + expect( + await projects.open('${root.path}/Project.cutdex', name: 'Project'), + isTrue, + ); + final initial = container + .read(projectsProvider) + .requireValue + .timelines + .single; + expect(initial.pinned, isTrue); + expect(await projects.createTimeline(name: 'Second'), isTrue); + final second = container + .read(projectsProvider) + .requireValue + .timeline! + .id; + expect(await projects.createTimeline(name: 'Third'), isTrue); + final third = container + .read(projectsProvider) + .requireValue + .timeline! + .id; + expect(await projects.createTimeline(name: 'Fourth'), isTrue); + final fourth = container + .read(projectsProvider) + .requireValue + .timeline! + .id; + expect(await projects.deleteTimeline(fourth), isTrue); + expect( + container.read(projectsProvider).requireValue.timeline?.id, + third, + ); + final projectId = container + .read(projectsProvider) + .requireValue + .activeProject! + .id; + expect(await projects.openTimeline(projectId, initial.id), isTrue); + expect(await projects.deleteTimeline(initial.id), isTrue); + expect( + container.read(projectsProvider).requireValue.timeline?.id, + second, + ); + expect(await projects.deleteTimeline(third), isTrue); + expect( + container.read(projectsProvider).requireValue.timeline?.id, + second, + ); + expect(await projects.deleteTimeline(second), isFalse); + } finally { + await container.read(projectsProvider.notifier).prepareToQuit(); + container.dispose(); + await root.delete(recursive: true); + } + }, + ); + + test( + 'all timeline providers are ready before active state is published', + () async { + final root = await Directory.systemTemp.createTemp('cutdex-switch-sync-'); + final viewSettings = _MemoryTimelineViewSettingsRepository(); + final container = ProviderContainer( + overrides: [ + deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop), + recentProjectsProvider.overrideWithValue( + MemoryRecentProjectsRepository(), + ), + resourceLocationSettingsRepositoryProvider.overrideWithValue( + MemoryResourceLocationSettingsRepository(root.path), + ), + timelineViewSettingsRepositoryProvider.overrideWithValue( + viewSettings, + ), + ], + ); + try { + final projects = container.read(projectsProvider.notifier); + expect( + await projects.open('${root.path}/Project.cutdex', name: 'Project'), + isTrue, + ); + final id = container + .read(projectsProvider) + .requireValue + .activeProject! + .id; + final firstId = container + .read(projectsProvider) + .requireValue + .timeline! + .id; + final firstProvider = editorTimelineProvider(id, firstId); + final firstSubscription = container.listen(firstProvider, (_, _) {}); + final firstSession = container.read(firstProvider).requireValue; + firstSubscription.close(); + final firstPreviewProvider = editorPreviewProvider(id, firstId); + final firstPreviewSubscription = container.listen( + firstPreviewProvider, + (_, _) {}, + ); + expect(container.read(firstPreviewProvider).hasValue, isTrue); + expect(container.read(firstPreviewProvider).requireValue, isNull); + firstPreviewSubscription.close(); + await container.pump(); + + expect(await projects.createTimeline(name: 'Second'), isTrue); + final secondId = container + .read(projectsProvider) + .requireValue + .timeline! + .id; + final secondProvider = editorTimelineProvider(id, secondId); + final secondSubscription = container.listen(secondProvider, (_, _) {}); + expect(container.read(secondProvider).hasValue, isTrue); + secondSubscription.close(); + final secondPreviewProvider = editorPreviewProvider(id, secondId); + final secondPreviewSubscription = container.listen( + secondPreviewProvider, + (_, _) {}, + ); + expect(container.read(secondPreviewProvider).hasValue, isTrue); + expect(container.read(secondPreviewProvider).requireValue, isNull); + secondPreviewSubscription.close(); + await container.pump(); + + final openingStates = []; + final stateSubscription = container.listen(projectsProvider, (_, next) { + openingStates.add(next.value?.openingTimelineId); + }); + expect(await projects.openTimeline(id, firstId), isTrue); + stateSubscription.close(); + expect(openingStates, isNot(contains(firstId))); + final returning = container.listen(firstProvider, (_, _) {}); + expect(container.read(firstProvider).asData?.value, same(firstSession)); + expect(viewSettings.loads, 2); + returning.close(); + } finally { + await container.read(projectsProvider.notifier).prepareToQuit(); + container.dispose(); + await root.delete(recursive: true); + } + }, + ); + test('opening a project restores its last timeline and handles missing records and empty projects', () async { + final root = await Directory.systemTemp.createTemp('cutdex-entry-'); + final recent = MemoryRecentProjectsRepository(); + final container = ProviderContainer( + overrides: [ + deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop), + recentProjectsProvider.overrideWithValue(recent), + resourceLocationSettingsRepositoryProvider.overrideWithValue( + MemoryResourceLocationSettingsRepository(root.path), + ), + ], + ); + final projects = container.read(projectsProvider.notifier); + expect( + await projects.open( + '${root.path}/A.cutdex', + name: 'A', + initialTimelineName: '时间线 1', + ), + isTrue, + ); + final id = container.read(projectsProvider).requireValue.activeProject!.id; + final first = container.read(projectsProvider).requireValue.timeline!.id; + expect(await projects.createTimeline(name: '时间线 2'), isTrue); + expect( + container + .read(projectsProvider) + .requireValue + .timelines + .map((timeline) => timeline.name), + containsAll(['时间线 1', '时间线 2']), + ); + final second = container + .read(projectsProvider) + .requireValue + .timelines + .firstWhere((project) => project.id != first) + .id; + expect(await projects.openTimeline(id, second), isTrue); + expect(await projects.open('${root.path}/B.cutdex', name: 'B'), isTrue); + expect(container.read(projectsProvider).requireValue.timeline, isNotNull); + expect(await projects.open('${root.path}/A.cutdex'), isTrue); + expect(container.read(projectsProvider).requireValue.timeline!.id, second); + expect(projects.cachedTimelineSession(id, second), isNotNull); + expect(projects.cachedTimelineSession(id, first), isNull); + expect(await projects.openTimeline(id, first), isTrue); + expect(projects.cachedTimelineSession(id, first), isNotNull); + expect(await projects.openTimeline(id, second), isTrue); + recent.projects[id] = 'deleted'; + expect(await projects.open('${root.path}/A.cutdex'), isTrue); + final current = container.read(projectsProvider).requireValue; + expect( + current.timelines.map((timeline) => timeline.id), + contains(current.timeline?.id), + ); + expect(recent.projects[id], current.timeline?.id); + await container.read(projectsProvider.notifier).prepareToQuit(); + container.dispose(); + await root.delete(recursive: true); + }); + + test( + 'tool imports publish project assets without depending on UI busy state', + () async { + final root = await Directory.systemTemp.createTemp( + 'cutdex-project-events-', + ); + final container = ProviderContainer( + overrides: [ + deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop), + recentProjectsProvider.overrideWithValue( + MemoryRecentProjectsRepository(), + ), + resourceLocationSettingsRepositoryProvider.overrideWithValue( + MemoryResourceLocationSettingsRepository(root.path), + ), + ], + ); + final projects = container.read(projectsProvider.notifier); + try { + expect( + await projects.open('${root.path}/Project.cutdex', name: 'Project'), + isTrue, + ); + expect(await projects.createTimeline(name: 'Timeline'), isTrue); + final current = container.read(projectsProvider).requireValue; + final session = await projects.openTimelineSession( + current.activeProject!.id, + current.timeline!.id, + ); + final busy = []; + final subscription = container.listen( + projectsProvider, + (_, next) => busy.add(next.requireValue.projectBusy), + ); + final file = await File('${root.path}/image.png').writeAsBytes([1]); + final result = await editorToolsFor(session, session.activeSequenceId!) + .invoke( + name: 'media.import', + arguments: {'path': file.path}, + context: const CommandContext(operationId: 'headless-import'), + ); + expect(result.edit, EditOutcome.committed); + expect( + container.read(projectsProvider).requireValue.assets.single.name, + 'image.png', + ); + expect(busy, isNotEmpty); + expect(busy, everyElement(isFalse)); + subscription.close(); + await session.close(); + } finally { + await container.read(projectsProvider.notifier).prepareToQuit(); + container.dispose(); + await root.delete(recursive: true); + } + }, + ); + + testWidgets( + 'editing page opens an empty project without creating a timeline', + (tester) async { + tester.view.physicalSize = const Size(1200, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final container = ProviderContainer( + overrides: [ + deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop), + conversationRepositoryProvider.overrideWith( + (ref) async => EmptyConversationRepository(), + ), + projectsProvider.overrideWith(_EmptyProjects.new), + ], + ); + final router = container.read(appRouterProvider); + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: MaterialApp.router( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + theme: EditorTheme.penDark, + routerConfig: router, + ), + ), + ); + await tester.pumpAndSettle(); + final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse); + await mouse.addPointer(location: Offset.zero); + await mouse.moveTo( + tester.getCenter(find.byKey(const Key('projects-heading'))), + ); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('create-project'))); + await mouse.removePointer(); + await tester.pumpAndSettle(); + expect(find.text('新建项目'), findsOneWidget); + await tester.tap(find.text('取消')); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const ValueKey('sidebar-project-empty'))); + await tester.pumpAndSettle(); + expect(router.routeInformationProvider.value.uri.path, '/'); + expect(find.text('项目中还没有时间线'), findsOneWidget); + expect(find.byTooltip('新建时间线'), findsNothing); + expect(find.byType(EditorWorkspace), findsNothing); + expect(find.byType(EditorPreviewPanel), findsNothing); + expect( + container.read(projectsProvider).requireValue.activeProject?.id, + 'empty', + ); + expect(container.read(projectsProvider).requireValue.timelines, isEmpty); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + container.dispose(); + }, + ); + + testWidgets('missing recent project stays visible and is dimmed', ( + tester, + ) async { + tester.platformDispatcher.localesTestValue = const [Locale('zh')]; + addTearDown(tester.platformDispatcher.clearLocalesTestValue); + final container = ProviderContainer( + overrides: [ + deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop), + conversationRepositoryProvider.overrideWith( + (ref) async => EmptyConversationRepository(), + ), + + projectsProvider.overrideWith(_MissingProjects.new), + workspaceViewSettingsRepositoryProvider.overrideWithValue( + _ExpandedMissingProjectSettings(), + ), + ], + ); + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: MaterialApp.router( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + theme: EditorTheme.penDark, + routerConfig: container.read(appRouterProvider), + ), + ), + ); + await tester.pumpAndSettle(); + final tile = tester.widget( + find.byKey(const ValueKey('sidebar-project-missing')), + ); + expect(tile.enabled, isTrue); + expect(tile.textColor, EditorTheme.penDark.disabledColor); + expect( + find.descendant( + of: find.byKey(const ValueKey('sidebar-project-missing')), + matching: find.byIcon(Icons.folder_off_outlined), + ), + findsOneWidget, + ); + expect( + find.descendant( + of: find.byKey(const ValueKey('sidebar-project-missing')), + matching: find.text('项目不可用'), + ), + findsOneWidget, + ); + await tester.pumpWidget(const SizedBox()); + container.dispose(); + }); + + testWidgets('project errors use a dismissible floating toast', ( + tester, + ) async { + tester.platformDispatcher.localesTestValue = const [Locale('zh')]; + addTearDown(tester.platformDispatcher.clearLocalesTestValue); + tester.view.physicalSize = const Size(1200, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final container = ProviderContainer( + overrides: [ + deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop), + conversationRepositoryProvider.overrideWith( + (ref) async => EmptyConversationRepository(), + ), + projectsProvider.overrideWith(_ErrorProjects.new), + ], + ); + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: MaterialApp.router( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + theme: EditorTheme.penDark, + routerConfig: container.read(appRouterProvider), + ), + ), + ); + await tester.pumpAndSettle(); + expect(find.byIcon(Icons.error_outline), findsOneWidget); + expect(find.text('操作失败,请重试'), findsOneWidget); + expect(tester.getTopRight(find.byIcon(Icons.close)).dx, lessThan(1200)); + await tester.tap(find.byIcon(Icons.close)); + await tester.pump(const Duration(milliseconds: 200)); + final opacity = tester.widgetList( + find.byType(AnimatedOpacity), + ); + expect(opacity.any((widget) => widget.opacity == 0), isTrue); + await tester.pumpWidget(const SizedBox()); + container.dispose(); + }); +} + +class _MemoryTimelineViewSettingsRepository + implements TimelineViewSettingsRepository { + int loads = 0; + + @override + Future load(String projectId, String timelineId) async { + loads++; + return const TimelineViewState(); + } + + @override + Future save( + String projectId, + String timelineId, + SequenceId sequenceId, + TimelineSequenceViewState state, + ) async {} +} + +class _EmptyProjects extends Projects { + static const project = RecentProject( + id: 'empty', + name: 'Empty', + path: '/Empty.cutdex', + ); + @override + Future build() async => const ProjectState(recent: [project]); + + @override + Future> listProjectTimelines( + RecentProject project, + ) async => const []; + + @override + Future open( + String path, { + String? name, + String? expectedId, + String? timelineId, + String? initialTimelineName, + bool Function()? isCurrent, + }) async { + state = AsyncData(state.requireValue.copyWith(activeProject: project)); + return true; + } +} + +class _MissingProjects extends Projects { + @override + Future build() async => const ProjectState( + recent: [ + RecentProject( + id: 'missing', + name: 'Missing', + path: '/Missing.cutdex', + availability: ProjectAvailability.missing, + ), + ], + ); +} + +class _ExpandedMissingProjectSettings + implements WorkspaceViewSettingsRepository { + @override + Future load() async => + const WorkspaceViewSettingsData(hasSavedState: true); + + @override + Future save(WorkspaceViewSettingsData settings) async {} +} + +class _ErrorProjects extends Projects { + @override + Future build() async => + const ProjectState(error: AppFailure(AppErrorCode.operationFailed)); +} diff --git a/test/project_location_directory_test.dart b/test/project_location_directory_test.dart new file mode 100644 index 0000000..33e1eed --- /dev/null +++ b/test/project_location_directory_test.dart @@ -0,0 +1,57 @@ +import 'dart:io'; + +import 'package:cutdex/workspace/persistence/project_location_directory.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + const service = ProjectLocationDirectory(); + late Directory root; + setUp(() async { + root = await Directory.systemTemp.createTemp('cutdex-location-'); + }); + tearDown(() => root.delete(recursive: true)); + + test( + 'inspection preserves a missing folder, preparation creates it', + () async { + final folder = Directory('${root.path}/deleted/projects'); + expect(await service.inspect(folder.path), ProjectLocationStatus.missing); + expect(await folder.exists(), isFalse); + expect(await root.list().toList(), isEmpty); + await service.prepare(folder.path); + expect(await service.inspect(folder.path), ProjectLocationStatus.ready); + expect(await folder.list().toList(), isEmpty); + }, + ); + + test('a file or broken symlink in the path is never replaced', () async { + final file = File('${root.path}/file'); + await file.writeAsString('keep'); + expect( + await service.inspect('${file.path}/projects'), + ProjectLocationStatus.unavailable, + ); + await expectLater( + service.prepare('${file.path}/projects'), + throwsStateError, + ); + expect(await file.readAsString(), 'keep'); + if (!Platform.isWindows) { + final link = Link('${root.path}/link'); + await link.create('${root.path}/missing'); + expect( + await service.inspect('${link.path}/projects'), + ProjectLocationStatus.unavailable, + ); + } + }); + + test('missing external mount paths are not recreated', () async { + if (Platform.isWindows) return; + final path = + '/Volumes/cutdex-offline-${DateTime.now().microsecondsSinceEpoch}/Projects'; + expect(await service.inspect(path), ProjectLocationStatus.unavailable); + await expectLater(service.prepare(path), throwsStateError); + expect(await Directory(path).exists(), isFalse); + }); +} diff --git a/test/project_locator_test.dart b/test/project_locator_test.dart new file mode 100644 index 0000000..0aa95e2 --- /dev/null +++ b/test/project_locator_test.dart @@ -0,0 +1,50 @@ +import 'dart:io'; + +import 'package:cutdex/persistence/app_database.dart'; +import 'package:cutdex/workspace/persistence/project_locator.dart'; +import 'package:cutdex/workspace/persistence/recent_projects.dart'; +import 'package:cutdex/workspace/project_state.dart'; +import 'package:drift/native.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + test('locator reports a real directory as available', () async { + final root = await Directory.systemTemp.createTemp('cutdex-locator-'); + addTearDown(() => root.delete(recursive: true)); + final location = await ProjectLocator().locate( + RecentProject(id: 'id', name: 'Demo', path: root.path), + ); + expect(location.availability, ProjectAvailability.available); + expect(location.project.path, root.path); + }); + + test('locator keeps a missing project record disabled', () async { + final location = await ProjectLocator().locate( + const RecentProject( + id: 'id', + name: 'Demo', + path: '/definitely-missing/Demo.cutdex', + ), + ); + expect(location.availability, ProjectAvailability.missing); + expect(location.project.availability, ProjectAvailability.missing); + }); + + test( + 'recent project storage preserves paths, order and last timelines', + () async { + final database = AppDatabase(NativeDatabase.memory()); + addTearDown(database.close); + final repository = DriftRecentProjectsRepository(database); + const record = RecentProject( + id: 'id', + name: 'Demo', + path: '/Demo.cutdex', + ); + await repository.save([record]); + await repository.rememberTimeline(record.id, 'timeline'); + expect(await repository.load(), [record]); + expect(await repository.lastTimeline(record.id), 'timeline'); + }, + ); +} diff --git a/test/project_properties_test.dart b/test/project_properties_test.dart new file mode 100644 index 0000000..0282fb0 --- /dev/null +++ b/test/project_properties_test.dart @@ -0,0 +1,200 @@ +import 'package:cutdex/app/editor_theme.dart'; + +import 'dart:async'; + +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex/features/properties/properties_panel.dart'; +import 'package:cutdex/workspace/timeline_provider.dart'; +import 'package:cutdex/workspace/timeline_session.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:cutdex_sdk/runtime/contracts.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'support/preview_fixture.dart'; + +void main() { + testWidgets('timeline switch does not expose the previous session', ( + tester, + ) async { + final f = (await tester.runAsync( + () => + createPreviewFixture(Uri.file('/test/audio.wav'), mediaType: 'audio'), + ))!; + addTearDown(() async { + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + final pending = Completer(); + final container = ProviderContainer( + overrides: [ + editorTimelineProvider( + 'project', + 'first', + ).overrideWith((ref) async => f.timeline), + editorTimelineProvider( + 'project', + 'second', + ).overrideWith((ref) => pending.future), + ], + ); + addTearDown(container.dispose); + + Widget panel(String timelineId) => UncontrolledProviderScope( + container: container, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + theme: EditorTheme.penDark, + home: Scaffold( + body: SizedBox( + width: 280, + child: EditorPropertiesPanel( + projectId: 'project', + timelineId: timelineId, + ), + ), + ), + ), + ); + + await tester.pumpWidget(panel('first')); + await tester.pumpAndSettle(); + expect(find.text('项目属性'), findsOneWidget); + expect( + find.ancestor( + of: find.byType(SingleChildScrollView), + matching: find.byType(ShaderMask), + ), + findsOneWidget, + ); + expect( + find.descendant( + of: find.byType(EditorPropertiesPanel), + matching: find.byType(ClipRRect), + ), + findsNothing, + ); + + await tester.pumpWidget(panel('second')); + await tester.pump(); + expect(find.text('项目属性'), findsNothing); + expect(find.byKey(const Key('properties-pending')), findsOneWidget); + expect(find.byType(CircularProgressIndicator), findsNothing); + + pending.complete(f.timeline); + await tester.pumpAndSettle(); + expect(find.text('项目属性'), findsOneWidget); + expect(find.byType(CircularProgressIndicator), findsNothing); + }); + + testWidgets('project properties follow edits and return after deselection', ( + tester, + ) async { + final f = (await tester.runAsync( + () => + createPreviewFixture(Uri.file('/test/audio.wav'), mediaType: 'audio'), + ))!; + await tester.pumpWidget( + ProviderScope( + overrides: [ + editorTimelineProvider( + 'project', + 'project', + ).overrideWith((ref) async => f.timeline), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + theme: EditorTheme.penDark, + home: const Scaffold( + body: SizedBox( + width: 280, + child: EditorPropertiesPanel( + projectId: 'project', + timelineId: 'project', + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect(find.text('项目属性'), findsOneWidget); + expect(find.text('Preview test'), findsOneWidget); + expect(find.text('1080 × 1920 px'), findsOneWidget); + expect(find.text('30 fps'), findsOneWidget); + expect(find.text('2.00 秒'), findsOneWidget); + await tester.tap(find.byKey(const ValueKey('project-settings-edit'))); + await tester.pumpAndSettle(); + expect(find.text('项目设置'), findsOneWidget); + await tester.enterText(find.byKey(const ValueKey('project-width')), '0'); + await tester.tap(find.byKey(const ValueKey('project-settings-save'))); + await tester.pump(); + expect(find.text('请输入 1–16384 的整数'), findsOneWidget); + expect(f.timeline.canvas, const ProjectCanvas(1080, 1920)); + await tester.enterText(find.byKey(const ValueKey('project-width')), '3840'); + await tester.enterText( + find.byKey(const ValueKey('project-height')), + '2160', + ); + await tester.tap(find.byKey(const ValueKey('project-frame-rate'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('29.97 fps').last); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const ValueKey('project-color-space'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('HDR · Rec.2020 PQ').last); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const ValueKey('project-settings-save'))); + await tester.runAsync(f.timeline.flush); + await tester.pumpAndSettle(); + expect(find.text('项目设置'), findsNothing); + expect(find.text('3840 × 2160 px'), findsOneWidget); + expect(find.text('29.97 fps'), findsOneWidget); + expect(f.timeline.projectColorSpace, RenderColorSpace.rec2020PQ); + expect( + f.timeline.view(SequenceId('one')).format.frameDuration, + RationalTime(1001, 30000), + ); + f.timeline.view(SequenceId('one')).undo(); + await tester.runAsync(f.timeline.flush); + await tester.pumpAndSettle(); + expect(find.text('1080 × 1920 px'), findsOneWidget); + expect(find.text('30 fps'), findsOneWidget); + expect(f.timeline.projectColorSpace, RenderColorSpace.rec709); + await tester.tap(find.byKey(const ValueKey('project-settings-edit'))); + await tester.pumpAndSettle(); + await tester.enterText(find.byKey(const ValueKey('project-width')), '1280'); + await tester.tap(find.text('取消')); + await tester.pumpAndSettle(); + expect(f.timeline.canvas, const ProjectCanvas(1080, 1920)); + f.timeline.commands.setCanvas(ProjectCanvas.widescreen); + await tester.pump(); + expect(find.text('1920 × 1080 px'), findsOneWidget); + final view = f.timeline.view(SequenceId('one')); + view.setSelection([ + view.version.kernelVersion.query().elementById(ElementId('clip'))!, + ]); + await tester.pump(); + expect(find.text('项目属性'), findsNothing); + expect(find.text('Preview clip'), findsNothing); + view.clearSelection(); + await tester.pump(); + expect(find.text('项目属性'), findsOneWidget); + f.timeline.selectSequence(SequenceId('empty')); + await tester.pump(); + expect(find.text('0.00 秒'), findsOneWidget); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + await tester.runAsync(() async { + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + }); +} diff --git a/test/project_workspace_test.dart b/test/project_workspace_test.dart new file mode 100644 index 0000000..6de5a8b --- /dev/null +++ b/test/project_workspace_test.dart @@ -0,0 +1,502 @@ +import 'support/creation_names.dart'; + +import 'dart:io'; + +import 'package:cutdex_sdk/editor/commands.dart'; + +import 'package:cutdex/workspace/persistence/project_workspace.dart'; +import 'package:cutdex/workspace/background_task_registry.dart'; +import 'package:cutdex/workspace/project_state.dart'; +import 'package:cutdex/workspace/media_import.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + test( + 'recent project sessions are reused and cache eviction closes old sessions', + () async { + final root = await Directory.systemTemp.createTemp( + 'cutdex-warm-projects-', + ); + final workspace = ProjectWorkspace(creationNames: testCreationNames); + addTearDown(() async { + await workspace.close(); + await root.delete(recursive: true); + }); + final timelines = await workspace.open( + '${root.path}/One.cutdex', + name: 'One', + ); + final firstId = workspace.project!.info.id; + final document = await workspace.loadTimeline( + firstId, + timelines.single.id, + ); + final session = await workspace.openTimelineSession(firstId, document); + await workspace.open('${root.path}/Two.cutdex', name: 'Two'); + await workspace.open('${root.path}/One.cutdex', expectedId: firstId); + final restored = await workspace.openTimelineSession(firstId, document); + expect(restored, same(session)); + expect(restored.acceptsEdits, isTrue); + await workspace.open('${root.path}/Two.cutdex'); + await workspace.open('${root.path}/Three.cutdex', name: 'Three'); + await workspace.open('${root.path}/Four.cutdex', name: 'Four'); + expect(workspace.cachedProjectIds.length, 3); + expect(workspace.cachedProjectIds, isNot(contains(firstId))); + expect(session.acceptsEdits, isFalse); + }, + ); + + test('superseded project loading preserves the current project', () async { + final root = await Directory.systemTemp.createTemp( + 'cutdex-cancel-project-', + ); + final workspace = ProjectWorkspace(creationNames: testCreationNames); + addTearDown(() async { + await workspace.close(); + await root.delete(recursive: true); + }); + await workspace.open('${root.path}/One.cutdex', name: 'One'); + final firstId = workspace.project!.info.id; + var checks = 0; + await expectLater( + workspace.open( + '${root.path}/Two.cutdex', + name: 'Two', + isCurrent: () => ++checks < 2, + ), + throwsA(isA()), + ); + expect(workspace.project!.info.id, firstId); + }); + + test('default timeline is pinned and deleting a prepared timeline clears its session', () async { + final root = await Directory.systemTemp.createTemp('cutdex-timeline-menu-'); + final workspace = ProjectWorkspace(creationNames: testCreationNames); + addTearDown(() async { + await workspace.close(); + await root.delete(recursive: true); + }); + final path = '${root.path}/Project.cutdex'; + final initial = await workspace.open(path, name: 'Project'); + expect(initial.single.pinned, isTrue); + final project = RecentProject( + id: workspace.project!.info.id, + name: 'Project', + path: path, + ); + final created = await workspace.createPreparedTimeline('Second'); + final pinned = await workspace.setTimelinePinned( + project, + created.document.id, + true, + ); + expect(pinned.map((item) => item.pinned), [isTrue, isTrue]); + final remaining = await workspace.deleteTimeline( + project, + created.document.id, + ); + expect(remaining.map((item) => item.id), [initial.single.id]); + expect( + workspace.cachedTimelineSession(project.id, created.document.id), + isNull, + ); + }); + + test('removed assets retain references and reimport restores the original record', () async { + final root = await Directory.systemTemp.createTemp('cutdex-asset-menu-'); + var workspace = ProjectWorkspace(creationNames: testCreationNames); + addTearDown(() async { + await workspace.close(); + await root.delete(recursive: true); + }); + await workspace.open('${root.path}/Project.cutdex', name: 'Project'); + final project = workspace.project!; + final sourceFile = await File('${root.path}/source.mov') + .writeAsString('original'); + final source = File(await sourceFile.resolveSymbolicLinks()); + await project.saveAsset( + AssetDocument( + id: 'asset', + name: 'Original', + storage: AssetStorage.external, + location: source.uri.toString(), + metadata: {'kind': 'video'}, + accessData: {'test': 'retained'}, + ), + ); + final renamed = (await workspace.editAsset( + project.info.id, + 'asset', + name: ' Renamed ', + )).single; + expect(renamed.name, 'Renamed'); + expect(renamed.location, source.uri.toString()); + expect(renamed.accessData['test'], 'retained'); + await expectLater( + workspace.editAsset('other', 'asset', name: 'wrong'), + throwsA(isA().having((e) => e.code, 'code', 'closed')), + ); + await project.saveCollection( + AssetCollection( + id: 'collection', + name: 'Collection', + assetIds: ['asset'], + ), + ); + final projectId = project.info.id; + expect(await workspace.editAsset(projectId, 'asset'), isEmpty); + expect((await project.listAssets()).single.id, 'asset'); + expect( + await project.resolveAsset((await project.listAssets()).single), + source.uri, + ); + await workspace.close(); + workspace = ProjectWorkspace(creationNames: testCreationNames); + await workspace.open('${root.path}/Project.cutdex'); + expect(await workspace.listAssets(projectId), isEmpty); + final restored = await workspace.importExternalMedia(projectId, [ + ExternalMediaFile(path: source.path), + ExternalMediaFile(path: source.path), + ]); + expect(restored.added, 1); + expect(restored.duplicates, 1); + expect(restored.assets.single.id, 'asset'); + expect(restored.assets.single.name, 'Renamed'); + expect(restored.assets.single.accessData['test'], 'retained'); + expect((await workspace.project!.listAssets()).length, 1); + await workspace.project!.saveAsset( + AssetDocument( + id: 'unused', + name: 'Unused', + storage: AssetStorage.external, + location: source.uri.toString(), + ), + ); + final remaining = await workspace.editAsset(projectId, 'unused'); + expect(remaining.map((asset) => asset.id), ['asset']); + expect(await source.readAsString(), 'original'); + }); + test( + 'project contains multiple durable timelines and releases its lock', + () async { + final root = await Directory.systemTemp.createTemp('cutdex-app-test-'); + final workspace = ProjectWorkspace(creationNames: testCreationNames); + addTearDown(() async { + await workspace.close(); + await root.delete(recursive: true); + }); + final path = '${root.path}/Project.cutdex'; + expect(await workspace.open(path, name: '项目'), hasLength(1)); + final id = workspace.project!.info.id; + await workspace.createTimeline('时间线一'); + final timelines = await workspace.createTimeline('时间线二'); + expect(timelines.map((item) => item.name), [ + 'Timeline 1', + '时间线一', + '时间线二', + ]); + final timeline = await workspace.loadTimeline(id, timelines.first.id); + expect(timeline.revision, greaterThan(0)); + expect(timeline.sequences.single.name, 'Main sequence'); + expect(timeline.sequences.single.elements, isEmpty); + expect(timeline.defaultSequenceId, timeline.sequences.single.id); + await workspace.close(); + + final reopened = await ProjectFile.open(Directory(path)); + try { + expect(reopened.info.id, id); + expect(await reopened.listTimelines(), hasLength(3)); + } finally { + await reopened.close(); + } + }, + ); + + test('prepared timeline is cached before it is published', () async { + final root = await Directory.systemTemp.createTemp('cutdex-prepared-'); + final registry = BackgroundTaskRegistry(); + final workspace = ProjectWorkspace( + creationNames: testCreationNames, + backgroundTasks: registry, + ); + addTearDown(() async { + await workspace.close(); + registry.dispose(); + await root.delete(recursive: true); + }); + await workspace.open('${root.path}/Project.cutdex', name: 'Project'); + final projectId = workspace.project!.info.id; + + final created = await workspace.createPreparedTimeline('Timeline 2'); + + expect(created.timelines.last.id, created.document.id); + expect( + workspace.cachedTimelineSession(projectId, created.document.id), + same(created.session), + ); + expect(registry.entries.map((entry) => entry.timelineId), [ + created.document.id, + ]); + await workspace.close(); + expect(registry.entries, isEmpty); + }); + + test( + 'failed opens preserve current project and successful switch caches it', + () async { + final root = await Directory.systemTemp.createTemp('cutdex-app-test-'); + final workspace = ProjectWorkspace(creationNames: testCreationNames); + addTearDown(() async { + await workspace.close(); + await root.delete(recursive: true); + }); + final path = '${root.path}/One.cutdex'; + await workspace.open(path, name: 'One'); + final id = workspace.project!.info.id; + await expectLater( + workspace.open('${root.path}/missing'), + throwsA(isA()), + ); + expect(workspace.project!.info.id, id); + await expectLater( + workspace.open(path, expectedId: 'wrong'), + throwsStateError, + ); + expect(workspace.project!.info.id, id); + await expectLater( + workspace.open(path, name: 'Overwrite'), + throwsA(isA()), + ); + expect(workspace.project!.info.id, id); + await workspace.open('${root.path}/Two.cutdex', name: 'Two'); + expect(workspace.cachedProjectIds, contains(id)); + await workspace.open(path, expectedId: id); + expect(workspace.project!.info.id, id); + }, + ); + + test( + 'timeline inspection and opening the same project are serialized', + () async { + final root = await Directory.systemTemp.createTemp('cutdex-app-race-'); + final creator = ProjectWorkspace(creationNames: testCreationNames); + final workspace = ProjectWorkspace(creationNames: testCreationNames); + addTearDown(() async { + await creator.close(); + await workspace.close(); + await root.delete(recursive: true); + }); + final path = '${root.path}/Project.cutdex'; + await creator.open(path, name: 'Project'); + await creator.createTimeline('Timeline'); + final id = creator.project!.info.id; + await creator.close(); + + final inspected = workspace.listProjectTimelines(path, expectedId: id); + final opened = workspace.open(path, expectedId: id); + + expect((await inspected).map((item) => item.name), contains('Timeline')); + expect((await opened).map((item) => item.name), contains('Timeline')); + expect(workspace.project!.info.id, id); + }, + ); + + test('close waits for accepted creation and prevents later work', () async { + final root = await Directory.systemTemp.createTemp('cutdex-app-test-'); + addTearDown(() => root.delete(recursive: true)); + final workspace = ProjectWorkspace(creationNames: testCreationNames); + final path = '${root.path}/Queued.cutdex'; + final opening = workspace.open(path, name: 'Queued'); + final creating = workspace.createTimeline('Saved before close'); + final closing = workspace.close(); + expect(workspace.close(), same(closing)); + await opening; + await creating; + await closing; + await expectLater(workspace.createTimeline('Late'), throwsStateError); + final file = await ProjectFile.open(Directory(path)); + try { + expect( + (await file.listTimelines()).map((item) => item.name), + contains('Saved before close'), + ); + } finally { + await file.close(); + } + }); + + test( + 'leased timeline survives project switch and is reused on return', + () async { + final root = await Directory.systemTemp.createTemp('cutdex-lease-test-'); + final workspace = ProjectWorkspace(creationNames: testCreationNames); + addTearDown(() async { + await workspace.close(); + await root.delete(recursive: true); + }); + final firstPath = '${root.path}/First.cutdex'; + final timelines = await workspace.open(firstPath, name: 'First'); + final projectId = workspace.project!.info.id; + final document = await workspace.loadTimeline( + projectId, + timelines.single.id, + ); + final session = await workspace.openTimelineSession(projectId, document); + final lease = await workspace.leaseTimeline(projectId, document.id); + + await workspace.open('${root.path}/Second.cutdex', name: 'Second'); + expect(session.acceptsEdits, isTrue); + await lease.validate(); + expect( + await workspace.listProjectTimelines(firstPath, expectedId: projectId), + hasLength(1), + ); + + await workspace.open(firstPath, expectedId: projectId); + final reopened = await workspace.loadTimeline(projectId, document.id); + final returned = await workspace.openTimelineSession(projectId, reopened); + expect(identical(returned, session), isTrue); + final manifest = File('$firstPath/manifest.json'); + final backup = await manifest.rename('$firstPath/manifest.json.backup'); + await expectLater(lease.validate(), throwsA(isA())); + await backup.rename(manifest.path); + await lease.release(); + expect(returned.acceptsEdits, isTrue); + }, + ); + + test('leased timeline survives switching to another timeline', () async { + final root = await Directory.systemTemp.createTemp( + 'cutdex-timeline-lease-', + ); + final workspace = ProjectWorkspace(creationNames: testCreationNames); + addTearDown(() async { + await workspace.close(); + await root.delete(recursive: true); + }); + final timelines = await workspace.open( + '${root.path}/Project.cutdex', + name: 'Project', + ); + final id = workspace.project!.info.id; + final firstDocument = await workspace.loadTimeline(id, timelines.single.id); + final firstSession = await workspace.openTimelineSession(id, firstDocument); + final lease = await workspace.leaseTimeline(id, firstDocument.id); + final added = await workspace.createTimeline('Second'); + final secondId = added + .singleWhere((item) => item.id != firstDocument.id) + .id; + final secondDocument = await workspace.loadTimeline(id, secondId); + final secondSession = await workspace.openTimelineSession( + id, + secondDocument, + ); + expect(firstSession.acceptsEdits, isTrue); + expect(secondSession.acceptsEdits, isTrue); + await lease.validate(); + await lease.release(); + expect(firstSession.acceptsEdits, isTrue); + expect(secondSession.acceptsEdits, isTrue); + final returnedDocument = await workspace.loadTimeline(id, firstDocument.id); + final returned = await workspace.openTimelineSession(id, returnedDocument); + expect(identical(returned, firstSession), isTrue); + }); + + test( + 'timeline switch keeps old UI notifiers alive until project close', + () async { + final root = await Directory.systemTemp.createTemp('cutdex-timeline-ui-'); + final workspace = ProjectWorkspace(creationNames: testCreationNames); + addTearDown(() async { + await workspace.close(); + await root.delete(recursive: true); + }); + final timelines = await workspace.open( + '${root.path}/Project.cutdex', + name: 'Project', + ); + final id = workspace.project!.info.id; + final first = await workspace.loadTimeline(id, timelines.single.id); + final session = await workspace.openTimelineSession(id, first); + final releaseViews = session.retainViews(); + final tasks = session.audioGainPreview; + final removals = session.view( + first.defaultSequenceId ?? first.sequences.first.id, + ); + + final added = await workspace.createTimeline('Second'); + final secondId = added.singleWhere((item) => item.id != first.id).id; + await workspace.loadTimeline(id, secondId); + + expect(session.acceptsEdits, isTrue); + void listener() {} + expect(() => tasks.addListener(listener), returnsNormally); + expect(() => removals.addListener(listener), returnsNormally); + tasks.removeListener(listener); + removals.removeListener(listener); + releaseViews(); + expect(() => tasks.addListener(listener), returnsNormally); + tasks.removeListener(listener); + await workspace.open('${root.path}/Other.cutdex', name: 'Other'); + expect(session.acceptsEdits, isTrue); + await workspace.close(); + expect(session.acceptsEdits, isFalse); + expect(() => tasks.addListener(listener), throwsAssertionError); + expect(() => removals.addListener(listener), throwsAssertionError); + }, + ); + + test('unleased sessions stay warm until workspace close', () async { + final root = await Directory.systemTemp.createTemp('cutdex-session-owner-'); + final workspace = ProjectWorkspace(creationNames: testCreationNames); + addTearDown(() async { + await workspace.close(); + await root.delete(recursive: true); + }); + final timelines = await workspace.open( + '${root.path}/First.cutdex', + name: 'First', + ); + final id = workspace.project!.info.id; + final first = await workspace.loadTimeline(id, timelines.single.id); + final firstSession = await workspace.openTimelineSession(id, first); + final added = await workspace.createTimeline('Second'); + final secondId = added.singleWhere((item) => item.id != first.id).id; + final second = await workspace.loadTimeline(id, secondId); + final secondSession = await workspace.openTimelineSession(id, second); + + await workspace.open('${root.path}/Other.cutdex', name: 'Other'); + expect(firstSession.acceptsEdits, isTrue); + await workspace.close(); + expect(firstSession.acceptsEdits, isFalse); + expect(secondSession.acceptsEdits, isFalse); + }); + + test('failed timeline selection leaves cached sessions usable', () async { + final root = await Directory.systemTemp.createTemp('cutdex-timeline-fail-'); + final workspace = ProjectWorkspace(creationNames: testCreationNames); + addTearDown(() async { + await workspace.close(); + await root.delete(recursive: true); + }); + final timelines = await workspace.open( + '${root.path}/Project.cutdex', + name: 'Project', + ); + final id = workspace.project!.info.id; + final document = await workspace.loadTimeline(id, timelines.single.id); + final session = await workspace.openTimelineSession(id, document); + + await expectLater( + workspace.loadTimeline(id, 'missing'), + throwsA(isA()), + ); + expect(session.acceptsEdits, isTrue); + final selected = await workspace.loadTimeline(id, document.id); + expect( + identical(await workspace.openTimelineSession(id, selected), session), + isTrue, + ); + }); +} diff --git a/test/property_consistency_test.dart b/test/property_consistency_test.dart new file mode 100644 index 0000000..1630a85 --- /dev/null +++ b/test/property_consistency_test.dart @@ -0,0 +1,172 @@ +import 'package:cutdex/app/editor_theme.dart'; +import 'package:cutdex/features/properties/audio_properties.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex_ui/widgets.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/runtime/contracts.dart'; +import 'package:cutdex_sdk/timeline/engine.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'support/preview_fixture.dart'; + +void main() { + for (final mode in [ + 'seek', + 'draft seek', + 'key', + 'invalid key', + 'precision', + ]) { + testWidgets('audio property consistency: $mode', (tester) async { + final f = (await tester.runAsync( + () => createPreviewFixture(Uri.file('/test/video.mov'), hasAudio: true), + ))!; + final seq = SequenceId('one'); + final id = ElementId('clip'); + final view = f.timeline.view(seq); + ElementRecord record() { + final q = view.version.kernelVersion.query(); + return q.element(q.elementById(id)!); + } + + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + theme: EditorTheme.penLight, + home: Scaffold( + body: SizedBox( + width: 225, + child: AudioProperties( + session: f.timeline, + sequence: seq, + clip: record(), + hasAudio: true, + ), + ), + ), + ), + ); + if (mode == 'seek') { + await tester.tap(find.byKey(const Key('audio-key'))); + await tester.pump(); + final slider = tester.widget(find.byType(AppSlider)); + slider.onChangeStart!(.5); + slider.onChanged!(.8); + final before = view.version.kernelVersion; + view.seekTo(TimelineClock.ticksPerSecond); + await tester.pump(); + expect( + tester.widget(find.byType(TextField)).controller!.text, + '0.0', + ); + tester.widget(find.byType(AppSlider)).onChanged!(.9); + tester.widget(find.byType(AppSlider)).onChangeEnd!(.8); + await tester.pump(); + final curve = record().parameters![ClipAudioGain.gainId]!; + expect(view.version.kernelVersion, same(before)); + expect(f.timeline.audioGainPreview.value, isNull); + expect(curve.keyframeAt(TimelineClock.ticksPerSecond), isNull); + expect(curve.keyframeAt(0)?.value, 0); + } else if (mode == 'draft seek') { + final before = view.version.kernelVersion; + await tester.enterText(find.byType(TextField), '-12'); + view.seekTo(TimelineClock.ticksPerSecond); + await tester.pump(); + await tester.testTextInput.receiveAction(TextInputAction.done); + await tester.pump(); + expect(view.version.kernelVersion, same(before)); + expect(ClipAudioGain.fromRecord(record()).db, 0); + } else if (mode == 'invalid key') { + final before = view.version.kernelVersion; + await tester.enterText(find.byType(TextField), '13'); + await tester.tap(find.byKey(const Key('audio-key'))); + await tester.pump(); + expect(view.version.kernelVersion, same(before)); + expect(record().parameters?[ClipAudioGain.gainId]?.length ?? 0, 0); + } else if (mode == 'key') { + await tester.enterText(find.byType(TextField), '-12'); + await tester.tap(find.byKey(const Key('audio-key'))); + await tester.pump(); + final curve = record().parameters![ClipAudioGain.gainId]!; + expect(curve.keyframeAt(0)?.value, -12); + expect( + tester.widget(find.byType(TextField)).controller!.text, + '-12.0', + ); + view.undo(); + await tester.pump(); + expect(record().parameters?[ClipAudioGain.gainId]?.length, 0); + expect(ClipAudioGain.fromRecord(record()).db, -12); + view.undo(); + await tester.pump(); + expect(ClipAudioGain.fromRecord(record()).db, 0); + } else { + for (final (input, expected) in [ + ('0.04', 0.0), + ('-0.04', 0.0), + ('0.06', .1), + ('-0.06', -.1), + ('12', 12.0), + ('-90', -90.0), + ]) { + await tester.enterText(find.byType(TextField), input); + await tester.testTextInput.receiveAction(TextInputAction.done); + await tester.pump(); + expect(ClipAudioGain.fromRecord(record()).db, expected); + expect( + tester.widget(find.byType(TextField)).controller!.text, + expected.toStringAsFixed(1), + ); + } + } + await tester.pumpWidget(const SizedBox()); + await tester.runAsync(() async { + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + }); + } + testWidgets('canvas entry points share integer bounds and undo', ( + tester, + ) async { + final f = (await tester.runAsync( + () => createPreviewFixture(Uri.file('/test/video.mov')), + ))!; + final seq = SequenceId('one'); + final before = f.timeline.version; + for (final size in [ + const ProjectCanvas(0, 1080), + const ProjectCanvas(16385, 1080), + const ProjectCanvas(1920, 1080.5), + const ProjectCanvas(double.infinity, 1080), + ]) { + expect( + () => f.timeline.commands.setCanvas(size), + throwsA(isA()), + ); + expect( + () => f.timeline.setProjectProperties( + sequence: seq, + canvas: size, + frameDuration: TimelineFormat.fps24.frameDuration, + colorSpace: RenderColorSpace.rec709, + ), + throwsArgumentError, + ); + expect(f.timeline.version, before); + } + final original = f.timeline.canvas; + f.timeline.commands.setCanvas(const ProjectCanvas(1, 16384)); + expect(f.timeline.canvas, const ProjectCanvas(1, 16384)); + f.timeline.view(seq).undo(); + expect(f.timeline.canvas, original); + await tester.runAsync(() async { + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + }); +} diff --git a/test/saved_edit_validation_test.dart b/test/saved_edit_validation_test.dart new file mode 100644 index 0000000..3770e16 --- /dev/null +++ b/test/saved_edit_validation_test.dart @@ -0,0 +1,82 @@ +import 'dart:io'; + +import 'package:cutdex/features/properties/canvas_presets.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../integration_test/support/saved_edit_validation.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + for (final changed in [false, true]) { + test( + 'public reopen validation ${changed ? 'detects changed edits' : 'retains saved edits'}', + () async { + final root = await Directory.systemTemp.createTemp( + 'cutdex-saved-edits-', + ); + addTearDown(() => root.delete(recursive: true)); + final directory = Directory('${root.path}/Test.cutdex'); + final sequence = SequenceId('sequence'); + final project = await ProjectFile.create( + directory, + name: 'Test', + initialTimeline: TimelineDocument( + id: 'timeline', + name: 'Timeline', + defaultSequenceId: sequence, + sequences: [ + TimelineDto( + id: sequence, + format: TimelineFormat.fps24, + primaryStorylineId: StorylineId('primary'), + storylines: [ + StorylineDto( + id: StorylineId('primary'), + elementIds: const [], + ), + ], + elements: const [], + ), + ], + ), + ); + final session = EditorSession( + document: await project.loadTimeline('timeline'), + persistence: await project.openTimelineSaveSession('timeline'), + ); + addTearDown(project.close); + addTearDown(session.close); + session.commands.setCanvas(ProjectCanvasPresets.values['4:3']!); + await session.flush(); + final validation = SavedEditValidation(); + await validation.capture(directory.path, 'timeline', session, sequence); + if (changed) { + session.commands.setCanvas(ProjectCanvasPresets.values['16:9']!); + } + await session.close(); + await project.close(); + var verified = 0; + final check = validation.verify( + wait: Future.delayed, + onVerified: (path, id, edits) { + expect(path, directory.path); + expect(id, 'timeline'); + expect(edits['canvas'], containsPair('width', 1440)); + verified++; + }, + ); + if (changed) { + await expectLater(check, throwsA(isA())); + expect(verified, 0); + } else { + await check; + expect(verified, 1); + } + }, + ); + } +} diff --git a/test/settings/settings_operation_test.dart b/test/settings/settings_operation_test.dart new file mode 100644 index 0000000..367c15b --- /dev/null +++ b/test/settings/settings_operation_test.dart @@ -0,0 +1,45 @@ +import 'dart:async'; + +import 'package:cutdex/settings/settings_operation.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + test( + 'duplicate submissions are suppressed and failures permit a retry', + () async { + final container = ProviderContainer(); + addTearDown(container.dispose); + final provider = settingsOperationProvider('save'); + final subscription = container.listen(provider, (_, _) {}); + addTearDown(subscription.close); + final operation = container.read(provider.notifier); + final release = Completer(); + var calls = 0; + final first = operation.run(() async { + calls++; + await release.future; + throw StateError('write failed'); + }); + expect(container.read(provider).isLoading, isTrue); + expect( + await operation.run(() async { + calls++; + }), + isFalse, + ); + release.complete(); + expect(await first, isFalse); + expect(container.read(provider).hasError, isTrue); + expect(calls, 1); + expect( + await operation.run(() async { + calls++; + }), + isTrue, + ); + expect(container.read(provider).hasError, isFalse); + expect(calls, 2); + }, + ); +} diff --git a/test/settings_save_order_test.dart b/test/settings_save_order_test.dart new file mode 100644 index 0000000..988f451 --- /dev/null +++ b/test/settings_save_order_test.dart @@ -0,0 +1,162 @@ +import 'dart:async'; + +import 'package:cutdex/features/settings/appearance_settings.dart'; +import 'package:cutdex/features/settings/language_settings.dart'; +import 'package:cutdex/persistence/app_settings_repositories.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + _testSettings( + name: 'appearance', + initial: AppAppearance.system, + first: AppAppearance.penLight, + second: AppAppearance.penDark, + container: (store) => ProviderContainer( + overrides: [ + appearanceSettingsRepositoryProvider.overrideWithValue( + _AppearanceRepository(store), + ), + ], + ), + load: (container) => container.read(appearanceSettingsProvider.future), + value: (container) => + container.read(appearanceSettingsProvider).requireValue, + save: (container, value) => + container.read(appearanceSettingsProvider.notifier).setMode(value), + ); + _testSettings( + name: 'language', + initial: AppLanguage.system, + first: AppLanguage.english, + second: AppLanguage.simplifiedChinese, + container: (store) => ProviderContainer( + overrides: [ + languageSettingsRepositoryProvider.overrideWithValue( + _LanguageRepository(store), + ), + ], + ), + load: (container) => container.read(languageSettingsProvider.future), + value: (container) => container.read(languageSettingsProvider).requireValue, + save: (container, value) => + container.read(languageSettingsProvider.notifier).setLanguage(value), + ); +} + +void _testSettings({ + required String name, + required T initial, + required T first, + required T second, + required ProviderContainer Function(_Store) container, + required Future Function(ProviderContainer) load, + required T Function(ProviderContainer) value, + required Future Function(ProviderContainer, T) save, +}) { + test('$name saves in order and publishes only committed values', () async { + final store = _Store(initial)..writeGate = Completer(); + final scope = container(store); + addTearDown(scope.dispose); + await load(scope); + final firstSave = save(scope, first); + await store.started.future; + final secondSave = save(scope, second); + await Future.delayed(Duration.zero); + expect(store.writes, [first]); + expect(value(scope), initial); + store.writeGate!.complete(); + await Future.wait([firstSave, secondSave]); + expect(store.writes, [first, second]); + expect(store.value, second); + expect(value(scope), second); + }); + + test('$name can save again after a failed write', () async { + final store = _Store(initial)..failWrites = true; + final scope = container(store); + addTearDown(scope.dispose); + await load(scope); + await expectLater(save(scope, first), throwsStateError); + expect(value(scope), initial); + expect(store.value, initial); + store.failWrites = false; + await save(scope, second); + expect(value(scope), second); + expect(store.value, second); + }); + + test('$name waits for initial load before saving', () async { + final store = _Store(initial)..loadGate = Completer(); + final scope = container(store); + addTearDown(scope.dispose); + final initialLoad = load(scope); + final pending = save(scope, first); + await Future.delayed(Duration.zero); + expect(store.writes, isEmpty); + store.loadGate!.complete(); + await initialLoad; + await pending; + expect(value(scope), first); + expect(store.value, first); + }); + + test('$name finishes an in-flight save safely after disposal', () async { + final store = _Store(initial)..writeGate = Completer(); + final scope = container(store); + await load(scope); + final firstSave = save(scope, first); + await store.started.future; + final queuedSave = save(scope, second); + scope.dispose(); + store.writeGate!.complete(); + await Future.wait([firstSave, queuedSave]); + expect(store.writes, [first]); + expect(store.value, first); + }); +} + +class _Store { + _Store(this.value); + + T value; + final writes = []; + final started = Completer(); + Completer? loadGate; + Completer? writeGate; + bool failWrites = false; + + Future load() async { + final snapshot = value; + await loadGate?.future; + return snapshot; + } + + Future save(T next) async { + writes.add(next); + if (!started.isCompleted) started.complete(); + await writeGate?.future; + if (failWrites) throw StateError('Storage unavailable'); + value = next; + } +} + +class _AppearanceRepository implements AppearanceSettingsRepository { + _AppearanceRepository(this.store); + final _Store store; + + @override + Future load() => store.load(); + @override + Future save(AppAppearance value) => store.save(value); +} + +class _LanguageRepository implements LanguageSettingsRepository { + _LanguageRepository(this.store); + final _Store store; + + @override + Future load() => store.load(); + @override + Future save(AppLanguage value) => store.save(value); +} diff --git a/test/source_preview_test.dart b/test/source_preview_test.dart new file mode 100644 index 0000000..497a4b4 --- /dev/null +++ b/test/source_preview_test.dart @@ -0,0 +1,22 @@ +import 'package:cutdex/workspace/preview_target.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + final asset = AssetDocument( + id: 'source', + name: 'portrait.mov', + storage: AssetStorage.external, + location: 'file:///source.mov', + ); + test('returning to timeline keeps the source position without editing timeline state', () { + final target = PreviewTarget(); + target.showAsset(asset); + target.positions[asset.id] = 42; + target.showTimeline(); + expect(target.asset, isNull); + target.showAsset(asset); + expect(target.positions[asset.id], 42); + target.dispose(); + }); +} diff --git a/test/speed_properties_test.dart b/test/speed_properties_test.dart new file mode 100644 index 0000000..50b836b --- /dev/null +++ b/test/speed_properties_test.dart @@ -0,0 +1,1535 @@ +import 'package:cutdex/app/editor_theme.dart'; + +import 'dart:math' as math; +import 'dart:ui' as ui; + +import 'package:cutdex/features/properties/speed_properties.dart'; +import 'package:cutdex/features/timeline/timeline_speed_editor.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex_ui/widgets.dart'; +import 'package:cutdex/workspace/timeline_session.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/timeline/engine.dart'; +import 'package:cutdex_sdk/timeline/layout.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:cutdex_sdk/timeline_ui.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'support/preview_fixture.dart'; + +void main() { + testWidgets('split speed then blade the clip at arbitrary playheads', ( + tester, + ) async { + final f = (await tester.runAsync( + () => createPreviewFixture( + Uri.file('/test/video.mov'), + clipDuration: RationalTime.seconds(600), + ), + ))!; + final sequence = SequenceId('one'); + final id = ElementId('clip'); + final controller = f.timeline.view(sequence); + final kernel = f.timeline.persistence.timeline(sequence); + f.timeline.setClipSpeed(sequence, id, 1.1); + f.timeline.setCustomSpeedEnabled(sequence, id, true); + final handle = kernel.current.query().elementById(id)!; + controller.setSelection([handle]); + controller.seekTo(666769090558); + final before = kernel.current.query().element(handle); + expect(() => before.retime!.sourceAt(666769090558), throwsArgumentError); + final history = kernel.historyVersions.length; + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + theme: EditorTheme.penLight, + home: Scaffold( + body: SizedBox( + width: 300, + height: 400, + child: SpeedProperties( + session: f.timeline, + sequence: sequence, + clip: id, + ), + ), + ), + ), + ); + await tester.tap(find.byKey(const Key('split-speed-segment'))); + await tester.pump(); + expect(find.byType(SnackBar), findsNothing); + expect(find.text('2 个速度区间'), findsOneWidget); + final split = kernel.current.query().element(handle); + expect(split.retime!.segments, hasLength(2)); + expect(split.retime!.segments.first.projectDuration, 666769090558); + expect(split.duration, before.duration); + expect(split.sourceStart, before.sourceStart); + expect(split.sourceDuration, before.sourceDuration); + expect(controller.playheadTick, 666769090558); + expect(controller.selectedIdentities, contains(handle)); + expect(kernel.historyVersions.length, history + 1); + controller.seekTo(327469570558); + expect( + () => split.retime!.sourceAt(controller.playheadTick), + throwsArgumentError, + ); + expect(controller.cutSelectionAtPlayhead(), isTrue); + expect(controller.commandRejection, isNull); + final cutVersion = kernel.current; + final query = cutVersion.query(); + final left = query.element(handle); + final right = query.element(query.elementAt(query.primaryStoryline, 1)); + expect(f.timeline.isCustomSpeedEnabled(sequence, left.id), isTrue); + expect(f.timeline.isCustomSpeedEnabled(sequence, right.id), isTrue); + expect(controller.geometry.primaryClipHeightFor(handle), 92); + expect( + controller.geometry.primaryClipHeightFor(query.elementById(right.id)!), + 92, + ); + expect(left.duration, 327469570558); + expect(left.duration + right.duration, split.duration); + expect(left.retime!.segments, hasLength(1)); + expect(right.retime!.segments, hasLength(2)); + expect(left.retime!.sourceAt(left.duration), right.retime!.sourceAt(0)); + expect(left.sourceStart, split.sourceStart); + expect( + right.sourceStart + right.sourceDuration, + split.sourceStart + split.sourceDuration, + ); + expect(kernel.historyVersions.length, history + 2); + f.timeline.undo(sequence); + expect(kernel.current.query().element(handle).duration, split.duration); + f.timeline.redo(sequence); + expect(kernel.current, same(cutVersion)); + expect(f.timeline.isCustomSpeedEnabled(sequence, right.id), isTrue); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.runAsync(() async { + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + }); + + for (final connected in [false, true]) { + for (final enabled in [false, true]) { + testWidgets( + 'blade inherits speed visibility: connected $connected, enabled $enabled', + (tester) async { + final duration = RationalTime.seconds(2); + final f = (await tester.runAsync( + () => createPreviewFixture( + Uri.file('/test/video.mov'), + timelineOverride: TimelineDto( + id: SequenceId('one'), + format: TimelineFormat.fps30, + primaryStorylineId: StorylineId('primary'), + storylines: [ + StorylineDto( + id: StorylineId('primary'), + elementIds: [ + if (!connected) ElementId('clip'), + ElementId('normal'), + ], + ), + ], + elements: [ + for (final id in ['clip', 'normal']) + ElementDto( + id: ElementId(id), + structure: ElementStructure.content, + payloadRef: PayloadRef('source'), + duration: duration, + sourceRange: TimeRange( + start: RationalTime.zero, + duration: duration, + ), + mediaRange: TimeRange( + start: RationalTime.zero, + duration: duration, + ), + ), + ], + connections: [ + if (connected) + ConnectionDto( + id: ConnectionId('connection'), + anchorId: ElementId('normal'), + targetId: ElementId('clip'), + anchorTime: RationalTime.zero, + targetTime: RationalTime.zero, + side: ConnectionSide.above, + ), + ], + ), + ), + ))!; + final sequence = SequenceId('one'); + final session = f.timeline; + final view = session.view(sequence); + final kernel = session.persistence.timeline(sequence); + session.setClipSpeed(sequence, ElementId('clip'), 1.1); + session.setCustomSpeedEnabled(sequence, ElementId('clip'), enabled); + final query = kernel.current.query(); + final clip = query.elementById(ElementId('clip'))!; + final normal = query.elementById(ElementId('normal'))!; + view.setSelection([connected ? LayoutBodyId.element(clip) : clip]); + view.setCamera(view.camera.panBy(verticalPixels: -100)); + await tester.pumpWidget( + MaterialApp( + theme: EditorTheme.penLight, + home: Scaffold( + body: SizedBox( + width: 800, + height: 400, + child: _speedSurface( + session: session, + sequence: sequence, + controller: view, + ), + ), + ), + ), + ); + final before = kernel.current; + view.seekTo(7 * TimelineClock.ticksPerSecond ~/ 10); + expect(view.cutSelectionAtPlayhead(), isTrue); + await tester.pump(); + final cutVersion = kernel.current; + final cutQuery = cutVersion.query(); + final rightId = kernel + .exportDto() + .elements + .singleWhere( + (e) => e.id != ElementId('clip') && e.id != ElementId('normal'), + ) + .id; + final right = cutQuery.elementById(rightId)!; + void expectHeaders(int count) { + expect( + find.byKey(const ValueKey('speed-segment-0')), + findsNWidgets(count), + ); + expect( + session.isCustomSpeedEnabled(sequence, ElementId('normal')), + isFalse, + ); + expect(view.geometry.primaryClipHeightFor(normal), 76); + } + + expect(session.isCustomSpeedEnabled(sequence, rightId), enabled); + expect(view.geometry.primaryClipHeightFor(right), enabled ? 92 : 76); + if (connected) { + expect( + view.version.scene.bodies[LayoutBodyId.element(right)]!.height, + enabled ? 92 : 76, + ); + } + expectHeaders(enabled ? 2 : 0); + view.clearSelection(); + await tester.pump(); + expectHeaders(enabled ? 2 : 0); + session.undo(sequence); + await tester.pump(); + expect(kernel.current, same(before)); + expectHeaders(enabled ? 1 : 0); + session.redo(sequence); + await tester.pump(); + expect(kernel.current, same(cutVersion)); + expectHeaders(enabled ? 2 : 0); + + // Each fragment can be disabled independently; its next split inherits + // that current choice rather than the original ancestor's choice. + session.setCustomSpeedEnabled(sequence, rightId, false); + await tester.pump(); + expectHeaders(enabled ? 1 : 0); + view.setSelection([connected ? LayoutBodyId.element(right) : right]); + view.seekTo(TimelineClock.ticksPerSecond); + expect(view.cutSelectionAtPlayhead(), isTrue); + await tester.pump(); + expectHeaders(enabled ? 1 : 0); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.runAsync(() async { + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + }, + ); + } + } + + for (final start in ['top', 'bottom', 'diagonal']) { + testWidgets('speed handle owns edge gestures: $start', (tester) async { + final f = (await tester.runAsync( + () => createPreviewFixture(Uri.file('/test/video.mov')), + ))!; + final sequence = SequenceId('one'); + final id = ElementId('clip'); + final controller = f.timeline.view(sequence); + final kernel = f.timeline.persistence.timeline(sequence); + final before = kernel.current; + final handle = before.query().elementById(id)!; + final original = before.query().element(handle); + final history = kernel.historyVersions.length; + f.timeline.setCustomSpeedEnabled(sequence, id, true); + await tester.pumpWidget( + MaterialApp( + theme: EditorTheme.penLight, + home: Scaffold( + body: SizedBox( + width: 800, + height: 400, + child: TimelineInteractionRegion( + controller: controller, + edgeScrollExtent: 0, + child: _speedSurface( + session: f.timeline, + sequence: sequence, + controller: controller, + ), + ), + ), + ), + ), + ); + final bar = tester.getRect(find.byKey(const ValueKey('speed-segment-0'))); + final viewport = TimelineViewportRect(width: 800, height: 400); + final edge = Offset(bar.right - 2.5, bar.top + 16 + 38); + expect( + controller.beginDrag( + viewport: viewport, + position: edge, + trimHitExtent: 6, + ), + isTrue, + ); + expect( + controller.finishDrag(viewport: viewport, position: edge), + isFalse, + ); + await tester.pump(); + expect(controller.trimOutlineEdgeFor(handle), TimelineTrimEdge.trailing); + // The bar stops 2 px before the clip edge; its pill is inset another 3 px. + final position = switch (start) { + 'top' => Offset(bar.right - 2.5, bar.top + 1), + 'bottom' => Offset(bar.right - 2.5, bar.bottom - 1), + _ => Offset(bar.right - 5.5, bar.center.dy), + }; + final gesture = await tester.startGesture( + position, + kind: ui.PointerDeviceKind.mouse, + ); + if (start == 'diagonal') { + await gesture.moveBy(const Offset(1, 30)); + await tester.pump(); + expect(controller.isDragging, isFalse); + expect(controller.trimOutlineEdgeFor(handle), isNull); + } + for (var i = 0; i < 2; i++) { + await gesture.moveBy(const Offset(-30, 0)); + await tester.pump(); + expect(controller.isDragging, isFalse); + expect(controller.trimOutlineEdgeFor(handle), isNull); + expect(controller.selectedIdentities, contains(handle)); + expect(kernel.current, same(before)); + } + final preview = controller + .project(TimelineViewportRect(width: 800, height: 400)) + .version + .kernelVersion + .query() + .element(handle); + expect(preview.duration, lessThan(original.duration)); + expect(preview.sourceStart, original.sourceStart); + expect(preview.sourceDuration, original.sourceDuration); + await gesture.up(); + await tester.pump(); + final committed = kernel.current.query().element(handle); + expect(committed.duration, preview.duration); + expect(committed.sourceStart, original.sourceStart); + expect(committed.sourceDuration, original.sourceDuration); + expect(kernel.historyVersions.length, history + 1); + expect(controller.trimOutlineEdgeFor(handle), isNull); + final published = kernel.current; + final updatedBar = tester.getRect( + find.byKey(const ValueKey('speed-segment-0')), + ); + final trim = await tester.startGesture( + Offset(updatedBar.right - 2.5, updatedBar.top + 16 + 38), + kind: ui.PointerDeviceKind.mouse, + ); + await trim.moveBy(const Offset(-24, 0)); + await tester.pump(); + expect(controller.isTrimming, isTrue); + expect(controller.dragRejection, isNull); + await trim.cancel(); + await tester.pump(); + expect(kernel.current, same(published)); + expect(kernel.historyVersions.length, history + 1); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.runAsync(() async { + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + }); + } + + testWidgets( + 'speed handle keeps the background stable when crossing 100 percent', + (tester) async { + final f = (await tester.runAsync( + () => createPreviewFixture(Uri.file('/test/video.mov')), + ))!; + final sequence = SequenceId('one'); + final id = ElementId('clip'); + final view = f.timeline.view(sequence); + final kernel = f.timeline.persistence.timeline(sequence); + final before = kernel.current; + final history = kernel.historyVersions.length; + f.timeline.setCustomSpeedEnabled(sequence, id, true); + const boundaryKey = Key('speed-drag-background'); + for (final theme in [EditorTheme.penLight, EditorTheme.penDark]) { + await tester.pumpWidget( + MaterialApp( + theme: theme, + home: Scaffold( + body: RepaintBoundary( + key: boundaryKey, + child: SizedBox( + width: 800, + height: 400, + child: _speedSurface( + session: f.timeline, + sequence: sequence, + controller: view, + ), + ), + ), + ), + ), + ); + await tester.pump(); + final sample = + tester.getTopLeft(find.byKey(ValueKey((sequence, id)))) + + const Offset(12, 11); + final color = await _surfacePixel(tester, boundaryKey, sample); + final gesture = await tester.startGesture( + tester.getCenter( + find.byKey(const ValueKey('speed-segment-handle-0')), + ), + ); + for (final delta in [30.0, 30.0, -60.0, -30.0, 30.0]) { + await gesture.moveBy(Offset(delta, 0)); + await tester.pump(); + expect( + await _surfacePixel(tester, boundaryKey, sample), + color, + reason: 'Changing speed through 100% must not toggle the background shade.', + ); + } + await gesture.cancel(); + await tester.pump(); + expect(kernel.current, same(before)); + expect(kernel.historyVersions.length, history); + expect(await _surfacePixel(tester, boundaryKey, sample), color); + } + await tester.pumpWidget(const SizedBox.shrink()); + await tester.runAsync(() async { + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + }, + ); + + testWidgets('speed sections share their clip stacking during overlaps', ( + tester, + ) async { + final sequence = SequenceId('one'); + final clipId = ElementId('clip'); + final otherId = ElementId('other'); + final f = (await tester.runAsync( + () => createPreviewFixture( + Uri.file('/test/video.mov'), + timelineOverride: TimelineDto( + id: sequence, + format: TimelineFormat.fps30, + primaryStorylineId: StorylineId('primary'), + storylines: [ + StorylineDto( + id: StorylineId('primary'), + elementIds: [clipId, otherId], + ), + ], + elements: [ + for (final id in [clipId, otherId]) + ElementDto( + id: id, + structure: ElementStructure.content, + payloadRef: PayloadRef('source'), + duration: RationalTime.seconds(2), + sourceRange: TimeRange( + start: RationalTime.zero, + duration: RationalTime.seconds(2), + ), + mediaRange: TimeRange( + start: RationalTime.zero, + duration: RationalTime.seconds(2), + ), + ), + ], + ), + ), + ))!; + final view = f.timeline.view(sequence); + final query = view.version.kernelVersion.query(); + final clip = query.elementById(clipId)!; + final other = query.elementById(otherId)!; + f.timeline.setCustomSpeedEnabled(sequence, clipId, true); + const boundaryKey = Key('speed-stacking-surface'); + const mediaColor = Color(0xff2468ac); + final viewport = TimelineViewportRect(width: 800, height: 400); + await tester.pumpWidget( + MaterialApp( + theme: EditorTheme.penLight, + home: Scaffold( + body: RepaintBoundary( + key: boundaryKey, + child: SizedBox( + width: 800, + height: 400, + child: _speedSurface( + session: f.timeline, + sequence: sequence, + controller: view, + theme: const TimelineThemeData.dark().copyWith( + visualClipColor: mediaColor, + playheadWidth: 0, + ), + ), + ), + ), + ), + ), + ); + await tester.pump(); + final stationaryPoint = + tester.getTopLeft(find.byKey(ValueKey((sequence, clipId)))) + + const Offset(12, 11); + final headerColor = await _surfacePixel( + tester, + boundaryKey, + stationaryPoint, + ); + final frame = view.project(viewport); + final otherIndex = List.generate( + frame.length, + (index) => index, + ).singleWhere((index) => frame.identityAt(index) == other); + final origin = + view.presentationBoundsAt(frame, otherIndex).topLeft + + const Offset(60, 40); + view.setSelection([other]); + expect(view.beginDrag(viewport: viewport, position: origin), isTrue); + view.updateDrag( + viewport: viewport, + position: origin + const Offset(-120, -30), + ); + await tester.pump(); + expect( + await _surfacePixel(tester, boundaryKey, stationaryPoint), + [36, 104, 172, 255], + reason: + 'A moving clip must cover the stationary clip and its speed header.', + ); + view.cancelDrag(); + await tester.pump(); + view.setSelection([clip]); + final clipOrigin = + tester.getTopLeft(find.byKey(ValueKey((sequence, clipId)))) + + const Offset(60, 40); + expect(view.beginDrag(viewport: viewport, position: clipOrigin), isTrue); + view.updateDrag( + viewport: viewport, + position: clipOrigin + const Offset(120, 30), + ); + await tester.pump(); + final movingPoint = + tester.getTopLeft(find.byKey(ValueKey((sequence, clipId)))) + + const Offset(12, 11); + expect( + await _surfacePixel(tester, boundaryKey, movingPoint), + headerColor, + reason: + 'A moving speed header must stay above clips underneath its owner.', + ); + view.cancelDrag(); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.runAsync(() async { + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + }); + + testWidgets( + 'speed backgrounds preserve selection and drag outlines without hover frames', + (tester) async { + final f = (await tester.runAsync( + () => createPreviewFixture(Uri.file('/test/video.mov')), + ))!; + final sequence = SequenceId('one'); + final id = ElementId('clip'); + final view = f.timeline.view(sequence); + final handle = view.version.kernelVersion.query().elementById(id)!; + f.timeline.setCustomSpeedEnabled(sequence, id, true); + const boundaryKey = Key('speed-outline-surface'); + const selectedColor = Color(0xffcc44aa); + final outlineTheme = const TimelineThemeData.dark().copyWith( + selectionOutlineColor: selectedColor, + selectionOutlineWidth: 2, + playheadWidth: 0, + ); + + Future> borderPixel() async { + await tester.pump(); + final boundary = tester.renderObject( + find.byKey(boundaryKey), + ); + final point = + tester.getTopLeft(find.byKey(ValueKey((sequence, id)))) - + tester.getTopLeft(find.byKey(boundaryKey)) + + const Offset(12, 0); + return (await tester.runAsync(() async { + final image = await boundary.toImage(pixelRatio: 1); + try { + final pixels = (await image.toByteData( + format: ui.ImageByteFormat.rawRgba, + ))!; + final offset = + (point.dy.floor() * image.width + point.dx.floor()) * 4; + return [for (var i = 0; i < 4; i++) pixels.getUint8(offset + i)]; + } finally { + image.dispose(); + } + }))!; + } + + for (final theme in [EditorTheme.penLight, EditorTheme.penDark]) { + view.setHoveredIdentity(null); + view.setSelection([handle]); + await tester.pumpWidget( + MaterialApp( + theme: theme, + home: Scaffold( + body: RepaintBoundary( + key: boundaryKey, + child: SizedBox( + width: 800, + height: 400, + child: _speedSurface( + session: f.timeline, + sequence: sequence, + controller: view, + theme: outlineTheme, + ), + ), + ), + ), + ), + ); + expect(await borderPixel(), [204, 68, 170, 255]); + view.clearSelection(); + final idlePixel = await borderPixel(); + expect(idlePixel, isNot([204, 68, 170, 255])); + view.setHoveredIdentity(handle); + expect(await borderPixel(), idlePixel); + view.setSelection([handle]); + expect(await borderPixel(), [204, 68, 170, 255]); + view.setHoveredIdentity(null); + final origin = + tester.getTopLeft(find.byKey(ValueKey((sequence, id)))) + + const Offset(60, 40); + final viewport = TimelineViewportRect(width: 800, height: 400); + expect(view.beginDrag(viewport: viewport, position: origin), isTrue); + view.updateDrag( + viewport: viewport, + position: origin + const Offset(30, 20), + ); + expect(await borderPixel(), [204, 68, 170, 255]); + view.cancelDrag(); + } + await tester.pumpWidget(const SizedBox.shrink()); + await tester.runAsync(() async { + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + }, + ); + + testWidgets('speed backgrounds retain their color over overlapping clips', ( + tester, + ) async { + final f = (await tester.runAsync( + () => createPreviewFixture(Uri.file('/test/video.mov')), + ))!; + final sequence = SequenceId('one'); + final id = ElementId('clip'); + final view = f.timeline.view(sequence); + f.timeline.setCustomSpeedEnabled(sequence, id, true); + const boundaryKey = Key('overlapping-speed-background'); + + Future> backgroundPixel(ThemeData theme, Color underneath) async { + await tester.pumpWidget( + MaterialApp( + theme: theme, + home: Scaffold( + body: RepaintBoundary( + key: boundaryKey, + child: SizedBox( + width: 800, + height: 400, + child: _speedSurface( + session: f.timeline, + sequence: sequence, + controller: view, + theme: theme.extension()!.copyWith( + primaryLaneBackgroundColor: underneath, + ), + ), + ), + ), + ), + ), + ); + await tester.pump(); + final boundary = tester.renderObject( + find.byKey(boundaryKey), + ); + final point = + tester.getTopLeft(find.byKey(const ValueKey('speed-segment-0'))) - + tester.getTopLeft(find.byKey(boundaryKey)) + + const Offset(10, 11); + return (await tester.runAsync(() async { + final image = await boundary.toImage(pixelRatio: 1); + try { + final pixels = (await image.toByteData( + format: ui.ImageByteFormat.rawRgba, + ))!; + final offset = + (point.dy.floor() * image.width + point.dx.floor()) * 4; + return [for (var i = 0; i < 4; i++) pixels.getUint8(offset + i)]; + } finally { + image.dispose(); + } + }))!; + } + + for (final theme in [EditorTheme.penLight, EditorTheme.penDark]) { + for (final speed in [1.0, 2.0]) { + f.timeline.setClipSpeed(sequence, id, speed); + final overRed = await backgroundPixel(theme, Colors.red); + final overBlue = await backgroundPixel(theme, Colors.blue); + expect( + overRed, + overBlue, + reason: + 'Underlying clip colors must not bleed through speed sections.', + ); + } + } + await tester.pumpWidget(const SizedBox.shrink()); + await tester.runAsync(() async { + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + }); + + testWidgets( + 'speed slider commits once, preserves source and supports undo and reset', + (tester) async { + final f = (await tester.runAsync( + () => createPreviewFixture(Uri.file('/test/video.mov'), hasAudio: true), + ))!; + final sequence = SequenceId('one'); + final id = ElementId('clip'); + final kernel = f.timeline.persistence.timeline(sequence); + final before = kernel.current; + final history = kernel.historyVersions.length; + final source = before.query().element(before.query().elementById(id)!); + final view = f.timeline.view(sequence); + view.setSelection([before.query().elementById(id)!]); + final selection = view.selectedIdentities.toList(); + // Preview and view-state consumers read the authoritative root inside + // the notification, before widgets rebuild on the next frame. + void observeLayout() { + view.version; + } + + view.editingChanges.addListener(observeLayout); + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + theme: EditorTheme.penLight, + home: Scaffold( + body: SizedBox( + width: 800, + height: 400, + child: Row( + children: [ + SizedBox( + width: 225, + child: SpeedProperties( + session: f.timeline, + sequence: sequence, + clip: id, + ), + ), + Expanded( + child: _speedSurface( + session: f.timeline, + sequence: sequence, + controller: view, + ), + ), + ], + ), + ), + ), + ), + ); + expect(f.timeline.isCustomSpeedEnabled(sequence, id), isFalse); + expect(view.geometry.primaryHeight, 88); + expect( + view.geometry.primaryClipHeightFor(before.query().elementById(id)!), + 76, + ); + expect(find.byKey(const ValueKey('speed-segment-0')), findsNothing); + expect( + tester + .widget( + find.byKey(const Key('split-speed-segment')), + ) + .onPressed, + isNull, + ); + await tester.tap(find.byKey(const Key('clip-custom-speed-toggle'))); + await tester.pumpAndSettle(); + expect(f.timeline.isCustomSpeedEnabled(sequence, id), isTrue); + expect(view.selectedIdentities, selection); + expect(view.geometry.primaryHeight, 98); + expect(find.byKey(const ValueKey('speed-segment-0')), findsOneWidget); + expect(kernel.current, same(before)); + expect(kernel.historyVersions.length, history); + AppSlider slider() => + tester.widget(find.byKey(const Key('clip-speed-slider'))); + final position = (math.log(2) / math.ln10 + 1) / 3; + slider().onChangeStart!(position); + slider().onChanged!(position); + await tester.pump(); + expect(find.text('2.00×'), findsOneWidget); + expect(kernel.current, same(before)); + expect(kernel.historyVersions.length, history); + final previewFrame = view.project( + TimelineViewportRect(width: 800, height: 400), + ); + expect(previewFrame.version.kernelVersion, isNot(same(before))); + final previewQuery = previewFrame.version.kernelVersion.query(); + expect( + previewQuery.element(previewQuery.elementById(id)!).duration, + source.duration ~/ 2, + ); + expect( + tester.getSize(find.byKey(const ValueKey('speed-segment-0'))).width, + closeTo(60, 1e-6), + ); + expect( + find.byWidgetPredicate( + (widget) => widget is Semantics && widget.properties.label == '200%', + ), + findsOneWidget, + ); + await tester.runAsync(() async { + slider().onChangeEnd!(position); + await f.timeline.flush(); + }); + await tester.pumpAndSettle(); + final q = kernel.current.query(); + final changed = q.element(q.elementById(id)!); + expect(changed.duration, source.duration ~/ 2); + expect(changed.sourceStart, source.sourceStart); + expect(changed.sourceDuration, source.sourceDuration); + expect(view.selectedIdentities, selection); + await tester.runAsync(() async { + f.timeline.undo(sequence); + await f.timeline.flush(); + }); + await tester.pumpAndSettle(); + expect(kernel.current, same(before)); + expect(find.text('1.00×'), findsOneWidget); + await tester.runAsync(() async { + for (final rate in [0.1, 100.0, 2.0]) { + f.timeline.setClipSpeed(sequence, id, rate); + final query = kernel.current.query(); + expect( + f.timeline.clipSpeed(query.element(query.elementById(id)!)), + closeTo(rate, 0.001), + ); + } + await f.timeline.flush(); + }); + await tester.pumpAndSettle(); + await tester.runAsync(() async { + await tester.tap(find.text('1×')); + await tester.pump(); + await f.timeline.flush(); + }); + await tester.pumpAndSettle(); + expect(find.text('1.00×'), findsOneWidget); + view.seekTo(source.duration ~/ 2); + await tester.pump(); + await tester.runAsync(() async { + await tester.tap(find.byKey(const Key('split-speed-segment'))); + await tester.pump(); + await f.timeline.flush(); + }); + await tester.pumpAndSettle(); + expect(find.text('2 个速度区间'), findsOneWidget); + expect(find.byKey(const Key('clip-speed-slider')), findsNothing); + final segmented = kernel.current; + final segmentedHistory = kernel.historyVersions.length; + await tester.tap(find.byKey(const Key('clip-custom-speed-toggle'))); + await tester.pumpAndSettle(); + expect(f.timeline.isCustomSpeedEnabled(sequence, id), isFalse); + expect(view.selectedIdentities, selection); + expect(view.geometry.primaryHeight, 88); + expect(find.byKey(const ValueKey('speed-segment-0')), findsNothing); + expect(kernel.current, same(segmented)); + expect(kernel.historyVersions.length, segmentedHistory); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.runAsync(() async { + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + }, + ); + + testWidgets('timeline speed handle expands the clip and commits once', ( + tester, + ) async { + final f = (await tester.runAsync( + () => createPreviewFixture(Uri.file('/test/video.mov'), hasAudio: true), + ))!; + final sequence = SequenceId('one'); + final id = ElementId('clip'); + final kernel = f.timeline.persistence.timeline(sequence); + final controller = f.timeline.view(sequence); + final handle = kernel.current.query().elementById(id)!; + controller.setSelection([handle]); + final before = kernel.current; + final history = kernel.historyVersions.length; + expect(controller.geometry.primaryHeight, 88); + expect(controller.geometry.primaryLaneHeight, 88); + expect(controller.geometry.primaryClipHeightFor(handle), 76); + f.timeline.setCustomSpeedEnabled(sequence, id, true); + expect(controller.geometry.primaryHeight, 98); + expect(controller.geometry.primaryLaneHeight, 88); + expect(controller.geometry.primaryLaneTop, 58); + expect(controller.geometry.primaryClipTopFor(handle), 48); + expect(controller.geometry.primaryClipHeightFor(handle), 92); + expect(kernel.current, same(before)); + expect(kernel.historyVersions.length, history); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SizedBox( + width: 800, + height: 400, + child: _speedSurface( + session: f.timeline, + sequence: sequence, + controller: controller, + ), + ), + ), + ), + ); + await tester.pump(); + expect(find.byKey(const ValueKey('speed-segment-0')), findsOneWidget); + expect( + tester.getSize(find.byKey(const ValueKey('speed-segment-0'))).height, + 14, + ); + final frame = controller.project( + TimelineViewportRect(width: 800, height: 400), + ); + final index = List.generate( + frame.length, + (index) => index, + ).singleWhere((index) => frame.identityAt(index) == handle); + final bounds = controller.presentationBoundsAt(frame, index); + expect(bounds.height, 92); + expect( + tester.getTopLeft(find.byKey(const ValueKey('speed-segment-0'))).dy, + bounds.top, + ); + final gesture = await tester.startGesture( + tester.getCenter(find.byKey(const ValueKey('speed-segment-handle-0'))), + ); + await gesture.moveBy(const Offset(30, 0)); + await tester.pump(); + await gesture.moveBy(const Offset(30, 0)); + await tester.pump(); + expect(kernel.current, same(before)); + expect(kernel.historyVersions.length, history); + final previewFrame = controller.project( + TimelineViewportRect(width: 800, height: 400), + ); + expect(previewFrame.version.kernelVersion, isNot(same(before))); + expect( + previewFrame.version.kernelVersion.query().element(handle).duration, + 3 * TimelineClock.ticksPerSecond, + ); + expect(controller.contentEndTick, 3 * TimelineClock.ticksPerSecond); + await gesture.up(); + await tester.pump(); + expect(kernel.current, isNot(same(before))); + expect(kernel.historyVersions.length, history + 1); + expect( + kernel.current.query().element(handle).duration, + 3 * TimelineClock.ticksPerSecond, + ); + f.timeline.setCustomSpeedEnabled(sequence, id, false); + await tester.pump(); + expect(find.byKey(const ValueKey('speed-segment-0')), findsNothing); + expect(controller.geometry.primaryHeight, 88); + expect(controller.geometry.primaryLaneHeight, 88); + expect(controller.geometry.primaryClipHeightFor(handle), 76); + expect(controller.geometry.primaryClipTopFor(handle), 54); + f.timeline.undo(sequence); + await tester.pump(); + expect(controller.geometry.primaryHeight, 88); + expect(controller.geometry.primaryClipHeightFor(handle), 76); + f.timeline.redo(sequence); + await tester.pump(); + expect(controller.geometry.primaryHeight, 88); + expect(controller.geometry.primaryClipHeightFor(handle), 76); + expect(kernel.historyVersions.length, history + 1); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.runAsync(() async { + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + }); + + testWidgets('speed dimensions preserve other clips and connected spacing', ( + tester, + ) async { + final duration = RationalTime.seconds(2); + final fixture = TimelineDto( + id: SequenceId('one'), + name: 'one', + format: TimelineFormat.fps30, + primaryStorylineId: StorylineId('primary'), + storylines: [ + StorylineDto( + id: StorylineId('primary'), + elementIds: [ElementId('clip'), ElementId('normal')], + ), + ], + elements: [ + for (final id in ['clip', 'normal', 'above', 'below']) + ElementDto( + id: ElementId(id), + structure: ElementStructure.content, + payloadRef: PayloadRef('source'), + duration: duration, + sourceRange: TimeRange( + start: RationalTime.zero, + duration: duration, + ), + mediaRange: TimeRange(start: RationalTime.zero, duration: duration), + ), + ], + connections: [ + for (final side in ConnectionSide.values) + ConnectionDto( + id: ConnectionId(side.name), + anchorId: ElementId('clip'), + targetId: ElementId(side.name), + anchorTime: RationalTime.zero, + targetTime: RationalTime.zero, + side: side, + ), + ], + ); + final f = (await tester.runAsync( + () => createPreviewFixture( + Uri.file('/test/video.mov'), + timelineOverride: fixture, + ), + ))!; + final sequence = SequenceId('one'); + final kernel = f.timeline.persistence.timeline(sequence); + final authored = kernel.current; + final history = kernel.historyVersions.length; + final query = authored.query(); + final main = query.elementById(ElementId('clip'))!; + final normal = query.elementById(ElementId('normal'))!; + final above = query.elementById(ElementId('above'))!; + final below = query.elementById(ElementId('below'))!; + final view = f.timeline.view(sequence); + final belowTop = view.version.placementOf(LayoutBodyId.element(below)).top; + final aboveTop = view.version.placementOf(LayoutBodyId.element(above)).top; + view.setSelection([main]); + f.timeline.setCustomSpeedEnabled(sequence, ElementId('clip'), true); + expect(view.geometry.primaryHeight, 98); + expect(view.geometry.primaryClipHeightFor(normal), 76); + expect(view.geometry.primaryClipTopFor(normal), 64); + expect( + view.version.placementOf(LayoutBodyId.element(below)).top, + belowTop + 10, + ); + expect(view.version.placementOf(LayoutBodyId.element(above)).top, aboveTop); + + await tester.pumpWidget( + MaterialApp( + theme: EditorTheme.penLight, + home: Scaffold( + body: SizedBox( + width: 800, + height: 400, + child: _speedSurface( + session: f.timeline, + sequence: sequence, + controller: view, + ), + ), + ), + ), + ); + view.setCamera(view.camera.panBy(verticalPixels: -100)); + view.clearSelection(); + await tester.pump(); + expect(view.geometry.primaryHeight, 98); + expect(view.geometry.primaryClipHeightFor(main), 92); + expect(find.byKey(const ValueKey('speed-segment-0')), findsOneWidget); + + // Every enabled clip retains its own header, independently of selection. + view.setSelection([above]); + f.timeline.setCustomSpeedEnabled(sequence, ElementId('above'), true); + await tester.pump(); + expect(view.geometry.primaryHeight, 98); + expect( + f.timeline.isCustomSpeedEnabled(sequence, ElementId('clip')), + isTrue, + ); + expect(find.byKey(const ValueKey('speed-segment-0')), findsNWidgets(2)); + final body = view.version.scene.bodies[LayoutBodyId.element(above)]!; + expect(body.height, 92); + expect(view.version.placementOf(body.id).top, aboveTop - 16); + expect( + view.version.placementOf(LayoutBodyId.element(below)).top, + belowTop + 10, + ); + view.setSelection([normal]); + await tester.pump(); + expect(find.byKey(const ValueKey('speed-segment-0')), findsNWidgets(2)); + f.timeline.setCustomSpeedEnabled(sequence, ElementId('normal'), true); + await tester.pump(); + expect(find.byKey(const ValueKey('speed-segment-0')), findsNWidgets(3)); + f.timeline.setCustomSpeedEnabled(sequence, ElementId('clip'), false); + await tester.pump(); + expect(view.geometry.primaryHeight, 98); + expect(view.geometry.primaryClipHeightFor(main), 76); + expect(view.geometry.primaryClipHeightFor(normal), 92); + expect(find.byKey(const ValueKey('speed-segment-0')), findsNWidgets(2)); + f.timeline.setCustomSpeedEnabled(sequence, ElementId('clip'), true); + f.timeline.setCustomSpeedEnabled(sequence, ElementId('normal'), false); + await tester.pump(); + expect(view.geometry.primaryClipHeightFor(normal), 76); + expect(find.byKey(const ValueKey('speed-segment-0')), findsNWidgets(2)); + f.timeline.selectSequence(SequenceId('empty')); + f.timeline.selectSequence(sequence); + await tester.pump(); + expect(find.byKey(const ValueKey('speed-segment-0')), findsNWidgets(2)); + final dragViewport = TimelineViewportRect(width: 800, height: 400); + Future checkClipDrag(ElementHandle source) async { + final frame = view.project(dragViewport); + final index = List.generate(frame.length, (index) => index).singleWhere( + (index) => view.elementForIdentity(frame.identityAt(index)) == source, + ); + final sourceBounds = view.presentationBoundsAt(frame, index); + final origin = Offset(sourceBounds.left + 60, sourceBounds.top + 40); + expect(view.beginDrag(viewport: dragViewport, position: origin), isTrue); + for (final delta in [const Offset(30, 20), const Offset(120, -20)]) { + view.updateDrag(viewport: dragViewport, position: origin + delta); + await tester.pump(); + expect(view.dragGhosts, isNotEmpty); + for (final ghost in view.dragGhosts) { + final record = query.element(ghost.body.id.owner); + if (!f.timeline.isCustomSpeedEnabled(sequence, record.id)) continue; + final expected = Offset( + view.camera.screenXForTick(ghost.body.start, dragViewport), + view.camera.screenYForWorld(ghost.top.toDouble(), dragViewport), + ); + expect( + tester.getTopLeft(find.byKey(ValueKey((sequence, record.id)))), + expected, + reason: 'The speed header must follow its moving clip, including carried clips.', + ); + } + } + view.cancelDrag(); + await tester.pump(); + expect(kernel.current, same(authored)); + expect(find.byKey(const ValueKey('speed-segment-0')), findsNWidgets(2)); + } + + await checkClipDrag(main); + await checkClipDrag(above); + view.setSelection([normal]); + await tester.pump(); + // Unselected clips remain editable, and each bar edits its own clip. + final aboveBar = find.descendant( + of: find.byKey(ValueKey((sequence, ElementId('above')))), + matching: find.byKey(const ValueKey('speed-segment-handle-0')), + ); + final drag = await tester.startGesture(tester.getCenter(aboveBar)); + await drag.moveBy(const Offset(30, 0)); + await tester.pump(); + await drag.moveBy(const Offset(30, 0)); + await tester.pump(); + await drag.up(); + await tester.pump(); + expect( + kernel.current.query().element(above).duration, + greaterThan(query.element(above).duration), + ); + expect( + kernel.current.query().element(main).duration, + query.element(main).duration, + ); + expect( + kernel.current.query().element(normal).duration, + query.element(normal).duration, + ); + expect(view.selectedIdentities, [normal]); + f.timeline.undo(sequence); + await tester.pump(); + expect(kernel.current, same(authored)); + expect(find.byKey(const ValueKey('speed-segment-0')), findsNWidgets(2)); + f.timeline.setCustomSpeedEnabled(sequence, ElementId('clip'), false); + await tester.pump(); + expect(view.geometry.primaryHeight, 88); + expect(view.geometry.primaryClipHeightFor(main), 76); + expect( + f.timeline.isCustomSpeedEnabled(sequence, ElementId('above')), + isTrue, + ); + expect(find.byKey(const ValueKey('speed-segment-0')), findsOneWidget); + expect(view.version.scene.bodies[LayoutBodyId.element(above)]!.height, 92); + expect(view.version.placementOf(LayoutBodyId.element(below)).top, belowTop); + expect(kernel.current, same(authored)); + expect(kernel.historyVersions.length, history + 1); + + f.timeline.setClipSpeed(sequence, ElementId('above'), 2); + f.timeline.setClipSpeed(sequence, ElementId('above'), 1); + f.timeline.setCustomSpeedEnabled(sequence, ElementId('above'), false); + for (final move in [ + f.timeline.undo, + f.timeline.undo, + f.timeline.redo, + f.timeline.redo, + ]) { + move(sequence); + expect(view.geometry.primaryHeight, 88); + expect( + view.version.scene.bodies[LayoutBodyId.element(above)]!.height, + 76, + ); + } + expect(kernel.historyVersions.length, history + 2); + await tester.pump(); + expect(find.byKey(const ValueKey('speed-segment-0')), findsNothing); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.runAsync(() async { + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + }); + + testWidgets('speed handle cancels when the authored version changes', ( + tester, + ) async { + final f = (await tester.runAsync( + () => createPreviewFixture(Uri.file('/test/video.mov'), hasAudio: true), + ))!; + final sequence = SequenceId('one'); + final id = ElementId('clip'); + final kernel = f.timeline.persistence.timeline(sequence); + final controller = f.timeline.view(sequence); + final handle = kernel.current.query().elementById(id)!; + controller.setSelection([handle]); + f.timeline.setCustomSpeedEnabled(sequence, id, true); + final history = kernel.historyVersions.length; + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SizedBox( + width: 800, + height: 400, + child: _speedSurface( + session: f.timeline, + sequence: sequence, + controller: controller, + ), + ), + ), + ), + ); + await tester.pump(); + final gesture = await tester.startGesture( + tester.getCenter(find.byKey(const ValueKey('speed-segment-handle-0'))), + ); + await gesture.moveBy(const Offset(30, 0)); + await tester.pump(); + expect( + controller + .project(TimelineViewportRect(width: 800, height: 400)) + .version + .kernelVersion, + isNot(same(kernel.current)), + ); + + f.timeline.setClipSpeed(sequence, id, 1.5); + final externallyChanged = kernel.current; + await tester.pump(); + await gesture.moveBy(const Offset(30, 0)); + await tester.pump(); + expect( + controller + .project(TimelineViewportRect(width: 800, height: 400)) + .version + .kernelVersion, + same(externallyChanged), + ); + await gesture.up(); + await tester.pump(); + expect(kernel.current, same(externallyChanged)); + expect(kernel.historyVersions.length, history + 1); + + await tester.pumpWidget(const SizedBox.shrink()); + await tester.runAsync(() async { + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + }); + + testWidgets('speed slider cancels when the authored version changes', ( + tester, + ) async { + final f = (await tester.runAsync( + () => createPreviewFixture(Uri.file('/test/video.mov'), hasAudio: true), + ))!; + final sequence = SequenceId('one'); + final id = ElementId('clip'); + final kernel = f.timeline.persistence.timeline(sequence); + final controller = f.timeline.view(sequence); + final history = kernel.historyVersions.length; + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + theme: EditorTheme.penLight, + home: Scaffold( + body: SizedBox( + width: 225, + child: SpeedProperties( + session: f.timeline, + sequence: sequence, + clip: id, + ), + ), + ), + ), + ); + AppSlider slider() => + tester.widget(find.byKey(const Key('clip-speed-slider'))); + final speed2 = (math.log(2) / math.ln10 + 1) / 3; + final speed3 = (math.log(3) / math.ln10 + 1) / 3; + slider().onChangeStart!(speed2); + slider().onChanged!(speed2); + await tester.pump(); + + f.timeline.setClipSpeed(sequence, id, 1.5); + final externallyChanged = kernel.current; + await tester.pump(); + slider().onChanged!(speed3); + await tester.pump(); + expect( + controller + .project(TimelineViewportRect(width: 800, height: 400)) + .version + .kernelVersion, + same(externallyChanged), + ); + slider().onChangeEnd!(speed3); + await tester.pump(); + expect(kernel.current, same(externallyChanged)); + expect(kernel.historyVersions.length, history + 1); + + await tester.pumpWidget(const SizedBox.shrink()); + await tester.runAsync(() async { + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + }); + + testWidgets('audio speed previews and commits through the shared path', ( + tester, + ) async { + final f = (await tester.runAsync( + () => createPreviewFixture( + Uri.file('/test/audio.wav'), + mediaType: 'audio', + hasAudio: true, + ), + ))!; + final sequence = SequenceId('one'); + final id = ElementId('clip'); + final kernel = f.timeline.persistence.timeline(sequence); + final before = kernel.current; + final history = kernel.historyVersions.length; + final controller = f.timeline.view(sequence); + final handle = before.query().elementById(id)!; + controller.setSelection([handle]); + f.timeline.setCustomSpeedEnabled(sequence, id, true); + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + theme: EditorTheme.penLight, + home: Scaffold( + body: SizedBox( + width: 800, + height: 400, + child: Row( + children: [ + SizedBox( + width: 225, + child: SpeedProperties( + session: f.timeline, + sequence: sequence, + clip: id, + ), + ), + Expanded( + child: _speedSurface( + session: f.timeline, + sequence: sequence, + controller: controller, + ), + ), + ], + ), + ), + ), + ), + ); + final slider = tester.widget( + find.byKey(const Key('clip-speed-slider')), + ); + final speed2 = (math.log(2) / math.ln10 + 1) / 3; + slider.onChangeStart!(speed2); + slider.onChanged!(speed2); + await tester.pump(); + expect(kernel.current, same(before)); + expect(kernel.historyVersions.length, history); + final preview = controller + .project(TimelineViewportRect(width: 575, height: 400)) + .version + .kernelVersion + .query(); + final previewRecord = preview.element(preview.elementById(id)!); + expect(previewRecord.duration, TimelineClock.ticksPerSecond); + expect(previewRecord.sourceDuration, 2 * TimelineClock.ticksPerSecond); + expect(f.timeline.payloadFor(previewRecord.payloadRef!)!.type, 'audio'); + expect( + find.byWidgetPredicate( + (widget) => widget is Semantics && widget.properties.label == '200%', + ), + findsOneWidget, + ); + + slider.onChangeEnd!(speed2); + await tester.pump(); + expect(kernel.historyVersions.length, history + 1); + expect( + kernel.current.query().element(handle).duration, + TimelineClock.ticksPerSecond, + ); + + await tester.pumpWidget(const SizedBox.shrink()); + await tester.runAsync(() async { + await f.workspace.close(); + await f.directory.delete(recursive: true); + }); + }); +} + +Widget _speedSurface({ + required EditorTimelineSession session, + required SequenceId sequence, + required TimelineViewController controller, + TimelineThemeData? theme, +}) => Builder( + builder: (context) => TimelineView( + controller: controller, + theme: theme, + paintClipHeader: TimelineSpeedEditor.headerPainter( + context, + session: session, + sequence: sequence, + ), + overlay: TimelineSpeedEditor( + session: session, + sequence: sequence, + controller: controller, + ), + ), +); + +Future> _surfacePixel( + WidgetTester tester, + Key boundaryKey, + Offset position, +) async { + final boundary = tester.renderObject( + find.byKey(boundaryKey), + ); + final point = position - tester.getTopLeft(find.byKey(boundaryKey)); + return (await tester.runAsync(() async { + final image = await boundary.toImage(pixelRatio: 1); + try { + final pixels = (await image.toByteData( + format: ui.ImageByteFormat.rawRgba, + ))!; + final offset = (point.dy.floor() * image.width + point.dx.floor()) * 4; + return [for (var i = 0; i < 4; i++) pixels.getUint8(offset + i)]; + } finally { + image.dispose(); + } + }))!; +} diff --git a/test/support/creation_names.dart b/test/support/creation_names.dart new file mode 100644 index 0000000..0353d1a --- /dev/null +++ b/test/support/creation_names.dart @@ -0,0 +1,7 @@ +import 'package:cutdex/workspace/persistence/timeline_creation_names.dart'; + +const testCreationNames = TimelineCreationNames( + timeline: 'Timeline 1', + sequence: 'Main sequence', + storyline: 'Main storyline', +); diff --git a/test/support/empty_conversation_repository.dart b/test/support/empty_conversation_repository.dart new file mode 100644 index 0000000..cb965ed --- /dev/null +++ b/test/support/empty_conversation_repository.dart @@ -0,0 +1,16 @@ +import 'dart:io'; + +import 'package:cutdex/integrations/agent/conversation_repository.dart'; + +class EmptyConversationRepository extends ConversationRepository { + EmptyConversationRepository() : super(Directory('/unused')); + + @override + Future> list( + String projectId, { + bool trash = false, + }) async => []; + + @override + Future selected(String projectId) async => null; +} diff --git a/test/support/memory_app_settings.dart b/test/support/memory_app_settings.dart new file mode 100644 index 0000000..df43557 --- /dev/null +++ b/test/support/memory_app_settings.dart @@ -0,0 +1,79 @@ +import 'package:cutdex/persistence/app_settings_repositories.dart'; +import 'package:cutdex/workspace/project_state.dart'; +import 'package:cutdex/workspace/persistence/recent_projects.dart'; + +class MemoryProjectLocationSettingsRepository + implements ProjectLocationSettingsRepository { + MemoryProjectLocationSettingsRepository([this.value]); + + String? value; + + @override + Future load() async => value; + + @override + Future save(String directory) async => value = directory; +} + +class MemoryResourceLocationSettingsRepository + implements ResourceLocationSettingsRepository { + MemoryResourceLocationSettingsRepository(this.value); + + String? value; + + @override + Future load() async => value; + + @override + Future save(String directory) async => value = directory; +} + +class MemoryMcpSettingsRepository implements McpSettingsRepository { + McpSettingsValue? value; + bool failWrites = false; + + @override + Future load() async => value; + + @override + Future save(McpSettingsValue configuration) async { + if (failWrites) throw StateError('write failed'); + value = configuration; + } +} + +class MemoryAppearanceSettingsRepository + implements AppearanceSettingsRepository { + AppAppearance value = AppAppearance.system; + bool failWrites = false; + + @override + Future load() async => value; + + @override + Future save(AppAppearance mode) async { + if (failWrites) throw StateError('write failed'); + value = mode; + } +} + +class MemoryRecentProjectsRepository implements RecentProjectsRepository { + List recent = []; + final projects = {}; + + @override + Future> load() async => List.of(recent); + + @override + Future save(List projects) async { + recent = List.of(projects); + } + + @override + Future lastTimeline(String projectId) async => projects[projectId]; + + @override + Future rememberTimeline(String projectId, String timelineId) async { + projects[projectId] = timelineId; + } +} diff --git a/test/support/preview_fixture.dart b/test/support/preview_fixture.dart new file mode 100644 index 0000000..ec96d8e --- /dev/null +++ b/test/support/preview_fixture.dart @@ -0,0 +1,114 @@ +import 'creation_names.dart'; + +import 'dart:io'; + +import 'package:cutdex/workspace/persistence/project_workspace.dart'; +import 'package:cutdex/workspace/timeline_session.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; + +Future< + ({ + Directory directory, + ProjectWorkspace workspace, + EditorTimelineSession timeline, + }) +> +createPreviewFixture( + Uri source, { + Map? toneMapping, + bool hasAudio = false, + String mediaType = 'video', + RationalTime? clipDuration, + TimelineDto? timelineOverride, + Map? renderSize, + List? payloads, +}) async { + final duration = clipDuration ?? RationalTime.seconds(2); + final directory = await Directory.systemTemp.createTemp( + 'cutdex-preview-test-', + ); + final workspace = ProjectWorkspace(creationNames: testCreationNames); + try { + await workspace.open( + '${directory.path}/Preview.cutdex', + name: 'Preview test', + ); + await workspace.project!.saveAsset( + AssetDocument( + id: 'media', + name: 'Test media', + storage: AssetStorage.external, + location: source.toString(), + ), + ); + TimelineDto sequence(String id, {bool empty = false}) => TimelineDto( + id: SequenceId(id), + name: id, + format: TimelineFormat.fps30, + primaryStorylineId: StorylineId('primary'), + storylines: [ + StorylineDto( + id: StorylineId('primary'), + elementIds: [if (!empty) ElementId('clip')], + ), + ], + elements: [ + if (!empty) + ElementDto( + id: ElementId('clip'), + name: 'Preview clip', + structure: ElementStructure.content, + payloadRef: PayloadRef('source'), + duration: duration, + sourceRange: TimeRange( + start: RationalTime.zero, + duration: duration, + ), + mediaRange: TimeRange(start: RationalTime.zero, duration: duration), + ), + ], + ); + await workspace.project!.saveTimeline( + TimelineDocument( + id: 'project', + name: 'Preview test', + sequences: [ + timelineOverride ?? sequence('one'), + sequence('empty', empty: true), + ], + defaultSequenceId: SequenceId('one'), + payloads: + payloads ?? + [ + PayloadDocument( + id: 'source', + type: mediaType, + assetIds: ['media'], + data: { + 'videoTrackIndex': 0, + if (hasAudio) 'audioTrackIndex': 0, + }, + ), + ], + settings: { + 'renderSize': renderSize ?? {'width': 1080, 'height': 1920}, + 'toneMapping': ?toneMapping, + }, + ), + ); + final document = await workspace.loadTimeline( + workspace.project!.info.id, + 'project', + ); + final timeline = await workspace.openTimelineSession( + workspace.project!.info.id, + document, + ); + return (directory: directory, workspace: workspace, timeline: timeline); + } catch (_) { + await workspace.close(); + await directory.delete(recursive: true); + rethrow; + } +} diff --git a/test/support/processing_fixture.dart b/test/support/processing_fixture.dart new file mode 100644 index 0000000..b3b958d --- /dev/null +++ b/test/support/processing_fixture.dart @@ -0,0 +1,46 @@ +import 'dart:io'; + +import 'package:cutdex/integrations/runtime/processing_configuration.dart'; + +/// File-presence fixture only: no worker is run and no model is downloaded. +Future processingFixture( + Directory root, + int capabilities, { + bool stale = false, +}) async { + final suffix = Platform.isWindows ? '.exe' : ''; + final paths = [ + 'runtime/bin/cutdex-processing-worker$suffix', + if (capabilities & 13 != 0) 'runtime/bin/ffmpeg$suffix', + if (capabilities & 1 != 0) ...[ + 'runtime/workers/asr/cutdex-asr-worker$suffix', + 'asr/ggml-model.bin', + 'asr/silero_vad.onnx', + ], + if (capabilities & 2 != 0) ...[ + 'runtime/workers/translation/cutdex-m2m100-worker$suffix', + 'translation/model.bin', + 'translation/config.json', + 'translation/shared_vocabulary.json', + 'translation/sentencepiece.bpe.model', + ], + if (capabilities & 4 != 0) ...[ + 'runtime/workers/audio/cutdex-audio-worker$suffix', + 'audio/melband.pt', + ], + if (capabilities & 8 != 0) 'background/model.onnx', + ]; + for (final path in paths) { + final file = File('${root.path}/$path'); + await file.parent.create(recursive: true); + await file.writeAsString('fixture'); + } + final base = stale ? '${root.path}/missing' : root.path; + return ProcessingConfiguration.fromPaths( + root: '${root.path}/runtime', + transcriptionPath: '$base/asr', + translationPath: '$base/translation', + vocalPath: '$base/audio/melband.pt', + backgroundRemovalPath: '$base/background/model.onnx', + )!; +} diff --git a/test/support/project_write_lock.dart b/test/support/project_write_lock.dart new file mode 100644 index 0000000..0743d26 --- /dev/null +++ b/test/support/project_write_lock.dart @@ -0,0 +1,23 @@ +import 'package:path/path.dart' as p; +import 'package:sqlite3/sqlite3.dart'; + +/// Holds a competing writer without depending on the SDK's table layout. +void Function() blockProjectWrites(String projectPath) { + final database = sqlite3.open(p.join(projectPath, 'project.sqlite')); + try { + database.execute('BEGIN IMMEDIATE'); + } catch (_) { + database.close(); + rethrow; + } + var released = false; + return () { + if (released) return; + released = true; + try { + database.execute('ROLLBACK'); + } finally { + database.close(); + } + }; +} diff --git a/test/theme_switch_controls_test.dart b/test/theme_switch_controls_test.dart new file mode 100644 index 0000000..c9e5d91 --- /dev/null +++ b/test/theme_switch_controls_test.dart @@ -0,0 +1,146 @@ +import 'package:cutdex/app/editor_theme.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex_ui/widgets.dart'; +import 'package:cutdex/shared/widgets/drop_to_add_overlay.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets( + 'theme switches preserve combobox query, focus and control styles', + (tester) async { + var selected = 0; + Future mount(ThemeData theme) async { + await tester.pumpWidget( + MaterialApp( + theme: theme, + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: SizedBox( + width: 300, + child: Column( + children: [ + AppTabs( + tabs: const [AppTab(0, 'General'), AppTab(1, 'Other')], + value: 0, + onChanged: (_) {}, + ), + AppCombobox( + emptyLabel: 'No matching options', + searchHint: 'Search options', + label: 'Choice', + value: selected, + options: const [ + AppSelectOption(0, 'Alpha'), + AppSelectOption(1, 'Beta'), + ], + onChanged: (value) => selected = value, + ), + AppSwitch(value: false, onChanged: (_) {}), + const ResourceDownloadProgress( + downloadedBytes: 0, + totalBytes: 1000, + status: '', + ), + const SizedBox(height: 40, child: DropToAddOverlay()), + ], + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + } + + await mount(EditorTheme.penLight); + final combo = find.byType(AppCombobox); + final initialState = tester.state(combo); + final input = find.descendant( + of: combo, + matching: find.byType(TextField), + ); + await tester.tap(input); + await tester.enterText(input, 'Bet'); + await tester.pumpAndSettle(); + + for (final (theme, background, border, label, scrim, track, thumb) in [ + ( + EditorTheme.penDark, + const Color(0xFF3F3F46).withValues(alpha: .3), + const Color(0xFFFCFCFC).withValues(alpha: .084), + const Color(0xFFFCFCFC).withValues(alpha: .55), + Colors.black.withValues(alpha: .62), + const Color(0x1AC8C8C8), + const Color(0xFFFCFCFC), + ), + ( + EditorTheme.penLight, + Colors.transparent, + Colors.transparent, + const Color(0xFF71717A), + Colors.black.withValues(alpha: .38), + const Color(0x0A020202), + const Color(0xFF020202), + ), + ]) { + await mount(theme); + expect(tester.state(combo), same(initialState)); + final field = tester.widget(input); + expect(field.controller!.text, 'Bet'); + expect(field.focusNode!.hasFocus, isTrue); + expect(find.text('Beta'), findsOneWidget); + + final container = tester.widget( + find.descendant(of: combo, matching: find.byType(Container)).first, + ); + expect((container.decoration! as BoxDecoration).color, background); + final tab = tester.widget( + find.widgetWithText(TextButton, 'General'), + ); + expect(tab.style!.side!.resolve({})!.color, border); + final progressLabel = tester.widget( + find.descendant( + of: find.byType(ResourceDownloadProgress), + matching: find.byType(Text), + ), + ); + expect(progressLabel.style!.color, label); + final overlay = tester.widget( + find.descendant( + of: find.byType(DropToAddOverlay), + matching: find.byType(ColoredBox), + ), + ); + expect(overlay.color, scrim); + final switchTrack = tester.widget( + find + .descendant( + of: find.byType(AppSwitch), + matching: find.byType(AnimatedContainer), + ) + .first, + ); + expect((switchTrack.decoration! as BoxDecoration).color, track); + final switchThumb = tester + .widgetList( + find.descendant( + of: find.byType(AppSwitch), + matching: find.byType(DecoratedBox), + ), + ) + .firstWhere( + (box) => + (box.decoration as BoxDecoration).shape == BoxShape.circle, + ); + expect((switchThumb.decoration as BoxDecoration).color, thumb); + expect(tester.takeException(), isNull); + } + + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + expect(selected, 1); + }, + ); +} diff --git a/test/timeline_empty_state_test.dart b/test/timeline_empty_state_test.dart new file mode 100644 index 0000000..098a179 --- /dev/null +++ b/test/timeline_empty_state_test.dart @@ -0,0 +1,37 @@ +import 'package:cutdex/app/editor_theme.dart'; +import 'package:cutdex/features/timeline/timeline_panel.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets('timeline empty state matches the wide drop-zone layout', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + theme: EditorTheme.penDark, + home: const Scaffold( + body: SizedBox( + width: 800, + height: 300, + child: TimelineEmptyDropZone( + primaryTop: 48, + primaryHeight: 72, + verticalOffset: 20, + ), + ), + ), + ), + ); + + final zone = find.byKey(const ValueKey('timeline-empty-drop-zone')); + expect(find.text('将媒体拖到此处以开始。'), findsOneWidget); + expect(tester.getSize(zone), const Size(768, 72)); + expect(tester.getTopLeft(zone), const Offset(16, 28)); + expect(tester.takeException(), isNull); + }); +} diff --git a/test/timeline_session_test.dart b/test/timeline_session_test.dart new file mode 100644 index 0000000..e7ec2ee --- /dev/null +++ b/test/timeline_session_test.dart @@ -0,0 +1,3770 @@ +import 'support/creation_names.dart'; + +import 'package:cutdex/app/editor_theme.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex/integrations/runtime/timeline_thumbnails.dart'; +import 'package:cutdex/features/media/transcription_dialog.dart'; +import 'package:cutdex_ui/widgets.dart'; +import 'package:cutdex_native/cutdex_native.dart'; +import 'package:cutdex/features/properties/canvas_presets.dart'; +import 'package:cutdex_sdk/editor.dart'; + +import 'dart:async'; +import 'dart:convert'; + +import 'package:cutdex/features/timeline/timeline_external_drop_target.dart'; +import 'package:cutdex/features/timeline/timeline_asset_drop_target.dart'; +import 'package:cutdex/features/media/media_asset_drag.dart'; + +import 'dart:io'; + +import 'package:cutdex/workspace/timeline_provider.dart'; + +import 'package:cutdex/features/timeline/timeline_panel.dart'; +import 'package:cutdex/features/properties/properties_panel.dart'; +import 'package:cutdex/features/properties/picture_properties.dart'; +import 'package:cutdex_sdk/preview.dart'; +import 'package:cutdex/features/preview/preview_panel.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex/features/media/media_panel.dart'; +import 'package:cutdex/workspace/projects.dart'; +import 'package:cutdex/workspace/project_state.dart'; +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex/workspace/persistence/project_workspace.dart'; +import 'package:cutdex/workspace/timeline_session.dart'; +import 'package:cutdex/workspace/timeline_view_state.dart'; +import 'package:cutdex/persistence/app_database.dart'; +import 'package:cutdex/persistence/app_settings_repositories.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:cutdex_sdk/timeline/engine.dart'; +import 'package:cutdex_sdk/timeline/layout.dart'; +import 'package:cutdex_sdk/timeline_ui.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:cutdex/workspace/media_import.dart'; +import 'package:cutdex/workspace/media_availability.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:drift/native.dart'; + +TimelineDto sequence(String id) => TimelineDto( + id: SequenceId(id), + name: id, + format: TimelineFormat.fps24, + primaryStorylineId: StorylineId('primary'), + storylines: [ + StorylineDto(id: StorylineId('primary'), elementIds: [ElementId('clip')]), + ], + elements: [ + ElementDto( + id: ElementId('clip'), + name: '真实工程片段', + structure: ElementStructure.content, + duration: RationalTime.seconds(10), + sourceRange: TimeRange( + start: RationalTime.zero, + duration: RationalTime.seconds(10), + ), + mediaRange: TimeRange( + start: RationalTime.zero, + duration: RationalTime.seconds(20), + ), + ), + ], +); + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late Directory root; + late ProjectWorkspace workspace; + late EditorTimelineSession session; + late String projectId; + setUp(() async { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('cutdex_native/file_drop'), + (_) async => null, + ); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('cutdex_native/file_drop/timeline'), + (_) async => null, + ); + root = await Directory.systemTemp.createTemp('cutdex-timeline-'); + workspace = ProjectWorkspace(creationNames: testCreationNames); + await workspace.open('${root.path}/Project.cutdex', name: 'Test'); + projectId = workspace.project!.info.id; + await workspace.project!.saveTimeline( + TimelineDocument( + id: 'project', + name: 'Test project', + sequences: [sequence('one'), sequence('two')], + defaultSequenceId: SequenceId('two'), + settings: const {'keep': true}, + payloads: [ + PayloadDocument( + id: 'unused', + type: 'custom', + data: const {'keep': 42}, + ), + ], + ), + ); + final project = await workspace.loadTimeline(projectId, 'project'); + session = await workspace.openTimelineSession(projectId, project); + }); + tearDown(() async { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('cutdex_native/file_drop'), + null, + ); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler( + const MethodChannel('cutdex_native/file_drop/timeline'), + null, + ); + await workspace.close(); + await root.delete(recursive: true); + }); + + for (final connected in [false, true]) { + test('detach audio is independent and atomic (connected=$connected)', () async { + final id = SequenceId('two'); + final videoId = ElementId('video-with-audio'); + final uri = Uri.file('/original.mov'); + await workspace.project!.saveAsset( + AssetDocument( + id: 'original', + name: 'Original', + storage: AssetStorage.external, + location: uri.toString(), + ), + ); + session.insertAsset( + sequenceId: id, + assetId: 'original', + assetName: 'Original', + uri: uri, + duration: RationalTime.seconds(4), + position: 0, + kind: 'video', + hasAudio: true, + clipId: videoId, + sourceStart: RationalTime.seconds(2), + mediaDuration: RationalTime.seconds(20), + ); + final engine = session.layout(id); + session.publishLayout( + id, + const LayoutIntervalEdit().preview( + kernel: session.persistence.timeline(id), + engine: engine, + projection: engine.currentComponents!.semanticProjection, + edit: (tx) { + final query = session.persistence.timeline(id).current.query(); + // The fixture's placeholder clip has no media binding. + tx.setEnabled(query.elementById(ElementId('clip'))!, false); + tx.retimePlayback( + session.persistence + .timeline(id) + .current + .query() + .elementById(videoId)!, + [ + RetimeSegmentDto( + projectDuration: RationalTime.seconds(2), + sourceStart: RationalTime.zero, + sourceDelta: RationalTime.seconds(4), + ), + ], + ); + }, + ), + ); + if (connected) { + await session.commands.executeEdit( + id, + PlaceClip( + clipId: videoId.value, + at: CommandTime( + 6 * TimelineClock.ticksPerSecond, + TimelineClock.ticksPerSecond, + ), + side: ClipPlacement.above, + ), + ); + } + session.commands.setAudio(sequence: id, clip: videoId, db: -6); + final kernel = session.persistence.timeline(id); + final before = kernel.current; + final q = before.query(); + final source = q.elementById(videoId)!; + final view = session.view(id); + view.setSelection([source]); + final selection = view.selectedIdentities.toList(); + expect(session.canDetachAudio(id, videoId), isTrue); + final audioId = session.detachAudio(id, videoId); + expect(view.selectedIdentities, selection); + final after = kernel.current; + final result = after.query(); + final audio = result.elementById(audioId)!; + final record = result.element(audio); + final link = result.connectionForTarget(audio)!; + expect(result.connectionOrderLocation(audio)!.side, ConnectionSide.below); + if (connected) expect(link.anchor, isNot(source)); + expect(result.absoluteStart(audio), q.absoluteStart(source)); + expect(record.duration, q.element(source).duration); + expect(record.sourceStart, q.element(source).sourceStart); + expect(record.sourceDuration, q.element(source).sourceDuration); + expect( + kernel + .exportElementDto(audio) + .retimeSegments + .map((s) => (s.projectDuration, s.sourceStart, s.sourceDelta)), + kernel + .exportElementDto(source) + .retimeSegments + .map((s) => (s.projectDuration, s.sourceStart, s.sourceDelta)), + ); + + expect(ClipAudioGain.fromRecord(record).db, -6); + expect(ClipAudioGain.fromRecord(record).muted, isFalse); + expect(ClipAudioGain.fromRecord(result.element(source)).muted, isTrue); + expect(session.canDetachAudio(id, videoId), isFalse); + final binding = session.mediaBinding(record.payloadRef!)!; + expect(binding.media.uri, uri); + expect(binding.media.id, 'original'); + expect(binding.videoTrackIndex, isNull); + expect(binding.audioTrackIndex, 0); + expect(session.payloadFor(record.payloadRef!)!.type, 'audio'); + CompiledExecution compileAudioState() => + const ExecutionCompiler().compile( + editorExecutionInput( + session, + id, + kernel.current, + EditorExecutionMedia( + bindings: { + for (final ref in [ + q.element(source).payloadRef!, + record.payloadRef!, + ]) + ref: ExecutionMediaBinding( + media: session.mediaBinding(ref)!.media, + videoTrackSelection: session + .mediaBinding(ref)! + .videoSelection, + audioTrackSelection: session + .mediaBinding(ref)! + .audioSelection, + ), + }, + ), + settings: session.settings, + canvas: session.canvas, + payloads: session.payloads.toList(), + ), + ); + final detachedPlan = compileAudioState().plan; + expect(detachedPlan.audioLayers.length, 2); + expect( + detachedPlan.audioLayers + .expand((layer) => layer.automation) + .any((curve) => curve.target == ClipAudioGain.detachedId), + isFalse, + ); + + session.setClipSpeed(id, audioId, 1); + final speedChanged = kernel.current.query(); + expect( + speedChanged.element(audio).duration, + 4 * TimelineClock.ticksPerSecond, + ); + expect( + speedChanged.element(source).duration, + 2 * TimelineClock.ticksPerSecond, + ); + final speedPlan = compileAudioState().plan; + final spedLayer = speedPlan.audioLayers.singleWhere( + (layer) => layer.id.contains(audioId.value), + ); + expect(spedLayer.timelineRange.duration.seconds, 4); + expect(spedLayer.sampleStart?.seconds, 2); + expect(spedLayer.sourceEnd?.seconds, 6); + session.undo(id); + expect(kernel.current, same(after)); + + session.undo(id); + expect(kernel.current, same(before)); + expect(session.canDetachAudio(id, videoId), isTrue); + session.redo(id); + expect(kernel.current, same(after)); + // Restoring the video's audio does not remove or alter the detached copy. + session.commands.setAudio(sequence: id, clip: videoId, muted: false); + final restored = kernel.current.query(); + expect(compileAudioState().plan.audioLayers.length, 2); + expect(restored.element(audio), same(record)); + expect(ClipAudioGain.fromRecord(restored.element(source)).muted, isFalse); + session.commands.setAudio(sequence: id, clip: audioId, db: -12); + expect( + ClipAudioGain.fromRecord(kernel.current.query().element(source)).db, + -6, + ); + await session.flush(); + final reopened = await workspace.loadTimeline( + projectId, + session.document.id, + ); + final saved = await workspace.openTimelineSession(projectId, reopened); + final savedQuery = saved.persistence.timeline(id).current.query(); + expect(savedQuery.elementById(audioId), isNotNull); + expect( + saved + .mediaBinding( + savedQuery.element(savedQuery.elementById(audioId)!).payloadRef!, + )! + .media + .uri, + uri, + ); + if (!identical(saved, session)) await saved.close(); + }); + } + + test('incoming preview cancels without history and preserves redo', () async { + final id = SequenceId('two'); + final kernel = session.persistence.timeline(id); + await workspace.project!.saveAsset( + AssetDocument( + id: 'saved', + name: 'saved', + storage: AssetStorage.external, + location: 'file:///saved.png', + ), + ); + session.insertAsset( + sequenceId: id, + assetId: 'saved', + assetName: 'saved', + uri: Uri.file('/saved.png'), + duration: RationalTime.seconds(2), + position: 0, + kind: 'image', + hasAudio: false, + ); + session.undo(id); + await session.flush(); + final before = kernel.current; + final redo = kernel.redoVersion; + final count = kernel.historyVersions.length; + final clip = session.beginIncomingClip( + media: MediaReference(id: 'incoming', uri: Uri.file('/incoming.mov')), + sequence: id, + name: 'incoming', + duration: RationalTime.seconds(3), + kind: 'video', + hasAudio: true, + ); + expect( + clip.incoming.seed.query().positionOf(clip.incoming.source).position, + 10 * TimelineClock.ticksPerSecond, + ); + for (final side in [ConnectionSide.above, null, ConnectionSide.below]) { + clip.update( + start: 2 * TimelineClock.ticksPerSecond, + side: side, + top: side == ConnectionSide.above ? -80 : 180, + ); + final query = clip.layout!.kernelVersion.query(); + final handle = query.elementById(clip.clipId)!; + expect(query.connectionOrderLocation(handle)?.side, side); + expect(kernel.current, same(before)); + expect(kernel.historyVersions.length, count); + } + clip.cancel(); + expect(kernel.current, same(before)); + expect(kernel.redoVersion, same(redo)); + expect(session.dirty, isFalse); + expect(session.payloadFor(PayloadRef(clip.payloadId)), isNull); + }); + + for (final side in [null, ConnectionSide.above, ConnectionSide.below]) { + test( + 'incoming $side commits once and undo removes payload reference', + () async { + final id = SequenceId('two'); + final kernel = session.persistence.timeline(id); + final before = kernel.current; + final count = kernel.historyVersions.length; + await workspace.project!.saveAsset( + AssetDocument( + id: 'incoming', + name: 'incoming', + storage: AssetStorage.external, + location: 'file:///incoming.mov', + ), + ); + final clip = session.beginIncomingClip( + media: MediaReference(id: 'incoming', uri: Uri.file('/incoming.mov')), + sequence: id, + name: 'incoming', + duration: RationalTime.seconds(3), + kind: 'video', + hasAudio: true, + ); + clip.update( + start: 2 * TimelineClock.ticksPerSecond, + side: side, + top: side == ConnectionSide.above ? -80 : 180, + ); + final preview = clip.layout!.kernelVersion; + clip.commit(assetId: 'incoming', uri: Uri.file('/incoming.mov')); + expect(kernel.current, same(preview)); + expect(kernel.historyVersions.length, count + 1); + final q = kernel.current.query(); + final handle = q.elementById(clip.clipId)!; + expect(q.connectionOrderLocation(handle)?.side, side); + if (side != null) { + expect(q.absoluteStart(handle), 2 * TimelineClock.ticksPerSecond); + } + session.undo(id); + expect(kernel.current, same(before)); + expect(session.canUndo(id), isFalse); + session.redo(id); + expect(kernel.current, same(preview)); + await session.flush(); + final saved = await workspace.project!.loadTimeline('project'); + expect(saved.payloads.any((p) => p.id == clip.payloadId), isTrue); + }, + ); + } + + test('incoming beyond tail creates and cancels its gap together', () { + final id = SequenceId('two'); + final kernel = session.persistence.timeline(id); + final before = kernel.current; + final clip = session.beginIncomingClip( + media: MediaReference(id: 'incoming', uri: Uri.file('/incoming.mov')), + sequence: id, + name: 'incoming', + duration: RationalTime.seconds(3), + kind: 'image', + hasAudio: false, + ); + clip.update( + start: 20 * TimelineClock.ticksPerSecond, + side: ConnectionSide.above, + top: -80, + ); + final q = clip.layout!.kernelVersion.query(); + expect( + q.absoluteStart(q.elementById(clip.clipId)!), + 20 * TimelineClock.ticksPerSecond, + ); + expect( + q.storylineSpan(q.primaryStoryline), + 23 * TimelineClock.ticksPerSecond, + ); + clip.cancel(); + expect(kernel.current, same(before)); + expect(kernel.canUndo, isFalse); + }); + + test( + 'empty incoming stays on Primary at zero and stale previews cannot commit', + () async { + final timelines = await workspace.createTimeline('Empty incoming'); + final document = await workspace.loadTimeline( + projectId, + timelines.singleWhere((d) => d.name == 'Empty incoming').id, + ); + session = await workspace.openTimelineSession(projectId, document); + final id = session.activeSequenceId!; + final kernel = session.persistence.timeline(id); + final clip = session.beginIncomingClip( + media: MediaReference(id: 'incoming', uri: Uri.file('/incoming.mov')), + sequence: id, + name: 'audio', + duration: RationalTime.seconds(3), + kind: 'audio', + hasAudio: true, + ); + clip.update( + start: 4 * TimelineClock.ticksPerSecond, + side: ConnectionSide.below, + top: 180, + ); + final q = clip.layout!.kernelVersion.query(); + expect(q.absoluteStart(q.elementById(clip.clipId)!), 0); + expect(q.connectionForTarget(q.elementById(clip.clipId)!), isNull); + expect(q.storylineLength(q.primaryStoryline), 1); + expect( + q.storylineSpan(q.primaryStoryline), + 3 * TimelineClock.ticksPerSecond, + ); + expect(kernel.canUndo, isFalse); + clip.cancel(); + expect( + kernel.current.query().storylineLength( + kernel.current.query().primaryStoryline, + ), + 0, + ); + final pending = session.beginIncomingClip( + media: MediaReference(id: 'incoming', uri: Uri.file('/incoming.mov')), + sequence: id, + name: 'pending', + duration: RationalTime.seconds(2), + kind: 'image', + hasAudio: false, + ); + pending.update(start: 0, top: 60); + final other = session.beginIncomingClip( + media: MediaReference(id: 'incoming', uri: Uri.file('/incoming.mov')), + sequence: id, + name: 'other', + duration: RationalTime.seconds(2), + kind: 'image', + hasAudio: false, + ); + other.update(start: 0, top: 60); + await workspace.project!.saveAsset( + AssetDocument( + id: 'other', + name: 'other', + storage: AssetStorage.external, + location: 'file:///other.png', + ), + ); + other.commit(assetId: 'other', uri: Uri.file('/other.png')); + final before = kernel.current; + expect( + () => pending.commit(assetId: 'pending', uri: Uri.file('/pending.png')), + throwsStateError, + ); + pending.cancel(); + expect(kernel.current, same(before)); + expect( + session.payloads.where((p) => p.assetIds.contains('pending')), + isEmpty, + ); + }, + ); + + test( + 'restores active sequence playhead and camera from local state', + () async { + final database = AppDatabase(NativeDatabase.memory()); + addTearDown(database.close); + final repository = DriftTimelineViewSettingsRepository(database); + final binding = await TimelineViewStateBinding.attach( + projectId: projectId, + timelineId: 'project', + session: session, + repository: repository, + ); + final sequenceId = SequenceId('one'); + session.selectSequence(sequenceId); + final view = session.view(sequenceId); + view.seekTo(720); + view.setCamera( + TimelineCamera( + baseTick: 240, + fractionalTick: .5, + pixelsPerTick: .25, + verticalOffset: 32, + ), + ); + await binding.close(); + + final document = await workspace.loadTimeline(projectId, 'project'); + session = await workspace.openTimelineSession(projectId, document); + final restored = await TimelineViewStateBinding.attach( + projectId: projectId, + timelineId: 'project', + session: session, + repository: repository, + ); + addTearDown(restored.close); + + expect(session.activeSequenceId, sequenceId); + final restoredView = session.view(sequenceId); + expect(restoredView.playheadTick, 720); + expect(restoredView.camera.baseTick, 240); + expect(restoredView.camera.fractionalTick, .5); + expect(restoredView.camera.pixelsPerTick, .25); + expect(restoredView.camera.verticalOffset, 32); + expect(restoredView.selectedIdentities, isEmpty); + }, + ); + + for (final mediaKind in ['audio', 'video']) { + testWidgets( + 'right-click caption menu targets $mediaKind and clears on empty space', + (tester) async { + final sequenceId = session.activeSequenceId!; + final uri = Uri.file('${root.path}/speech.wav'); + await tester.runAsync( + () => workspace.project!.saveAsset( + AssetDocument( + id: 'speech', + name: 'Speech', + storage: AssetStorage.external, + location: uri.toString(), + ), + ), + ); + session.insertAsset( + sequenceId: sequenceId, + assetId: 'speech', + assetName: 'Speech', + uri: uri, + duration: RationalTime.seconds(5), + position: 0, + kind: mediaKind, + hasAudio: true, + clipId: ElementId('speech-clip'), + ); + await tester.runAsync(session.flush); + final controller = session.view(sequenceId); + controller.setSelection([ + controller.version.kernelVersion.query().elementById( + ElementId('clip'), + )!, + ]); + await tester.pumpWidget( + ProviderScope( + overrides: [ + projectsProvider.overrideWith( + () => _ViewProjects(session, projectId), + ), + editorTimelineProvider( + projectId, + 'project', + ).overrideWith((ref) async => session), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + theme: EditorTheme.penDark, + home: Scaffold( + body: EditorTimelinePanel( + projectId: projectId, + timelineId: 'project', + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + final surface = tester.getRect( + find.byKey(const Key('editor-timeline-surface')), + ); + Future rightClick(Offset point) async { + final gesture = await tester.startGesture( + point, + kind: PointerDeviceKind.mouse, + buttons: kSecondaryMouseButton, + ); + await gesture.up(); + await tester.pumpAndSettle(); + } + + final frame = controller.project( + TimelineViewportRect(width: surface.width, height: surface.height), + ); + final speech = controller.version.kernelVersion.query().elementById( + ElementId('speech-clip'), + )!; + final index = List.generate(frame.length, (i) => i).firstWhere( + (i) => switch (frame.identityAt(i)) { + ElementHandle h => h == speech, + LayoutBodyId body => body.owner == speech, + _ => false, + }, + ); + await rightClick( + surface.topLeft + + Offset( + frame.screenLeftAt(index) + 20, + frame.screenTopAt(index) + 20, + ), + ); + expect(find.text('生成字幕'), findsOneWidget); + expect( + tester + .widget( + find.byWidgetPredicate( + (w) => w is AppMenuItem && w.label == '分离音频', + ), + ) + .onPressed, + mediaKind == 'audio' ? isNull : isNotNull, + ); + + await tester.tap(find.text('生成字幕')); + await tester.pumpAndSettle(); + final dialog = tester.widget( + find.byType(TranscriptionDialog), + ); + expect(dialog.target!.clipId, 'speech-clip'); + expect(dialog.target!.sequence, sequenceId); + expect(dialog.target!.mediaId, 'speech'); + expect(dialog.target!.audioStream, 0); + await tester.tap(find.byTooltip('关闭')); + await tester.pumpAndSettle(); + if (mediaKind == 'video') { + await rightClick( + surface.topLeft + + Offset( + frame.screenLeftAt(index) + 20, + frame.screenTopAt(index) + 20, + ), + ); + await tester.runAsync(() async { + await tester.tap(find.text('分离音频')); + await tester.pump(); + await session.flush(); + }); + await tester.pumpAndSettle(); + final q = controller.version.kernelVersion.query(); + final source = q.elementById(ElementId('speech-clip'))!; + expect(ClipAudioGain.fromRecord(q.element(source)).muted, isTrue); + expect( + controller.selectedIdentities.map(controller.elementForIdentity), + [source], + ); + final detachedId = session.persistence + .timeline(sequenceId) + .exportDto() + .elements + .singleWhere( + (element) => + element.payloadRef != null && + session.payloadFor(element.payloadRef!)?.type == 'audio', + ) + .id; + final detached = q.elementById(detachedId)!; + expect( + q.connectionOrderLocation(detached)!.side, + ConnectionSide.below, + ); + expect( + session.payloadFor(q.element(detached).payloadRef!)!.type, + 'audio', + ); + final detachedRecord = q.element(detached); + final videoPoint = + surface.topLeft + + Offset( + frame.screenLeftAt(index) + 20, + frame.screenTopAt(index) + 20, + ); + session.setUnavailableAssets({'speech': 'missing'}); + await tester.pumpAndSettle(); + await rightClick(videoPoint); + expect(find.text('恢复音频'), findsOneWidget); + expect(find.text('分离音频'), findsNothing); + final beforeRestore = controller.version.kernelVersion; + await tester.runAsync(() async { + await tester.tap(find.text('恢复音频')); + await tester.pump(); + await session.flush(); + }); + await tester.pumpAndSettle(); + session.setUnavailableAssets({}); + final restored = controller.version.kernelVersion.query(); + expect( + ClipAudioGain.fromRecord(restored.element(source)).muted, + isFalse, + ); + expect(restored.element(detached), same(detachedRecord)); + await rightClick(videoPoint); + expect(find.text('分离音频'), findsOneWidget); + expect(find.text('恢复音频'), findsNothing); + await tester.tapAt(surface.topLeft + const Offset(2, 2)); + await tester.pumpAndSettle(); + await tester.runAsync(() async { + session.undo(sequenceId); + await session.flush(); + }); + expect(controller.version.kernelVersion, same(beforeRestore)); + await tester.pumpAndSettle(); + await tester.runAsync(() async { + session.commands.setAudio( + sequence: sequenceId, + clip: ElementId('speech-clip'), + muted: false, + ); + session.commands.setAudio( + sequence: sequenceId, + clip: ElementId('speech-clip'), + muted: true, + ); + await session.flush(); + }); + await tester.pumpAndSettle(); + await rightClick(videoPoint); + expect(find.text('恢复音频'), findsOneWidget); + await tester.tapAt(surface.topLeft + const Offset(2, 2)); + await tester.pumpAndSettle(); + } + // The bottom edge now contains the floating scrollbar hit target. + await rightClick(surface.topLeft + Offset(80, surface.height - 30)); + expect(controller.selectedIdentities, isEmpty); + final item = tester.widget( + find.byWidgetPredicate((w) => w is AppMenuItem && w.label == '生成字幕'), + ); + expect(item.onPressed, isNull); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.runAsync(session.flush); + }, + ); + } + + test( + 'host layout configuration is shared by SDK commands and the viewport', + () { + final custom = EditorTimelineSession( + document: session.document, + persistence: session.persistence, + layoutConfiguration: const EditorLayoutConfiguration( + primaryTop: 90, + primaryHeight: 110, + clipHeight: 84, + innerGap: 12, + bodyGap: 7, + ), + ); + final id = custom.document.sequences.first.id; + final view = custom.view(id); + final access = custom.timeline(id); + expect(view.geometry.primaryTop, 90); + expect(view.geometry.primaryHeight, 110); + expect(access.primaryTop, view.geometry.primaryTop); + expect(access.primaryHeight, view.geometry.primaryHeight); + expect(access.engine, same(custom.layout(id))); + final policies = access.engine.current!.policy.stacks.values; + expect(policies.map((p) => p.primaryBoundary).toSet(), {90, 200}); + expect(policies.every((p) => p.innerGap == 12 && p.bodyGap == 7), isTrue); + custom.dispose(); + }, + ); + + testWidgets( + 'pending timeline session keeps the editor area free of loading chrome', + (tester) async { + final pending = Completer(); + await tester.pumpWidget( + ProviderScope( + overrides: [ + projectsProvider.overrideWith( + () => _ViewProjects(session, projectId), + ), + editorTimelineProvider( + projectId, + 'pending', + ).overrideWith((ref) => pending.future), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + theme: EditorTheme.penDark, + home: Scaffold( + body: EditorTimelinePanel( + projectId: projectId, + timelineId: 'pending', + ), + ), + ), + ), + ); + await tester.pump(); + + expect(find.byType(CircularProgressIndicator), findsNothing); + expect(find.byKey(const Key('timeline-pending')), findsOneWidget); + + pending.complete(session); + await tester.pumpAndSettle(); + }, + ); + + testWidgets('timeline switch keeps the toolbar element mounted', ( + tester, + ) async { + final created = await tester.runAsync( + () => workspace.createPreparedTimeline('Second'), + ); + final second = created!.session; + Widget panel(String timelineId) => ProviderScope( + overrides: [ + // ignore: riverpod_lint/scoped_providers_should_specify_dependencies + projectsProvider.overrideWith(() => _ViewProjects(session, projectId)), + // ignore: riverpod_lint/scoped_providers_should_specify_dependencies + editorTimelineProvider( + projectId, + 'project', + ).overrideWith((ref) => session), + // ignore: riverpod_lint/scoped_providers_should_specify_dependencies + editorTimelineProvider( + projectId, + second.document.id, + ).overrideWith((ref) => second), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + theme: EditorTheme.penDark, + home: Scaffold( + body: EditorTimelinePanel( + key: const Key('timeline-panel'), + projectId: projectId, + timelineId: timelineId, + ), + ), + ), + ); + + await tester.pumpWidget(panel('project')); + await tester.pumpAndSettle(); + final toolbar = tester.element(find.byKey(const Key('timeline-toolbar'))); + + await tester.pumpWidget(panel(second.document.id)); + await tester.pump(); + + expect( + tester.element(find.byKey(const Key('timeline-toolbar'))), + same(toolbar), + ); + expect(find.byKey(const Key('timeline-pending')), findsNothing); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets( + 'closing a project keeps mounted timeline views alive until detached', + (tester) async { + final container = ProviderContainer( + overrides: [ + projectsProvider.overrideWith( + () => _ViewProjects(session, projectId), + ), + ], + ); + await container.read(projectsProvider.future); + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + theme: EditorTheme.penDark, + home: Scaffold( + body: EditorTimelinePanel( + projectId: projectId, + timelineId: 'project', + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + final controller = session.view(session.activeSequenceId!); + await tester.runAsync(session.close); + expect(session.acceptsEdits, isFalse); + // The old tree may rebuild while the next project loads from disk. + tester.element(find.byType(TimelineView)).markNeedsBuild(); + await tester.pump(); + expect(tester.takeException(), isNull); + void listener() {} + controller.addListener(listener); + controller.removeListener(listener); + await tester.pumpWidget(const SizedBox()); + await tester.pumpAndSettle(); + container.dispose(); + expect(() => controller.addListener(listener), throwsFlutterError); + }, + ); + + for (final (labelText, fieldKey) in const [ + ('旋转', 'picture-rotation'), + ('X', 'picture-x'), + ('Y', 'picture-y'), + ('W', 'picture-scale-x'), + ('H', 'picture-scale-y'), + ]) { + for (final action in [ + 'commit', + 'fast', + 'unlocked', + if (labelText == 'W' || labelText == 'H') ...['lower', 'upper'], + 'fallback', + if (labelText == '旋转') ...[ + 'wrap_positive', + 'wrap_negative', + 'wrap_boundary', + 'wrap_multiple', + 'wrap_reverse', + ], + 'escape', + 'cancel', + 'tap', + 'return', + 'stale', + 'dispose', + 'sequence', + ]) { + testWidgets('$labelText scrub $action preserves one edit boundary', ( + tester, + ) async { + final id = SequenceId('two'); + final view = session.view(id); + final base = view.version.kernelVersion; + var expectedVersion = base; + final preview = _LivePropertyPreview(session); + addTearDown(preview.close); + await tester.pumpWidget( + ProviderScope( + overrides: [ + editorPreviewProvider(projectId, 'project').overrideWith(( + ref, + ) async { + if (action == 'fallback') throw StateError('No preview'); + return preview; + }), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + theme: EditorTheme.penLight, + home: Scaffold( + body: SizedBox( + width: 225, + child: PictureProperties( + projectId: projectId, + timelineId: 'project', + session: session, + sequence: id, + clip: base.query().element( + base.query().elementById(ElementId('clip'))!, + ), + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + if (action == 'unlocked') { + await tester.tap(find.byKey(const Key('picture-lock'))); + await tester.pumpAndSettle(); + } + final label = find.text(labelText); + final gesture = await tester.startGesture( + tester.getCenter(label), + kind: PointerDeviceKind.mouse, + ); + final distance = switch (action) { + 'lower' => -20000.0, + 'upper' => 20000.0, + 'wrap_negative' => -190.0, + 'wrap_boundary' => 180.0, + 'wrap_multiple' => 750.0, + 'wrap_positive' || 'wrap_reverse' => 190.0, + 'fast' => 20.0, + _ => 50.0, + }; + if (action != 'tap') { + await gesture.moveBy(const Offset(20, 0)); + await tester.pump(); + if (action != 'fast') { + await gesture.moveBy(Offset(distance - 20, 0)); + await tester.pump(); + } + final field = tester.widget( + find.descendant( + of: find.byKey(ValueKey(fieldKey)), + matching: find.byType(TextField), + ), + ); + final expected = switch (action) { + 'lower' => 1.0, + 'upper' => 10000.0, + 'wrap_negative' => 170.0, + 'wrap_boundary' => -180.0, + 'wrap_multiple' => 30.0, + 'wrap_positive' || 'wrap_reverse' => -170.0, + _ => + (labelText == 'W' || labelText == 'H') + ? 100 + distance + : distance, + }; + expect(double.parse(field.controller!.text), closeTo(expected, .01)); + if (action != 'fallback') { + final timeline = preview.transforms.valueFor(ElementId('clip'))!; + if (labelText == 'W' || labelText == 'H') { + expect( + labelText == 'W' ? timeline.scale : timeline.scaleY, + closeTo(expected / 100, 1e-9), + ); + expect( + labelText == 'W' ? timeline.scaleY : timeline.scale, + closeTo(action == 'unlocked' ? 1 : expected / 100, 1e-9), + ); + } else if (labelText == 'X') { + expect( + timeline.x, + closeTo(distance / session.canvas.width, 1e-9), + ); + expect(timeline.y, 0); + } else if (labelText == 'Y') { + expect( + timeline.y, + closeTo(distance / session.canvas.height, 1e-9), + ); + expect(timeline.x, 0); + } else if (labelText == '旋转') { + expect(timeline.rotation, closeTo(expected, 1e-9)); + } + } + expect(view.version.kernelVersion, same(base)); + expect(session.dirty, isFalse); + if (action == 'wrap_reverse') { + await gesture.moveBy(const Offset(-40, 0)); + await tester.pump(); + expect(double.parse(field.controller!.text), 150); + expect( + preview.transforms.valueFor(ElementId('clip'))!.rotation, + 150, + ); + } + if (action == 'escape') { + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + } else if (action == 'cancel') { + await gesture.cancel(); + } else if (action == 'return') { + await gesture.moveBy(Offset(-distance, 0)); + } else if (action == 'dispose') { + await tester.pumpWidget(const SizedBox()); + } else if (action == 'sequence') { + session.selectSequence(SequenceId('one')); + } else if (action == 'stale') { + final edit = session.previewParameters( + id, + ElementId('clip'), + const ClipTransform(x: .2).parameters, + ); + session.commitParameters( + id, + edit, + parameterTargets: ClipTransform.targets, + ); + expectedVersion = view.version.kernelVersion; + } + } + if (action != 'cancel') await gesture.up(); + // Flush real file IO before settle advances the autosave's fake clock. + await tester.runAsync(session.flush); + await tester.pumpAndSettle(); + if (action.startsWith('wrap_') || + [ + 'commit', + 'fast', + 'fallback', + 'unlocked', + 'lower', + 'upper', + ].contains(action)) { + expect(view.version.kernelVersion, isNot(same(base))); + view.undo(); + expect(view.version.kernelVersion, same(base)); + } else { + expect(view.version.kernelVersion, same(expectedVersion)); + } + expect(preview.transforms.hasPending, isFalse); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + await tester.runAsync(session.flush); + }); + } + } + + testWidgets( + 'picture values follow uncommitted gestures and restore on cancel', + (tester) async { + final id = SequenceId('two'); + final clipId = ElementId('clip'); + final view = session.view(id); + final base = view.version.kernelVersion; + final preview = _LivePropertyPreview(session); + addTearDown(preview.close); + var previewNotifications = 0; + preview.busy = false; + preview.addListener(() => previewNotifications++); + await tester.pumpWidget( + ProviderScope( + overrides: [ + editorPreviewProvider( + projectId, + 'project', + ).overrideWith((ref) async => preview), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + theme: AppTheme.propertiesPanelTheme(EditorTheme.penLight), + home: Scaffold( + body: SizedBox( + width: 225, + child: PictureProperties( + projectId: projectId, + timelineId: 'project', + session: session, + sequence: id, + clip: base.query().element(base.query().elementById(clipId)!), + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + String text(String key) => tester + .widget( + find.descendant( + of: find.byKey(ValueKey(key)), + matching: find.byType(TextField), + ), + ) + .controller! + .text; + PreviewVisual visual(ClipTransform value) => PreviewVisual( + layerId: 'video', + elementId: clipId, + lane: 0, + transform: value, + geometry: const PreviewGeometry( + center: Offset(100, 100), + size: Size(200, 200), + ), + ); + expect(find.byType(Slider), findsNothing); + expect(find.byKey(const ValueKey('picture-scale-y')), findsOneWidget); + expect(text('picture-scale-x'), '100'); + expect( + tester.getSize(find.byKey(const Key('picture-lock'))), + const Size.square(AppControlSize.propertyControl), + ); + expect( + tester + .getSize( + find.descendant( + of: find.byKey(const ValueKey('picture-scale-y')), + matching: find.byType(TextField), + ), + ) + .height, + AppControlSize.propertyControl, + ); + expect( + tester.getSize(find.byKey(const ValueKey('picture-align-left'))).height, + AppControlSize.propertyControl, + ); + expect( + tester.getSize(find.byKey(const Key('picture-lock'))), + tester.getSize(find.byKey(const ValueKey('picture-key-scale'))), + ); + expect( + tester.getRect(find.byKey(const ValueKey('picture-key-scale'))).left - + tester.getRect(find.byKey(const ValueKey('picture-scale-y'))).right, + AppSpacing.small, + ); + final canvasDrag = preview.transforms.begin( + visual(const ClipTransform()), + )!; + canvasDrag.update(const ClipTransform(scale: 1.5)); + await tester.pump(); + final lockControl = tester.widget( + find.byKey(const Key('picture-lock')), + ); + final alignControl = tester.widget( + find.byKey(const ValueKey('picture-align-left')), + ); + expect(lockControl.onPressed, isNotNull); + expect(alignControl.onPressed, isNotNull); + lockControl.onPressed!(); + alignControl.onPressed!(); + await tester.pump(); + expect(preview.aspectRatioLocked, isTrue); + expect(find.byType(Slider), findsNothing); + expect(text('picture-scale-x'), '150'); + expect(preview.transforms.hasPending, isTrue); + expect(view.version.kernelVersion, same(base)); + canvasDrag.cancel(); + await tester.pump(); + preview.busy = true; + await tester.pump(); + final busyAlignControl = tester.widget( + find.byKey(const ValueKey('picture-align-left')), + ); + expect(busyAlignControl.onPressed, isNotNull); + busyAlignControl.onPressed!(); + await tester.pump(); + expect(view.version.kernelVersion, same(base)); + preview.busy = false; + await tester.tap(find.byKey(const Key('picture-lock'))); + await tester.pumpAndSettle(); + expect(preview.aspectRatioLocked, isFalse); + expect(previewNotifications, 1); + previewNotifications = 0; + final edit = preview.transforms.begin(visual(const ClipTransform()))!; + for (final (pixels, expected) in [ + (-0.0, '0'), + (-1e-12, '0'), + (-0.004, '0'), + (0.004, '0'), + (-0.006, '-0.01'), + (-10.5, '-10.5'), + ]) { + edit.update( + ClipTransform( + x: pixels / session.canvas.width, + y: pixels / session.canvas.height, + rotation: pixels, + ), + ); + await tester.pump(); + expect(text('picture-x'), expected); + expect(text('picture-y'), expected); + expect(text('picture-rotation'), expected); + expect(edit.value.x, pixels / session.canvas.width); + expect(view.version.kernelVersion, same(base)); + } + for (var i = 1; i <= 3; i++) { + edit.update( + ClipTransform( + x: i * .1, + y: i * -.1, + scale: i.toDouble(), + scaleY: i * .5, + rotation: i * 10, + ), + ); + await tester.pump(); + for (final field in tester.widgetList( + find.byType(TextField), + )) { + expect(field.enabled, isTrue); + expect(field.readOnly, isTrue); + expect(field.canRequestFocus, isFalse); + } + expect( + double.parse(text('picture-x')), + closeTo(i * .1 * session.canvas.width, .01), + ); + expect( + double.parse(text('picture-y')), + closeTo(i * -.1 * session.canvas.height, .01), + ); + expect(double.parse(text('picture-scale-x')), i * 100); + expect(double.parse(text('picture-scale-y')), i * 50); + expect(double.parse(text('picture-rotation')), i * 10); + expect(view.version.kernelVersion, same(base)); + expect(session.dirty, isFalse); + expect(previewNotifications, 0); + } + await edit.end(); + await tester.pump(); + for (final field in tester.widgetList( + find.byType(TextField), + )) { + expect(field.enabled, isTrue); + expect(field.readOnly, isFalse); + expect(field.canRequestFocus, isTrue); + } + await tester.runAsync(session.flush); + expect(text('picture-rotation'), '30'); + final committed = view.version.kernelVersion; + final next = preview.transforms.begin(visual(edit.value))!; + next.update(edit.value.copyWith(rotation: 80)); + await tester.pump(); + expect(text('picture-rotation'), '80'); + next.cancel(); + await tester.pump(); + expect(text('picture-rotation'), '30'); + expect(view.version.kernelVersion, same(committed)); + expect(session.dirty, isFalse); + view.undo(); + expect(view.version.kernelVersion, same(base)); + await tester.pumpWidget(const SizedBox()); + await tester.runAsync(session.flush); + }, + ); + + testWidgets( + 'property panel stays at both edges during repeated trackpad scrolling', + (tester) async { + final id = SequenceId('two'); + final asset = AssetDocument( + id: 'video', + name: 'Video', + storage: AssetStorage.external, + location: 'file:///video.mov', + ); + await tester.runAsync(() => workspace.project!.saveAsset(asset)); + session.insertAsset( + sequenceId: id, + assetId: asset.id, + assetName: asset.name, + uri: Uri.file('/video.mov'), + duration: RationalTime.seconds(3), + position: 0, + kind: 'video', + hasAudio: false, + ); + await tester.runAsync(session.flush); + final view = session.view(id); + final query = view.version.kernelVersion.query(); + final clipId = session.persistence + .timeline(id) + .exportDto() + .elements + .singleWhere((element) => element.name == asset.name) + .id; + final clip = query.elementById(clipId)!; + session.selectSequence(id); + view.setSelection([clip]); + view.seekTo(query.absoluteStart(clip)); + + await tester.pumpWidget( + ProviderScope( + overrides: [ + editorTimelineProvider( + projectId, + 'project', + ).overrideWith((ref) async => session), + editorPreviewProvider(projectId, 'project').overrideWith( + (ref) async => + throw StateError('No native preview in scroll test'), + ), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + theme: EditorTheme.penLight.copyWith( + platform: TargetPlatform.macOS, + ), + home: Scaffold( + body: SizedBox( + width: 225, + height: 240, + child: EditorPropertiesPanel( + projectId: projectId, + timelineId: 'project', + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + final scroller = find + .byWidgetPredicate( + (widget) => + widget is SingleChildScrollView && + widget.scrollDirection == Axis.vertical, + ) + .first; + final scrollable = find + .descendant(of: scroller, matching: find.byType(Scrollable)) + .first; + final position = tester.state(scrollable).position; + expect(position.maxScrollExtent, greaterThan(0)); + final extent = position.maxScrollExtent; + for (final bottom in [false, true]) { + final edge = bottom ? extent : position.minScrollExtent; + position.jumpTo(edge); + await tester.pumpAndSettle(); + for (var repeat = 0; repeat < 3; repeat++) { + final gesture = await tester.createGesture( + kind: PointerDeviceKind.trackpad, + ); + await gesture.panZoomStart( + tester.getTopLeft(scroller) + const Offset(10, 20), + ); + for (var i = 1; i <= 8; i++) { + await gesture.panZoomUpdate( + tester.getTopLeft(scroller) + const Offset(10, 20), + pan: Offset(0, (bottom ? -1 : 1) * i * 12.0), + timeStamp: Duration(milliseconds: i * 16), + ); + await tester.pump(const Duration(milliseconds: 16)); + expect(position.maxScrollExtent, extent); + expect( + position.pixels, + closeTo(edge, .01), + reason: 'bottom=$bottom repeat=$repeat step=$i', + ); + } + await gesture.panZoomEnd( + timeStamp: const Duration(milliseconds: 160), + ); + await tester.pumpAndSettle(); + expect(position.pixels, closeTo(edge, .01)); + await tester.sendEventToBinding( + PointerScrollEvent( + position: tester.getTopLeft(scroller) + const Offset(10, 20), + scrollDelta: Offset(0, bottom ? 60 : -60), + ), + ); + await tester.pumpAndSettle(); + expect(position.pixels, closeTo(edge, .01)); + } + } + position.jumpTo(extent / 2); + await tester.pumpAndSettle(); + await tester.sendEventToBinding( + PointerScrollEvent( + position: tester.getTopLeft(scroller) + const Offset(10, 20), + scrollDelta: const Offset(0, 10), + ), + ); + await tester.pumpAndSettle(); + expect(position.pixels, closeTo(extent / 2 + 10, .01)); + await tester.pumpWidget(const SizedBox()); + }, + ); + + testWidgets( + 'property refresh preserves focused selection and scroll offset', + (tester) async { + final id = SequenceId('two'); + final view = session.view(id); + final scroll = ScrollController(); + addTearDown(scroll.dispose); + await tester.pumpWidget( + ProviderScope( + overrides: [ + editorPreviewProvider(projectId, 'project').overrideWith( + (ref) async => + throw StateError('No native preview in input test'), + ), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + theme: EditorTheme.penLight, + home: Scaffold( + body: SizedBox( + width: 225, + height: 220, + child: SingleChildScrollView( + controller: scroll, + child: ListenableBuilder( + listenable: view, + builder: (_, _) { + final query = view.version.kernelVersion.query(); + return PictureProperties( + projectId: projectId, + timelineId: 'project', + session: session, + sequence: id, + clip: query.element( + query.elementById(ElementId('clip'))!, + ), + ); + }, + ), + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + final field = find.descendant( + of: find.byKey(const ValueKey('picture-scale-x')), + matching: find.byType(TextField), + ); + await tester.ensureVisible(field); + await tester.pumpAndSettle(); + await tester.tap(field); + await tester.pumpAndSettle(); + final controller = tester.widget(field).controller!; + const selection = TextSelection(baseOffset: 0, extentOffset: 2); + controller.selection = selection; + await tester.pumpAndSettle(); + scroll.jumpTo(120); + await tester.pumpAndSettle(); + final offset = scroll.offset; + for (var i = 1; i <= 5; i++) { + view.seekTo(i * TimelineClock.ticksPerSecond); + await tester.pumpAndSettle(); + expect(scroll.offset, closeTo(offset, .01)); + expect(controller.selection, selection); + } + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + }, + ); + + testWidgets('picture inputs commit axes, preserve ratio, validate and undo', ( + tester, + ) async { + final id = SequenceId('two'); + final view = session.view(id); + final clipId = ElementId('clip'); + final base = view.version.kernelVersion; + ClipTransform current() { + final query = view.version.kernelVersion.query(); + return ClipTransform.fromRecord( + query.element(query.elementById(clipId)!), + ); + } + + await tester.pumpWidget( + ProviderScope( + overrides: [ + editorPreviewProvider(projectId, 'project').overrideWith( + (ref) async => throw StateError('No native preview in input test'), + ), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + theme: EditorTheme.penLight, + home: Scaffold( + body: SizedBox( + width: 225, + child: ListenableBuilder( + listenable: view, + builder: (_, _) { + final query = view.version.kernelVersion.query(); + return PictureProperties( + projectId: projectId, + timelineId: 'project', + session: session, + sequence: id, + clip: query.element(query.elementById(clipId)!), + ); + }, + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + Future input(String field, String text) async { + final finder = find.descendant( + of: find.byKey(ValueKey(field)), + matching: find.byType(TextField), + ); + await tester.enterText(finder, text); + await tester.testTextInput.receiveAction(TextInputAction.done); + await tester.pump(); + await tester.runAsync(session.flush); + await tester.pumpAndSettle(); + } + + await input('picture-scale-x', '150'); + expect(current().scale, 1.5); + expect(current().scaleY, 1.5); + view.undo(); + expect(view.version.kernelVersion, same(base)); + view.redo(); + await tester.runAsync(session.flush); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('picture-lock'))); + await tester.pumpAndSettle(); + await input('picture-scale-y', '50'); + expect(current().scale, 1.5); + expect(current().scaleY, .5); + await tester.tap(find.byKey(const Key('picture-lock'))); + await tester.pumpAndSettle(); + await input('picture-scale-x', '300'); + expect(current().scale, 3); + expect(current().scaleY, 1); + await input('picture-x', '192'); + await input('picture-y', '-108'); + expect(current().x, closeTo(192 / session.canvas.width, 1e-9)); + expect(current().y, closeTo(-108 / session.canvas.height, 1e-9)); + await input('picture-rotation', '37'); + expect(current().rotation, 37); + final valid = view.version.kernelVersion; + await input('picture-scale-x', '0'); + expect(view.version.kernelVersion, same(valid)); + await input('picture-rotation', 'NaN'); + expect(view.version.kernelVersion, same(valid)); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pumpAndSettle(); + expect(find.text('无效数值'), findsNothing); + await tester.runAsync(session.flush); + final saved = await tester.runAsync( + () => workspace.project!.loadTimeline('project'), + ); + final clip = saved!.sequences + .singleWhere((s) => s.id == id) + .elements + .single; + expect( + clip.parameters + .singleWhere((p) => p.definition.id == 'canvas.scale.y') + .definition + .defaultValue, + 1, + ); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + }); + + test('canvas settings save with edits and survive subsequent full saves and reopen', () async { + final view = session.view(SequenceId('one')); + final original = view.version.kernelVersion; + session.commands.setCanvas(ProjectCanvasPresets.values['4:3']!); + expect(identical(original, view.version.kernelVersion), isTrue); + final saving = session.flush(); + session.commands.setCanvas(ProjectCanvasPresets.values['9:16']!); + await saving; + expect(session.dirty, isFalse); + var saved = await workspace.project!.loadTimeline('project'); + expect(saved.settings['renderSize'], {'width': 1080.0, 'height': 1920.0}); + expect(saved.settings['keep'], isTrue); + view.setSelection([ + view.version.kernelVersion.query().elementById(ElementId('clip'))!, + ]); + view.seekTo(5 * TimelineClock.ticksPerSecond); + view.cutSelectionAtPlayhead(); + await session.flush(); + saved = await workspace.project!.loadTimeline('project'); + expect(saved.settings['renderSize'], {'width': 1080.0, 'height': 1920.0}); + expect(saved.sequences.first.elements, hasLength(2)); + await workspace.close(); + workspace = ProjectWorkspace(creationNames: testCreationNames); + await workspace.open('${root.path}/Project.cutdex'); + final reopened = await workspace.openTimelineSession(projectId, saved); + expect(reopened.canvas, ProjectCanvasPresets.values['9:16']); + }); + + test('cut without selection keeps the resulting clips unselected', () async { + final view = session.view(SequenceId('one')); + view.seekTo(5 * TimelineClock.ticksPerSecond); + expect(view.selectedIdentities, isEmpty); + expect(view.canCutSelection, isTrue); + expect(view.cutSelectionAtPlayhead(), isTrue); + expect(view.selectedIdentities, isEmpty); + await session.flush(); + final saved = await workspace.project!.loadTimeline('project'); + expect(saved.sequences.first.elements, hasLength(2)); + }); + + test( + 'cut, undo, redo and delete save the authoritative kernel across reopen', + () async { + final view = session.view(SequenceId('one')); + view.setSelection([ + view.version.kernelVersion.query().elementById(ElementId('clip'))!, + ]); + view.seekTo(5 * TimelineClock.ticksPerSecond); + view.cutSelectionAtPlayhead(); + expect(view.selectedIdentities, hasLength(2)); + expect(session.dirty, isTrue); + await session.flush(); + var saved = await workspace.project!.loadTimeline('project'); + expect(saved.sequences.first.elements, hasLength(2)); + view.undo(); + await session.flush(); + saved = await workspace.project!.loadTimeline('project'); + expect(saved.sequences.first.elements, hasLength(1)); + view.redo(); + view.setSelection([ + view.version.kernelVersion.query().elementById(ElementId('clip'))!, + ]); + view.deleteSelection(); + // Reopening the project verifies the persisted state, not the cached session. + await workspace.close(); + workspace = ProjectWorkspace(creationNames: testCreationNames); + await workspace.open('${root.path}/Project.cutdex'); + saved = await workspace.loadTimeline(projectId, 'project'); + expect(saved.sequences.first.elements, hasLength(1)); + expect( + saved.sequences.first.elements.single.duration, + RationalTime.seconds(5), + ); + expect( + saved.sequences.last.elements.single.duration, + RationalTime.seconds(10), + ); + expect(saved.settings['keep'], isTrue); + expect(saved.payloads.single.data['keep'], 42); + final reopened = await workspace.openTimelineSession(projectId, saved); + expect(reopened.view(SequenceId('one')).canUndo, isFalse); + }, + ); + + test('repeated cuts and full saves keep the database usable', () async { + final view = session.view(SequenceId('one')); + for (var iteration = 0; iteration < 20; iteration++) { + view.setSelection([ + view.version.kernelVersion.query().elementById(ElementId('clip'))!, + ]); + view.seekTo(5 * TimelineClock.ticksPerSecond); + view.cutSelectionAtPlayhead(); + await session.flush(); + expect( + (await workspace.project!.loadTimeline('project')) + .sequences + .first + .elements, + hasLength(2), + ); + + view.undo(); + await session.flush(); + expect( + (await workspace.project!.loadTimeline('project')) + .sequences + .first + .elements, + hasLength(1), + ); + } + }); + + test('concurrent session closes share disposal and preserve a cut', () async { + final view = session.view(SequenceId('one')); + view.setSelection([ + view.version.kernelVersion.query().elementById(ElementId('clip'))!, + ]); + view.seekTo(5 * TimelineClock.ticksPerSecond); + view.cutSelectionAtPlayhead(); + final closing = session.close(); + expect(session.close(), same(closing)); + await closing; + await session.close(); + expect( + (await workspace.project!.loadTimeline('project')) + .sequences + .first + .elements, + hasLength(2), + ); + }); + + test( + 'disposing during a cut save does not notify disposed listeners', + () async { + final view = session.view(SequenceId('one')); + view.setSelection([ + view.version.kernelVersion.query().elementById(ElementId('clip'))!, + ]); + view.seekTo(5 * TimelineClock.ticksPerSecond); + view.cutSelectionAtPlayhead(); + final saving = session.flush(); + expect(session.saving, isTrue); + session.dispose(); + await saving; + expect( + (await workspace.project!.loadTimeline('project')) + .sequences + .first + .elements, + hasLength(2), + ); + }, + ); + + test('camera and selection do not save; committed edits autosave', () async { + final view = session.view(SequenceId('two')); + final initial = (await workspace.project!.loadTimeline('project')).revision; + view.seekTo(3 * TimelineClock.ticksPerSecond); + view.panBy(horizontalPixels: 20); + view.setSelection([ + view.version.kernelVersion.query().elementById(ElementId('clip'))!, + ]); + await session.flush(); + expect( + (await workspace.project!.loadTimeline('project')).revision, + initial, + ); + view.deleteSelection(); + await Future.delayed(const Duration(milliseconds: 500)); + await session.flush(); + expect( + (await workspace.project!.loadTimeline('project')) + .sequences + .last + .elements, + isEmpty, + ); + expect(session.dirty, isFalse); + }); + + test('save conflict retains edits and prevents a project switch', () async { + final view = session.view(SequenceId('one')); + final current = await workspace.project!.loadTimeline('project'); + await workspace.project!.saveTimeline(current); + view.setSelection([ + view.version.kernelVersion.query().elementById(ElementId('clip'))!, + ]); + view.deleteSelection(); + await expectLater(session.flush(), throwsA(isA())); + expect(session.dirty, isTrue); + expect(session.error, isNotNull); + await expectLater( + workspace.open('${root.path}/Other.cutdex', name: 'Other'), + throwsA(isA()), + ); + expect(workspace.project!.info.id, projectId); + expect(view.canUndo, isTrue); + // Keep the persisted external revision; dispose this intentionally conflicted fixture. + await expectLater(workspace.close(), throwsA(isA())); + // A failed save must leave the workspace available to recover the edits. + expect(await workspace.listAssets(projectId), isEmpty); + await expectLater(workspace.close(), throwsA(isA())); + session.dispose(); + await workspace.project!.close(); + workspace = ProjectWorkspace(creationNames: testCreationNames); + }); + + test('imported video inserts at time, keeps source reference and survives undo/redo and reopen', () async { + final file = await File('${root.path}/source.mp4').writeAsBytes([1, 2, 3]); + final sourceUri = File(await file.resolveSymbolicLinks()).uri; + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + messenger.setMockMethodCallHandler(const MethodChannel('cutdex_runtime'), ( + call, + ) async { + expect(call.method, 'probe'); + expect((call.arguments as Map)['media']['uri'], sourceUri.toString()); + return { + 'duration': {'numerator': '3', 'denominator': 1}, + 'videoTrackCount': 1, + 'videoTrackIds': [1], + 'audioTrackCount': 1, + 'audioTrackIds': [1], + 'audioTracks': [ + { + 'start': {'numerator': '0', 'denominator': 1}, + 'duration': {'numerator': '2', 'denominator': 1}, + }, + ], + 'isProtected': false, + }; + }); + addTearDown( + () => messenger.setMockMethodCallHandler( + const MethodChannel('cutdex_runtime'), + null, + ), + ); + final imported = await workspace.importExternalMedia(projectId, [ + ExternalMediaFile(path: file.path), + ]); + final asset = imported.assets.single; + final view = session.view(SequenceId('one')); + await session.commands.insertMedia( + sequence: SequenceId('one'), + assetId: asset.id, + position: 5 * TimelineClock.ticksPerSecond, + ); + expect(view.canUndo, isTrue); + expect(session.dirty, isTrue); + expect(session.assetUris[asset.id], sourceUri); + await session.flush(); + var saved = await workspace.project!.loadTimeline('project'); + expect(saved.sequences.first.elements.map((e) => e.duration.seconds), [ + 5, + 3, + 5, + ]); + final payload = saved.payloads.singleWhere( + (p) => p.assetIds.contains(asset.id), + ); + expect(payload.type, 'video'); + expect(payload.data['audioTrackIndex'], 0); + expect(saved.sequences.first.elements[1].payloadRef?.value, payload.id); + view.undo(); + await session.flush(); + expect( + (await workspace.project!.loadTimeline('project')) + .sequences + .first + .elements, + hasLength(1), + ); + view.redo(); + await session.flush(); + await workspace.close(); + workspace = ProjectWorkspace(creationNames: testCreationNames); + await workspace.open('${root.path}/Project.cutdex'); + saved = await workspace.loadTimeline(projectId, 'project'); + final reopened = await workspace.openTimelineSession(projectId, saved); + expect(reopened.assetUris[asset.id], sourceUri); + expect(saved.sequences.first.elements, hasLength(3)); + expect(await file.readAsBytes(), [1, 2, 3]); + expect( + (await workspace.project!.listAssets()).single.storage, + AssetStorage.external, + ); + }); + + test( + 'shared insertion rejects a timeline change while media I/O is preparing', + () async { + final file = await File('${root.path}/slow.mp4').writeAsBytes([1]); + final imported = await workspace.importExternalMedia(projectId, [ + ExternalMediaFile(path: file.path), + ]); + final entered = Completer(); + final release = Completer(); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + messenger.setMockMethodCallHandler( + const MethodChannel('cutdex_runtime'), + (call) async { + entered.complete(); + await release.future; + return { + 'duration': {'numerator': '3', 'denominator': 1}, + 'videoTrackCount': 1, + 'videoTrackIds': [1], + 'audioTrackCount': 0, + 'audioTrackIds': [], + 'audioTracks': [], + 'isProtected': false, + }; + }, + ); + addTearDown( + () => messenger.setMockMethodCallHandler( + const MethodChannel('cutdex_runtime'), + null, + ), + ); + final insertion = session.commands.insertMedia( + sequence: SequenceId('one'), + assetId: imported.assets.single.id, + position: 0, + ); + final rejected = expectLater( + insertion, + throwsA( + isA().having((e) => e.code, 'code', 'staleVersion'), + ), + ); + await entered.future; + session.commands.setCanvas(ProjectCanvasPresets.values['4:3']!); + final before = session.view(SequenceId('one')).version; + release.complete(); + await rejected; + expect(session.view(SequenceId('one')).version, same(before)); + expect(session.assetUris.containsKey(imported.assets.single.id), isFalse); + }, + ); + + test('image inserts beyond tail with gap; rejected insert does not create history or metadata', () async { + final file = await File('${root.path}/image.png').writeAsBytes([1]); + final imported = await workspace.importExternalMedia(projectId, [ + ExternalMediaFile(path: file.path), + ]); + final view = session.view(SequenceId('one')); + await expectLater( + session.commands.insertMedia( + sequence: SequenceId('one'), + assetId: imported.assets.single.id, + position: -1, + ), + throwsA(anything), + ); + expect(view.canUndo, isFalse); + expect(session.payloads, hasLength(1)); + await session.commands.insertMedia( + sequence: SequenceId('one'), + assetId: imported.assets.single.id, + position: 12 * TimelineClock.ticksPerSecond, + ); + await session.flush(); + final saved = await workspace.project!.loadTimeline('project'); + expect(saved.sequences.first.elements.map((e) => e.duration.seconds), [ + 10, + 2, + 5, + ]); + expect(saved.sequences.first.elements[1].structure, ElementStructure.gap); + expect(saved.payloads.last.type, 'image'); + }); + + test( + 'probe failure leaves active and retained project kernels untouched', + () async { + final file = await File('${root.path}/broken.mp4').writeAsBytes([1]); + final imported = await workspace.importExternalMedia(projectId, [ + ExternalMediaFile(path: file.path), + ]); + final view = session.view(SequenceId('one')); + final before = view.version; + await expectLater( + session.commands.insertMedia( + sequence: SequenceId('one'), + assetId: imported.assets.single.id, + position: 0, + ), + throwsStateError, + ); + expect(view.version, same(before)); + expect(session.dirty, isFalse); + await workspace.open('${root.path}/Other.cutdex', name: 'Other'); + // Retained projects intentionally keep their sessions usable. + expect(session.acceptsEdits, isTrue); + await expectLater( + session.commands.insertMedia( + sequence: SequenceId('one'), + assetId: imported.assets.single.id, + position: 0, + ), + throwsStateError, + ); + expect(view.version, same(before)); + expect(session.dirty, isFalse); + }, + ); + + test( + 'audio inserts into an empty primary and persists its audio binding', + () async { + final projects = await workspace.createTimeline('Empty'); + final project = projects.singleWhere((p) => p.name == 'Empty'); + final document = await workspace.loadTimeline(projectId, project.id); + session = await workspace.openTimelineSession(projectId, document); + final file = await File('${root.path}/audio.wav').writeAsBytes([1]); + final imported = await workspace.importExternalMedia(projectId, [ + ExternalMediaFile(path: file.path), + ]); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + messenger.setMockMethodCallHandler( + const MethodChannel('cutdex_runtime'), + (_) async => { + 'duration': {'numerator': '7', 'denominator': 2}, + 'videoTrackCount': 0, + 'videoTrackIds': [], + 'audioTrackCount': 1, + 'audioTrackIds': [1], + 'audioTracks': [ + { + 'start': {'numerator': '0', 'denominator': 1}, + 'duration': {'numerator': '2', 'denominator': 1}, + }, + ], + 'isProtected': false, + }, + ); + addTearDown( + () => messenger.setMockMethodCallHandler( + const MethodChannel('cutdex_runtime'), + null, + ), + ); + final id = session.activeSequenceId!; + await session.commands.insertMedia( + sequence: id, + assetId: imported.assets.single.id, + position: 0, + ); + final view = session.view(id); + final query = view.version.kernelVersion.query(); + final element = query.element( + query.storylineElements(query.primaryStoryline).single, + ); + expect(session.classify(element).name, 'audioOnly'); + await session.flush(); + final saved = await workspace.project!.loadTimeline(project.id); + expect( + saved.sequences.single.elements.single.duration, + RationalTime(7, 2), + ); + expect(saved.payloads.single.type, 'audio'); + expect(saved.payloads.single.data, {'audioTrackIndex': 0}); + view.undo(); + await session.flush(); + expect( + (await workspace.project!.loadTimeline(project.id)) + .sequences + .single + .elements, + isEmpty, + ); + }, + ); + + testWidgets( + 'Finder drag remains active when the timeline target is replaced', + (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.macOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + const dropChannel = MethodChannel('cutdex_native/file_drop/timeline'); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + final nativeCalls = []; + messenger.setMockMethodCallHandler(dropChannel, (call) async { + nativeCalls.add(call); + return null; + }); + Widget editor(String id) => ProviderScope( + overrides: [ + // ignore: riverpod_lint/scoped_providers_should_specify_dependencies + projectsProvider.overrideWith( + () => _DropProjects(session, projectId), + ), + ], + child: MaterialApp( + home: Scaffold( + body: TimelineExternalDropTarget( + key: ValueKey(id), + projectId: projectId, + session: session, + sequenceId: SequenceId('two'), + child: const SizedBox.expand(), + ), + ), + ), + ); + await tester.pumpWidget(editor('old')); + await tester.pumpAndSettle(); + await tester.pumpWidget(editor('new')); + await tester.pumpAndSettle(); + final target = tester.state( + find.byType(TimelineExternalDropTarget), + ); + // A pending probe is enough to observe which widget receives the event. + const runtimeChannel = MethodChannel('cutdex_runtime'); + final probe = Completer(); + messenger.setMockMethodCallHandler( + runtimeChannel, + (call) => probe.future, + ); + addTearDown( + () => messenger.setMockMethodCallHandler(runtimeChannel, null), + ); + await messenger.handlePlatformMessage( + dropChannel.name, + const StandardMethodCodec().encodeMethodCall( + const MethodCall('event', { + 'phase': 'enter', + 'session': 1, + 'x': 125.0, + 'y': 65.0, + 'files': [ + {'path': '/replacement.mov'}, + ], + }), + ), + (_) {}, + ); + await tester.pump(); + expect(target.file?.localPath, '/replacement.mov'); + expect( + nativeCalls.lastWhere((call) => call.method == 'setRegion').arguments, + isNotNull, + ); + await tester.pumpWidget(const SizedBox()); + probe.complete(null); + await tester.pumpAndSettle(); + expect( + nativeCalls.lastWhere((call) => call.method == 'setRegion').arguments, + isNull, + ); + debugDefaultTargetPlatformOverride = null; + }, + ); + + testWidgets( + 'inactive timeline routes release late drags without probing media', + (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.macOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + final messenger = tester.binding.defaultBinaryMessenger; + const dropChannel = MethodChannel('cutdex_native/file_drop/timeline'); + const runtimeChannel = MethodChannel('cutdex_runtime'); + final nativeCalls = []; + var probes = 0; + messenger.setMockMethodCallHandler(dropChannel, (call) async { + nativeCalls.add(call); + return null; + }); + messenger.setMockMethodCallHandler(runtimeChannel, (_) async { + probes++; + return jsonEncode({'value': null}); + }); + addTearDown( + () => messenger.setMockMethodCallHandler(runtimeChannel, null), + ); + await tester.pumpWidget( + ProviderScope( + overrides: [ + projectsProvider.overrideWith( + () => _DropProjects(session, projectId), + ), + ], + child: MaterialApp( + home: TickerMode( + enabled: false, + child: TimelineExternalDropTarget( + projectId: projectId, + session: session, + sequenceId: SequenceId('two'), + child: const SizedBox.expand(), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + final target = tester.state( + find.byType(TimelineExternalDropTarget), + ); + await target.event( + const NativeFileDropEvent( + phase: NativeFileDropPhase.enter, + session: 7, + position: Offset(125, 65), + paths: ['/late.mov'], + ), + ); + await tester.pumpAndSettle(); + expect(target.sessionId, isNull); + expect(probes, 0); + expect( + nativeCalls + .where((call) => call.method == 'release') + .map((call) => call.arguments), + [ + {'session': 7}, + ], + ); + await tester.pumpWidget(const SizedBox()); + await tester.pumpAndSettle(); + debugDefaultTargetPlatformOverride = null; + }, + ); + + testWidgets( + 'hiding a timeline cancels hover but retains access until probing finishes', + (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.macOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + final messenger = tester.binding.defaultBinaryMessenger; + const dropChannel = MethodChannel('cutdex_native/file_drop/timeline'); + const runtimeChannel = MethodChannel('cutdex_runtime'); + final nativeCalls = []; + final probe = Completer(); + final visible = ValueNotifier(true); + addTearDown(visible.dispose); + messenger.setMockMethodCallHandler(dropChannel, (call) async { + nativeCalls.add(call); + return null; + }); + messenger.setMockMethodCallHandler(runtimeChannel, (_) => probe.future); + addTearDown( + () => messenger.setMockMethodCallHandler(runtimeChannel, null), + ); + await tester.pumpWidget( + ProviderScope( + overrides: [ + projectsProvider.overrideWith( + () => _DropProjects(session, projectId), + ), + ], + child: MaterialApp( + home: ValueListenableBuilder( + valueListenable: visible, + builder: (_, enabled, child) => + TickerMode(enabled: enabled, child: child!), + child: TimelineExternalDropTarget( + projectId: projectId, + session: session, + sequenceId: SequenceId('two'), + child: const SizedBox.expand(), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + final target = tester.state( + find.byType(TimelineExternalDropTarget), + ); + await target.event( + const NativeFileDropEvent( + phase: NativeFileDropPhase.enter, + session: 7, + position: Offset(125, 65), + paths: ['/late.mov'], + ), + ); + await tester.pump(); + expect(target.sessionId, 7); + visible.value = false; + await tester.pumpAndSettle(); + final hiddenSession = target.sessionId; + expect(nativeCalls.where((call) => call.method == 'release'), isEmpty); + probe.complete(jsonEncode({'value': null})); + await tester.pumpAndSettle(); + expect(hiddenSession, isNull); + expect( + nativeCalls + .where((call) => call.method == 'release') + .map((call) => call.arguments), + [ + {'session': 7}, + ], + ); + expect(session.dirty, false); + await tester.pumpWidget(const SizedBox()); + await tester.pumpAndSettle(); + debugDefaultTargetPlatformOverride = null; + }, + ); + + for (final fail in [false, true]) { + testWidgets( + 'closing a Finder drop waits for pending import before releasing access (fail=$fail)', + (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.macOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + const dropChannel = MethodChannel('cutdex_native/file_drop/timeline'); + const runtimeChannel = MethodChannel('cutdex_runtime'); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + final nativeCalls = []; + messenger.setMockMethodCallHandler(dropChannel, (call) async { + nativeCalls.add(call); + return null; + }); + messenger.setMockMethodCallHandler(runtimeChannel, (call) async { + if (call.method == 'probe') { + return { + 'duration': {'numerator': '20', 'denominator': 1}, + 'videoTrackCount': 1, + 'videoTrackIds': [1], + 'audioTrackCount': 0, + 'audioTrackIds': [], + 'isProtected': false, + 'audioTracks': >[], + 'videoDisplaySizes': [ + {'width': 1920, 'height': 1080}, + ], + }; + } + return null; + }); + addTearDown(() { + messenger.setMockMethodCallHandler(dropChannel, null); + messenger.setMockMethodCallHandler(runtimeChannel, null); + }); + final projects = _ImportingDropProjects(session, projectId); + final target = GlobalKey(); + await tester.pumpWidget( + ProviderScope( + overrides: [projectsProvider.overrideWith(() => projects)], + child: MaterialApp( + home: Scaffold( + body: TimelineExternalDropTarget( + key: target, + projectId: projectId, + session: session, + sequenceId: SequenceId('two'), + child: const SizedBox.expand(), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + target.currentState!.enterExternal( + 1, + '/slow.mov', + const Offset(125, 65), + ); + await tester.pumpAndSettle(); + expect(target.currentState!.incomingClip, isNotNull); + final dropping = target.currentState!.drop(); + await tester.pump(); + expect(projects._importStarted.isCompleted, isTrue); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(); + expect(nativeCalls.where((call) => call.method == 'release'), isEmpty); + if (fail) { + projects._importResult.completeError(StateError('import failed')); + } else { + projects._importResult.complete( + MediaImportResult( + assets: [ + AssetDocument( + id: 'imported', + name: 'slow.mov', + storage: AssetStorage.external, + location: Uri.file('/slow.mov').toString(), + metadata: const {'kind': 'video'}, + ), + ], + added: 1, + duplicates: 0, + failures: [], + ), + ); + } + await dropping; + await tester.pumpAndSettle(); + expect( + nativeCalls + .where((call) => call.method == 'release') + .map((call) => call.arguments), + [ + {'session': 1}, + ], + ); + expect(session.dirty, isFalse); + expect( + session.persistence.timeline(SequenceId('two')).canUndo, + isFalse, + ); + expect(tester.takeException(), isNull); + debugDefaultTargetPlatformOverride = null; + }, + ); + } + + testWidgets( + 'Finder hover uses the shared timeline renderer and temporary media binding', + (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.macOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + const dropChannel = MethodChannel('cutdex_native/file_drop/timeline'); + const runtimeChannel = MethodChannel('cutdex_runtime'); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + final thumbnails = RuntimeTimelineThumbnails( + resolveMedia: (ref) => session.mediaBinding(ref)?.media, + resolveTrackSelection: (ref) => + session.mediaBinding(ref)?.videoSelection, + ); + addTearDown(thumbnails.dispose); + final view = session.view(SequenceId('two')); + final nativeCalls = []; + final thumbnailTimes = []; + Completer? probeGate; + messenger.setMockMethodCallHandler(dropChannel, (call) async { + nativeCalls.add(call); + return null; + }); + messenger.setMockMethodCallHandler(runtimeChannel, (call) async { + if (call.method == 'probe') { + await probeGate?.future; + return { + 'duration': {'numerator': '20', 'denominator': 1}, + 'videoTrackCount': 1, + 'videoTrackIds': [1], + 'audioTrackCount': 1, + 'audioTrackIds': [1], + 'isProtected': false, + 'audioTracks': [ + { + 'start': {'numerator': '0', 'denominator': 1}, + 'duration': {'numerator': '20', 'denominator': 1}, + }, + ], + 'videoDisplaySizes': [ + {'width': 1920, 'height': 1080}, + ], + }; + } + if (call.method == 'thumbnails') { + final times = (call.arguments as Map)['times'] as List; + thumbnailTimes.addAll(times); + return [ + for (final time in times) + { + 'requestedTime': time, + 'actualTime': time, + 'width': 1, + 'height': 1, + 'format': 'jpeg', + 'data': base64Decode( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a9uoAAAAASUVORK5CYII=', + ), + }, + ]; + } + return null; + }); + addTearDown(() { + messenger.setMockMethodCallHandler(dropChannel, null); + messenger.setMockMethodCallHandler(runtimeChannel, null); + }); + await tester.pumpWidget( + ProviderScope( + overrides: [ + projectsProvider.overrideWith( + () => _DropProjects(session, projectId), + ), + ], + child: MaterialApp( + home: Scaffold( + body: TimelineExternalDropTarget( + projectId: projectId, + session: session, + sequenceId: SequenceId('two'), + child: TimelineView( + controller: view, + thumbnails: thumbnails, + classifyContent: session.classify, + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + Future send(String phase, {int id = 1}) async { + await messenger.handlePlatformMessage( + dropChannel.name, + const StandardMethodCodec().encodeMethodCall( + MethodCall('event', { + 'phase': phase, + 'session': id, + 'x': 125.0, + 'y': 65.0, + 'files': [ + {'path': '/hover.mov'}, + ], + }), + ), + (_) {}, + ); + } + + await send('enter'); + await tester.pumpAndSettle(); + expect(view.dragGhost, isNotNull); + expect(view.dragGhost!.top, 53); + expect( + view.dragGhost!.body.start, + 50 * TimelineFormat.fps24.frameGrid.quantumTicks, + ); + final preview = view.project( + TimelineViewportRect(width: 800, height: 600), + ); + final record = preview.version.kernelVersion.query().element( + view.dragGhost!.source.owner, + ); + expect(record.name, 'hover.mov'); + expect( + session.mediaBinding(record.payloadRef!)!.media.uri, + Uri.file('/hover.mov'), + ); + expect(thumbnailTimes, isNotEmpty); + expect(find.byType(Image), findsNothing); + final count = thumbnailTimes.length; + await send('move'); + await tester.pumpAndSettle(); + expect(thumbnailTimes.length, count); + expect(session.dirty, isFalse); + await send('exit'); + await tester.pumpAndSettle(); + expect(view.dragGhost, isNull); + expect(session.mediaBinding(record.payloadRef!), isNull); + expect(nativeCalls.where((c) => c.method == 'release'), hasLength(1)); + expect(session.dirty, isFalse); + probeGate = Completer(); + await send('enter'); + await tester.pump(); + await send('exit'); + final previousProbe = probeGate; + probeGate = null; + try { + await send('enter', id: 2); + await tester.pump(); + await tester.pump(); + expect( + view.dragGhost, + isNotNull, + reason: 'A cancelled probe must not block a new drag', + ); + await send('exit', id: 2); + } finally { + previousProbe.complete(); + } + await tester.pumpAndSettle(); + expect(view.dragGhost, isNull); + expect(session.dirty, isFalse); + expect(session.persistence.timeline(SequenceId('two')).canUndo, isFalse); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + debugDefaultTargetPlatformOverride = null; + }, + ); + + testWidgets( + 'Windows Explorer hover exposes files before drop and renders a clip', + (tester) async { + debugDefaultTargetPlatformOverride = TargetPlatform.windows; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + const runtimeChannel = MethodChannel('cutdex_runtime'); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + const dropChannel = MethodChannel('cutdex_native/file_drop/timeline'); + messenger.setMockMethodCallHandler(dropChannel, (_) async => null); + addTearDown(() => messenger.setMockMethodCallHandler(dropChannel, null)); + messenger.setMockMethodCallHandler(runtimeChannel, (call) async { + final request = + jsonDecode((call.arguments as Map)['request'] as String) as Map; + return jsonEncode({ + 'value': request['method'] == 'probe' + ? { + 'duration': {'numerator': '12', 'denominator': 1}, + 'videoTrackCount': 1, + 'videoTrackIds': [1], + 'audioTrackCount': 0, + 'audioTrackIds': [], + 'isProtected': false, + 'audioTracks': [], + } + : null, + }); + }); + addTearDown( + () => messenger.setMockMethodCallHandler(runtimeChannel, null), + ); + await tester.pumpWidget( + ProviderScope( + overrides: [ + projectsProvider.overrideWith( + () => _DropProjects(session, projectId), + ), + ], + child: MaterialApp( + home: Scaffold( + body: TimelineExternalDropTarget( + projectId: projectId, + session: session, + sequenceId: SequenceId('two'), + child: const SizedBox.expand(), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + await ProviderScope.containerOf( + tester.element(find.byType(TimelineExternalDropTarget)), + ).read(projectsProvider.future); + await tester.pumpAndSettle(); + Future send(String phase, double x) async { + final done = Completer(); + messenger.handlePlatformMessage( + 'cutdex_native/file_drop/timeline', + const StandardMethodCodec().encodeMethodCall( + MethodCall('event', { + 'phase': phase, + 'session': 1, + 'x': x, + 'y': 65.0, + 'files': phase == 'enter' + ? [ + {'path': r'C:\media\hover.mov'}, + ] + : [], + }), + ), + (_) => done.complete(), + ); + await done.future; + await tester.pumpAndSettle(); + } + + await send('enter', 125.0); + expect(session.view(SequenceId('two')).dragGhost, isNotNull); + expect(session.dirty, isFalse); + await send('move', 126.0); + expect(session.view(SequenceId('two')).dragGhost, isNotNull); + await send('exit', 126.0); + expect(session.view(SequenceId('two')).dragGhost, isNull); + expect(session.dirty, isFalse); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + debugDefaultTargetPlatformOverride = null; + }, + ); + + testWidgets( + 'project video hover reuses drag geometry; cancel restores feedback', + (tester) async { + final asset = AssetDocument( + id: 'video', + name: 'project.mov', + storage: AssetStorage.external, + location: 'file:///project.mov', + metadata: const {'kind': 'video'}, + ); + final projects = _DropProjects(session, projectId, mediaAsset: asset); + final drag = MediaAssetDrag(projectId: projectId, assetId: asset.id); + const runtimeChannel = MethodChannel('cutdex_runtime'); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + + messenger.setMockMethodCallHandler(runtimeChannel, (call) async { + if (call.method == 'probe') { + return { + 'duration': {'numerator': '20', 'denominator': 1}, + 'videoTrackCount': 1, + 'videoTrackIds': [1], + 'audioTrackCount': 0, + 'audioTrackIds': [], + 'audioTracks': [], + 'isProtected': false, + }; + } + return null; + }); + addTearDown( + () => messenger.setMockMethodCallHandler(runtimeChannel, null), + ); + await tester.pumpWidget( + ProviderScope( + overrides: [projectsProvider.overrideWith(() => projects)], + child: MaterialApp( + home: Scaffold( + body: Row( + children: [ + SizedBox( + width: 180, + child: Draggable( + data: drag, + dragAnchorStrategy: pointerDragAnchorStrategy, + feedback: ValueListenableBuilder( + valueListenable: drag.feedbackVisible, + builder: (_, visible, _) => visible + ? const Text('source feedback') + : const SizedBox.shrink(), + ), + child: const Text('drag source'), + ), + ), + Expanded( + child: TimelineAssetDropTarget( + projectId: projectId, + session: session, + sequenceId: SequenceId('two'), + child: const SizedBox.expand(), + ), + ), + ], + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + await ProviderScope.containerOf( + tester.element(find.byType(TimelineAssetDropTarget)), + ).read(projectsProvider.future); + await tester.pumpAndSettle(); + final gesture = await tester.startGesture( + tester.getCenter(find.text('drag source')), + ); + await gesture.moveBy(const Offset(20, 0)); + await tester.pump(); + await gesture.moveTo(const Offset(305, 65)); + await tester.pumpAndSettle(); + final view = session.view(SequenceId('two')); + expect(view.dragGhost, isNotNull); + expect( + view.dragGhost!.body.end - view.dragGhost!.body.start, + 20 * TimelineClock.ticksPerSecond, + ); + expect(find.text('source feedback'), findsNothing); + expect(drag.feedbackVisible.value, isFalse); + expect(session.dirty, isFalse); + await gesture.moveTo(const Offset(365, 210)); + await tester.pumpAndSettle(); + expect(view.dragGhost!.top, 198); + final ghost = view.dragGhost!; + final preview = view.project( + TimelineViewportRect(width: 620, height: 600), + ); + expect( + preview.version.kernelVersion + .query() + .connectionOrderLocation(ghost.source.owner) + ?.side, + ConnectionSide.below, + ); + expect( + view.dragGhost!.body.start, + 74 * TimelineFormat.fps24.frameGrid.quantumTicks, + ); + await gesture.moveTo(const Offset(50, 500)); + await tester.pumpAndSettle(); + expect(view.dragGhost, isNull); + expect(drag.feedbackVisible.value, isTrue); + expect(find.text('source feedback'), findsOneWidget); + await gesture.up(); + await tester.pumpAndSettle(); + expect(session.persistence.timeline(SequenceId('two')).canUndo, isFalse); + expect(session.dirty, isFalse); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + }, + ); + + testWidgets( + 'empty timeline ghost moves freely but drops on Primary at zero', + (tester) async { + await tester.runAsync(() async { + final timelines = await workspace.createTimeline('Empty drop'); + final document = await workspace.loadTimeline( + projectId, + timelines.singleWhere((d) => d.name == 'Empty drop').id, + ); + session = await workspace.openTimelineSession(projectId, document); + }); + final projects = _DropProjects(session, projectId); + await tester.runAsync(() => workspace.project!.saveAsset(projects.asset)); + final id = session.activeSequenceId!; + final view = session.view(id); + final kernel = session.persistence.timeline(id); + final before = kernel.current; + final incoming = ValueNotifier(null); + final target = GlobalKey(); + addTearDown(incoming.dispose); + await tester.pumpWidget( + ProviderScope( + overrides: [projectsProvider.overrideWith(() => projects)], + child: MaterialApp( + home: Scaffold( + body: TimelineExternalDropTarget( + key: target, + projectId: projectId, + session: session, + sequenceId: id, + incoming: incoming, + child: TimelineView(controller: view), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + for (final point in [ + const Offset(180, 10), + const Offset(240, 65), + const Offset(300, 210), + ]) { + incoming.value = (asset: projects.asset, globalPosition: point); + await tester.pumpAndSettle(); + final ghost = view.dragGhost!; + expect(ghost.top, point.dy.round() - 12); + expect( + ghost.body.start, + (point.dx / 60 * TimelineClock.ticksPerSecond).round(), + ); + expect(kernel.current, same(before)); + final q = view + .project(TimelineViewportRect(width: 800, height: 600)) + .version + .kernelVersion + .query(); + expect(q.absoluteStart(ghost.source.owner), 0); + expect(q.connectionForTarget(ghost.source.owner), isNull); + expect(q.storylineLength(q.primaryStoryline), 1); + } + final clipId = target.currentState!.incomingClip!.clipId; + await tester.runAsync(() async { + await target.currentState!.drop(); + await session.flush(); + }); + await tester.pumpAndSettle(); + final q = kernel.current.query(); + final clip = q.elementById(clipId)!; + expect(q.absoluteStart(clip), 0); + expect(q.connectionForTarget(clip), isNull); + expect(q.storylineLength(q.primaryStoryline), 1); + expect(view.dragGhost, isNull); + session.undo(id); + expect(kernel.current, same(before)); + expect(session.canUndo(id), isFalse); + await tester.runAsync(session.flush); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + }, + ); + + for (final pending in [false, true]) { + testWidgets( + 'replacing incoming source clears preview and pending media ($pending)', + (tester) async { + final projects = _DropProjects(session, projectId); + final ready = Completer(); + if (pending) projects.mediaReady = ready.future; + final oldSource = ValueNotifier(null); + final newSource = ValueNotifier(null); + addTearDown(oldSource.dispose); + addTearDown(newSource.dispose); + final id = SequenceId('two'); + final view = session.view(id); + final before = session.persistence.timeline(id).current; + final target = GlobalKey(); + Widget surface( + ValueNotifier source, + ) => ProviderScope( + // ignore: riverpod_lint/scoped_providers_should_specify_dependencies + overrides: [projectsProvider.overrideWith(() => projects)], + child: MaterialApp( + home: Scaffold( + body: TimelineExternalDropTarget( + key: target, + projectId: projectId, + session: session, + sequenceId: id, + incoming: source, + child: TimelineView(controller: view), + ), + ), + ), + ); + await tester.pumpWidget(surface(oldSource)); + oldSource.value = ( + asset: projects.asset, + globalPosition: const Offset(180, 210), + ); + await tester.pump(); + final payload = target.currentState!.incomingClip?.payloadId; + if (!pending) expect(view.dragGhost, isNotNull); + await tester.pumpWidget(surface(newSource)); + ready.complete(); + await tester.pumpAndSettle(); + expect(view.dragGhost, isNull); + expect(target.currentState!.incomingClip, isNull); + expect(target.currentState!.hasPreview, isFalse); + if (payload != null) { + expect(session.mediaBinding(PayloadRef(payload)), isNull); + } + expect(session.persistence.timeline(id).current, same(before)); + expect(session.canUndo(id), isFalse); + expect(session.dirty, isFalse); + oldSource.value = ( + asset: projects.asset, + globalPosition: const Offset(240, 210), + ); + await tester.pumpAndSettle(); + expect(view.dragGhost, isNull); + newSource.value = oldSource.value; + await tester.pumpAndSettle(); + expect(view.dragGhost, isNotNull); + newSource.value = null; + await tester.pumpAndSettle(); + expect(view.dragGhost, isNull); + await tester.pumpWidget(const SizedBox()); + }, + ); + } + + testWidgets( + 'image movement waits for media resolution before creating a clip', + (tester) async { + final projects = _DropProjects(session, projectId); + final ready = Completer(); + projects.mediaReady = ready.future; + final incoming = ValueNotifier(null); + addTearDown(incoming.dispose); + final view = session.view(SequenceId('two')); + await tester.pumpWidget( + ProviderScope( + overrides: [projectsProvider.overrideWith(() => projects)], + child: MaterialApp( + home: Scaffold( + body: TimelineExternalDropTarget( + projectId: projectId, + session: session, + sequenceId: SequenceId('two'), + incoming: incoming, + child: TimelineView(controller: view), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + incoming.value = ( + asset: projects.asset, + globalPosition: const Offset(125, 65), + ); + await tester.pump(); + incoming.value = ( + asset: projects.asset, + globalPosition: const Offset(126, 65), + ); + await tester.pump(); + try { + expect( + view.dragGhost, + isNull, + reason: 'Do not create an unbound placeholder clip', + ); + } finally { + ready.complete(); + } + await tester.pumpAndSettle(); + final frame = view.project(TimelineViewportRect(width: 800, height: 600)); + final clip = frame.version.kernelVersion.query().element( + view.dragSource!.owner, + ); + expect( + session.mediaBinding(clip.payloadRef!)?.media.id, + projects.asset.id, + ); + incoming.value = null; + await tester.pumpAndSettle(); + expect(view.dragGhost, isNull); + expect(session.dirty, isFalse); + await tester.pumpWidget(const SizedBox()); + }, + ); + + testWidgets( + 'media card drag uses frame-aligned viewport position; cancelled drag does not insert', + (tester) async { + final controller = _DropProjects(session, projectId); + final fixture = await controller.build(); + await tester.runAsync( + () => workspace.project!.saveAsset(fixture.assets.single), + ); + await tester.pumpWidget( + ProviderScope( + overrides: [ + projectsProvider.overrideWith(() => controller), + mediaAvailabilityProvider( + projectId, + fixture.assets.single, + ).overrideWith((ref) async => MediaAvailability.available), + editorTimelineProvider( + projectId, + 'project', + ).overrideWith((ref) async => session), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + theme: EditorTheme.penLight, + home: Scaffold( + body: Row( + children: [ + SizedBox(width: 260, child: MediaPanel(projectId: projectId)), + Expanded( + child: EditorTimelinePanel( + projectId: projectId, + timelineId: 'project', + ), + ), + ], + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + final source = find.text('image.png'); + final surface = tester.getRect( + find.byKey(const Key('editor-timeline-surface')), + ); + final gesture = await tester.startGesture(tester.getCenter(source)); + await gesture.moveBy(const Offset(20, 0)); + await tester.pump(); + await gesture.moveTo(Offset(surface.left + 125, surface.top + 65)); + await tester.pump(); + expect(session.view(SequenceId('two')).dragGhost, isNotNull); + expect(session.dirty, isFalse); + final incomingId = tester + .state( + find.byType(TimelineExternalDropTarget), + ) + .incomingClip! + .clipId; + await gesture.up(); + await tester.pump(); + await tester.runAsync(session.flush); + await tester.pumpAndSettle(); + final kernel = session.persistence.timeline(SequenceId('two')); + final query = kernel.current.query(); + final inserted = query.elementById(incomingId)!; + expect( + session.payloadFor(query.element(inserted).payloadRef!)!.assetIds, + ['asset'], + ); + expect( + query.absoluteStart(inserted), + 50 * TimelineFormat.fps24.frameGrid.quantumTicks, + ); + final committed = kernel.current; + await tester.runAsync(session.flush); + final cancelled = await tester.startGesture(tester.getCenter(source)); + await cancelled.moveBy(const Offset(20, 0)); + await tester.pump(); + await cancelled.moveTo(const Offset(10, 550)); + await cancelled.up(); + await tester.pumpAndSettle(); + expect(kernel.current, same(committed)); + expect(session.dirty, isFalse); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + }, + ); + + testWidgets( + 'properties follow clip type, sequence and selection without editing history', + (tester) async { + final sequenceId = SequenceId('two'); + for (final kind in ['video', 'audio', 'image']) { + final asset = AssetDocument( + id: kind, + name: '$kind asset', + storage: AssetStorage.external, + location: 'file:///$kind', + ); + await tester.runAsync(() => workspace.project!.saveAsset(asset)); + session.insertAsset( + sequenceId: sequenceId, + assetId: asset.id, + assetName: asset.name, + uri: Uri.file('/$kind'), + duration: RationalTime.seconds(3), + position: 10 * TimelineClock.ticksPerSecond, + kind: kind, + hasAudio: kind != 'image', + ); + } + await tester.runAsync(session.flush); + final view = session.view(sequenceId); + final kernel = session.persistence.timeline(sequenceId); + final savedVersion = kernel.current; + ElementHandle handle(String kind) { + final id = kernel + .exportDto() + .elements + .singleWhere((e) => e.name == '$kind asset') + .id; + return view.version.kernelVersion.query().elementById(id)!; + } + + Future select(String kind, {bool body = false}) async { + view.setSelection([ + body ? LayoutBodyId.element(handle(kind)) : handle(kind), + ]); + await tester.pumpAndSettle(); + } + + void tabs(List expected) { + for (final name in [ + 'picture', + 'mask', + 'audio', + 'speed', + 'animation', + 'basic', + ]) { + expect( + find.byKey(ValueKey('property-tab-$name')), + expected.contains(name) ? findsOneWidget : findsNothing, + ); + } + } + + view.clearSelection(); + await tester.pumpWidget( + ProviderScope( + overrides: [ + editorTimelineProvider( + projectId, + 'project', + ).overrideWith((ref) async => session), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + theme: EditorTheme.penLight, + home: Scaffold( + body: SizedBox( + width: 225, + child: EditorPropertiesPanel( + projectId: projectId, + timelineId: 'project', + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect(find.text('项目属性'), findsOneWidget); + tabs([]); + await select('video'); + tabs(['picture', 'mask', 'audio', 'speed', 'animation']); + expect(find.text('属性'), findsNothing); + expect( + find.ancestor(of: find.text('对齐'), matching: find.byType(ShaderMask)), + findsOneWidget, + ); + final panelTop = tester.getTopLeft(find.byType(EditorPropertiesPanel)).dy; + final tabBounds = tester.getRect( + find.byKey(const ValueKey('property-tab-picture')), + ); + expect(tabBounds.height, AppControlSize.headerButton); + expect( + tabBounds.left - + tester.getRect(find.byType(EditorPropertiesPanel)).left, + 6, + ); + expect(tabBounds.top - panelTop, 6); + final pictureLabel = find.descendant( + of: find.byKey(const ValueKey('property-tab-picture')), + matching: find.text('画面'), + ); + expect(pictureLabel, findsOneWidget); + expect( + tester.getTopLeft(find.text('对齐')).dx, + tester.getTopLeft(pictureLabel).dx, + ); + final propertyContentLeft = tester.getTopLeft(find.text('对齐')).dx; + final sectionTitle = tester.widget(find.text('对齐')).style!; + expect(sectionTitle.fontSize, 13); + expect(sectionTitle.height, 1.4); + expect(sectionTitle.fontWeight, FontWeight.w500); + expect(sectionTitle.color, EditorTheme.penLight.colorScheme.onSurface); + expect(tabBounds.top, greaterThanOrEqualTo(panelTop)); + expect( + tabBounds.bottom, + lessThanOrEqualTo(panelTop + AppControlSize.panelToolbar), + ); + expect(find.byKey(const Key('property-clip-name')), findsNothing); + expect(find.text('video asset'), findsNothing); + await tester.tap(find.byKey(const ValueKey('property-tab-speed'))); + await tester.pumpAndSettle(); + expect(find.text('1.00×'), findsOneWidget); + expect( + session.isCustomSpeedEnabled( + sequenceId, + view.version.kernelVersion.query().element(handle('video')).id, + ), + isFalse, + ); + expect(view.geometry.primaryHeight, 88); + await tester.tap(find.byKey(const Key('clip-custom-speed-toggle'))); + await tester.pumpAndSettle(); + expect( + session.isCustomSpeedEnabled( + sequenceId, + view.version.kernelVersion.query().element(handle('video')).id, + ), + isTrue, + ); + expect(view.geometry.primaryHeight, 98); + await tester.tap(find.byKey(const ValueKey('property-tab-picture'))); + await tester.pumpAndSettle(); + expect(view.geometry.primaryHeight, 98); + await tester.tap(find.byKey(const ValueKey('property-tab-speed'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('clip-custom-speed-toggle'))); + await tester.pumpAndSettle(); + expect( + session.isCustomSpeedEnabled( + sequenceId, + view.version.kernelVersion.query().element(handle('video')).id, + ), + isFalse, + ); + expect(view.geometry.primaryHeight, 88); + expect(kernel.current, same(savedVersion)); + expect(tester.getTopLeft(find.text('速度')).dx, propertyContentLeft); + expect( + tester.getSize(find.byKey(const Key('split-speed-segment'))).height, + AppControlSize.propertyControl, + ); + view.seekTo( + view.version.kernelVersion.query().absoluteStart(handle('video')) + + TimelineClock.ticksPerSecond, + ); + await tester.pumpAndSettle(); + expect( + find.text('1.00×'), + findsOneWidget, + ); // Playhead does not reset tabs. + view.seekTo( + view.version.kernelVersion.query().absoluteEnd(handle('video')), + ); + await tester.pumpAndSettle(); + tabs(['picture', 'mask', 'audio', 'speed', 'animation']); + expect(find.text('项目属性'), findsNothing); + expect(find.text('1.00×'), findsOneWidget); + expect(view.selectedIdentities, isNotEmpty); + view.seekTo( + view.version.kernelVersion.query().absoluteEnd(handle('video')) + 1, + ); + await tester.pumpAndSettle(); + tabs(['picture', 'mask', 'audio', 'speed', 'animation']); + expect(find.text('项目属性'), findsNothing); + await select('audio', body: true); + tabs(['audio', 'speed']); + expect(find.byKey(const Key('audio-db')), findsOneWidget); + expect(tester.getTopLeft(find.text('音量')).dx, propertyContentLeft); + expect( + tester.getSize(find.byKey(const Key('audio-key'))), + const Size.square(AppControlSize.propertyControl), + ); + expect( + tester.getSize(find.byKey(const Key('audio-db'))).height, + AppControlSize.propertyControl, + ); + expect( + tester + .widget( + find.descendant( + of: find.byKey(const Key('audio-db')), + matching: find.byType(TextField), + ), + ) + .controller! + .text, + '0.0', + ); + await select('image'); + tabs(['picture', 'mask', 'animation']); + expect(find.byType(PictureProperties), findsOneWidget); + view.setSelection([handle('image'), handle('video')]); + await tester.pumpAndSettle(); + tabs([]); + expect(find.textContaining('已选择 2 个片段'), findsOneWidget); + view.setSelection([const ElementHandle(99999, 1)]); + await tester.pumpAndSettle(); + tabs([]); + await select('video'); + session.selectSequence(SequenceId('one')); + await tester.pumpAndSettle(); + tabs([]); + final otherView = session.view(SequenceId('one')); + otherView.setSelection([ + otherView.version.kernelVersion.query().elementById(ElementId('clip'))!, + ]); + await tester.pumpAndSettle(); + tabs(['basic']); + session.selectSequence(sequenceId); + await tester.pumpAndSettle(); + tabs(['picture', 'mask', 'audio', 'speed', 'animation']); + expect(kernel.current, same(savedVersion)); + expect(session.dirty, isFalse); + view.deleteSelection(); + await tester.pumpAndSettle(); + tabs([]); + expect(find.text('video asset'), findsNothing); + view.undo(); + await select('video'); + tabs(['picture', 'mask', 'audio', 'speed', 'animation']); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + await tester.runAsync(session.flush); + }, + ); + + for (final locale in const [Locale('zh')]) { + testWidgets('renders and edits the timeline in $locale', (tester) async { + await tester.pumpWidget( + ProviderScope( + overrides: [ + editorTimelineProvider( + projectId, + 'project', + ).overrideWith((ref) async => session), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: locale, + + theme: EditorTheme.penLight, + home: Scaffold( + body: EditorTimelinePanel( + projectId: projectId, + timelineId: 'project', + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + expect(find.byType(TimelineRuler), findsOneWidget); + expect(find.byType(TimelineView), findsOneWidget); + final localized = AppLocalizations.of( + tester.element(find.byType(EditorTimelinePanel)), + )!; + expect( + Directionality.of(tester.element(find.byType(EditorTimelinePanel))), + TextDirection.ltr, + ); + expect( + Directionality.of(tester.element(find.byType(TimelineView))), + TextDirection.ltr, + ); + + expect( + tester.widget(find.byType(TimelineView)).controller, + same(session.view(SequenceId('two'))), + ); + final view = session.view(SequenceId('two')); + final beforeEmptyDelete = view.version.kernelVersion; + view.clearSelection(); + await tester.pump(); + expect(view.canDeleteSelection, isFalse); + final deleteButton = find.byKey( + const ValueKey('timeline-delete-selection'), + ); + expect(tester.widget(deleteButton).onPressed, isNotNull); + await tester.tap(deleteButton); + await tester.pump(); + expect(view.version.kernelVersion, same(beforeEmptyDelete)); + view.setSelection([ + view.version.kernelVersion.query().elementById(ElementId('clip'))!, + ]); + view.seekTo(5 * TimelineClock.ticksPerSecond); + await tester.pump(); + final toolbarButtons = find.descendant( + of: find.byKey(const Key('timeline-toolbar')), + matching: find.byType(IconButton), + ); + expect(toolbarButtons, findsNWidgets(6)); + final toolbarBounds = tester.getRect( + find.byKey(const Key('timeline-toolbar')), + ); + final panelBounds = tester.getRect(find.byType(EditorTimelinePanel)); + expect(toolbarBounds.left, panelBounds.left); + expect(toolbarBounds.right, panelBounds.right); + final buttonBounds = []; + for (final button in toolbarButtons.evaluate()) { + final bounds = tester.getRect( + find.byElementPredicate((e) => e == button), + ); + buttonBounds.add(bounds); + expect( + bounds.size, + const Size(AppControlSize.headerButton, AppControlSize.headerButton), + ); + expect((button.widget as IconButton).iconSize, AppIconSize.header); + } + expect(buttonBounds.first.left - panelBounds.left, AppSpacing.gap); + for (var i = 1; i < buttonBounds.length; i++) { + expect( + buttonBounds[i].left - buttonBounds[i - 1].right, + AppSpacing.tiny, + ); + } + for (final (tooltip, sourceStart) in [ + (localized.trimLeftTooltip, 5 * TimelineClock.ticksPerSecond), + (localized.trimRightTooltip, 0), + ]) { + final before = view.version.kernelVersion; + await tester.tap(find.byTooltip(tooltip)); + await tester.pump(); + final q = view.version.kernelVersion.query(); + final clip = q.element(q.elementById(ElementId('clip'))!); + expect(clip.duration, 5 * TimelineClock.ticksPerSecond); + expect(clip.sourceStart, sourceStart); + await tester.tap(find.byTooltip(localized.undo)); + await tester.pump(); + expect(view.version.kernelVersion, same(before)); + expect(view.canUndo, isFalse); + } + view.seekTo(0); + await tester.pump(); + expect( + tester + .widget( + find.byKey(const ValueKey('timeline-trim-left')), + ) + .onPressed, + isNull, + ); + expect( + tester + .widget( + find.byKey(const ValueKey('timeline-trim-right')), + ) + .onPressed, + isNull, + ); + view.seekTo(5 * TimelineClock.ticksPerSecond); + await tester.pump(); + await tester.tap(find.byTooltip(localized.splitAtPlayhead)); + await tester.pump(); + expect(view.canUndo, isTrue); + await tester.tap(find.byTooltip(localized.undo)); + await tester.pump(); + expect(view.canRedo, isTrue); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox()); + await tester.runAsync(() => session.flush()); + }); + } +} + +class _LivePropertyPreview extends PreviewController { + @override + bool busy = true; + _LivePropertyPreview(EditorTimelineSession timeline) + : super( + timeline: timeline, + runtime: CutdexRuntime(), + activeSequence: () => timeline.activeSequenceId, + viewForSequence: timeline.view, + ); + + @override + PreviewVisual? visualForProperties(ElementId element) => + visuals.where((visual) => visual.elementId == element).firstOrNull; + + @override + List get visuals { + final query = viewForSequence(activeSequence()!).version.kernelVersion + .query(); + final id = ElementId('clip'); + return transforms.project([ + PreviewVisual( + layerId: 'video', + elementId: id, + lane: 0, + transform: ClipTransform.fromRecord( + query.element(query.elementById(id)!), + ), + geometry: const PreviewGeometry( + center: Offset(100, 100), + size: Size(200, 200), + ), + ), + ], Size(canvas.width, canvas.height)); + } + + @override + PreviewTransformSession get transforms => _transforms; + + late final _transforms = PreviewTransformSession( + canBegin: () => true, + select: (_) {}, + prepareNative: () async => true, + updateNative: (_, _, rendered) => rendered(), + commit: (id, value) { + final sequence = activeSequence()!; + final edit = timeline.previewParameters(sequence, id, value.parameters); + timeline.commitParameters( + sequence, + edit, + parameterTargets: ClipTransform.targets, + ); + }, + cancelNative: () {}, + failed: (error) => throw error, + changed: () {}, + ); +} + +class _ViewProjects extends _DropProjects { + _ViewProjects(super.session, super.projectId); + + @override + Future openTimelineSession( + String projectId, + String timelineId, + ) async => session; +} + +class _DropProjects extends Projects { + _DropProjects(this.session, this.projectId, {AssetDocument? mediaAsset}) + : asset = + mediaAsset ?? + AssetDocument( + id: 'asset', + name: 'image.png', + storage: AssetStorage.external, + location: 'file:///image.png', + metadata: const {'kind': 'image'}, + ); + final EditorTimelineSession session; + final String projectId; + final AssetDocument asset; + @visibleForTesting + Future? mediaReady; + + @override + Future withAssetMedia( + String? projectId, + AssetDocument asset, + Future Function(MediaReference) action, + ) async { + await mediaReady; + return action( + MediaReference( + id: asset.id, + uri: Uri.parse(asset.location), + isImage: asset.metadata['kind'] == 'image', + ), + ); + } + + @override + Future build() async => ProjectState( + activeProject: RecentProject( + id: projectId, + name: 'Project', + path: '/Project.cutdex', + ), + timeline: session.document, + assets: [asset], + ); +} + +class _ImportingDropProjects extends _DropProjects { + _ImportingDropProjects(super.session, super.projectId); + final _importStarted = Completer(); + final _importResult = Completer(); + + @override + Future importExternalMedia( + String projectId, + List files, { + bool Function()? isCancelled, + }) { + _importStarted.complete(); + return _importResult.future; + } +} diff --git a/test/timeline_speed_layout_test.dart b/test/timeline_speed_layout_test.dart new file mode 100644 index 0000000..6acc1bc --- /dev/null +++ b/test/timeline_speed_layout_test.dart @@ -0,0 +1,63 @@ +import 'dart:ui'; + +import 'package:cutdex/features/timeline/timeline_speed_layout.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/timeline_ui.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + test( + 'zoomed segment hit targets remain inside their painted clip header', + () { + final segments = [ + for (var i = 0; i < 3; i++) + ClipSpeedSegment( + index: i, + projectStart: i, + projectDuration: 1, + sourceDuration: 2, + ), + ]; + for (final pixelsPerTick in [.1, .5, 2.0, 20.0]) { + final clip = TimelineClipLayout( + bounds: Rect.fromLTWH(120, 48, 3 * pixelsPerTick, 92), + headerHeight: 16, + ); + final layout = TimelineSpeedLayout( + clip: clip, + segments: segments, + pixelsPerTick: pixelsPerTick, + ); + expect(layout.bounds.height, 14); + for (final segment in layout.segments) { + expect(segment.cell.right, lessThanOrEqualTo(layout.bounds.right)); + expect(segment.cell.left, greaterThanOrEqualTo(layout.bounds.left)); + for (final region in [ + segment.bar, + segment.handle, + segment.handleHit, + ]) { + expect(region.left, greaterThanOrEqualTo(segment.cell.left)); + expect(region.right, lessThanOrEqualTo(segment.cell.right)); + expect(region.top, greaterThanOrEqualTo(layout.bounds.top)); + expect(region.bottom, lessThanOrEqualTo(layout.bounds.bottom)); + } + expect(segment.handleHit.top, segment.bar.top); + expect(segment.handleHit.bottom, segment.bar.bottom); + expect( + segment.handleHit.left, + greaterThanOrEqualTo(segment.bar.left), + ); + expect(segment.handleHit.right, lessThanOrEqualTo(segment.bar.right)); + expect( + segment.handleHit.width, + lessThanOrEqualTo(TimelineSpeedSegmentLayout.handleHitWidth), + ); + if (!segment.handle.isEmpty) { + expect(segment.handleHit.contains(segment.handle.center), isTrue); + } + } + } + }, + ); +} diff --git a/test/timeline_thumbnails_test.dart b/test/timeline_thumbnails_test.dart new file mode 100644 index 0000000..5774bae --- /dev/null +++ b/test/timeline_thumbnails_test.dart @@ -0,0 +1,774 @@ +import 'dart:async'; +import 'dart:ui' as ui; + +import 'package:cutdex/integrations/runtime/timeline_thumbnails.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline/engine.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + const channel = MethodChannel('cutdex_runtime'); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + final element = ElementRecord( + id: ElementId('clip'), + structure: ElementStructure.content, + sourceStart: 0, + sourceDuration: TimelineClock.ticksPerSecond * 10, + duration: TimelineClock.ticksPerSecond * 10, + enabled: true, + payloadRef: PayloadRef('payload'), + ); + RuntimeTimelineThumbnails create({ + int limit = 256, + int concurrency = 2, + int batchSize = 4, + }) => RuntimeTimelineThumbnails( + resolveMedia: (_) => + MediaReference(id: 'source', uri: Uri.file('/source.mov')), + maximumEntries: limit, + maximumConcurrent: concurrency, + maximumBatchSize: batchSize, + ); + ui.Image? demand( + RuntimeTimelineThumbnails frames, + int tick, { + int sourceSpanTicks = 1, + ui.Size logicalSize = const ui.Size(80, 40), + double devicePixelRatio = 2, + }) => frames.imageFor( + element, + tick, + sourceSpanTicks: sourceSpanTicks, + logicalSize: logicalSize, + devicePixelRatio: devicePixelRatio, + ); + tearDown(() => messenger.setMockMethodCallHandler(channel, null)); + + test('sampling uses finite media bounds or an uncapped source grid', () { + int sample(int tick, int? end) => RuntimeTimelineThumbnails.sampledTickFor( + sourceTick: tick, + sourceSpanTicks: 8, + minimumTick: 3, + maximumTickExclusive: end, + ); + expect(sample(0, 22), 3); + expect(sample(35, 22), 16); + expect(sample(0, null), 3); + expect(sample(21, null), 24); + }); + + testWidgets('a freeze frame with zero source span still requests its image', ( + tester, + ) async { + var calls = 0; + messenger.setMockMethodCallHandler(channel, (_) async { + calls++; + throw PlatformException(code: 'unavailable'); + }); + final frames = create(); + addTearDown(frames.dispose); + final tick = 10 * TimelineClock.ticksPerSecond; + final frozen = element.copyWith( + sourceStart: tick, + sourceDuration: 0, + mediaStart: 0, + mediaDuration: 30 * TimelineClock.ticksPerSecond, + retime: RetimeMapRecord([ + RetimeSegmentRecord( + projectDuration: element.duration, + sourceStart: tick, + sourceDelta: 0, + ), + ]), + ); + frames.beginFrame(); + frames.imageFor( + frozen, + tick, + sourceSpanTicks: 1, + logicalSize: const Size(80, 40), + devicePixelRatio: 2, + ); + frames.endFrame(); + await tester.pump(); + expect(calls, 1); + }); + + for (final leading in [true, false]) { + testWidgets('trimmed media keeps the same cached cell: leading $leading', ( + tester, + ) async { + var calls = 0; + messenger.setMockMethodCallHandler(channel, (_) async { + calls++; + throw PlatformException(code: 'unavailable'); + }); + final frames = create(); + addTearDown(frames.dispose); + final clip = element.copyWith( + sourceStart: 5 * TimelineClock.ticksPerSecond, + sourceDuration: 10 * TimelineClock.ticksPerSecond, + mediaStart: 0, + mediaDuration: 30 * TimelineClock.ticksPerSecond, + ); + final tick = ((leading ? 5.25 : 14.75) * TimelineClock.ticksPerSecond) + .round(); + void paint(ElementRecord record) { + frames.beginFrame(); + frames.imageFor( + record, + tick, + sourceSpanTicks: TimelineClock.ticksPerSecond, + logicalSize: const Size(80, 40), + devicePixelRatio: 2, + ); + frames.endFrame(); + } + + paint(clip); + await tester.pump(); + await tester.pump(); + expect(calls, 1); + for (final removed in [0.5, 1.0, 1.5]) { + final delta = (removed * TimelineClock.ticksPerSecond).round(); + paint( + clip.copyWith( + sourceStart: clip.sourceStart + (leading ? delta : 0), + sourceDuration: clip.sourceDuration - delta, + duration: clip.duration - delta, + ), + ); + await tester.pump(); + await tester.pump(); + expect( + calls, + 1, + reason: 'Cropping a cell must not change its cache key', + ); + } + }); + } + + test( + 'thumbnail requests and cached failures are isolated by selected track', + () async { + var index = 0; + final indices = []; + messenger.setMockMethodCallHandler(channel, (call) async { + if (call.method == 'capabilities') { + return { + 'contractVersion': 1, + 'features': {'media.trackSelection': 'available'}, + }; + } + indices.add( + ((call.arguments as Map)['trackSelection'] as Map)['index'] as int, + ); + throw PlatformException(code: 'unavailable'); + }); + final frames = RuntimeTimelineThumbnails( + resolveMedia: (_) => + MediaReference(id: 'shared', uri: Uri.file('/shared.mov')), + resolveTrackSelection: (_) => TrackSelection.index(index), + ); + addTearDown(frames.dispose); + for (index = 0; index < 2; index++) { + frames.beginFrame(); + demand(frames, 0); + frames.endFrame(); + await Future.delayed(Duration.zero); + await Future.delayed(Duration.zero); + } + expect(indices, [0, 1]); + }, + ); + + testWidgets('still image tiles share one source-time request', ( + tester, + ) async { + final calls = >[]; + final media = []; + messenger.setMockMethodCallHandler(channel, (call) async { + media.add((call.arguments as Map)['media']); + calls.add((call.arguments as Map)['times'] as List); + throw PlatformException(code: 'unavailable'); + }); + final frames = RuntimeTimelineThumbnails( + resolveMedia: (_) => MediaReference( + id: 'still', + uri: Uri.file('/still.heic'), + isImage: true, + ), + ); + frames.beginFrame(); + for (final tick in [0, 100, TimelineClock.ticksPerSecond * 9]) { + demand(frames, tick); + } + frames.endFrame(); + await tester.pump(); + expect(calls, [ + [MediaTime(0, TimelineClock.ticksPerSecond).toMap()], + ]); + expect(media.single, containsPair('isImage', true)); + frames.dispose(); + }); + + test('painted device pixels are quantized to stable resolution tiers', () { + expect( + RuntimeTimelineThumbnails.maximumEdgeFor( + logicalSize: const ui.Size(82, 46), + devicePixelRatio: 2, + ), + 192, + ); + expect( + RuntimeTimelineThumbnails.maximumEdgeFor( + logicalSize: const ui.Size(26, 46), + devicePixelRatio: 2, + ), + 128, + ); + expect( + () => RuntimeTimelineThumbnails.maximumEdgeFor( + logicalSize: ui.Size.zero, + devicePixelRatio: 2, + ), + throwsArgumentError, + ); + }); + + test('nearby zoom centers snap to a stable source-time pyramid', () { + final frames = create(); + addTearDown(frames.dispose); + expect(frames.maximumBatchSize, 4); + final span = TimelineClock.ticksPerSecond * 3 ~/ 5; + final interval = RuntimeTimelineThumbnails.samplingIntervalFor(span); + expect(interval, lessThanOrEqualTo(span)); + expect(interval * 2, greaterThan(span)); + final first = RuntimeTimelineThumbnails.sampledTickFor( + sourceTick: TimelineClock.ticksPerSecond * 3, + sourceSpanTicks: span, + minimumTick: 0, + maximumTickExclusive: TimelineClock.ticksPerSecond * 10, + ); + final nearby = RuntimeTimelineThumbnails.sampledTickFor( + sourceTick: TimelineClock.ticksPerSecond * 3 + interval ~/ 16, + sourceSpanTicks: span - 1, + minimumTick: 0, + maximumTickExclusive: TimelineClock.ticksPerSecond * 10, + ); + expect(nearby, first); + }); + + testWidgets( + 'visible requests are bounded, old pending work is discarded, and late disposal is safe', + (tester) async { + final calls = >[]; + final waiting = >[]; + messenger.setMockMethodCallHandler(channel, (call) { + expectSync(call.method, 'thumbnails'); + final args = call.arguments as Map; + calls.add([ + for (final time in args['times'] as List) + int.parse((time as Map)['numerator'] as String), + ]); + expectSync(args['maximumWidth'], 192); + expectSync(args['maximumHeight'], 192); + expectSync(args['tolerance'], MediaTime(1, 4).toMap()); + final result = Completer(); + waiting.add(result); + return result.future; + }); + final frames = create(limit: 3, concurrency: 1); + frames.beginFrame(); + for (var i = 0; i < 6; i++) { + demand(frames, i); + } + frames.endFrame(); + await tester.pump(); + expect(calls, [ + [0], + ]); + frames.beginFrame(); + demand(frames, 50); + frames.endFrame(); + waiting.first.completeError(PlatformException(code: 'unavailable')); + await tester.pump(); + expect(calls, [ + [0], + [50], + ]); + frames.dispose(); + waiting.last.completeError(PlatformException(code: 'unavailable')); + await tester.pump(); + expect(calls, [ + [0], + [50], + ]); + expect(tester.takeException(), isNull); + }, + ); + + testWidgets('large visible ranges load in small progressive batches', ( + tester, + ) async { + final calls = >[]; + final waiting = >[]; + messenger.setMockMethodCallHandler(channel, (call) { + final args = call.arguments as Map; + calls.add([ + for (final time in args['times'] as List) + int.parse((time as Map)['numerator'] as String), + ]); + final result = Completer(); + waiting.add(result); + return result.future; + }); + final frames = create(limit: 32, concurrency: 1); + addTearDown(frames.dispose); + frames.beginFrame(); + for (var tick = 0; tick < 17; tick++) { + demand(frames, tick); + } + frames.endFrame(); + await tester.pump(); + expect(calls.map((batch) => batch.length), [1]); + + waiting[0].completeError(PlatformException(code: 'unavailable')); + await tester.pump(); + expect(calls.map((batch) => batch.length), [1, 4]); + + waiting[1].completeError(PlatformException(code: 'unavailable')); + await tester.pump(); + expect(calls.map((batch) => batch.length), [1, 4, 4]); + + waiting[2].completeError(PlatformException(code: 'unavailable')); + await tester.pump(); + expect(calls.map((batch) => batch.length), [1, 4, 4, 4]); + + waiting[3].completeError(PlatformException(code: 'unavailable')); + await tester.pump(); + expect(calls.map((batch) => batch.length), [1, 4, 4, 4, 4]); + + waiting[4].completeError(PlatformException(code: 'unavailable')); + await tester.pump(); + expect(tester.takeException(), isNull); + }); + + testWidgets('first visible tile is requested ahead of its batch', ( + tester, + ) async { + final calls = >[]; + final pending = >[]; + messenger.setMockMethodCallHandler(channel, (call) { + final times = (call.arguments as Map)['times'] as List; + calls.add([ + for (final time in times) + int.parse((time as Map)['numerator'] as String), + ]); + final completion = Completer(); + pending.add(completion); + return completion.future; + }); + final frames = create(concurrency: 2); + addTearDown(frames.dispose); + frames.beginFrame(); + for (var tick = 0; tick < 6; tick++) { + demand(frames, tick); + } + frames.endFrame(); + await tester.pump(); + expect(calls, [ + [0], + [1, 2, 3, 4], + ]); + for (final completion in List.of(pending)) { + completion.completeError(PlatformException(code: 'unavailable')); + } + await tester.pump(); + expect(calls, [ + [0], + [1, 2, 3, 4], + [5], + ]); + pending.last.completeError(PlatformException(code: 'unavailable')); + await tester.pump(); + expect(tester.takeException(), isNull); + }); + + testWidgets( + 'decoded images repaint once, retain aspect ratio and are reused until eviction', + (tester) async { + final recorder = ui.PictureRecorder(); + Canvas(recorder).drawColor(Colors.green, BlendMode.src); + final picture = recorder.endRecording(); + final bytes = await tester.runAsync(() async { + final image = await picture.toImage(9, 16); + try { + return (await image.toByteData(format: ui.ImageByteFormat.png))! + .buffer + .asUint8List(); + } finally { + image.dispose(); + picture.dispose(); + } + }); + var calls = 0; + messenger.setMockMethodCallHandler(channel, (call) async { + calls++; + final times = (call.arguments as Map)['times'] as List; + return [ + for (final time in times) + { + 'requestedTime': time, + 'actualTime': time, + 'width': 9, + 'height': 16, + 'format': 'jpeg', + 'data': bytes, + }, + ]; + }); + final frames = create(limit: 1); + var repaints = 0; + Completer? ready; + frames.addListener(() { + repaints++; + ready?.complete(); + }); + addTearDown(frames.dispose); + await tester.runAsync(() async { + ready = Completer(); + frames.beginFrame(); + demand(frames, 123); + frames.endFrame(); + await ready!.future.timeout(const Duration(seconds: 5)); + }); + frames.beginFrame(); + final first = demand(frames, 123)!; + expect(first.width, 9); + expect(first.height, 16); + expect(frames.aspectRatioFor(element), 9 / 16); + frames.endFrame(); + await tester.pump(); + expect(calls, 1); + expect(repaints, 1); + await tester.runAsync(() async { + ready = Completer(); + frames.beginFrame(); + demand(frames, 456); + frames.endFrame(); + await ready!.future.timeout(const Duration(seconds: 5)); + }); + expect(calls, 2); + expect(first.debugDisposed, isTrue); + }, + ); + + testWidgets('imported media keeps preview frames and aspect ratio', ( + tester, + ) async { + final recorder = ui.PictureRecorder(); + Canvas(recorder).drawColor(Colors.blue, BlendMode.src); + final picture = recorder.endRecording(); + final bytes = await tester.runAsync(() async { + final image = await picture.toImage(16, 9); + try { + return (await image.toByteData(format: ui.ImageByteFormat.png))!.buffer + .asUint8List(); + } finally { + image.dispose(); + picture.dispose(); + } + }); + var calls = 0; + messenger.setMockMethodCallHandler(channel, (call) async { + calls++; + return [ + for (final time in (call.arguments as Map)['times'] as List) + { + 'requestedTime': time, + 'actualTime': time, + 'width': 16, + 'height': 9, + 'format': 'jpeg', + 'data': bytes, + }, + ]; + }); + var media = MediaReference(id: '/source.mov', uri: Uri.file('/source.mov')); + final frames = RuntimeTimelineThumbnails(resolveMedia: (_) => media); + addTearDown(frames.dispose); + late Completer ready; + frames.addListener(() { + if (!ready.isCompleted) ready.complete(); + }); + await tester.runAsync(() async { + ready = Completer(); + frames.beginFrame(); + demand(frames, 123); + frames.endFrame(); + await ready.future.timeout(const Duration(seconds: 5)); + }); + frames.beginFrame(); + final preview = demand(frames, 123); + expect(preview, isNotNull); + frames.endFrame(); + media = MediaReference(id: 'imported-asset', uri: media.uri); + frames.beginFrame(); + expect(demand(frames, 123), same(preview)); + expect(frames.aspectRatioFor(element), 16 / 9); + frames.endFrame(); + await tester.pump(); + expect(calls, 1); + // Reusing an asset ID for a different file must still invalidate the cache. + media = MediaReference(id: media.id, uri: Uri.file('/other.mov')); + frames.beginFrame(); + expect(demand(frames, 123), isNull); + expect(frames.aspectRatioFor(element), isNull); + }); + + testWidgets('a lower tier stays visible while a higher DPR tier loads', ( + tester, + ) async { + final recorder = ui.PictureRecorder(); + Canvas(recorder).drawColor(Colors.blue, BlendMode.src); + final picture = recorder.endRecording(); + final bytes = await tester.runAsync(() async { + final image = await picture.toImage(16, 9); + try { + return (await image.toByteData(format: ui.ImageByteFormat.png))!.buffer + .asUint8List(); + } finally { + image.dispose(); + picture.dispose(); + } + }); + final edges = []; + messenger.setMockMethodCallHandler(channel, (call) async { + final args = call.arguments as Map; + edges.add(args['maximumWidth'] as int); + return [ + for (final time in args['times'] as List) + { + 'requestedTime': time, + 'actualTime': time, + 'width': 16, + 'height': 9, + 'format': 'jpeg', + 'data': bytes, + }, + ]; + }); + final frames = create(limit: 2); + addTearDown(frames.dispose); + Completer? ready; + frames.addListener(() => ready?.complete()); + await tester.runAsync(() async { + ready = Completer(); + frames.beginFrame(); + demand(frames, 123, logicalSize: const ui.Size(20, 20)); + frames.endFrame(); + await ready!.future.timeout(const Duration(seconds: 5)); + }); + frames.beginFrame(); + final low = demand(frames, 123, logicalSize: const ui.Size(80, 40)); + frames.endFrame(); + expect( + low, + isNotNull, + reason: 'The loaded lower tier should be a fallback', + ); + await tester.runAsync(() async { + ready = Completer(); + await ready!.future.timeout(const Duration(seconds: 5)); + }); + frames.beginFrame(); + final high = demand(frames, 123, logicalSize: const ui.Size(80, 40)); + frames.endFrame(); + expect(edges, [64, 192]); + expect(high, isNotNull); + expect(identical(high, low), isFalse); + }); + + testWidgets( + 'a nearby cached sample stays visible across pyramid level changes', + (tester) async { + final recorder = ui.PictureRecorder(); + Canvas(recorder).drawColor(Colors.purple, BlendMode.src); + final picture = recorder.endRecording(); + final bytes = await tester.runAsync(() async { + final image = await picture.toImage(16, 9); + try { + return (await image.toByteData(format: ui.ImageByteFormat.png))! + .buffer + .asUint8List(); + } finally { + image.dispose(); + picture.dispose(); + } + }); + final requestedTicks = []; + messenger.setMockMethodCallHandler(channel, (call) async { + final args = call.arguments as Map; + expect(args['tolerance'], MediaTime(1, 4).toMap()); + final times = args['times'] as List; + requestedTicks.addAll([ + for (final time in times) + int.parse((time as Map)['numerator'] as String), + ]); + return [ + for (final time in times) + { + 'requestedTime': time, + 'actualTime': time, + 'width': 16, + 'height': 9, + 'format': 'jpeg', + 'data': bytes, + }, + ]; + }); + final frames = create(concurrency: 1); + addTearDown(frames.dispose); + Completer? ready; + frames.addListener(() { + if (ready case final pending? when !pending.isCompleted) { + pending.complete(); + } + }); + final coarseSpan = TimelineClock.ticksPerSecond; + final coarseTick = RuntimeTimelineThumbnails.sampledTickFor( + sourceTick: TimelineClock.ticksPerSecond * 3, + sourceSpanTicks: coarseSpan, + minimumTick: 0, + maximumTickExclusive: TimelineClock.ticksPerSecond * 10, + ); + await tester.runAsync(() async { + ready = Completer(); + frames.beginFrame(); + demand(frames, coarseTick, sourceSpanTicks: coarseSpan); + frames.endFrame(); + await ready!.future.timeout(const Duration(seconds: 5)); + }); + + final fineSpan = coarseSpan ~/ 2; + final fineTick = + coarseTick + RuntimeTimelineThumbnails.samplingIntervalFor(fineSpan); + ui.Image? fallback; + await tester.runAsync(() async { + ready = Completer(); + frames.beginFrame(); + fallback = demand(frames, fineTick, sourceSpanTicks: fineSpan); + frames.endFrame(); + await ready!.future.timeout(const Duration(seconds: 5)); + }); + expect( + fallback, + isNotNull, + reason: 'A pyramid transition must not expose an empty tile', + ); + frames.beginFrame(); + final replacement = demand(frames, fineTick, sourceSpanTicks: fineSpan); + frames.endFrame(); + expect(requestedTicks, [coarseTick, fineTick]); + expect(replacement, isNotNull); + expect(identical(replacement, fallback), isFalse); + }, + ); + + testWidgets( + 'completed batches retain frames that just moved outside the viewport', + (tester) async { + final recorder = ui.PictureRecorder(); + Canvas(recorder).drawColor(Colors.orange, BlendMode.src); + final picture = recorder.endRecording(); + final bytes = await tester.runAsync(() async { + final image = await picture.toImage(16, 9); + try { + return (await image.toByteData(format: ui.ImageByteFormat.png))! + .buffer + .asUint8List(); + } finally { + image.dispose(); + picture.dispose(); + } + }); + var calls = 0; + late final RuntimeTimelineThumbnails frames; + messenger.setMockMethodCallHandler(channel, (call) async { + calls++; + final requestedTimes = (call.arguments as Map)['times'] as List; + + // Simulate a pan while this native request is in flight. + frames.beginFrame(); + demand(frames, 20); + frames.endFrame(); + return [ + for (final time in requestedTimes) + { + 'requestedTime': time, + 'actualTime': time, + 'width': 16, + 'height': 9, + 'format': 'jpeg', + 'data': bytes, + }, + ]; + }); + frames = create(limit: 4, concurrency: 1); + addTearDown(frames.dispose); + Completer? ready; + frames.addListener(() { + if (ready case final pending? when !pending.isCompleted) { + pending.complete(); + } + }); + + await tester.runAsync(() async { + ready = Completer(); + frames.beginFrame(); + demand(frames, 10); + demand(frames, 20); + frames.endFrame(); + await ready!.future.timeout(const Duration(seconds: 5)); + }); + expect(calls, 2); + + frames.beginFrame(); + expect( + demand(frames, 10), + isNotNull, + reason: 'A completed neighboring frame should remain in the LRU cache', + ); + frames.endFrame(); + await tester.pump(); + expect(calls, 2); + }, + ); + + testWidgets( + 'failed frames do not trigger repeated native requests on repaint', + (tester) async { + var calls = 0; + messenger.setMockMethodCallHandler(channel, (_) async { + calls++; + throw PlatformException(code: 'unsupported'); + }); + final frames = create(); + addTearDown(frames.dispose); + for (var i = 0; i < 3; i++) { + frames.beginFrame(); + demand(frames, 12); + frames.endFrame(); + await tester.pump(); + } + expect(calls, 1); + }, + ); +} diff --git a/test/timeline_waveforms_test.dart b/test/timeline_waveforms_test.dart new file mode 100644 index 0000000..be5abac --- /dev/null +++ b/test/timeline_waveforms_test.dart @@ -0,0 +1,393 @@ +import 'dart:async'; + +import 'package:cutdex/integrations/runtime/timeline_waveforms.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline/engine.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + const channel = MethodChannel('cutdex_runtime'); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + ElementRecord element(String id) => ElementRecord( + id: ElementId(id), + structure: ElementStructure.content, + duration: TimelineClock.ticksPerSecond, + sourceStart: 0, + sourceDuration: TimelineClock.ticksPerSecond, + enabled: true, + payloadRef: PayloadRef(id), + ); + Map response() => { + 'sampleRate': 4.0, + 'sourceStartSeconds': 0.0, + 'frameCount': 4, + 'trackId': 1, + 'channelCount': 1, + 'levels': [ + { + 'samplesPerBucket': 2, + 'channels': [ + [-0.5, 0.5, 0.25, -1.0, 1.0, 0.7], + ], + }, + ], + }; + Future flush() => Future.delayed(Duration.zero); + tearDown(() => messenger.setMockMethodCallHandler(channel, null)); + + test( + 'audio presence follows the binding before loading and after separation', + () { + var bound = true; + final source = RuntimeTimelineWaveforms( + resolveMedia: (ref) => bound && ref.value == 'video' + ? MediaReference(id: 'video', uri: Uri.file('/movie.mov')) + : null, + ); + expect(source.hasAudioFor(element('video')), isTrue); + expect(source.hasAudioFor(element('silent-video')), isFalse); + expect(source.hasAudioFor(element('image')), isFalse); + bound = false; + expect(source.hasAudioFor(element('video')), isFalse); + source.dispose(); + expect(source.hasAudioFor(element('video')), isFalse); + }, + ); + + test( + 'different selected tracks never share a waveform cache entry', + () async { + final indices = []; + messenger.setMockMethodCallHandler(channel, (call) async { + if (call.method == 'capabilities') { + return { + 'contractVersion': 1, + 'features': { + 'media.waveform': 'available', + 'media.trackSelection': 'available', + }, + }; + } + indices.add( + ((call.arguments as Map)['trackSelection'] as Map)['index'] as int, + ); + return response(); + }); + final source = RuntimeTimelineWaveforms( + resolveMedia: (_) => + MediaReference(id: 'shared', uri: Uri.file('/shared.mov')), + resolveTrackSelection: (ref) => + TrackSelection.index(ref.value == 'a' ? 0 : 1), + ); + addTearDown(source.dispose); + source.beginFrame(); + source.waveformFor(element('a')); + source.waveformFor(element('b')); + source.endFrame(); + await flush(); + await flush(); + expect(indices, unorderedEquals([0, 1])); + expect(source.waveformFor(element('a')), isNotNull); + expect(source.waveformFor(element('b')), isNotNull); + }, + ); + + test( + 'gain changes repaint shared envelopes without decoding again', + () async { + var loads = 0; + messenger.setMockMethodCallHandler(channel, (call) async { + if (call.method == 'capabilities') { + return { + 'contractVersion': 1, + 'features': {'media.waveform': 'available'}, + }; + } + loads++; + return response(); + }); + final gain = ValueNotifier(1.0); + final source = RuntimeTimelineWaveforms( + resolveMedia: (_) => + MediaReference(id: 'shared', uri: Uri.file('/shared.wav')), + resolveGain: (clip) => clip.id == ElementId('a') ? gain.value : 1, + gainChanges: gain, + ); + source.beginFrame(); + source.waveformFor(element('a')); + source.endFrame(); + await flush(); + final original = source.waveformFor(element('a'))!; + var repaints = 0; + source.addListener(() => repaints++); + gain.value = 2; + final amplified = source.waveformFor(element('a'))!; + expect(amplified.amplitudeScale, 2); + expect(amplified.levels, same(original.levels)); + expect(source.waveformFor(element('b'))!.amplitudeScale, 1); + gain.value = 0; + expect(source.waveformFor(element('a'))!.amplitudeScale, 0); + expect(repaints, 2); + expect(loads, 1); + source.dispose(); + gain.value = 1; + expect(repaints, 2); + gain.dispose(); + }, + ); + + test( + 'requests after paint, deduplicates and stops notifying after disposal', + () async { + final pending = Completer(); + var loads = 0; + messenger.setMockMethodCallHandler(channel, (call) async { + if (call.method == 'capabilities') { + return { + 'contractVersion': 1, + 'features': {'media.waveform': 'available'}, + }; + } + loads++; + return pending.future; + }); + final source = RuntimeTimelineWaveforms( + resolveMedia: (_) => + MediaReference(id: 'shared', uri: Uri.file('/shared.wav')), + ); + var notifications = 0; + source.addListener(() => notifications++); + source.beginFrame(); + expect(source.waveformFor(element('a')), isNull); + source.waveformFor(element('b')); + expect(loads, 0); + source.endFrame(); + await flush(); + expect(loads, 1); + source.beginFrame(); + source.waveformFor(element('a')); + source.endFrame(); + await flush(); + expect(loads, 1); + source.dispose(); + pending.complete(response()); + await flush(); + expect(notifications, 0); + }, + ); + + test( + 'limits concurrency, caches ready data and evicts old sources', + () async { + final pending = >[]; + messenger.setMockMethodCallHandler(channel, (call) async { + if (call.method == 'capabilities') { + return { + 'contractVersion': 1, + 'features': {'media.waveform': 'available'}, + }; + } + final completer = Completer(); + pending.add(completer); + return completer.future; + }); + final source = RuntimeTimelineWaveforms( + maximumEntries: 2, + maximumConcurrent: 1, + resolveMedia: (ref) => + MediaReference(id: ref.value, uri: Uri.file('/${ref.value}.wav')), + ); + addTearDown(source.dispose); + source.beginFrame(); + source.waveformFor(element('a')); + source.waveformFor(element('b')); + source.endFrame(); + await flush(); + expect(pending.length, 1); + pending[0].complete(response()); + await flush(); + expect(pending.length, 2); + pending[1].complete(response()); + await flush(); + expect(source.waveformFor(element('a')), isNotNull); + source.beginFrame(); + source.waveformFor(element('c')); + source.endFrame(); + await flush(); + pending[2].complete(response()); + await flush(); + expect(source.waveformFor(element('c')), isNotNull); + expect(source.waveformFor(element('b')), isNull); + }, + ); + + test('unsupported platforms do not issue waveform requests', () async { + final calls = []; + messenger.setMockMethodCallHandler(channel, (call) async { + calls.add(call.method); + return {'contractVersion': 1, 'features': {}}; + }); + final source = RuntimeTimelineWaveforms( + resolveMedia: (_) => MediaReference(id: 'a', uri: Uri.file('/a.wav')), + ); + addTearDown(source.dispose); + for (var i = 0; i < 3; i++) { + source.beginFrame(); + source.waveformFor(element('a')); + source.endFrame(); + await flush(); + } + expect(calls, ['capabilities']); + }); + + test( + 'all visible sources load even when they exceed the warm cache limit', + () async { + var loads = 0; + messenger.setMockMethodCallHandler(channel, (call) async { + if (call.method == 'capabilities') { + return { + 'contractVersion': 1, + 'features': {'media.waveform': 'available'}, + }; + } + loads++; + return response(); + }); + final source = RuntimeTimelineWaveforms( + maximumEntries: 2, + resolveMedia: (ref) => + MediaReference(id: ref.value, uri: Uri.file('/${ref.value}.wav')), + ); + addTearDown(source.dispose); + source.beginFrame(); + for (final id in ['a', 'b', 'c']) { + source.waveformFor(element(id)); + } + source.endFrame(); + for (var i = 0; i < 6; i++) { + await flush(); + } + expect(loads, 3); + for (final id in ['a', 'b', 'c']) { + expect(source.waveformFor(element(id)), isNotNull); + } + source.beginFrame(); + source.waveformFor(element('c')); + source.endFrame(); + await flush(); + expect(source.waveformFor(element('a')), isNull); + }, + ); + + for (final failingMethod in ['capabilities', 'waveform']) { + testWidgets( + 'transient $failingMethod failure recovers without reopening the timeline', + (tester) async { + var failures = 0; + messenger.setMockMethodCallHandler(channel, (call) async { + if (call.method == failingMethod && failures++ == 0) { + throw PlatformException( + code: 'unavailable', + details: {'retryable': true}, + ); + } + if (call.method == 'capabilities') { + return { + 'contractVersion': 1, + 'features': {'media.waveform': 'available'}, + }; + } + return response(); + }); + final source = RuntimeTimelineWaveforms( + resolveMedia: (_) => MediaReference(id: 'a', uri: Uri.file('/a.wav')), + ); + addTearDown(source.dispose); + source.beginFrame(); + source.waveformFor(element('a')); + source.endFrame(); + await tester.pump(); + expect(source.waveformFor(element('a')), isNull); + await tester.pump(const Duration(seconds: 1)); + await tester.pump(); + expect(source.waveformFor(element('a')), isNotNull); + }, + ); + } + + testWidgets('persistent transient errors have a finite retry budget', ( + tester, + ) async { + var loads = 0; + messenger.setMockMethodCallHandler(channel, (call) async { + if (call.method == 'capabilities') { + return { + 'contractVersion': 1, + 'features': {'media.waveform': 'available'}, + }; + } + loads++; + throw PlatformException( + code: 'unavailable', + details: {'retryable': true}, + ); + }); + final source = RuntimeTimelineWaveforms( + resolveMedia: (_) => MediaReference(id: 'a', uri: Uri.file('/a.wav')), + ); + addTearDown(source.dispose); + source.beginFrame(); + source.waveformFor(element('a')); + source.endFrame(); + await tester.pump(); + expect(loads, 1); + await tester.pump(const Duration(seconds: 1)); + expect(loads, 2); + await tester.pump(const Duration(seconds: 2)); + expect(loads, 3); + await tester.pump(const Duration(minutes: 1)); + expect(loads, 3); + }); + + testWidgets('leaving the viewport cancels pending retries', (tester) async { + var loads = 0; + messenger.setMockMethodCallHandler(channel, (call) async { + if (call.method == 'capabilities') { + return { + 'contractVersion': 1, + 'features': {'media.waveform': 'available'}, + }; + } + loads++; + throw PlatformException( + code: 'unavailable', + details: {'retryable': true}, + ); + }); + final source = RuntimeTimelineWaveforms( + resolveMedia: (_) => MediaReference(id: 'a', uri: Uri.file('/a.wav')), + ); + source.beginFrame(); + source.waveformFor(element('a')); + source.endFrame(); + await tester.pump(); + source.beginFrame(); + source.endFrame(); + await tester.pump(const Duration(seconds: 5)); + expect(loads, 1); + source.beginFrame(); + source.waveformFor(element('a')); + source.endFrame(); + await tester.pump(); + expect(loads, 2); + source.dispose(); + await tester.pump(const Duration(seconds: 5)); + expect(loads, 2); + }); +} diff --git a/test/transcription_tools_test.dart b/test/transcription_tools_test.dart new file mode 100644 index 0000000..55e3be6 --- /dev/null +++ b/test/transcription_tools_test.dart @@ -0,0 +1,3382 @@ +import 'package:cutdex/app/editor_theme.dart'; +import 'package:cutdex_agent/cutdex_agent.dart'; +import 'package:cutdex/integrations/agent/editor_agent_tools.dart'; +import 'package:crypto/crypto.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:cutdex/integrations/runtime/processing_resource_repository.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex_ui/theme.dart'; +import 'package:cutdex_ui/widgets.dart'; + +import 'dart:async'; +import 'dart:io'; +import 'dart:convert'; + +import 'package:cutdex/integrations/editor_command_host.dart'; +import 'package:cutdex/integrations/editor_tools.dart'; +import 'package:cutdex/integrations/runtime/processing_configuration.dart'; +import 'package:cutdex/workspace/timeline_session.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/runtime/contracts.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:cutdex_sdk/timeline/layout.dart'; +import 'package:cutdex_sdk/runtime/execution.dart'; +import 'package:cutdex_sdk/tools.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:cutdex/features/media/transcription_dialog.dart'; +import 'package:cutdex/features/media/background_tasks_dialog.dart'; +import 'package:cutdex/workspace/background_task_registry.dart'; +import 'package:cutdex/workspace/background_task_state.dart'; +import 'package:cutdex/features/media/subtitle_task_actions.dart'; +import 'package:cutdex/features/properties/caption_properties.dart'; + +class Media implements EditorMediaService { + Media(this.source); + final Uri source; + MediaTime audioStart = MediaTime(0, 1); + Completer? pending; + bool audio = true; + @override + Future prepare(String id) async { + if (id != 'source') throw StateError('missing media'); + if (pending != null) return pending!.future; + return PreparedEditorMedia( + asset: EditorMediaAsset(id: id, name: 'Speech'), + uri: source, + duration: RationalTime.seconds(5), + kind: EditorMediaKind.audio, + hasAudio: audio, + audioTracks: [ + MediaTrackTiming(start: audioStart, duration: MediaTime(5, 1)), + ], + ); + } + + @override + Future> query() async => [ + EditorMediaAsset(id: 'source', name: 'Speech'), + ]; + @override + Future importFile( + String path, { + bool Function()? isCancelled, + }) => throw UnimplementedError(); +} + +class Backend implements AudioTranscriptionBackend { + int calls = 0; + AudioTranscriptionRequest? lastRequest; + final gate = Completer(); + final started = Completer(); + bool fail = false; + bool mismatch = false; + bool emitAfterCancellation = false; + bool publishAfterCancellation = false; + @override + Future transcribe( + AudioTranscriptionRequest request, { + required void Function(TranscriptionProgress) onProgress, + required void Function(TranscriptionCue) onCue, + required ProcessingTaskSignal Function() taskSignal, + }) async { + calls++; + lastRequest = request; + if (!started.isCompleted) started.complete(); + onProgress(const TranscriptionProgress('ASRInference', 0, 1)); + onCue(const TranscriptionCue(200, 1200, '测试字幕')); + while (!gate.isCompleted && taskSignal() == ProcessingTaskSignal.none) { + await Future.delayed(const Duration(milliseconds: 5)); + } + if (taskSignal() != ProcessingTaskSignal.none) { + if (emitAfterCancellation) { + onCue(const TranscriptionCue(1400, 1800, '迟到字幕')); + } + if (!publishAfterCancellation) { + throw ProcessingException( + taskSignal() == ProcessingTaskSignal.cancel + ? 'cancelled' + : 'interrupted', + 'Stopped', + ); + } + } + if (fail) throw const ProcessingException('processingFailed', 'Failed'); + final document = SubtitleDocument( + cues: [ + SubtitleCue(200, 1200, mismatch ? '不一致' : '测试字幕'), + if (publishAfterCancellation) const SubtitleCue(1400, 1800, '迟到字幕'), + ], + ); + final subtitles = File.fromUri( + request.destination.resolve('subtitles.json'), + ); + await subtitles.parent.create(recursive: true); + await subtitles.writeAsString(jsonEncode(document.toJson())); + await File.fromUri(request.destination.resolve('transcript.json')) + .writeAsString( + jsonEncode({ + 'schemaVersion': 1, + 'sourceStartMs': request.sourceStartMs, + 'sourcePath': request.source.toFilePath(), + 'audioStream': request.audioStream, + 'durationMs': 5000, + 'detectedLanguages': ['zh'], + 'cues': document.cues.map((c) => c.toJson()).toList(), + }), + ); + for (final name in ['subtitles.srt', 'subtitles.vtt']) { + final file = File.fromUri(request.destination.resolve(name)); + if (!await file.exists()) await file.writeAsString('测试字幕'); + } + return AudioTranscriptionResult( + directory: request.destination, + durationMs: 5000, + document: document, + cues: [ + TranscriptionCue(200, 1200, mismatch ? '不一致' : '测试字幕'), + if (publishAfterCancellation) + const TranscriptionCue(1400, 1800, '迟到字幕'), + ], + ); + } +} + +class TranslationBackend implements SubtitleTranslationBackend { + int calls = 0; + SubtitleTranslationRequest? lastRequest; + + @override + Future translateSubtitles( + SubtitleTranslationRequest request, { + required void Function(ProcessingProgress) onProgress, + required ProcessingTaskSignal Function() taskSignal, + }) async { + final sourceDocument = await SubtitleDocument.read(request.source); + calls++; + lastRequest = request; + onProgress(const ProcessingProgress('translation', 1, 1)); + final directory = Directory.fromUri(request.destination); + await directory.create(recursive: true); + final translated = SubtitleDocument( + language: request.targetLanguage, + cues: const [SubtitleCue(200, 1200, '你好')], + ); + await File('${directory.path}/subtitles.json') + .writeAsString(jsonEncode(translated.toJson())); + await File('${directory.path}/translation.json').writeAsString( + jsonEncode({ + 'schemaVersion': 1, + 'provider': 'm2m100418m', + 'sourceLanguage': request.sourceLanguage, + 'targetLanguage': request.targetLanguage, + 'cues': [ + { + 'startMs': 200, + 'endMs': 1200, + 'sourceText': sourceDocument.cues.single.text, + 'text': '你好', + }, + ], + }), + ); + for (final name in ['subtitles.srt', 'subtitles.vtt']) { + await File('${directory.path}/$name').writeAsString('你好'); + } + return SubtitleTranslationResult( + directory: request.destination, + document: SubtitleDocument( + language: request.targetLanguage, + cues: const [SubtitleCue(200, 1200, '你好')], + ), + sourceLanguage: request.sourceLanguage, + targetLanguage: request.targetLanguage, + cues: const [ + TranslatedSubtitleCue( + startMs: 200, + endMs: 1200, + sourceText: 'こんにちは', + text: '你好', + ), + ], + ); + } +} + +class CaptionBackend implements CaptionFileBackend { + CaptionFileDocument document = CaptionFileDocument( + format: CaptionFileFormat.srt, + languageTag: 'en-US', + cues: [ + CaptionFileCue( + start: MediaTime(1, 2), + duration: MediaTime(1, 1), + text: 'Imported caption', + ), + ], + ); + CaptionFileFormat? writtenFormat; + String? writtenLanguage; + MediaTime? writtenFrameDuration; + bool? writtenAllowChanges; + List? writtenCues; + bool failRead = false; + + @override + Future readCaptionFile( + Uri source, + CaptionFileFormat format, + ) async { + if (failRead) throw const FormatException('invalid caption fixture'); + return document; + } + + @override + Future writeCaptionFile({ + required Uri destination, + required CaptionFileFormat format, + required List cues, + String languageTag = 'und', + MediaTime? frameDuration, + bool dropFrame = false, + bool allowChanges = false, + MediaTime? mediaDuration, + CaptionTimeRounding rounding = CaptionTimeRounding.exact, + }) async { + writtenFormat = format; + writtenLanguage = languageTag; + writtenFrameDuration = frameDuration; + writtenAllowChanges = allowChanges; + writtenCues = cues; + return CaptionFileWriteResult( + destination: destination, + cues: cues, + changes: const [], + ); + } +} + +Future settle(EditorTimelineSession session) async { + for ( + var i = 0; + i < 2000 && session.transcriptions!.tasks.any((task) => !task.terminal); + i++ + ) { + await Future.delayed(const Duration(milliseconds: 10)); + } + expect(session.transcriptions!.tasks.every((task) => task.terminal), true); +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + final sequence = SequenceId('main'); + late Directory root; + late ProjectFile project; + late EditorTimelineSession session; + late Media media; + late Backend backend; + late TranslationBackend translationBackend; + late CaptionBackend captionBackend; + + setUp(() async { + root = await Directory.systemTemp.createTemp('cutdex-transcription-'); + project = await ProjectFile.create( + Directory('${root.path}/test.cutdex'), + name: 'Test', + ); + final document = TimelineDocument( + id: 'p', + name: 'Speech', + sequences: [ + TimelineDto( + id: sequence, + format: TimelineFormat.fps30, + primaryStorylineId: StorylineId('primary'), + storylines: [ + StorylineDto(id: StorylineId('primary'), elementIds: []), + ], + elements: [], + ), + ], + ); + await project.saveTimeline(document); + media = Media(Uri.file('${root.path}/speech.wav')); + backend = Backend(); + translationBackend = TranslationBackend(); + captionBackend = CaptionBackend(); + session = EditorTimelineSession( + document: await project.loadTimeline('p'), + persistence: await project.openTimelineSaveSession('p'), + media: media, + transcriptionBackend: backend, + transcriptionModel: Uri.directory('${root.path}/model'), + translationBackend: translationBackend, + translationModel: Uri.directory('${root.path}/m2m100'), + captionFiles: captionBackend, + ); + }); + tearDown(() async { + await session.close(); + await project.close(); + await root.delete(recursive: true); + }); + + Future invoke( + String name, + String id, + Map args, + ) => editorToolsFor(session, sequence).invoke( + name: name, + arguments: args, + context: CommandContext(operationId: id), + ); + Map args() => { + 'mediaId': 'source', + 'destination': '${root.path}/captions', + }; + + Future reopenSession() async { + await session.close(); + await project.close(); + project = await ProjectFile.open(Directory('${root.path}/test.cutdex')); + session = EditorTimelineSession( + document: await project.loadTimeline('p'), + persistence: await project.openTimelineSaveSession('p'), + media: media, + transcriptionBackend: backend, + transcriptionModel: Uri.directory('${root.path}/model'), + translationBackend: translationBackend, + translationModel: Uri.directory('${root.path}/m2m100'), + captionFiles: captionBackend, + ); + await session.restoreProcessingTasks(); + } + + test('published recognition survives missing terminal checkpoint and repeated reopen', () async { + backend.gate.complete(); + final result = await invoke('media.transcribe', 'durable-asr', args()); + await settle(session); + final records = await session.persistence.readProcessingTasks(); + final record = records.single; + await session.persistence.writeProcessingTask(record['id'] as String, { + ...record, + 'status': 'running', + }); + for (var i = 0; i < 2; i++) { + await reopenSession(); + final task = session.transcriptions!.task( + result.data['taskId'] as String, + ); + expect(task.status, TranscriptionStatus.succeeded); + expect(task.result!.cues.single.text, '测试字幕'); + await invoke('media.transcribe', 'same-request-$i', args()); + expect(backend.calls, 1); + } + }); + + test('published subtitles remain usable when the model is not installed after restart', () async { + backend.gate.complete(); + final first = await invoke('media.transcribe', 'model-removed', args()); + await settle(session); + await session.close(); + session = EditorTimelineSession( + document: await project.loadTimeline('p'), + persistence: await project.openTimelineSaveSession('p'), + media: media, + ); + await session.restoreProcessingTasks(); + expect(session.transcriptions!.recognitionAvailable, false); + expect( + session.transcriptions!.task(first.data['taskId'] as String).status, + TranscriptionStatus.succeeded, + ); + final status = await invoke('transcription.query', 'recovered-query', { + 'taskId': first.data['taskId'], + }); + expect(status.status, CommandStatus.succeeded); + expect(status.data['status'], 'succeeded'); + expect(backend.calls, 1); + }); + + test( + 'translation publication survives restart and does not rerun the backend', + () async { + backend.gate.complete(); + await invoke('media.transcribe', 'source-asr', args()); + await settle(session); + final source = session.transcriptions!.tasks.single.result!.subtitles + .toFilePath(); + final arguments = { + 'source': source, + 'sourceLanguage': 'zh', + 'targetLanguage': 'en', + }; + final started = await invoke( + 'subtitle.translate', + 'translate-durable', + arguments, + ); + final task = session.transcriptions!.translationTask( + started.data['taskId'] as String, + ); + while (!task.terminal) { + await Future.delayed(const Duration(milliseconds: 10)); + } + expect(task.status, TranscriptionStatus.succeeded); + await reopenSession(); + expect( + session.transcriptions!.translationTask(task.id).status, + TranscriptionStatus.succeeded, + ); + await invoke('subtitle.translate', 'translate-again', arguments); + expect(translationBackend.calls, 1); + }, + ); + + test('interrupted recognition stays idle on reopen and explicit retry reuses destination', () async { + final result = await invoke('media.transcribe', 'interrupted-asr', args()); + await backend.started.future; + final destination = backend.lastRequest!.destination; + await reopenSession(); + expect( + session.transcriptions!.task(result.data['taskId'] as String).status, + TranscriptionStatus.interrupted, + ); + expect(backend.calls, 1); + backend.gate.complete(); + await invoke('media.transcribe', 'explicit-retry', args()); + await settle(session); + expect(backend.calls, 2); + expect(backend.lastRequest!.destination, destination); + }); + + test( + 'reconfiguration retains task history and close still cancels active work', + () async { + final service = session.transcriptions!; + final result = await invoke('media.transcribe', 'lifecycle', args()); + final task = service.task(result.data['taskId'] as String); + await backend.started.future; + expect( + () => session.configureProcessing( + translationBackend: translationBackend, + translationModel: Uri.directory('${root.path}/changed'), + ), + throwsA(isA()), + ); + expect(session.transcriptions, same(service)); + session.configureProcessing( + transcriptionBackend: backend, + transcriptionModel: service.modelDirectory, + ); + await session.close(); + expect(task.terminal, isTrue); + expect( + () => session.configureProcessing( + translationBackend: translationBackend, + translationModel: Uri.directory('${root.path}/changed'), + ), + throwsA(isA()), + ); + }, + ); + + test( + 'invalid optional configuration leaves all existing services unchanged', + () { + final service = session.transcriptions!; + final model = service.translationModel; + expect( + () => session.configureProcessing( + translationBackend: translationBackend, + translationModel: Uri.directory('${root.path}/changed'), + vocalSeparationModel: Uri.file('${root.path}/unpaired.pt'), + ), + throwsArgumentError, + ); + expect(session.transcriptions, same(service)); + expect(service.translationModel, model); + }, + ); + + test('completed tasks survive later model installation', () async { + final service = session.transcriptions!; + final result = await invoke('media.transcribe', 'history', args()); + backend.gate.complete(); + await settle(session); + final task = service.task(result.data['taskId'] as String); + session.configureProcessing( + translationBackend: translationBackend, + translationModel: Uri.directory('${root.path}/changed'), + ); + expect(session.transcriptions, same(service)); + expect(session.transcriptions!.task(task.id), same(task)); + expect(task.result, isNotNull); + }); + + test( + 'installing translation separately preserves recognition availability', + () { + session.configureProcessing( + translationBackend: translationBackend, + translationModel: Uri.directory('${root.path}/new-m2m100'), + ); + expect(session.transcriptions!.recognitionAvailable, isTrue); + expect(session.transcriptions!.translationAvailable, isTrue); + expect(session.transcriptions!.backend, same(backend)); + expect( + session.transcriptions!.translationModel, + Uri.directory('${root.path}/new-m2m100'), + ); + }, + ); + + test('translation tool reads the portable subtitle document without editing captions', () async { + final start = await invoke('media.transcribe', 'recognize-ja', { + 'mediaId': 'source', + 'language': 'ja', + 'destination': '${root.path}/recognized', + }); + backend.gate.complete(); + await settle(session); + final subtitles = session.transcriptions! + .task(start.data['taskId'] as String) + .result! + .subtitles; + + await session.close(); + session = EditorTimelineSession( + document: await project.loadTimeline('p'), + persistence: await project.openTimelineSaveSession('p'), + media: media, + translationBackend: translationBackend, + translationModel: Uri.directory('${root.path}/m2m100'), + ); + expect(session.transcriptions!.recognitionAvailable, isFalse); + expect( + session.supportedCommandOperations, + isNot(contains(EditorOperation.startTranscription)), + ); + final translated = await invoke('subtitle.translate', 'translate-ja', { + 'source': subtitles.toFilePath(), + 'sourceLanguage': 'ja', + 'targetLanguage': 'en', + 'threads': 4, + }); + expect(translated.status, CommandStatus.succeeded); + final taskId = translated.data['taskId'] as String; + for ( + var i = 0; + i < 100 && !session.transcriptions!.translationTask(taskId).terminal; + i++ + ) { + await Future.delayed(const Duration(milliseconds: 5)); + } + final queried = await invoke('subtitleTranslation.query', 'query-ja', { + 'taskId': taskId, + }); + expect(queried.data['status'], 'succeeded'); + expect((queried.data['result'] as Map)['cueCount'], 1); + expect(translationBackend.lastRequest!.source, subtitles); + expect(translationBackend.lastRequest!.targetLanguage, 'en'); + expect(translationBackend.lastRequest!.execution.threads, 4); + expect( + session.persistence.timeline(sequence).exportDto().elements, + isEmpty, + ); + }); + + test('caption role applies once, compiles text and restores content through undo and save', () async { + await project.saveAsset( + AssetDocument( + id: 'source', + name: 'Speech', + storage: AssetStorage.external, + location: media.source.toString(), + ), + ); + session.insertAsset( + sequenceId: sequence, + assetId: 'source', + assetName: 'Speech', + uri: media.source, + duration: RationalTime.seconds(5), + position: 0, + kind: 'audio', + hasAudio: true, + clipId: ElementId('clip'), + ); + final start = await invoke('media.transcribe', 'recognize', { + 'mediaId': 'source', + 'destination': '${root.path}/out', + }); + backend.gate.complete(); + await settle(session); + final args = { + 'taskId': start.data['taskId'], + 'clipId': 'clip', + 'expectedVersion': session.version, + }; + final applied = await invoke('transcription.apply', 'apply', args); + expect(applied.status, CommandStatus.succeeded, reason: applied.message); + expect(applied.edit, EditOutcome.committed); + final repeated = await invoke('transcription.apply', 'apply', args); + expect(repeated.data, applied.data); + final id = (applied.data['captionIds'] as List).single as String; + final track = session.persistence + .timeline(sequence) + .current + .query() + .elementById(ElementId(applied.data['roleId'] as String))!; + final owner = LayoutBodyId.element(track); + final components = session.layout(sequence).currentComponents!; + expect(components.isExpanded(owner), true); + final cueBody = components.componentBodies(owner).single; + expect( + components.scene.bodies[cueBody]!.height, + session.layoutConfiguration.captionHeight, + ); + final controller = session.view(sequence); + final frame = controller.project( + TimelineViewportRect(width: 800, height: 400), + ); + int indexOf(Object identity) => List.generate( + frame.length, + (index) => index, + ).singleWhere((index) => frame.identityAt(index) == identity); + final roleBounds = controller.presentationBoundsAt(frame, indexOf(owner)); + final cueBounds = controller.presentationBoundsAt(frame, indexOf(cueBody)); + expect(roleBounds.top, cueBounds.top); + expect(roleBounds.height, cueBounds.height); + expect(roleBounds.height, session.layoutConfiguration.captionHeight); + final viewport = TimelineViewportRect(width: 800, height: 400); + expect( + controller + .hitTest(viewport: viewport, position: cueBounds.center) + ?.identity, + cueBody, + ); + expect( + controller + .hitTest( + viewport: viewport, + position: Offset(roleBounds.right - 1, roleBounds.center.dy), + ) + ?.identity, + isNull, + ); + controller.setSelection([owner]); + expect(controller.selectedIdentities, isEmpty); + expect( + controller.hitTestRect(viewport: viewport, rectangle: roleBounds), + isNot(contains(owner)), + ); + expect(session.resolveCaptionComponent(sequence, cueBody), isNotNull); + expect(session.caption(sequence, id).text, '测试字幕'); + final transformed = await invoke('clip.setTransform', 'move-caption', { + 'clipId': id, + 'at': {'numerator': '1', 'denominator': 2}, + 'x': 192, + 'y': 108, + 'scaleX': 1.2, + 'scaleY': .8, + 'rotation': 15, + }); + expect(transformed.status, CommandStatus.succeeded); + final transformedQuery = session.persistence + .timeline(sequence) + .current + .query(); + final transformedCaption = transformedQuery.element( + transformedQuery.elementById(ElementId(id))!, + ); + final captionTransform = ClipTransform.fromRecord(transformedCaption); + expect(captionTransform.x, closeTo(.1, 1e-9)); + expect(captionTransform.y, closeTo(.1, 1e-9)); + expect(captionTransform.scale, 1.2); + expect(captionTransform.scaleY, .8); + expect(captionTransform.rotation, 15); + session.undo(sequence); + final restoredQuery = session.persistence + .timeline(sequence) + .current + .query(); + final restoredTransform = ClipTransform.fromRecord( + restoredQuery.element(restoredQuery.elementById(ElementId(id))!), + ); + expect(restoredTransform.x, 0); + expect(restoredTransform.y, 0); + expect(restoredTransform.scale, 1); + expect(restoredTransform.scaleY, 1); + expect(restoredTransform.rotation, 0); + final unchanged = session.version; + session.setCaption(sequence, SetCaption(captionId: id, text: '测试字幕')); + expect(session.version, unchanged); + for (final invalid in [ + SetCaption(captionId: id, text: 'bad\u0000text'), + SetCaption(captionId: id, color: 'red'), + SetCaption(captionId: id, duration: CommandTime(0, 1)), + SetCaption(captionId: id, start: CommandTime(1, 11)), + ]) { + expect( + () => session.setCaption(sequence, invalid), + throwsA(isA()), + ); + expect(session.version, unchanged); + } + final deleted = await invoke('timeline.delete', 'delete-cue', { + 'clipId': id, + }); + expect(deleted.status, CommandStatus.succeeded, reason: deleted.message); + expect( + () => session.caption(sequence, id), + throwsA(isA()), + ); + session.undo(sequence); + final kernel = session.persistence.timeline(sequence); + final before = session.version; + final changed = await invoke('caption.set', 'edit-text', { + 'captionId': id, + 'text': '新字幕', + 'fontSize': 36, + 'start': {'numerator': '1', 'denominator': 2}, + 'duration': {'numerator': '2', 'denominator': 1}, + }); + expect(changed.status, CommandStatus.succeeded, reason: changed.message); + expect(session.version, isNot(before)); + expect(session.caption(sequence, id).text, '新字幕'); + final input = editorExecutionInput( + session, + sequence, + kernel.current, + EditorExecutionMedia( + bindings: { + for (final payload in session.payloads) + if (payload.type == 'audio') + PayloadRef(payload.id): ExecutionMediaBinding( + media: MediaReference(id: 'source', uri: media.source), + videoTrackSelection: null, + audioTrackSelection: TrackSelection.index(0), + ), + }, + ), + settings: session.settings, + canvas: session.canvas, + payloads: session.payloads.toList(), + ); + final compiled = const ExecutionCompiler().compile(input); + expect(compiled.plan.visualLayers.single.text!.text, '新字幕'); + expect(compiled.plan.visualLayers.single.text!.canvas.width, 1728); + expect(compiled.plan.visualLayers.single.text!.canvas.height, 259); + expect(compiled.plan.visualLayers.single.text!.bottomAligned, isTrue); + expect(compiled.plan.visualLayers.single.text!.positionY, -0.30); + expect(compiled.plan.visualLayers.single.timelineRange.start.seconds, 0.5); + expect(compiled.plan.visualLayers.single.timelineRange.duration.seconds, 2); + session.undo(sequence); + expect(session.caption(sequence, id).text, '测试字幕'); + session.undo(sequence); + expect(kernel.current.query().elementById(ElementId(id)), isNull); + session.redo(sequence); + session.redo(sequence); + await session.flush(); + expect(session.dirty, false); + await session.close(); + session = EditorTimelineSession( + document: await project.loadTimeline('p'), + persistence: await project.openTimelineSaveSession('p'), + ); + expect(session.caption(sequence, id).text, '新字幕'); + final queried = await invoke('caption.query', 'after-reopen', { + 'captionId': id, + }); + expect(queried.data['text'], '新字幕'); + expect( + session.caption(sequence, id).render(session.canvas).bottomAligned, + isTrue, + ); + }); + + Future applyFixture() async { + await project.saveAsset( + AssetDocument( + id: 'source', + name: 'Speech', + storage: AssetStorage.external, + location: media.source.toString(), + ), + ); + session.insertAsset( + sequenceId: sequence, + assetId: 'source', + assetName: 'Speech', + uri: media.source, + duration: RationalTime.seconds(5), + position: 0, + kind: 'audio', + hasAudio: true, + clipId: ElementId('clip'), + ); + final started = await invoke('media.transcribe', 'start-fixture', args()); + backend.gate.complete(); + await settle(session); + return started.data['taskId'] as String; + } + + test('clip transcription decodes only the trimmed source window', () async { + media.audioStart = MediaTime(1, 1); + await project.saveAsset( + AssetDocument( + id: 'source', + name: 'Speech', + storage: AssetStorage.external, + location: media.source.toString(), + ), + ); + session.insertAsset( + sequenceId: sequence, + assetId: 'source', + assetName: 'Speech', + uri: media.source, + duration: RationalTime.seconds(5), + position: 0, + kind: 'audio', + hasAudio: true, + clipId: ElementId('clip'), + ); + final trimmed = await invoke('timeline.trim', 'trim-for-asr', { + 'clipId': 'clip', + 'duration': {'numerator': '3', 'denominator': 1}, + 'leading': true, + }); + expect(trimmed.status, CommandStatus.succeeded); + final started = await invoke('media.transcribe', 'clip-asr', { + 'mediaId': 'source', + 'clipId': 'clip', + 'language': 'zh', + }); + expect(started.status, CommandStatus.succeeded); + backend.gate.complete(); + await settle(session); + expect(backend.lastRequest?.sourceStartMs, 1000); + expect(backend.lastRequest?.sourceSeekMs, 2000); + expect(backend.lastRequest?.sourceDurationMs, 3000); + final applied = await invoke('transcription.apply', 'apply-clip-asr', { + 'taskId': started.data['taskId'], + 'clipId': 'clip', + }); + expect(applied.status, CommandStatus.succeeded, reason: applied.message); + expect(applied.data['cueCount'], 1); + final query = session.persistence.timeline(sequence).current.query(); + final clip = query.elementById(ElementId('clip'))!; + final caption = query.elementById( + ElementId((applied.data['captionIds'] as List).single as String), + )!; + expect( + query.absoluteStart(caption) - query.absoluteStart(clip), + 200 * TimelineClock.ticksPerSecond ~/ 1000, + ); + expect(query.element(caption).duration, TimelineClock.ticksPerSecond); + }); + + test( + 'model-authored captions create distinct tracks and append atomically', + () async { + await project.saveAsset( + AssetDocument( + id: 'source', + name: 'Speech', + storage: AssetStorage.external, + location: media.source.toString(), + ), + ); + session.insertAsset( + sequenceId: sequence, + assetId: 'source', + assetName: 'Speech', + uri: media.source, + duration: RationalTime.seconds(5), + position: 0, + kind: 'audio', + hasAudio: true, + clipId: ElementId('clip'), + ); + final dispatcher = editorToolsFor(session, sequence); + final agentTools = editorAgentTools({'timeline': dispatcher}); + expect( + agentTools.map((tool) => tool.name), + containsAll([ + 'captionTrack_create', + 'caption_add', + 'caption_query', + 'subtitle_translate', + ]), + ); + Future> agentInvoke( + String name, + String id, + Map args, + ) async { + final tool = agentTools.singleWhere((tool) => tool.name == name); + final arguments = {'workspaceId': 'timeline', ...args}; + expect(tool.validate(arguments), isNull); + final result = await tool.execute( + ToolCall(id: id, name: name, arguments: arguments), + ToolContext( + sessionId: 'test', + runId: 'test', + operationId: id, + cancellation: CancellationToken(), + onProgress: (_) {}, + ), + ); + expect(result.isError, isFalse, reason: result.text); + return (result.data['data'] as Map).cast(); + } + + Future track(String id, String language) async { + final result = await agentInvoke('captionTrack_create', id, { + 'name': id, + 'language': language, + 'expectedVersion': session.version, + }); + return result['roleId'] as String; + } + + Map cue(String text, int start) => { + 'text': text, + 'start': {'numerator': '$start', 'denominator': 2}, + 'duration': {'numerator': '1', 'denominator': 2}, + }; + final ja = await track('Japanese', 'ja'); + final original = await invoke('caption.add', 'original', { + 'roleId': ja, + 'cues': [cue('こんにちは', 1)], + }); + expect( + original.status, + CommandStatus.succeeded, + reason: original.message, + ); + final sourceId = (original.data['captionIds'] as List).single as String; + final tracks = await invoke('caption.list', 'list-tracks', {}); + expect(tracks.status, CommandStatus.succeeded); + expect((tracks.data['tracks'] as List).single['cueCount'], 1); + expect(tracks.data.containsKey('cues'), isFalse); + + final source = await invoke('caption.query', 'read-source', { + 'captionId': sourceId, + }); + expect(source.data['text'], 'こんにちは'); + final zh = await track('Chinese', 'zh'); + final otherZh = await track('Chinese alternative', 'zh'); + expect(otherZh, isNot(zh)); + final first = await invoke('caption.addTranslations', 'translated-one', { + 'roleId': zh, + 'cues': [ + {'text': '你好', 'sourceCaptionId': sourceId}, + ], + 'expectedVersion': session.version, + }); + expect(first.status, CommandStatus.succeeded, reason: first.message); + final firstId = (first.data['captionIds'] as List).single as String; + expect( + session.queryCaption(sequence, firstId)['start'], + source.data['start'], + ); + expect( + session.queryCaption(sequence, firstId)['duration'], + source.data['duration'], + ); + final beforeBatch = session.version; + final batch = await invoke('caption.add', 'translated-batch', { + 'roleId': zh, + 'cues': [cue('再见', 6), cue('谢谢', 4)], + 'expectedVersion': beforeBatch, + }); + expect(batch.status, CommandStatus.succeeded, reason: batch.message); + expect(batch.data['cueCount'], 2); + final batchIds = (batch.data['captionIds'] as List).cast(); + expect(session.caption(sequence, batchIds.first).text, '谢谢'); + expect(session.caption(sequence, sourceId).text, 'こんにちは'); + final page = await invoke('caption.list', 'page-one', { + 'roleId': zh, + 'limit': 2, + }); + expect(page.status, CommandStatus.succeeded, reason: page.message); + expect(page.data['total'], 3); + expect(page.data['nextOffset'], 2); + expect((page.data['cues'] as List).map((c) => c['text']), ['你好', '谢谢']); + final lastPage = await invoke('caption.list', 'page-two', { + 'roleId': zh, + 'offset': 2, + 'limit': 2, + }); + expect((lastPage.data['cues'] as List).single['text'], '再见'); + expect(lastPage.data['nextOffset'], isNull); + expect(lastPage.data['saveState'], 'saved'); + expect( + (await invoke('caption.list', 'bad-page', {'limit': 101})).status, + CommandStatus.rejected, + ); + expect( + (await invoke('caption.list', 'missing-role', { + 'roleId': 'missing', + })).status, + CommandStatus.rejected, + ); + + final version = session.version; + final invalidTranslation = await invoke( + 'caption.addTranslations', + 'invalid-translation-batch', + { + 'roleId': zh, + 'cues': [ + {'sourceCaptionId': sourceId, 'text': 'valid'}, + {'sourceCaptionId': 'missing', 'text': 'invalid'}, + ], + }, + ); + expect(invalidTranslation.status, CommandStatus.rejected); + expect(session.version, version); + for (final args in [ + { + 'roleId': zh, + 'cues': [cue('valid', 0), cue(' ', 2)], + }, + { + 'roleId': 'clip', + 'cues': [cue('invalid target', 0)], + }, + { + 'roleId': 'missing', + 'cues': [cue('missing target', 0)], + }, + {'roleId': zh, 'cues': []}, + { + 'roleId': zh, + 'cues': [ + {'text': 'x', 'sourceCaptionId': 'missing'}, + ], + }, + { + 'roleId': zh, + 'cues': [ + {...cue('x', 0), 'sourceCaptionId': sourceId}, + ], + }, + { + 'roleId': zh, + 'cues': [cue('stale', 0)], + 'expectedVersion': beforeBatch, + }, + { + 'roleId': zh, + 'cues': [ + {'text': 'missing timing'}, + ], + }, + ]) { + final rejected = await invoke( + 'caption.add', + 'invalid-${args.toString()}', + args, + ); + expect( + rejected.status, + CommandStatus.rejected, + reason: rejected.message, + ); + expect(session.version, version); + } + expect( + (await invoke('timeline.undo', 'undo-batch', {})).status, + CommandStatus.succeeded, + ); + for (final id in batchIds) { + expect( + session.persistence + .timeline(sequence) + .current + .query() + .elementById(ElementId(id)), + isNull, + ); + } + expect(session.caption(sequence, firstId).text, '你好'); + expect( + (await invoke('timeline.redo', 'redo-batch', {})).status, + CommandStatus.succeeded, + ); + await reopenSession(); + expect(session.caption(sequence, sourceId).text, 'こんにちは'); + expect(session.caption(sequence, firstId).text, '你好'); + expect(session.caption(sequence, batchIds.first).text, '谢谢'); + }, + ); + + test( + 'translation applies to trimmed clip in its own role and undoes once', + () async { + media.audioStart = MediaTime(1, 1); + await project.saveAsset( + AssetDocument( + id: 'source', + name: 'Speech', + storage: AssetStorage.external, + location: media.source.toString(), + ), + ); + session.insertAsset( + sequenceId: sequence, + assetId: 'source', + assetName: 'Speech', + uri: media.source, + duration: RationalTime.seconds(5), + position: 0, + kind: 'audio', + hasAudio: true, + clipId: ElementId('clip'), + ); + expect( + (await invoke('timeline.trim', 'trim-for-translation', { + 'clipId': 'clip', + 'duration': {'numerator': '3', 'denominator': 1}, + 'leading': true, + })).status, + CommandStatus.succeeded, + ); + final recognized = await invoke('media.transcribe', 'recognize-ja', { + 'mediaId': 'source', + 'clipId': 'clip', + 'language': 'ja', + }); + backend.gate.complete(); + await settle(session); + final original = await invoke('transcription.apply', 'apply-ja', { + 'taskId': recognized.data['taskId'], + 'clipId': 'clip', + }); + expect( + original.status, + CommandStatus.succeeded, + reason: original.message, + ); + final started = await invoke('subtitle.translate', 'translate-zh', { + 'source': session.transcriptions! + .task(recognized.data['taskId'] as String) + .result! + .subtitles + .toFilePath(), + 'sourceLanguage': 'ja', + 'targetLanguage': 'zh', + }); + expect(started.status, CommandStatus.succeeded, reason: started.message); + for ( + var i = 0; + i < 200 && + session.transcriptions!.translationTasks.any((t) => !t.terminal); + i++ + ) { + await Future.delayed(const Duration(milliseconds: 10)); + } + final applied = await invoke('subtitleTranslation.apply', 'apply-zh', { + 'taskId': started.data['taskId'], + 'clipId': 'clip', + 'source': media.source.toFilePath(), + 'sourceStartMs': 1000, + }); + expect(applied.status, CommandStatus.succeeded, reason: applied.message); + expect(applied.data['roleId'], isNot(original.data['roleId'])); + final query = session.persistence.timeline(sequence).current.query(); + final clip = query.elementById(ElementId('clip'))!; + final captionId = (applied.data['captionIds'] as List).single as String; + final caption = query.elementById(ElementId(captionId))!; + expect( + query.absoluteStart(caption) - query.absoluteStart(clip), + 200 * TimelineClock.ticksPerSecond ~/ 1000, + ); + expect(session.caption(sequence, captionId).text, '你好'); + expect( + (await invoke('timeline.undo', 'undo-zh', {})).status, + CommandStatus.succeeded, + ); + expect( + session.persistence + .timeline(sequence) + .current + .query() + .elementById(ElementId(captionId)), + isNull, + ); + expect(session.captionRole(sequence, language: 'ja'), isNotNull); + final mismatched = await invoke( + 'subtitleTranslation.apply', + 'wrong-clip', + { + 'taskId': started.data['taskId'], + 'clipId': 'missing', + 'source': media.source.toFilePath(), + }, + ); + expect(mismatched.status, CommandStatus.rejected); + }, + ); + + test('transcriptions reuse one sequence caption role', () async { + final task = await applyFixture(); + final first = await invoke('transcription.apply', 'apply-role-1', { + 'taskId': task, + 'clipId': 'clip', + 'expectedVersion': session.version, + }); + final second = await invoke('transcription.apply', 'apply-role-2', { + 'taskId': task, + 'clipId': 'clip', + 'expectedVersion': session.version, + }); + expect(second.data['roleId'], first.data['roleId']); + + final query = session.persistence.timeline(sequence).current.query(); + final role = query.elementById(ElementId(first.data['roleId'] as String))!; + final rolePayload = session.payloadFor(query.element(role).payloadRef!); + expect(rolePayload?.type, 'caption-role'); + expect(query.absoluteStart(role), 0); + final child = query.element(role).containerStoryline!; + expect( + query.storylineElements(child).where((handle) { + final ref = query.element(handle).payloadRef; + return ref != null && session.payloadFor(ref)?.type == 'caption'; + }), + hasLength(2), + ); + }); + + test( + 'caption sidecar tools import and export through the runtime port', + () async { + await project.saveAsset( + AssetDocument( + id: 'source', + name: 'Speech', + storage: AssetStorage.external, + location: media.source.toString(), + ), + ); + session.insertAsset( + sequenceId: sequence, + assetId: 'source', + assetName: 'Speech', + uri: media.source, + duration: RationalTime.seconds(5), + position: 0, + kind: 'audio', + hasAudio: true, + clipId: ElementId('clip'), + ); + final imported = await invoke('caption.import', 'import-srt', { + 'source': '${root.path}/captions.srt', + 'format': 'srt', + 'expectedVersion': session.version, + }); + expect( + imported.status, + CommandStatus.succeeded, + reason: imported.message, + ); + expect(imported.edit, EditOutcome.committed); + final id = (imported.data['captionIds'] as List).single as String; + expect(session.caption(sequence, id).text, 'Imported caption'); + + final exported = await invoke('caption.export', 'export-scc', { + 'destination': '${root.path}/captions.scc', + 'format': 'cea608', + 'languageTag': 'en-US', + 'frameDuration': {'numerator': '1001', 'denominator': 30000}, + 'allowChanges': true, + 'expectedVersion': session.version, + }); + expect( + exported.status, + CommandStatus.succeeded, + reason: exported.message, + ); + expect(exported.edit, EditOutcome.notApplicable); + expect(captionBackend.writtenFormat, CaptionFileFormat.scenaristCea608); + expect(captionBackend.writtenLanguage, 'en-US'); + expect(captionBackend.writtenFrameDuration!.numerator, 1001); + expect(captionBackend.writtenAllowChanges, true); + expect(captionBackend.writtenCues!.single.text, 'Imported caption'); + }, + ); + + test( + 'caption import rejects an empty timeline without an unknown outcome', + () async { + final result = await invoke('caption.import', 'empty-timeline-srt', { + 'source': '${root.path}/captions.srt', + 'format': 'srt', + 'expectedVersion': session.version, + }); + expect(result.status, CommandStatus.rejected); + expect(result.code, 'missingCaptionAnchor'); + expect(result.edit, EditOutcome.notCommitted); + }, + ); + + test( + 'caption import reports decoder failures as a rejected command', + () async { + captionBackend.failRead = true; + final result = await invoke('caption.import', 'invalid-srt', { + 'source': '${root.path}/invalid.srt', + 'format': 'srt', + 'expectedVersion': session.version, + }); + expect(result.status, CommandStatus.rejected); + expect(result.code, 'captionImportFailed'); + expect(result.edit, EditOutcome.notCommitted); + }, + ); + + test('caption export rejects a role after its last cue is deleted', () async { + final task = await applyFixture(); + final applied = await invoke('transcription.apply', 'apply-empty-role', { + 'taskId': task, + 'clipId': 'clip', + 'expectedVersion': session.version, + }); + final captionId = (applied.data['captionIds'] as List).single as String; + await invoke('timeline.delete', 'delete-last-caption', { + 'clipId': captionId, + 'expectedVersion': session.version, + }); + final result = await invoke('caption.export', 'export-empty-role', { + 'destination': '${root.path}/empty.srt', + 'format': 'srt', + 'expectedVersion': session.version, + }); + expect(result.status, CommandStatus.rejected); + expect(result.code, 'emptyCaptions'); + expect(result.edit, EditOutcome.notApplicable); + }); + + for (final moveLeft in [false, true]) { + test('caption component drag expands role ${moveLeft ? "left" : "right"} ' + 'and preserves sibling times with undo', () async { + final task = await applyFixture(); + final applied = await invoke('transcription.apply', 'apply-drag', { + 'taskId': task, + 'clipId': 'clip', + 'expectedVersion': session.version, + }); + final captionId = (applied.data['captionIds'] as List).single as String; + session.splitCaption( + sequence, + SplitCaption(captionId: captionId, offset: CommandTime(1, 2)), + ); + if (moveLeft) { + session.insertAsset( + sequenceId: sequence, + assetId: 'source', + assetName: 'Earlier speech', + uri: media.source, + duration: RationalTime.seconds(2), + position: 0, + kind: 'audio', + hasAudio: true, + clipId: ElementId('earlier'), + ); + } + final kernel = session.persistence.timeline(sequence); + final before = kernel.current; + final q = before.query(); + final cue = q.elementById(ElementId(captionId))!; + final parent = q.localContext(cue).storyline; + final sibling = q + .storylineElements(parent) + .firstWhere( + (candidate) => + candidate != cue && q.element(candidate).payloadRef != null, + ); + final siblingStart = q.absoluteStart(sibling); + final identity = session.captionComponentFor(sequence, cue)!; + final start = (moveLeft ? 0 : 6) * TimelineClock.ticksPerSecond; + final duration = 2 * TimelineClock.ticksPerSecond; + session.setCaptionComponentInterval(sequence, identity, start, duration); + final after = kernel.current; + final updated = after.query(); + expect(updated.absoluteStart(cue), start); + expect(updated.element(cue).duration, duration); + expect(updated.absoluteStart(sibling), siblingStart); + final body = session + .layout(sequence) + .current! + .scene + .bodies[session.captionComponentFor(sequence, cue)!]; + expect(body?.start, start); + expect(body?.end, start + duration); + await session.executeCommand(sequence, const UndoEdit()); + expect(kernel.current, before); + await session.executeCommand(sequence, const RedoEdit()); + expect(kernel.current, after); + }); + } + + test( + 'caption commands expose sequence time after the connected role moves', + () async { + final task = await applyFixture(); + final applied = await invoke('transcription.apply', 'apply-time-domain', { + 'taskId': task, + 'clipId': 'clip', + 'expectedVersion': session.version, + }); + final captionId = (applied.data['captionIds'] as List).single as String; + session.insertAsset( + sequenceId: sequence, + assetId: 'source', + assetName: 'Earlier speech', + uri: media.source, + duration: RationalTime.seconds(2), + position: 0, + kind: 'audio', + hasAudio: true, + clipId: ElementId('earlier'), + ); + final query = session.queryCaption(sequence, captionId); + expect(query['start'], {'numerator': '11', 'denominator': 5}); + final beforeRole = await invoke( + 'transcription.apply', + 'apply-before-role', + { + 'taskId': task, + 'clipId': 'earlier', + 'expectedVersion': session.version, + }, + ); + expect(beforeRole.code, 'captionBeforeRole'); + + session.setCaption( + sequence, + SetCaption( + captionId: captionId, + start: CommandTime(3, 1), + expectedVersion: session.version, + ), + ); + final timeline = session.persistence.timeline(sequence).current.query(); + expect( + timeline.absoluteStart(timeline.elementById(ElementId(captionId))!), + TimelineClock.ticksPerSecond * 3, + ); + }, + ); + + test( + 'caption tools split and merge cues as one undoable edit each', + () async { + final task = await applyFixture(); + final applied = await invoke('transcription.apply', 'apply-split', { + 'taskId': task, + 'clipId': 'clip', + 'expectedVersion': session.version, + }); + final original = (applied.data['captionIds'] as List).single as String; + final styled = await invoke('caption.set', 'style-caption', { + 'captionId': original, + 'strokeColor': '#336699', + 'strokeWidth': 2, + 'expectedVersion': session.version, + }); + expect(styled.status, CommandStatus.succeeded, reason: styled.message); + final split = await invoke('caption.split', 'split-caption', { + 'captionId': original, + 'offset': {'numerator': '1', 'denominator': 2}, + 'expectedVersion': session.version, + }); + expect(split.status, CommandStatus.succeeded, reason: split.message); + final query = session.persistence.timeline(sequence).current.query(); + final track = query.elementById( + ElementId(applied.data['roleId'] as String), + )!; + final child = query.element(track).containerStoryline!; + final cues = query + .storylineElements(child) + .where((handle) => query.element(handle).payloadRef != null) + .toList(); + expect(cues, hasLength(2)); + expect( + cues.map( + (handle) => + session.caption(sequence, query.element(handle).id.value).text, + ), + ['测试', '字幕'], + ); + for (final cue in cues) { + final caption = session.caption(sequence, query.element(cue).id.value); + expect(caption.render(session.canvas).bottomAligned, isTrue); + expect(caption.positionY, -0.30); + expect(caption.strokeColor, '#336699'); + expect(caption.strokeWidth, 2); + } + final merged = await invoke('caption.merge', 'merge-captions', { + 'captionIds': cues + .map((handle) => query.element(handle).id.value) + .toList(), + 'expectedVersion': session.version, + }); + expect(merged.status, CommandStatus.succeeded, reason: merged.message); + final after = session.persistence.timeline(sequence).current.query(); + expect( + after + .storylineElements(child) + .where((handle) => after.element(handle).payloadRef != null), + hasLength(1), + ); + expect(session.caption(sequence, original).text, '测试\n字幕'); + expect( + session + .caption(sequence, original) + .render(session.canvas) + .bottomAligned, + isTrue, + ); + expect(session.caption(sequence, original).positionY, -0.30); + expect(session.caption(sequence, original).strokeColor, '#336699'); + expect(session.caption(sequence, original).strokeWidth, 2); + session.undo(sequence); + expect( + session.persistence + .timeline(sequence) + .current + .query() + .storylineElements(child) + .where( + (handle) => + session.persistence + .timeline(sequence) + .current + .query() + .element(handle) + .payloadRef != + null, + ), + hasLength(2), + ); + }, + ); + + test('derived caption cue drag and trim commit authored timing', () async { + final task = await applyFixture(); + final applied = await invoke('transcription.apply', 'apply-gesture', { + 'taskId': task, + 'clipId': 'clip', + 'expectedVersion': session.version, + }); + final cueId = (applied.data['captionIds'] as List).single as String; + final roleId = applied.data['roleId'] as String; + final controller = session.view(sequence); + final viewport = TimelineViewportRect(width: 800, height: 400); + + LayoutBodyId cueBody() { + final query = controller.version.kernelVersion.query(); + final track = query.elementById(ElementId(roleId))!; + return session + .layout(sequence) + .currentComponents! + .componentBodies(LayoutBodyId.element(track)) + .single; + } + + final selected = await invoke('selection.set', 'select-cue', { + 'clipIds': [cueId], + }); + expect(selected.status, CommandStatus.succeeded, reason: selected.message); + expect(controller.selectedIdentities.single, cueBody()); + + Rect boundsOf(LayoutBodyId body) { + final frame = controller.project(viewport); + final index = List.generate( + frame.length, + (i) => i, + ).singleWhere((i) => frame.identityAt(i) == body); + return Rect.fromLTWH( + frame.screenLeftAt(index), + frame.screenTopAt(index), + frame.screenWidthAt(index), + frame.screenHeightAt(index), + ); + } + + var body = cueBody(); + var bounds = boundsOf(body); + expect( + controller.hitTest(viewport: viewport, position: bounds.center)?.identity, + body, + reason: '$bounds', + ); + expect( + controller.beginDrag(viewport: viewport, position: bounds.center), + true, + ); + expect( + controller.finishDrag( + viewport: viewport, + position: bounds.center + const Offset(60, 0), + ), + true, + ); + var query = session.persistence.timeline(sequence).current.query(); + var cue = query.elementById(ElementId(cueId))!; + expect( + query.localContext(cue).start, + TimelineClock.ticksPerSecond * 6 ~/ 5, + ); + expect(query.element(cue).duration, TimelineClock.ticksPerSecond); + + body = cueBody(); + bounds = boundsOf(body); + expect( + controller.beginDrag( + viewport: viewport, + position: Offset(bounds.right - 1, bounds.center.dy), + trimHitExtent: 8, + ), + true, + ); + expect( + controller.finishDrag( + viewport: viewport, + position: Offset(bounds.right - 31, bounds.center.dy), + ), + true, + ); + query = session.persistence.timeline(sequence).current.query(); + cue = query.elementById(ElementId(cueId))!; + expect( + query.localContext(cue).start, + TimelineClock.ticksPerSecond * 6 ~/ 5, + ); + expect(query.element(cue).duration, TimelineClock.ticksPerSecond ~/ 2); + }); + + test('apply rejects stale, missing, mismatched and cancelled targets without changing history', () async { + final task = await applyFixture(); + final version = session.version; + for (final (clip, expected, code) in [ + ('missing', version, 'missingClip'), + ('clip', 'old', 'staleVersion'), + ]) { + final result = await invoke('transcription.apply', code, { + 'taskId': task, + 'clipId': clip, + 'expectedVersion': expected, + }); + expect(result.code, code); + expect(session.version, version); + } + await expectLater( + session.applyTranscription( + sequence, + ApplyTranscription(taskId: task, clipId: 'clip'), + isCancelled: () => true, + ), + throwsA( + isA().having((e) => e.code, 'code', 'cancelled'), + ), + ); + expect(session.version, version); + media.pending = Completer(); + final applying = session.applyTranscription( + sequence, + ApplyTranscription(taskId: task, clipId: 'clip'), + ); + session.commands.applyEdit(sequence, const DeleteClip('clip')); + media.pending!.complete( + PreparedEditorMedia( + asset: EditorMediaAsset(id: 'source', name: 'Speech'), + uri: media.source, + duration: RationalTime.seconds(5), + kind: EditorMediaKind.audio, + hasAudio: true, + ), + ); + await expectLater( + applying, + throwsA( + isA().having((e) => e.code, 'code', 'staleVersion'), + ), + ); + }); + + testWidgets( + 'background task panel applies to its fixed target without a chooser', + (tester) async { + await tester.runAsync(() async { + await applyFixture(); + await session.subtitleWorkflows.start( + sequence: sequence, + command: const StartTranscription(mediaId: 'source', clipId: 'clip'), + name: 'Speech', + ); + await settle(session); + }); + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + theme: EditorTheme.penDark, + home: Scaffold(body: BackgroundTasksDialog(session: session)), + ), + ), + ); + session.view(sequence).clearSelection(); + expect(find.text('应用原文字幕'), findsNothing); + await tester.tap(find.text('Speech')); + await tester.pumpAndSettle(); + expect(find.text('任务详情'), findsOneWidget); + await tester.ensureVisible(find.text('应用原文字幕').first); + await tester.runAsync(() async { + await tester.tap(find.text('应用原文字幕').first); + for ( + var i = 0; + i < 100 && + session.persistence.timeline(sequence).current.connectionCount == + 0; + i++ + ) { + await Future.delayed(const Duration(milliseconds: 10)); + } + }); + await tester.pump(); + expect(find.text('选择目标片段'), findsNothing); + expect(session.persistence.timeline(sequence).current.connectionCount, 1); + expect(find.text('已添加 1 条字幕,可在属性面板编辑。'), findsOneWidget); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.runAsync(session.flush); + }, + ); + + testWidgets( + 'MCP caption edit updates visible fields and undo restores them', + (tester) async { + late String id; + await tester.runAsync(() async { + final task = await applyFixture(); + final result = await session.applyTranscription( + sequence, + ApplyTranscription(taskId: task, clipId: 'clip'), + ); + id = (result['captionIds'] as List).single as String; + }); + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + home: Scaffold( + body: Align( + alignment: Alignment.topRight, + child: SizedBox( + width: 280, + child: CaptionProperties( + session: session, + sequence: sequence, + clipId: id, + ), + ), + ), + ), + ), + ); + expect(find.text('测试字幕'), findsOneWidget); + expect( + find.ancestor(of: find.text('测试字幕'), matching: find.byType(ShaderMask)), + findsOneWidget, + ); + expect( + find.byKey(const ValueKey('caption-property-tab-captions')), + findsOneWidget, + ); + expect( + find.byKey(const ValueKey('caption-property-tab-text')), + findsOneWidget, + ); + for (final key in const [ + 'caption-fontSize', + 'caption-strokeWidth', + 'caption-positionY', + 'caption-start', + 'caption-duration', + ]) { + expect(find.byKey(Key(key)), findsOneWidget); + } + expect(find.text('描边颜色'), findsOneWidget); + await tester.runAsync(() async { + session.setCaption( + sequence, + SetCaption( + captionId: id, + start: CommandTime(1, 1000), + duration: CommandTime(1, 1000), + positionY: -.298, + ), + ); + await session.flush(); + }); + await tester.pump(); + String fieldText(String key) => tester + .widget( + find.descendant( + of: find.byKey(ValueKey(key)), + matching: find.byType(TextField), + ), + ) + .controller! + .text; + expect(fieldText('caption-start'), '0.001'); + expect(fieldText('caption-duration'), '0.001'); + expect(fieldText('caption-positionY'), '-0.298'); + await tester.runAsync(() async => session.undo(sequence)); + await tester.pump(); + + await tester.tap( + find.byKey(const ValueKey('caption-property-tab-captions')), + ); + await tester.pump(); + expect(find.byKey(ValueKey('caption-list-$id')), findsOneWidget); + expect(find.byKey(const Key('caption-fontSize')), findsNothing); + await tester.tap(find.byKey(ValueKey('caption-list-$id'))); + await tester.pump(); + expect(find.byKey(ValueKey('caption-list-$id')), findsOneWidget); + expect(find.byKey(const Key('caption-fontSize')), findsNothing); + await tester.tap(find.byKey(const ValueKey('caption-property-tab-text'))); + await tester.pump(); + expect(find.byKey(const Key('caption-fontSize')), findsOneWidget); + final versionBeforeScrub = session.version; + await tester.drag(find.text('字号'), const Offset(50, 0)); + await tester.pump(); + expect(session.caption(sequence, id).fontSize, closeTo(58, 1e-9)); + expect(session.version, isNot(versionBeforeScrub)); + await tester.runAsync(() async => session.undo(sequence)); + await tester.pump(); + expect(session.caption(sequence, id).fontSize, 48); + final access = EditorToolAccess(session); + addTearDown(access.dispose); + final connection = access.server.connect(); + addTearDown(connection.close); + final response = await tester.runAsync( + () => connection.handleJson( + jsonEncode({ + 'jsonrpc': '2.0', + 'id': 1, + 'method': 'tools/call', + 'params': { + '_meta': { + 'io.modelcontextprotocol/protocolVersion': '2026-07-28', + 'io.modelcontextprotocol/clientCapabilities': + {}, + }, + 'name': 'caption.set', + 'arguments': { + 'workspaceId': access.workspaces.keys.single, + 'operationId': 'mcp-text', + 'captionId': id, + 'text': '来自 MCP 的字幕', + 'strokeColor': '#FF0000', + 'strokeWidth': 2, + }, + }, + }), + ), + ); + expect(response.toString(), contains('来自 MCP 的字幕')); + await tester.pump(); + expect(find.text('来自 MCP 的字幕'), findsOneWidget); + expect(session.caption(sequence, id).strokeColor, '#FF0000'); + expect(session.caption(sequence, id).strokeWidth, 2); + await tester.runAsync(() async { + session.undo(sequence); + }); + await tester.pump(); + expect(find.text('测试字幕'), findsOneWidget); + final role = session.captionRole(sequence)!; + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + home: Scaffold( + body: SizedBox( + width: 280, + child: CaptionProperties( + session: session, + sequence: sequence, + clipId: session.persistence + .timeline(sequence) + .current + .query() + .element(role) + .id + .value, + ), + ), + ), + ), + ); + expect( + find.byKey(const ValueKey('caption-property-tab-captions')), + findsOneWidget, + ); + expect( + find.byKey(const ValueKey('caption-property-tab-text')), + findsNothing, + ); + expect(find.byKey(ValueKey('caption-list-$id')), findsOneWidget); + await tester.pumpWidget(const SizedBox.shrink()); + }, + ); + + testWidgets('caption overview selects the chosen text cue', (tester) async { + await tester.binding.setSurfaceSize(const Size(280, 240)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + late String firstId; + late String secondId; + await tester.runAsync(() async { + final task = await applyFixture(); + final first = await session.applyTranscription( + sequence, + ApplyTranscription(taskId: task, clipId: 'clip'), + ); + final second = await session.applyTranscription( + sequence, + ApplyTranscription(taskId: task, clipId: 'clip'), + ); + firstId = (first['captionIds'] as List).single as String; + secondId = (second['captionIds'] as List).single as String; + }); + Widget panel(String clipId) => MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + home: Scaffold( + body: SizedBox( + width: 280, + child: CaptionProperties( + session: session, + sequence: sequence, + clipId: clipId, + ), + ), + ), + ); + await tester.pumpWidget(panel(firstId)); + await tester.tap( + find.byKey(const ValueKey('caption-property-tab-captions')), + ); + await tester.pump(); + for (final id in [firstId, secondId]) { + final row = tester.getRect(find.byKey(ValueKey('caption-list-$id'))); + final number = tester.getRect(find.byKey(ValueKey('caption-number-$id'))); + final content = tester.getRect( + find.byKey(ValueKey('caption-content-$id')), + ); + final action = tester.getRect(find.byKey(ValueKey('caption-action-$id'))); + expect(row.height, 28); + final list = tester.getRect( + find.ancestor( + of: find.byKey(ValueKey('caption-list-$id')), + matching: find.byType(ListView), + ), + ); + expect(row.left - list.left, 14); + expect(number.left - row.left, 0); + expect(content.left - number.right, 6); + expect(number.right, lessThan(content.left)); + expect(content.right, lessThan(action.left)); + expect(number.center.dy, closeTo(content.center.dy, 0.1)); + expect(content.center.dy, closeTo(action.center.dy, 0.1)); + expect(action.right, lessThanOrEqualTo(row.right)); + } + await tester.runAsync(() async { + session.setCaption( + sequence, + SetCaption(captionId: secondId, text: 'Searchable CAPTION ' * 20), + ); + await session.flush(); + }); + await tester.pump(); + final search = find.byKey(const ValueKey('caption-search')); + final searchBounds = tester.getRect(search); + final wrapBounds = tester.getRect( + find.byKey(const ValueKey('caption-wrap-toggle')), + ); + expect(searchBounds.height, 28); + expect(wrapBounds.height, 28); + expect(searchBounds.top, wrapBounds.top); + expect(searchBounds.bottom, wrapBounds.bottom); + await tester.enterText(search, ' searchable '); + await tester.pump(); + expect(find.byKey(ValueKey('caption-list-$firstId')), findsNothing); + expect(find.byKey(ValueKey('caption-list-$secondId')), findsOneWidget); + expect( + tester + .widget(find.byKey(ValueKey('caption-number-$secondId'))) + .data, + '2', + ); + expect( + tester.getSize(find.byKey(ValueKey('caption-list-$secondId'))).height, + 28, + ); + await tester.enterText(search, 'no such caption'); + await tester.pump(); + expect(find.text('没有匹配的字幕'), findsOneWidget); + await tester.enterText(search, ''); + await tester.pump(); + expect(find.byKey(ValueKey('caption-list-$firstId')), findsOneWidget); + final toolbarPosition = tester.getTopLeft(search); + await tester.tap(find.byKey(const ValueKey('caption-wrap-toggle'))); + await tester.pump(); + expect( + tester.getSize(find.byKey(ValueKey('caption-list-$secondId'))).height, + greaterThan(28), + ); + expect(tester.getTopLeft(search), toolbarPosition); + final list = find.byKey(const ValueKey('caption-scroll-list')); + expect(list, findsOneWidget); + expect( + find.ancestor(of: search, matching: find.byType(ShaderMask)), + findsNothing, + ); + expect( + find.ancestor(of: list, matching: find.byType(ShaderMask)), + findsOneWidget, + ); + expect(tester.widget(list).physics, isA()); + final scroll = tester + .state( + find.descendant(of: list, matching: find.byType(Scrollable)), + ) + .position; + expect(scroll.extentBefore, 0); + expect(scroll.extentAfter, greaterThan(24)); + await tester.drag(list, const Offset(0, -60)); + await tester.pumpAndSettle(); + expect(scroll.pixels, greaterThan(0)); + scroll.jumpTo(scroll.maxScrollExtent / 2); + await tester.pumpAndSettle(); + expect(scroll.extentBefore, greaterThan(0)); + expect(scroll.extentAfter, greaterThan(0)); + scroll.jumpTo(scroll.maxScrollExtent); + await tester.pumpAndSettle(); + expect(scroll.extentAfter, 0); + expect(tester.getTopLeft(search), toolbarPosition); + expect(tester.takeException(), isNull); + await tester.tap(find.byKey(const ValueKey('caption-wrap-toggle'))); + await tester.pump(); + expect( + tester.getSize(find.byKey(ValueKey('caption-list-$secondId'))).height, + 28, + ); + await tester.pumpAndSettle(); + expect(scroll.extentAfter, 0); + expect(scroll.extentBefore, 0); + await tester.tap(find.byKey(ValueKey('caption-action-$secondId'))); + await tester.pump(); + + final identity = session.view(sequence).selectedIdentities.single; + expect(identity, isA()); + final selected = session.resolveCaptionComponent( + sequence, + identity as LayoutBodyId, + ); + expect( + session.persistence + .timeline(sequence) + .current + .query() + .element(selected!) + .id + .value, + secondId, + ); + await tester.pumpWidget(panel(secondId)); + await tester.pumpAndSettle(); + final selectedRow = find.byKey(ValueKey('caption-list-$secondId')); + expect(selectedRow, findsOneWidget); + expect(find.byKey(const ValueKey('caption-search')), findsOneWidget); + expect(find.byKey(const Key('caption-fontSize')), findsNothing); + final selectedColor = Theme.of(tester.element(selectedRow)) + .colorScheme + .onSurface + .withValues(alpha: .05); + expect( + find.ancestor( + of: selectedRow, + matching: find.byWidgetPredicate( + (widget) => widget is Material && widget.color == selectedColor, + ), + ), + findsOneWidget, + ); + await tester.tap(selectedRow); + await tester.pump(); + expect(selectedRow, findsOneWidget); + expect(find.byKey(const Key('caption-fontSize')), findsNothing); + }); + + test( + 'completed transcription output is reused and persists inside the project', + () async { + final version = session.version; + final revision = session.persistence.revision; + final first = await invoke('media.transcribe', 'managed-first', { + 'mediaId': 'source', + }); + expect(first.status, CommandStatus.succeeded); + await backend.started.future; + final output = Directory.fromUri(backend.lastRequest!.destination); + expect( + output.uri.toString(), + startsWith(project.directory.uri.resolve('artifacts/').toString()), + ); + expect(await output.exists(), false); + expect(await output.parent.exists(), true); + // Model publication writes into the reserved leaf, never an existing folder. + await output.create(); + final caption = File('${output.path}/subtitles.srt'); + await caption.writeAsString('测试字幕'); + backend.gate.complete(); + await settle(session); + await invoke('media.transcribe', 'managed-second', {'mediaId': 'source'}); + await settle(session); + expect(backend.lastRequest!.destination, output.uri); + expect(backend.calls, 1); + expect(session.version, version); + expect(session.persistence.revision, revision); + expect(session.dirty, false); + expect(session.canUndo(sequence), false); + await session.close(); + await project.close(); + project = await ProjectFile.open(project.directory); + expect(await caption.readAsString(), '测试字幕'); + }, + ); + + test('tool start is nonblocking, shares UI notifications and deduplicates requests', () async { + final version = session.version; + var notifications = 0; + session.addListener(() => notifications++); + final first = await invoke('media.transcribe', 'start', args()); + expect(first.status, CommandStatus.succeeded); + expect(first.edit, EditOutcome.notApplicable); + await backend.started.future; + expect( + (await invoke('media.transcribe', 'start', args())).data['taskId'], + first.data['taskId'], + ); + final state = await invoke('transcription.query', 'query', { + 'taskId': first.data['taskId'], + }); + expect(state.data['status'], 'running'); + expect((state.data['progress'] as Map)['stage'], 'ASRInference'); + expect(state.data['timelineCueCount'], 1); + expect( + (state.data['timelineCues'] as List).single, + containsPair('text', '测试字幕'), + ); + expect((await invoke('media.transcribe', 'other', args())).code, 'busy'); + backend.gate.complete(); + await settle(session); + final result = await invoke('transcription.query', 'query', { + 'taskId': first.data['taskId'], + }); + expect(result.data['status'], 'succeeded'); + expect((result.data['result'] as Map)['cueCount'], 1); + expect(backend.calls, 1); + expect(notifications, greaterThan(2)); + expect(session.version, version); + expect(session.dirty, false); + expect(session.canUndo(sequence), false); + }); + + test('cancel reaches the active backend and keeps the original operation receipt', () async { + final started = await invoke('media.transcribe', 'start', args()); + await backend.started.future; + final id = started.data['taskId']; + expect( + (await invoke('transcription.cancel', 'cancel', {'taskId': id})).status, + CommandStatus.succeeded, + ); + await settle(session); + expect( + session.transcriptions!.tasks.single.status, + TranscriptionStatus.cancelled, + ); + await invoke('media.transcribe', 'start', args()); + expect(backend.calls, 1); + expect( + (await invoke('transcription.cancel', 'missing', { + 'taskId': 'missing', + })).code, + 'missingTask', + ); + }); + + test('cancelled transcription ignores late backend cues', () async { + backend.emitAfterCancellation = true; + final started = await invoke('media.transcribe', 'late-cue', args()); + await backend.started.future; + await invoke('transcription.cancel', 'cancel-late-cue', { + 'taskId': started.data['taskId'], + }); + await settle(session); + + final task = session.transcriptions!.tasks.single; + expect(task.status, TranscriptionStatus.cancelled); + expect(task.timelineCues.map((cue) => cue.text), ['测试字幕']); + }); + + test('published result can win a late transcription cancellation', () async { + backend.emitAfterCancellation = true; + backend.publishAfterCancellation = true; + final started = await invoke('media.transcribe', 'published-late', args()); + await backend.started.future; + await invoke('transcription.cancel', 'cancel-published-late', { + 'taskId': started.data['taskId'], + }); + await settle(session); + + final task = session.transcriptions!.tasks.single; + expect(task.status, TranscriptionStatus.succeeded); + expect(task.result!.cues.map((cue) => cue.text), ['测试字幕', '迟到字幕']); + expect(task.timelineCues.map((cue) => cue.text), ['测试字幕']); + }); + + test('close interrupts queued media preparation without waiting on workspace I/O', () async { + media.pending = Completer(); + await invoke('media.transcribe', 'start', args()); + await session.close().timeout(const Duration(seconds: 2)); + expect( + session.transcriptions!.tasks.single.status, + TranscriptionStatus.interrupted, + ); + expect(backend.calls, 0); + media.pending!.completeError(StateError('project switched')); + await Future.delayed(Duration.zero); + }); + + test( + 'invalid request and source without audio never invoke native recognition', + () async { + expect( + (await invoke('media.transcribe', 'bad-lang', { + ...args(), + 'language': 'invalid', + })).code, + 'invalidArguments', + ); + expect( + (await invoke('media.transcribe', 'removed-duration', { + ...args(), + 'maximumDurationSeconds': 60, + })).code, + 'invalidArguments', + ); + expect( + (await invoke('media.transcribe', 'version', { + ...args(), + 'expectedVersion': session.version, + })).code, + 'invalidArguments', + ); + media.audio = false; + await invoke('media.transcribe', 'no-audio', args()); + await settle(session); + expect(session.transcriptions!.tasks.single.error, 'noAudio'); + expect(backend.calls, 0); + }, + ); + + test( + 'failed jobs can be retried with a new ID without replaying old requests', + () async { + backend.fail = true; + backend.gate.complete(); + final first = await invoke('media.transcribe', 'failed', args()); + await settle(session); + final firstDestination = backend.lastRequest!.destination; + expect( + session.transcriptions!.task(first.data['taskId'] as String).status, + TranscriptionStatus.failed, + ); + backend.fail = false; + final retry = await invoke('media.transcribe', 'retry', args()); + await settle(session); + expect(backend.lastRequest!.destination, firstDestination); + expect( + session.transcriptions!.task(retry.data['taskId'] as String).status, + TranscriptionStatus.succeeded, + ); + expect(backend.calls, 2); + await invoke('media.transcribe', 'failed', args()); + expect(backend.calls, 2); + }, + ); + + test('a mismatched final artifact never becomes applicable', () async { + backend.mismatch = true; + backend.gate.complete(); + await invoke('media.transcribe', 'mismatch', args()); + await settle(session); + final task = session.transcriptions!.tasks.single; + expect(task.status, TranscriptionStatus.failed); + expect(task.error, 'invalidResult'); + expect(task.result, isNull); + expect(task.timelineCues.single.text, '测试字幕'); + }); + + test( + 'completed task history stays bounded without disabling transcription', + () async { + backend.gate.complete(); + for (var index = 0; index < 33; index++) { + final result = await invoke('media.transcribe', 'history-$index', { + ...args(), + 'destination': '${root.path}/captions-$index', + }); + expect(result.status, CommandStatus.succeeded); + await settle(session); + } + + expect(backend.calls, 33); + expect(session.transcriptions!.tasks, hasLength(32)); + expect( + session.transcriptions!.tasks.every( + (task) => task.status == TranscriptionStatus.succeeded, + ), + true, + ); + }, + ); + + test( + 'closing a project interrupts its active transcription before returning', + () async { + await invoke('media.transcribe', 'active', args()); + await backend.started.future; + await session.close(); + expect( + session.transcriptions!.tasks.single.status, + TranscriptionStatus.interrupted, + ); + expect(session.acceptsEdits, false); + }, + ); + + test('background task cancellation prevents automatic translation', () async { + final job = await session.subtitleWorkflows.start( + sequence: sequence, + command: const StartTranscription(mediaId: 'source', language: 'ja'), + name: 'Speech', + targetLanguage: 'zh', + ); + await backend.started.future; + await session.subtitleWorkflows.cancel(job); + await settle(session); + await Future.delayed(const Duration(milliseconds: 10)); + expect(job.status, TranscriptionStatus.cancelled); + expect(job.terminal, true); + expect(session.subtitleWorkflows.runningCount, 0); + expect(translationBackend.lastRequest, isNull); + }); + + test( + 'background failed task can be retried with a new recognition task', + () async { + backend.fail = true; + backend.gate.complete(); + final first = await session.subtitleWorkflows.start( + sequence: sequence, + command: const StartTranscription(mediaId: 'source'), + name: 'Speech', + ); + await settle(session); + expect(first.status, TranscriptionStatus.failed); + backend.fail = false; + await session.subtitleWorkflows.retry(first); + await settle(session); + final retry = session.subtitleWorkflows.tasks.last; + expect(retry.recognition.id, isNot(first.recognition.id)); + expect(retry.status, TranscriptionStatus.succeeded); + expect(backend.calls, 2); + }, + ); + + test( + 'task snapshots preserve prior status while the SDK task mutates', + () async { + final registry = BackgroundTaskRegistry(); + final container = ProviderContainer(); + addTearDown(() { + container.dispose(); + registry.dispose(); + }); + registry.register( + projectId: 'project', + projectName: 'Project', + session: session, + ); + final provider = backgroundTasksProvider(registry: registry); + final completedSnapshot = Completer(); + container.listen(provider, (_, snapshot) { + if (snapshot.runningCount == 0 && + snapshot.subtitles.singleOrNull?.status == + TranscriptionStatus.succeeded && + !completedSnapshot.isCompleted) { + completedSnapshot.complete(); + } + }); + final job = await session.subtitleWorkflows.start( + sequence: sequence, + command: const StartTranscription(mediaId: 'source'), + name: 'Speech', + ); + await backend.started.future; + final before = container.read(provider); + expect(before.runningCount, 1); + expect(before.subtitles.single.status, TranscriptionStatus.running); + expect(before.subtitles.single.recognizedCues, 1); + expect(before.subtitles.single.recentCues, ['测试字幕']); + expect(before.subtitles.single.resultCues, isEmpty); + expect(before.subtitles.single.recognitionAvailable, isFalse); + backend.gate.complete(); + await settle(session); + await session.flush(); + await completedSnapshot.future.timeout(const Duration(seconds: 5)); + final after = container.read(provider); + expect(job.status, TranscriptionStatus.succeeded); + expect(after.runningCount, 0); + expect(after.subtitles.single.status, TranscriptionStatus.succeeded); + expect(after.subtitles.single.resultCues, ['测试字幕']); + expect(after.subtitles.single.recognitionAvailable, isTrue); + expect(before.subtitles.single.status, TranscriptionStatus.running); + expect(before.subtitles.single.resultCues, isEmpty); + expect(before.subtitles.single.recognitionAvailable, isFalse); + }, + ); + + test( + 'subtitle application keeps the version captured before a target chooser', + () async { + await applyFixture(); + final job = await session.subtitleWorkflows.start( + sequence: sequence, + command: const StartTranscription(mediaId: 'source', clipId: 'clip'), + name: 'Speech', + ); + await settle(session); + final version = session.version; + session.commands.applyEdit(sequence, const DeleteClip('clip')); + final container = ProviderContainer(); + addTearDown(container.dispose); + final provider = subtitleTaskActionsProvider(session, job.id); + container.listen(provider, (_, _) {}); + await container + .read(provider.notifier) + .apply(job, 'clip', expectedVersion: version); + final failure = container.read(provider).error as SubtitleActionException; + expect(failure.kind, SubtitleActionKind.original); + expect( + failure.cause, + isA().having( + (value) => value.code, + 'code', + 'staleVersion', + ), + ); + expect(session.persistence.timeline(sequence).current.connectionCount, 0); + }, + ); + + testWidgets('empty background tasks use menu row spacing', (tester) async { + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + home: Scaffold(body: BackgroundTasksContent(session: session)), + ), + ), + ); + final row = find.byKey(const Key('background-tasks-empty-state')); + final label = find.text('暂无后台任务'); + expect(tester.getSize(row).height, AppMenuMetrics.rowHeight); + expect(tester.getRect(label).left - tester.getRect(row).left, 8); + expect(find.text('后台任务'), findsNothing); + }); + + testWidgets('task popover shows results in a bounded scrolling list', ( + tester, + ) async { + await tester.runAsync(applyFixture); + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + home: Scaffold( + body: Align( + alignment: Alignment.topLeft, + child: AppPopover( + width: 384, + maxHeight: 180, + builder: (_, toggle) => IconButton( + onPressed: toggle, + icon: const Icon(Icons.task_alt), + ), + child: BackgroundTasksContent(session: session), + ), + ), + ), + ), + ), + ); + await tester.tap(find.byType(IconButton)); + await tester.pumpAndSettle(); + expect(find.text('后台任务'), findsNothing); + expect(find.textContaining('字幕已生成'), findsOneWidget); + expect(find.text('应用原文字幕'), findsNothing); + expect(find.byIcon(Icons.chevron_right), findsNothing); + final taskRow = find + .ancestor(of: find.text('source'), matching: find.byType(InkWell)) + .first; + expect( + tester.widget(taskRow).hoverColor, + AppSidebarColors.of(tester.element(taskRow)).hover, + ); + await tester.tap(find.text('source')); + await tester.pumpAndSettle(); + expect(find.text('任务详情'), findsOneWidget); + await tester.ensureVisible(find.text('应用原文字幕')); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pumpAndSettle(); + expect(find.text('任务详情'), findsNothing); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets( + 'closing subtitle download keeps it in background until cancelled', + (tester) async { + session.transcriptions!.configure( + backend: null, + modelDirectory: null, + translationBackend: null, + translationModel: null, + ); + late Completer speechStarted; + late Completer speechRelease; + late Completer translationStarted; + late Completer translationRelease; + late HttpServer server; + late ProcessingResourceRepository repository; + await tester.runAsync(() async { + speechStarted = Completer(); + speechRelease = Completer(); + translationStarted = Completer(); + translationRelease = Completer(); + server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0); + final payloads = { + ProcessingCapability.transcription: List.filled(20, 1), + ProcessingCapability.translation: List.filled(60, 2), + }; + repository = ProcessingResourceRepository( + root: Directory('${root.path}/resources/Processing'), + catalog: [ + for (final entry in payloads.entries) + ProcessingResourcePackage( + capability: entry.key, + id: entry.key.name, + version: '1', + name: 'Private model name', + description: '', + artifacts: [ + ProcessingResourceArtifact( + path: 'model.bin', + url: Uri.parse( + 'http://127.0.0.1:${server.port}/${entry.key.name}', + ), + sha256: sha256.convert(entry.value).toString(), + bytes: entry.value.length, + ), + ], + ), + ], + ); + server.listen((request) async { + final capability = ProcessingCapability.values.byName( + request.uri.pathSegments.single, + ); + if (capability == ProcessingCapability.transcription) { + speechStarted.complete(); + await speechRelease.future; + } else { + translationStarted.complete(); + await translationRelease.future; + } + try { + request.response.add(payloads[capability]!); + await request.response.close(); + } on SocketException { + // The dialog cancelled the pending response. + } on HttpException { + // The dialog cancelled the pending response. + } + }); + }); + addTearDown(() async { + if (!speechRelease.isCompleted) speechRelease.complete(); + if (!translationRelease.isCompleted) translationRelease.complete(); + await server.close(force: true); + repository.dispose(); + }); + final container = ProviderContainer( + overrides: [ + processingResourceRepositoryProvider.overrideWith( + (ref) async => repository, + ), + ], + ); + addTearDown(container.dispose); + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + home: Scaffold( + body: Builder( + builder: (context) => TextButton( + onPressed: () => showAppDialog( + context: context, + builder: (_) => TranscriptionDialog.forCurrentTask( + session: session, + asset: AssetDocument( + id: 'source', + name: 'Speech', + storage: AssetStorage.external, + location: '/speech.wav', + ), + ), + ), + child: const Text('Open'), + ), + ), + ), + ), + ), + ); + await tester.tap(find.text('Open')); + await tester.pumpAndSettle(); + await tester.runAsync(() async { + await HttpOverrides.runWithHttpOverrides(() async { + await tester.tap( + find.byKey(const Key('download-transcription-resource')), + ); + await speechStarted.future.timeout(const Duration(seconds: 5)); + }, _LocalDownloadHttpOverrides()); + }); + await tester.pump(); + expect(find.text('语音识别资源'), findsOneWidget); + expect(find.text('0%'), findsOneWidget); + expect(find.text('取消下载'), findsOneWidget); + expect(find.text('后台下载'), findsOneWidget); + expect(find.textContaining('正在下载…'), findsNothing); + expect(find.textContaining('下载资源大小'), findsNothing); + expect(find.text('暂停'), findsOneWidget); + expect(find.text('Private model name'), findsNothing); + expect(find.byType(LinearProgressIndicator), findsOneWidget); + expect( + tester + .widget( + find.byType(LinearProgressIndicator), + ) + .value, + 0, + ); + await tester.tap(find.text('暂停')); + await tester.pump(); + expect(repository.subtitlePaused, isTrue); + expect(find.text('已暂停'), findsOneWidget); + expect(find.text('继续'), findsOneWidget); + await tester.tap(find.text('继续')); + await tester.pump(); + expect(repository.subtitlePaused, isFalse); + expect(find.text('暂停'), findsOneWidget); + await tester.runAsync(() async { + speechRelease.complete(); + await translationStarted.future.timeout(const Duration(seconds: 5)); + }); + await tester.pump(); + expect(find.text('语音识别资源'), findsNothing); + expect(find.text('翻译资源'), findsOneWidget); + expect(find.text('25%'), findsOneWidget); + expect(find.byType(LinearProgressIndicator), findsOneWidget); + expect( + tester + .widget( + find.byType(LinearProgressIndicator), + ) + .value, + .25, + ); + await tester.tap( + find.byKey(const Key('background-transcription-resource')), + ); + await tester.pumpAndSettle(); + expect(find.byType(TranscriptionDialog), findsNothing); + expect( + repository.installFor(ProcessingCapability.translation).state, + ProcessingResourceState.downloading, + ); + await tester.tap(find.text('Open')); + await tester.pumpAndSettle(); + expect(find.byType(TranscriptionDialog), findsOneWidget); + expect(find.text('翻译资源'), findsOneWidget); + expect(find.text('下载'), findsNothing); + expect(find.text('暂停'), findsOneWidget); + await tester.tap(find.byKey(const Key('app-dialog-close-button'))); + await tester.pumpAndSettle(); + expect( + repository.installFor(ProcessingCapability.translation).state, + ProcessingResourceState.downloading, + ); + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + home: Scaffold( + body: BackgroundTasksContent( + session: session, + repository: repository, + ), + ), + ), + ), + ); + expect(find.text('Private model name'), findsNothing); + expect(find.text('下载语音与翻译资源'), findsOneWidget); + final backgroundProgress = tester.widget( + find.byType(ResourceDownloadProgress), + ); + expect(backgroundProgress.downloadedBytes, 20); + expect(backgroundProgress.totalBytes, 80); + expect( + find.byKey(const Key('background-download-pause-button')), + findsOneWidget, + ); + await tester.tap(find.text('下载语音与翻译资源')); + await tester.pumpAndSettle(); + expect(find.byType(TranscriptionDialog), findsOneWidget); + expect(find.text('任务详情'), findsNothing); + expect(find.text('生成字幕需要这些资源。下载完成后会自动开始处理。'), findsOneWidget); + expect(find.text('翻译资源'), findsOneWidget); + final resumedProgress = tester.widget( + find.byType(ResourceDownloadProgress).last, + ); + expect(resumedProgress.downloadedBytes, 20); + expect(resumedProgress.totalBytes, 80); + await tester.tap( + find.byKey(const Key('download-transcription-resource')), + ); + await tester.pump(); + expect(repository.subtitlePaused, isTrue); + await tester.tap( + find.byKey(const Key('download-transcription-resource')), + ); + await tester.pump(); + expect(repository.subtitlePaused, isFalse); + await tester.tap( + find.descendant( + of: find.byType(TranscriptionDialog), + matching: find.text('取消下载'), + ), + ); + await tester.pumpAndSettle(); + expect(find.text('取消下载?'), findsOneWidget); + expect( + repository.installFor(ProcessingCapability.translation).state, + ProcessingResourceState.downloading, + ); + await tester.tap(find.text('继续下载')); + await tester.pumpAndSettle(); + expect(find.byType(TranscriptionDialog), findsOneWidget); + await tester.tap(find.byKey(const Key('app-dialog-close-button'))); + await tester.pumpAndSettle(); + expect(find.byType(TranscriptionDialog), findsNothing); + await tester.tap( + find.byKey(const Key('background-download-pause-button')), + ); + await tester.pump(); + expect(repository.subtitlePaused, isTrue); + expect(find.text('继续'), findsOneWidget); + await tester.tap( + find.byKey(const Key('background-download-pause-button')), + ); + await tester.pump(); + expect(repository.subtitlePaused, isFalse); + await tester.tap(find.text('取消')); + await tester.pumpAndSettle(); + expect(find.text('取消下载?'), findsOneWidget); + expect( + repository.installFor(ProcessingCapability.translation).state, + ProcessingResourceState.downloading, + ); + await tester.tap(find.text('继续下载')); + await tester.pumpAndSettle(); + expect( + repository.installFor(ProcessingCapability.translation).state, + ProcessingResourceState.downloading, + ); + await tester.tap(find.text('取消')); + await tester.pumpAndSettle(); + await tester.tap( + find.byKey(const Key('confirm-resource-download-cancel')), + ); + await tester.pump(); + await tester.runAsync(() async { + for ( + var i = 0; + i < 100 && + repository.installFor(ProcessingCapability.translation).state == + ProcessingResourceState.downloading; + i++ + ) { + await Future.delayed(const Duration(milliseconds: 10)); + } + }); + expect( + repository.installFor(ProcessingCapability.transcription).state, + ProcessingResourceState.installed, + ); + expect( + repository.installFor(ProcessingCapability.translation).state, + ProcessingResourceState.notInstalled, + ); + expect(find.byType(TranscriptionDialog), findsNothing); + expect(tester.takeException(), isNull); + }, + ); + + testWidgets('missing subtitle resources show one download dialog', ( + tester, + ) async { + session.transcriptions!.configure( + backend: null, + modelDirectory: null, + translationBackend: null, + translationModel: null, + ); + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + home: Scaffold( + body: Builder( + builder: (context) => TextButton( + onPressed: () => showAppDialog( + context: context, + builder: (_) => TranscriptionDialog( + session: session, + asset: AssetDocument( + id: 'source', + name: 'Speech', + storage: AssetStorage.external, + location: '/speech.wav', + ), + ), + ), + child: const Text('Open'), + ), + ), + ), + ), + ), + ); + await tester.tap(find.text('Open')); + await tester.pumpAndSettle(); + expect(find.text('下载语音与翻译资源'), findsOneWidget); + expect(find.text('生成字幕需要这些资源。下载完成后会自动开始处理。'), findsOneWidget); + expect(find.text('需下载 1.1 GB'), findsOneWidget); + expect(find.textContaining('Whisper'), findsNothing); + expect(find.textContaining('M2M100'), findsNothing); + expect(find.text('下载'), findsOneWidget); + expect(find.byType(AppSelect), findsNothing); + expect(find.text('后台下载'), findsNothing); + expect(find.textContaining('资源位置'), findsNothing); + await tester.tap(find.text('取消')); + await tester.pumpAndSettle(); + expect(find.byType(TranscriptionDialog), findsNothing); + session.transcriptions!.configure( + backend: backend, + modelDirectory: Uri.directory('${root.path}/model'), + translationBackend: null, + translationModel: null, + ); + await tester.tap(find.text('Open')); + await tester.pumpAndSettle(); + expect(find.text('生成字幕需要这些资源。下载完成后会自动开始处理。'), findsOneWidget); + expect(find.text('需下载 496 MB'), findsOneWidget); + expect(find.text('下载'), findsOneWidget); + expect(find.byType(AppSelect), findsNothing); + await tester.tap(find.text('取消')); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + }); + + testWidgets( + 'generate button recognizes then translates without separate controls', + (tester) async { + await tester.runAsync( + () => project.saveAsset( + AssetDocument( + id: 'source', + name: 'Speech', + storage: AssetStorage.external, + location: media.source.toString(), + ), + ), + ); + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + home: Scaffold( + body: Builder( + builder: (context) => TextButton( + onPressed: () => showAppDialog( + context: context, + builder: (_) => TranscriptionDialog( + session: session, + asset: AssetDocument( + id: 'source', + name: 'Speech', + storage: AssetStorage.external, + location: '/speech.wav', + ), + ), + ), + child: const Text('Open'), + ), + ), + ), + ), + ), + ); + await tester.tap(find.text('Open')); + await tester.pumpAndSettle(); + expect(find.text('字幕翻译'), findsNothing); + expect(find.text('开始翻译'), findsNothing); + expect(find.text('选择识别文件'), findsNothing); + expect(find.text('关闭'), findsNothing); + final menus = tester + .widgetList>(find.byType(AppSelect)) + .toList(); + menus[0].onChanged!('ja'); + menus[1].onChanged!('zh'); + await tester.pump(); + await tester.runAsync(() async { + await tester.tap(find.text('生成字幕')); + await backend.started.future.timeout(const Duration(seconds: 5)); + }); + await tester.pumpAndSettle(); + expect(find.byType(TranscriptionDialog), findsNothing); + expect(session.subtitleWorkflows.runningCount, 1); + await tester.runAsync(() async { + await File.fromUri( + backend.lastRequest!.destination.resolve('subtitles.json'), + ).create(recursive: true); + backend.gate.complete(); + await settle(session); + }); + await tester.pump(); + await tester.runAsync(() async { + for ( + var i = 0; + i < 100 && translationBackend.lastRequest == null; + i++ + ) { + await Future.delayed(const Duration(milliseconds: 10)); + } + }); + expect(backend.lastRequest!.language, 'ja'); + expect(translationBackend.lastRequest!.sourceLanguage, 'ja'); + expect(translationBackend.lastRequest!.targetLanguage, 'zh'); + expect( + translationBackend.lastRequest!.source, + session.subtitleWorkflows.tasks.single.recognition.result!.subtitles, + ); + await tester.runAsync(() async { + for ( + var i = 0; + i < 100 && !session.subtitleWorkflows.tasks.single.terminal; + i++ + ) { + await Future.delayed(const Duration(milliseconds: 10)); + } + }); + expect(session.subtitleWorkflows.runningCount, 0); + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + home: Scaffold(body: BackgroundTasksDialog(session: session)), + ), + ), + ); + await tester.pump(); + expect(find.text('Speech'), findsAtLeastNWidgets(1)); + await tester.tap(find.text('Speech')); + await tester.pumpAndSettle(); + expect(find.text('应用原文字幕'), findsOneWidget); + expect(find.text('应用翻译字幕'), findsOneWidget); + await tester.pumpWidget(const SizedBox.shrink()); + }, + ); + + testWidgets( + 'task panel applies translated subtitles using the recognition window', + (tester) async { + await tester.runAsync(() async { + media.audioStart = MediaTime(1, 1); + await project.saveAsset( + AssetDocument( + id: 'source', + name: 'Speech', + storage: AssetStorage.external, + location: media.source.toString(), + ), + ); + session.insertAsset( + sequenceId: sequence, + assetId: 'source', + assetName: 'Speech', + uri: media.source, + duration: RationalTime.seconds(5), + position: 0, + kind: 'audio', + hasAudio: true, + clipId: ElementId('clip'), + ); + final trimmed = await invoke('timeline.trim', 'trim-ui-translation', { + 'clipId': 'clip', + 'duration': {'numerator': '3', 'denominator': 1}, + 'leading': true, + }); + expect(trimmed.status, CommandStatus.succeeded); + final job = await session.subtitleWorkflows.start( + sequence: sequence, + command: const StartTranscription( + mediaId: 'source', + clipId: 'clip', + language: 'ja', + ), + name: 'Speech', + targetLanguage: 'zh', + ); + backend.gate.complete(); + for (var i = 0; i < 200 && !job.terminal; i++) { + await Future.delayed(const Duration(milliseconds: 10)); + } + expect(job.status, TranscriptionStatus.succeeded); + expect(job.recognition.sourceStartMs, 1000); + expect( + job.translation!.command.source, + job.recognition.result!.subtitles.toFilePath(), + ); + }); + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + home: Scaffold(body: BackgroundTasksDialog(session: session)), + ), + ), + ); + await tester.tap(find.text('Speech')); + await tester.pumpAndSettle(); + await tester.ensureVisible(find.text('应用翻译字幕')); + await tester.runAsync(() async { + await tester.tap(find.text('应用翻译字幕')); + await session.flush(); + }); + await tester.pumpAndSettle(); + final dto = session.persistence.timeline(sequence).exportDto(); + final captionElement = dto.elements.singleWhere( + (e) => + e.payloadRef != null && + session.payloadFor(e.payloadRef!)?.type == 'caption', + ); + expect(session.caption(sequence, captionElement.id.value).text, '你好'); + final query = session.persistence.timeline(sequence).current.query(); + expect( + query.absoluteStart(query.elementById(captionElement.id)!) - + query.absoluteStart(query.elementById(ElementId('clip'))!), + 200 * TimelineClock.ticksPerSecond ~/ 1000, + ); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.runAsync(session.flush); + }, + ); + + testWidgets('MCP updates the background task panel', (tester) async { + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + home: Scaffold(body: BackgroundTasksDialog(session: session)), + ), + ), + ); + final access = EditorToolAccess(session); + addTearDown(access.dispose); + final connection = access.server.connect(); + addTearDown(connection.close); + final response = await tester.runAsync( + () => connection.handleJson( + jsonEncode({ + 'jsonrpc': '2.0', + 'id': 1, + 'method': 'tools/call', + 'params': { + '_meta': { + 'io.modelcontextprotocol/protocolVersion': '2026-07-28', + 'io.modelcontextprotocol/clientCapabilities': {}, + }, + 'name': 'media.transcribe', + 'arguments': { + 'workspaceId': access.workspaces.keys.single, + 'operationId': 'mcp-start', + ...args(), + }, + }, + }), + ), + ); + expect(response.toString(), contains('taskId')); + await tester.runAsync(() => backend.started.future); + await tester.pump(); + expect(find.textContaining('正在识别…'), findsOneWidget); + expect(find.text('测试字幕'), findsNothing); + await tester.tap(find.text('source')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 300)); + expect(find.text('已识别 1 条'), findsOneWidget); + expect(find.text('测试字幕'), findsOneWidget); + expect(session.transcriptions!.tasks, hasLength(1)); + await tester.runAsync(() async { + final completed = Completer(); + void onTaskUpdated() { + if (session.transcriptions!.tasks.single.terminal && + !completed.isCompleted) { + completed.complete(); + } + } + + // Terminal status is assigned before persistence and the final UI notice. + session.addListener(onTaskUpdated); + try { + backend.gate.complete(); + await completed.future.timeout(const Duration(seconds: 20)); + } finally { + session.removeListener(onTaskUpdated); + } + }); + await tester.pump(); + expect(find.text('字幕已生成'), findsOneWidget); + expect(find.text('1 条字幕'), findsOneWidget); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + testWidgets('background task panel displays the concrete failure code', ( + tester, + ) async { + backend.fail = true; + backend.gate.complete(); + await tester.runAsync(() async { + await invoke('media.transcribe', 'failed-dialog', args()); + await settle(session); + }); + await tester.pumpWidget( + ProviderScope( + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + + home: Scaffold(body: BackgroundTasksDialog(session: session)), + ), + ), + ); + expect(find.text('失败'), findsOneWidget); + expect(find.textContaining('processingFailed'), findsNothing); + await tester.tap(find.text('source')); + await tester.pumpAndSettle(); + expect(find.text('识别失败:原生识别处理失败(processingFailed)'), findsOneWidget); + await tester.pumpWidget(const SizedBox.shrink()); + }); + + final config = ProcessingConfiguration.configured(); + test('configured M2M100 model exposes subtitle translation', () { + expect(config, isNotNull); + expect(config!.translationModel, isNotNull); + expect( + File.fromUri(config.translationModel!.resolve('model.bin')).existsSync(), + isTrue, + ); + }, skip: config?.translationModel == null); + final fixture = Platform.environment['CUTDEX_ASR_FIXTURE']; + test('real Whisper Turbo through editor tools produces files and an editable track', () async { + await session.close(); + session = EditorTimelineSession( + document: await project.loadTimeline('p'), + persistence: await project.openTimelineSaveSession('p'), + media: Media(Uri.file(fixture!)), + transcriptionBackend: config!.backend, + transcriptionModel: config.transcriptionModel!, + translationBackend: config.translationModel == null + ? null + : config.backend, + translationModel: config.translationModel, + ); + final result = await invoke('media.transcribe', 'real', { + 'mediaId': 'source', + 'language': 'auto', + }); + expect(result.status, CommandStatus.succeeded); + for ( + var i = 0; + i < 6000 && session.transcriptions!.tasks.any((t) => !t.terminal); + i++ + ) { + await Future.delayed(const Duration(milliseconds: 20)); + } + final task = session.transcriptions!.tasks.single; + expect(task.status, TranscriptionStatus.succeeded, reason: task.error); + expect(task.result!.cues, isNotEmpty); + expect( + await File.fromUri(task.result!.srt).readAsString(), + contains(task.result!.cues.first.text), + ); + final transcript = jsonDecode( + await File.fromUri(task.result!.transcript).readAsString(), + ) as Map; + expect(transcript['sourcePath'], fixture); + expect(transcript['audioStream'], 0); + expect(transcript['sourceStartMs'], 0); + await project.saveAsset( + AssetDocument( + id: 'source', + name: 'Speech', + storage: AssetStorage.external, + location: Uri.file(fixture).toString(), + ), + ); + session.insertAsset( + sequenceId: sequence, + assetId: 'source', + assetName: 'Speech', + uri: Uri.file(fixture), + duration: RationalTime.seconds(5), + position: 0, + kind: 'audio', + hasAudio: true, + clipId: ElementId('real-clip'), + ); + final applied = await invoke('transcription.apply', 'real-apply', { + 'taskId': task.id, + 'clipId': 'real-clip', + }); + expect(applied.status, CommandStatus.succeeded, reason: applied.message); + final ids = (applied.data['captionIds'] as List).cast(); + expect(ids, hasLength(task.result!.cues.length)); + final id = ids.first; + expect(session.caption(sequence, id).text, task.result!.cues.first.text); + if (config.translationModel != null) { + final translated = await invoke('subtitle.translate', 'real-translate', { + 'source': task.result!.subtitles.toFilePath(), + 'sourceLanguage': 'en', + 'targetLanguage': 'zh', + }); + expect(translated.status, CommandStatus.succeeded); + final translation = session.transcriptions!.translationTask( + translated.data['taskId'] as String, + ); + for (var i = 0; i < 3000 && !translation.terminal; i++) { + await Future.delayed(const Duration(milliseconds: 10)); + } + expect( + translation.status, + TranscriptionStatus.succeeded, + reason: translation.error, + ); + expect(translation.result!.document.cues, isNotEmpty); + final appliedTranslation = await invoke( + 'subtitleTranslation.apply', + 'real-apply-translation', + { + 'taskId': translation.id, + 'clipId': 'real-clip', + 'source': fixture, + 'audioStream': 0, + 'sourceStartMs': 0, + }, + ); + expect( + appliedTranslation.status, + CommandStatus.succeeded, + reason: appliedTranslation.message, + ); + final translatedId = + (appliedTranslation.data['captionIds'] as List).first as String; + expect( + session.caption(sequence, translatedId).text, + translation.result!.document.cues.first.text, + ); + } + await session.flush(); + }, skip: config?.transcriptionModel == null || fixture == null); +} + +final class _LocalDownloadHttpOverrides extends HttpOverrides {} diff --git a/test/view_settings_test.dart b/test/view_settings_test.dart new file mode 100644 index 0000000..c83ebed --- /dev/null +++ b/test/view_settings_test.dart @@ -0,0 +1,145 @@ +import 'dart:async'; + +import 'package:cutdex/persistence/app_settings_repositories.dart'; +import 'package:cutdex/workspace/view_settings.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +class _WorkspaceRepository implements WorkspaceViewSettingsRepository { + WorkspaceViewSettingsData value = const WorkspaceViewSettingsData(); + final writes = []; + Completer? gate; + bool failWrites = false; + + @override + Future load() async => value; + + @override + Future save(WorkspaceViewSettingsData settings) async { + writes.add(settings); + await gate?.future; + if (failWrites) throw StateError('write failed'); + value = settings; + } +} + +class _ProjectRepository implements ProjectViewSettingsRepository { + final values = {}; + final writes = []; + bool failLoads = false; + + @override + Future load(String projectId) async { + if (failLoads) throw StateError('unavailable'); + return values[projectId] ?? const ProjectViewSettingsData(); + } + + @override + Future save(String projectId, ProjectViewSettingsData settings) async { + writes.add(projectId); + values[projectId] = settings; + } +} + +void main() { + test( + 'workspace saves remain ordered while a previous write is pending', + () async { + final repository = _WorkspaceRepository()..gate = Completer(); + final container = ProviderContainer.test( + overrides: [ + workspaceViewSettingsRepositoryProvider.overrideWithValue(repository), + ], + ); + await container.read(workspaceViewSettingsProvider.future); + final controller = container.read(workspaceViewSettingsProvider.notifier); + controller.setSidebarWidth(220); + final first = controller.save(activeProjectId: 'first'); + controller.setSidebarWidth(300); + final second = controller.save(activeProjectId: 'second'); + await Future.delayed(Duration.zero); + expect(repository.writes, hasLength(1)); + expect(repository.writes.single.sidebarWidth, 220); + expect( + container.read(workspaceViewSettingsProvider).requireValue.sidebarWidth, + 300, + ); + repository.gate!.complete(); + await Future.wait([first, second]); + expect(repository.writes.map((value) => value.activeProjectId), [ + 'first', + 'second', + ]); + expect(repository.value.sidebarWidth, 300); + }, + ); + + test( + 'workspace can clear the active project and save after a failed write', + () async { + final repository = _WorkspaceRepository(); + final container = ProviderContainer.test( + overrides: [ + workspaceViewSettingsRepositoryProvider.overrideWithValue(repository), + ], + ); + await container.read(workspaceViewSettingsProvider.future); + final controller = container.read(workspaceViewSettingsProvider.notifier); + await controller.save(activeProjectId: 'project'); + repository.failWrites = true; + await expectLater( + controller.save(activeProjectId: null), + throwsStateError, + ); + repository.failWrites = false; + await controller.save(activeProjectId: null); + expect(repository.value.activeProjectId, isNull); + }, + ); + + test( + 'project view settings survive subscription changes and stay isolated', + () async { + final repository = _ProjectRepository(); + final container = ProviderContainer.test( + overrides: [ + projectViewSettingsRepositoryProvider.overrideWithValue(repository), + ], + ); + final firstProvider = projectViewSettingsProvider('first'); + final subscription = container.listen(firstProvider, (_, _) {}); + await container.read(firstProvider.future); + final first = container.read(firstProvider.notifier); + first.setPropertiesOpen(true); + first.setTimelineHeight(240); + await first.save(); + subscription.close(); + await container.pump(); + expect(container.read(firstProvider).requireValue.propertiesOpen, isTrue); + expect( + await container.read(projectViewSettingsProvider('second').future), + const ProjectViewSettingsData(), + ); + final restored = ProviderContainer.test( + overrides: [ + projectViewSettingsRepositoryProvider.overrideWithValue(repository), + ], + ); + expect((await restored.read(firstProvider.future)).timelineHeight, 240); + expect(repository.writes, ['first']); + }, + ); + + test('unavailable project preferences do not prevent editing', () async { + final repository = _ProjectRepository()..failLoads = true; + final container = ProviderContainer.test( + overrides: [ + projectViewSettingsRepositoryProvider.overrideWithValue(repository), + ], + ); + expect( + await container.read(projectViewSettingsProvider('project').future), + const ProjectViewSettingsData(), + ); + }); +} diff --git a/test/widget_test.dart b/test/widget_test.dart new file mode 100644 index 0000000..2a4d31b --- /dev/null +++ b/test/widget_test.dart @@ -0,0 +1,2216 @@ +import 'package:cutdex/workspace/workspace_mode.dart'; +import 'package:cutdex/app/editor_theme.dart'; +import 'package:cutdex/integrations/platform/device_experience.dart'; + +import 'support/empty_conversation_repository.dart'; + +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex/persistence/app_settings_repositories.dart'; + +import 'dart:async'; +import 'dart:io'; + +import 'package:cutdex/features/timeline/timeline_panel.dart'; +import 'package:cutdex/features/preview/preview_panel.dart'; +import 'package:cutdex/features/properties/properties_panel.dart'; +import 'package:cutdex/features/media/media_panel.dart'; +import 'package:cutdex/features/assistant/agent_chat_panel.dart'; +import 'package:cutdex/features/editor/editor_page.dart'; +import 'package:cutdex_ui/theme.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/services.dart'; +import 'package:cutdex/workspace/projects.dart'; +import 'package:cutdex/workspace/project_state.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex/app/app.dart'; +import 'package:cutdex/app/router/app_router.dart'; +import 'package:cutdex/integrations/agent/conversation_repository.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +Future _hoverProjectHeader(WidgetTester tester) async { + final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse); + await mouse.addPointer(location: Offset.zero); + await mouse.moveTo( + tester.getCenter(find.byKey(const Key('projects-heading'))), + ); + await tester.pumpAndSettle(); + addTearDown(mouse.removePointer); +} + +void main() { + testWidgets('workspace stays hidden while startup data loads', ( + tester, + ) async { + tester.view.physicalSize = const Size(1200, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + await tester.pumpWidget( + ProviderScope( + overrides: [ + deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop), + conversationRepositoryProvider.overrideWith( + (ref) async => EmptyConversationRepository(), + ), + projectsProvider.overrideWith(_LoadingProjects.new), + ], + child: const CutdexApp(), + ), + ); + await tester.pump(); + expect(find.byKey(const Key('projects-window-header')), findsNothing); + expect(find.byKey(const Key('project-sidebar-separator')), findsNothing); + expect(find.byType(EditorWorkspace), findsNothing); + expect(find.text('CUTDEX'), findsOneWidget); + expect(find.text('Opening workspace…'), findsOneWidget); + expect(find.byType(CircularProgressIndicator), findsNothing); + expect(find.byType(FadeTransition), findsWidgets); + expect(find.text('No projects yet'), findsNothing); + }); + + testWidgets( + 'composer is available before selecting a project and keeps the draft', + (tester) async { + tester.view.physicalSize = const Size(1200, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + await tester.pumpWidget( + ProviderScope( + overrides: [ + deviceExperienceProvider.overrideWithValue( + DeviceExperience.desktop, + ), + projectsProvider.overrideWith(_UnselectedProjects.new), + conversationRepositoryProvider.overrideWith( + (ref) async => _GroupedConversationRepository({}), + ), + ], + child: const CutdexApp(), + ), + ); + await tester.pumpAndSettle(); + final input = find.descendant( + of: find.byKey(const Key('agent-composer')), + matching: find.byType(TextField), + ); + expect(input, findsOneWidget); + final projectBar = find.byKey(const Key('composer-project-bar')); + final composer = find.byKey(const Key('agent-composer')); + expect(tester.getSize(projectBar).height, 60); + expect( + tester.getRect(projectBar).left, + tester.getRect(composer).left + 13, + ); + expect( + tester.getRect(projectBar).right, + tester.getRect(composer).right - 13, + ); + expect(tester.getRect(projectBar).top + 38, tester.getRect(composer).top); + expect(find.text('Select project'), findsOneWidget); + await tester.enterText(input, 'Keep this before selecting'); + await tester.tap(find.byKey(const Key('composer-project-trigger'))); + await tester.pumpAndSettle(); + final search = find.byKey(const Key('composer-project-search')); + await tester.enterText(search, 'unmatched'); + await tester.pumpAndSettle(); + expect(find.text('No matching projects'), findsOneWidget); + expect(find.byKey(const Key('composer-new-project')), findsOneWidget); + await tester.enterText(search, '测试'); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const ValueKey('composer-project-project'))); + await tester.pumpAndSettle(); + expect(search, findsNothing); + expect( + tester.widget(input).controller!.text, + 'Keep this before selecting', + ); + expect(find.text('Select project'), findsNothing); + await tester.tap(find.byKey(const Key('composer-project-trigger'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('composer-new-project'))); + await tester.pumpAndSettle(); + expect(search, findsNothing); + expect(find.byKey(const Key('app-dialog-frame')), findsOneWidget); + await tester.tap(find.text('Cancel')); + await tester.pumpAndSettle(); + expect( + tester.widget(input).controller!.text, + 'Keep this before selecting', + ); + }, + ); + + testWidgets('project selection coalesces clicks and ignores stale loads', ( + tester, + ) async { + tester.view.physicalSize = const Size(1200, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final projects = _DelayedProjects(); + await tester.pumpWidget( + ProviderScope( + overrides: [ + deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop), + projectsProvider.overrideWith(() => projects), + conversationRepositoryProvider.overrideWith( + (ref) async => _GroupedConversationRepository({}), + ), + ], + child: const CutdexApp(), + ), + ); + await tester.pumpAndSettle(); + bool selected(String id) => tester + .widget(find.byKey(ValueKey('sidebar-project-$id'))) + .selected; + Future click(String id) async { + await tester.tap(find.byKey(ValueKey('sidebar-project-$id'))); + await tester.pump(); + } + + await click('other'); + expect(selected('other'), isTrue); + expect(projects.requests, isEmpty); + expect(find.byKey(const Key('editor-project-loading')), findsNothing); + await tester.pump(const Duration(milliseconds: 40)); + await click('third'); + await click('third'); + await tester.pump(const Duration(milliseconds: 100)); + expect(projects.requests.map((r) => r.$1), ['third']); + expect(selected('third'), isTrue); + expect(find.byKey(const Key('editor-project-loading')), findsNothing); + await tester.pump(const Duration(milliseconds: 70)); + expect(find.byKey(const Key('editor-project-loading')), findsOneWidget); + await click('other'); + expect(selected('other'), isTrue); + projects.requests.first.$2.complete(true); + await tester.pump(); + expect(projects.state.requireValue.activeProject?.id, 'project'); + await tester.pump(const Duration(milliseconds: 100)); + expect(projects.requests.map((r) => r.$1), ['third', 'other']); + projects.requests.last.$2.complete(false); + await tester.pumpAndSettle(); + expect(selected('project'), isTrue); + expect(find.byKey(const Key('editor-project-loading')), findsNothing); + await click('other'); + await tester.pump(const Duration(milliseconds: 100)); + projects.requests.last.$2.complete(true); + await tester.pumpAndSettle(); + expect(selected('other'), isTrue); + expect(projects.requests.length, 3); + await click('other'); + await tester.pumpAndSettle(); + expect(projects.requests.length, 3); + }); + + testWidgets('busy operations keep sidebar and timeline controls visible', ( + tester, + ) async { + tester.view.physicalSize = const Size(1200, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + await tester.pumpWidget( + ProviderScope( + overrides: [ + deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop), + conversationRepositoryProvider.overrideWith( + (ref) async => EmptyConversationRepository(), + ), + projectsProvider.overrideWith(_BusyProjects.new), + ], + child: const CutdexApp(), + ), + ); + await tester.pumpAndSettle(); + expect( + tester + .widget(find.byKey(const Key('create-project'))) + .onPressed, + isNotNull, + ); + expect( + tester + .widget( + find.byKey(const ValueKey('sidebar-project-project')), + ) + .enabled, + isTrue, + ); + expect(find.byKey(const Key('projects-heading')), findsOneWidget); + final addTimeline = find.byKey(const Key('timeline-add-button')); + expect(tester.widget(addTimeline).onPressed, isNotNull); + expect( + find.descendant(of: addTimeline, matching: find.byIcon(Icons.add)), + findsOneWidget, + ); + expect( + tester + .widget( + find.byKey(const ValueKey('timeline-tab-project')), + ) + .onPressed, + isNotNull, + ); + }); + + testWidgets('new conversation remains an in-memory draft', (tester) async { + tester.view.physicalSize = const Size(1200, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final root = (await tester.runAsync( + () => Directory.systemTemp.createTemp('cutdex-chat-ui-'), + ))!; + addTearDown(() => root.delete(recursive: true)); + final repository = _EmptyConversationRepository( + Directory('${root.path}/Conversations'), + ); + final container = ProviderContainer( + overrides: [ + deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop), + projectsProvider.overrideWith(_TestProjects.new), + conversationRepositoryProvider.overrideWith((ref) async => repository), + ], + // This project fixture has no persistence session to reopen on retry. + retry: (_, _) => null, + ); + addTearDown(container.dispose); + await tester.pumpWidget( + UncontrolledProviderScope(container: container, child: const CutdexApp()), + ); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('projects-heading'))); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('project-popover')), findsNothing); + final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse); + await mouse.addPointer(location: Offset.zero); + await mouse.moveTo( + tester.getCenter(find.byKey(const ValueKey('sidebar-project-project'))), + ); + await tester.pumpAndSettle(); + await tester.tap( + find.byKey(const ValueKey('new-agent-conversation-project')), + ); + await mouse.removePointer(); + await tester.pumpAndSettle(); + expect(await tester.runAsync(repository.root.exists), isFalse); + }); + + testWidgets('sidebar mode is saved and restored after rebuilding the app', ( + tester, + ) async { + tester.view.physicalSize = const Size(1200, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final settings = _MemoryWorkspaceViewSettings(); + Future launch() async { + await tester.pumpWidget( + ProviderScope( + key: UniqueKey(), + overrides: [ + deviceExperienceProvider.overrideWithValue( + DeviceExperience.desktop, + ), + projectsProvider.overrideWith(_TestProjects.new), + workspaceViewSettingsRepositoryProvider.overrideWithValue(settings), + conversationRepositoryProvider.overrideWith( + (ref) async => _GroupedConversationRepository({}), + ), + ], + child: const CutdexApp(), + ), + ); + await tester.pumpAndSettle(); + } + + Future switchMode(String name) async { + await tester.tap(find.byKey(const Key('sidebar-mode-trigger'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(ValueKey('sidebar-mode-$name'))); + await tester.pumpAndSettle(); + } + + await launch(); + expect(find.byKey(const Key('agent-mode-layout')), findsOneWidget); + await switchMode('cut'); + expect(settings.value.mode, WorkspaceMode.cut); + await tester.pumpWidget(const SizedBox()); + await launch(); + expect(find.byKey(const Key('cut-mode-layout')), findsOneWidget); + await switchMode('agent'); + expect(settings.value.mode, WorkspaceMode.agent); + await tester.pumpWidget(const SizedBox()); + await launch(); + expect(find.byKey(const Key('agent-mode-layout')), findsOneWidget); + }); + + testWidgets('sidebar mode defaults to Agent and can select Cut', ( + tester, + ) async { + tester.view.physicalSize = const Size(1200, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + await tester.pumpWidget( + ProviderScope( + overrides: [ + deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop), + conversationRepositoryProvider.overrideWith( + (ref) async => EmptyConversationRepository(), + ), + projectsProvider.overrideWith(_TestProjects.new), + ], + child: const CutdexApp(), + ), + ); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('agent-mode-layout')), findsOneWidget); + Color chatSurface() => tester + .element(find.byKey(const Key('agent-conversation'))) + .findAncestorWidgetOfExactType()! + .color!; + ColorScheme chatColors() => + Theme.of(tester.element(find.byKey(const Key('agent-conversation')))) + .colorScheme; + expect( + tester + .widget(find.byKey(const Key('agent-conversation'))) + .child, + isNot(isA()), + ); + expect(chatSurface(), chatColors().surface); + final projectTitle = find.byKey(const Key('workspace-project-title')); + final titlePosition = tester.getTopLeft(projectTitle); + expect( + find.descendant( + of: find.byKey(const Key('agent-content-header')), + matching: projectTitle, + ), + findsOneWidget, + ); + final chatElement = tester.element(find.byType(AgentChatPanel)); + final editorElement = tester.element(find.byType(EditorWorkspace)); + final input = find.descendant( + of: find.byType(AgentChatPanel), + matching: find.byType(TextField), + ); + await tester.enterText(input, 'Keep this draft'); + final trigger = find.byKey(const Key('sidebar-mode-trigger')); + final modeButton = tester.widget(trigger); + expect(modeButton.style!.backgroundColor!.resolve({}), Colors.transparent); + expect( + modeButton.style!.backgroundColor!.resolve({WidgetState.hovered}), + isNot(Colors.transparent), + ); + expect(tester.getSize(trigger).width, lessThan(160)); + expect( + tester.getSize(find.byKey(const Key('projects-window-header'))).height, + AppControlSize.headerButton, + ); + expect( + find.descendant(of: trigger, matching: find.text('Agent')), + findsOneWidget, + ); + await tester.tap(trigger); + await tester.pumpAndSettle(); + final modeStrings = AppLocalizations.of(tester.element(trigger))!; + expect(find.text(modeStrings.agentLayoutDescription), findsOneWidget); + expect(find.text(modeStrings.editingLayoutDescription), findsOneWidget); + expect( + tester.getSize(find.byKey(const ValueKey('sidebar-mode-cut'))).height, + 56, + ); + + await tester.tap(find.byKey(const ValueKey('sidebar-mode-cut'))); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('cut-mode-layout')), findsOneWidget); + expect(chatSurface(), chatColors().surfaceContainerLow); + expect(tester.getTopLeft(projectTitle), titlePosition); + expect( + find.descendant( + of: find.byKey(const Key('editor-content-header')), + matching: projectTitle, + ), + findsOneWidget, + ); + expect( + find.byKey(const Key('sidebar-projects-conversations')), + findsNothing, + ); + expect(tester.element(find.byType(AgentChatPanel)), same(chatElement)); + expect(tester.element(find.byType(EditorWorkspace)), same(editorElement)); + expect(tester.widget(input).controller!.text, 'Keep this draft'); + await tester.tap(find.byKey(const Key('cut-projects-trigger'))); + await tester.pumpAndSettle(); + expect( + find.byKey(const Key('sidebar-projects-conversations')), + findsOneWidget, + ); + await tester.tap(find.byKey(const ValueKey('sidebar-project-project'))); + await tester.pumpAndSettle(); + expect( + find.byKey(const Key('sidebar-projects-conversations')), + findsNothing, + ); + expect( + find.descendant(of: trigger, matching: find.text('Cut')), + findsOneWidget, + ); + await tester.tap(trigger); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const ValueKey('sidebar-mode-agent'))); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('agent-mode-layout')), findsOneWidget); + expect(tester.element(find.byType(AgentChatPanel)), same(chatElement)); + expect(tester.element(find.byType(EditorWorkspace)), same(editorElement)); + expect(tester.widget(input).controller!.text, 'Keep this draft'); + }); + + testWidgets('Agent right edge resizes independently and respects limits', ( + tester, + ) async { + tester.view.physicalSize = const Size(1200, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + await tester.pumpWidget( + ProviderScope( + overrides: [ + deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop), + conversationRepositoryProvider.overrideWith( + (ref) async => EmptyConversationRepository(), + ), + projectsProvider.overrideWith(_TestProjects.new), + ], + child: const CutdexApp(), + ), + ); + await tester.pumpAndSettle(); + final navigation = find.byKey(const Key('sidebar-projects-conversations')); + final resize = find.byKey(const Key('agent-panel-resize')); + final navigationWidth = tester.getSize(navigation).width; + final chatWidth = tester.getSize(find.byType(AgentChatPanel)).width; + final chatElement = tester.element(find.byType(AgentChatPanel)); + await tester.drag(resize, const Offset(80, 0)); + await tester.pumpAndSettle(); + expect(tester.getSize(find.byType(AgentChatPanel)).width, chatWidth + 80); + expect(tester.getSize(navigation).width, navigationWidth); + expect(tester.element(find.byType(AgentChatPanel)), same(chatElement)); + await tester.drag(resize, const Offset(-2000, 0)); + await tester.pumpAndSettle(); + expect( + tester.getSize(find.byType(AgentChatPanel)).width, + greaterThanOrEqualTo(219), + ); + await tester.drag(resize, const Offset(2000, 0)); + await tester.pumpAndSettle(); + expect(find.byType(EditorWorkspace), findsNothing); + expect(tester.getSize(navigation).width, navigationWidth); + expect(tester.takeException(), isNull); + }); + + testWidgets('Agent buffers collapse by one third and restores at 560', ( + tester, + ) async { + tester.view.physicalSize = const Size(1200, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + await tester.pumpWidget( + ProviderScope( + overrides: [ + deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop), + conversationRepositoryProvider.overrideWith( + (ref) async => EmptyConversationRepository(), + ), + projectsProvider.overrideWith(_TestProjects.new), + ], + child: const CutdexApp(), + ), + ); + await tester.pumpAndSettle(); + final editor = tester.element(find.byType(EditorWorkspace)); + final resize = find.byKey(const Key('agent-panel-resize')); + await tester.drag(resize, const Offset(159, 0)); + await tester.pumpAndSettle(); + expect(tester.getSize(find.byType(EditorWorkspace)).width, 480); + final drag = await tester.startGesture(tester.getCenter(resize)); + await drag.moveBy(const Offset(159, 0)); + await tester.pumpAndSettle(); + expect(tester.getSize(find.byType(EditorWorkspace)).width, 480); + await drag.moveBy(const Offset(1, 0)); + await drag.up(); + await tester.pumpAndSettle(); + expect(find.byType(EditorWorkspace), findsNothing); + expect( + tester.element(find.byType(EditorWorkspace, skipOffstage: false)), + same(editor), + ); + await tester.drag(resize, const Offset(-560, 0)); + await tester.pumpAndSettle(); + expect(find.byType(EditorWorkspace), findsNothing); + await tester.drag(resize, const Offset(-561, 0)); + await tester.pumpAndSettle(); + expect(tester.getSize(find.byType(EditorWorkspace)).width, 560); + expect(tester.element(find.byType(EditorWorkspace)), same(editor)); + await tester.drag(resize, const Offset(2000, 0)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('expand-editor-button'))); + await tester.pumpAndSettle(); + expect(tester.getSize(find.byType(EditorWorkspace)).width, 560); + expect(tester.element(find.byType(EditorWorkspace)), same(editor)); + expect(find.byKey(const Key('expand-editor-button')), findsNothing); + expect(tester.takeException(), isNull); + }); + + testWidgets('expand editor collapses project sidebar when space is limited', ( + tester, + ) async { + tester.view.physicalSize = const Size(1000, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + await tester.pumpWidget( + ProviderScope( + overrides: [ + deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop), + conversationRepositoryProvider.overrideWith( + (ref) async => EmptyConversationRepository(), + ), + projectsProvider.overrideWith(_TestProjects.new), + ], + child: const CutdexApp(), + ), + ); + await tester.pumpAndSettle(); + final chat = tester.element(find.byType(AgentChatPanel)); + await tester.drag( + find.byKey(const Key('agent-panel-resize')), + const Offset(2000, 0), + ); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('expand-editor-button'))); + await tester.pumpAndSettle(); + expect( + find.byKey(const Key('sidebar-projects-conversations')), + findsNothing, + ); + expect(tester.getSize(find.byType(EditorWorkspace)).width, 561); + expect(tester.element(find.byType(AgentChatPanel)), same(chat)); + expect(tester.takeException(), isNull); + }); + + testWidgets('sidebar groups conversations under projects', (tester) async { + tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark; + addTearDown(tester.platformDispatcher.clearPlatformBrightnessTestValue); + tester.view.physicalSize = const Size(1200, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + ConversationMetadata conversation(String projectId, int index) => + ConversationMetadata( + id: '$projectId-$index', + projectId: projectId, + title: 'Conversation $index', + createdAt: DateTime.utc(2026, 9, 24), + updatedAt: DateTime.utc(2026, 9, 24), + providerId: 'provider', + modelId: 'model', + timelineId: projectId, + pending: false, + responseDurationsMs: const [], + ); + final repository = _GroupedConversationRepository({ + 'project': [for (var i = 1; i <= 7; i++) conversation('project', i)], + 'other': [conversation('other', 1)], + }); + await tester.pumpWidget( + ProviderScope( + overrides: [ + deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop), + projectsProvider.overrideWith(_GroupedProjects.new), + conversationRepositoryProvider.overrideWith( + (ref) async => repository, + ), + ], + child: const CutdexApp(), + ), + ); + await tester.pumpAndSettle(); + expect( + find.byKey(const ValueKey('sidebar-project-project')), + findsOneWidget, + ); + expect(find.byKey(const ValueKey('sidebar-project-other')), findsOneWidget); + expect( + find.byKey(const ValueKey('sidebar-conversation-project-1')), + findsOneWidget, + ); + expect( + find.byKey(const ValueKey('sidebar-conversation-project-6')), + findsNothing, + ); + expect( + find.byKey(const ValueKey('sidebar-conversation-other-1')), + findsOneWidget, + ); + final projectRow = find.byKey(const ValueKey('sidebar-project-project')); + final chatRow = find.byKey( + const ValueKey('sidebar-conversation-project-1'), + ); + expect(tester.getSize(projectRow).height, 30); + expect(tester.getSize(chatRow).height, 30); + final selectedProjectTile = tester.widget(projectRow); + expect(selectedProjectTile.selected, isTrue); + expect( + selectedProjectTile.hoverColor, + AppSidebarColors.of(tester.element(projectRow)).hover, + ); + expect( + selectedProjectTile.focusColor, + AppSidebarColors.of(tester.element(projectRow)).hover, + ); + final modeButton = find.byKey(const Key('sidebar-mode-trigger')); + expect( + tester.getTopLeft(modeButton).dy, + tester.getBottomLeft(find.byKey(const Key('projects-window-header'))).dy, + ); + expect( + tester.getTopLeft(find.byKey(const Key('projects-heading'))).dy - + tester.getBottomLeft(modeButton).dy, + 4, + ); + final conversationText = tester.widget( + find.descendant(of: chatRow, matching: find.text('Conversation 1')), + ); + expect(conversationText.style?.fontSize, 14); + expect(conversationText.style?.height, closeTo(20 / 14, 0.001)); + expect(conversationText.style?.fontVariations, const [ + FontVariation('wght', 430), + ]); + expect( + conversationText.style?.color, + const Color(0xFFFCFCFC).withValues(alpha: 0.85), + ); + expect( + tester + .getTopLeft( + find.byKey(const ValueKey('sidebar-conversation-project-2')), + ) + .dy - + tester.getTopLeft(chatRow).dy, + 31, + ); + expect(tester.getRect(chatRow).left, tester.getRect(projectRow).left); + expect(tester.getRect(chatRow).right, tester.getRect(projectRow).right); + expect( + tester + .getTopLeft( + find.descendant(of: chatRow, matching: find.text('Conversation 1')), + ) + .dx, + tester + .getTopLeft( + find.descendant(of: projectRow, matching: find.byType(Text)).first, + ) + .dx, + ); + await tester.tap(chatRow, buttons: kSecondaryMouseButton); + await tester.pumpAndSettle(); + await tester.tap(find.text('Rename')); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('app-dialog-frame')), findsOneWidget); + expect(find.text('Rename chat'), findsOneWidget); + expect(find.text('Keep it short and easy to recognize.'), findsOneWidget); + await tester.enterText(find.byType(TextFormField), 'Updated chat'); + await tester.tap(find.widgetWithText(FilledButton, 'Save')); + await tester.pumpAndSettle(); + expect(repository.groups['project']!.first.title, 'Updated chat'); + expect(find.text('Updated chat'), findsOneWidget); + await tester.tap(chatRow, buttons: kSecondaryMouseButton); + await tester.pumpAndSettle(); + await tester.tap(find.text('Delete permanently…')); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('app-dialog-frame')), findsOneWidget); + expect(find.textContaining('This cannot be undone.'), findsOneWidget); + await tester.tap(find.text('Cancel')); + await tester.pumpAndSettle(); + expect(chatRow, findsOneWidget); + await tester.tap( + find.byKey(const ValueKey('sidebar-project-toggle-project')), + ); + await tester.pumpAndSettle(); + expect(chatRow, findsNothing); + expect( + tester + .getTopLeft(find.byKey(const ValueKey('sidebar-project-other'))) + .dy - + tester.getBottomLeft(projectRow).dy, + 1, + ); + await tester.tap( + find.byKey(const ValueKey('sidebar-project-toggle-project')), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('Show more')); + await tester.pumpAndSettle(); + expect( + find.byKey(const ValueKey('sidebar-conversation-project-7')), + findsOneWidget, + ); + }); + + testWidgets( + 'empty project hint follows expansion and project menu offers removal', + (tester) async { + tester.view.physicalSize = const Size(1200, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + await tester.pumpWidget( + ProviderScope( + overrides: [ + deviceExperienceProvider.overrideWithValue( + DeviceExperience.desktop, + ), + projectsProvider.overrideWith(_GroupedProjects.new), + conversationRepositoryProvider.overrideWith( + (ref) async => _GroupedConversationRepository({}), + ), + ], + child: const CutdexApp(), + ), + ); + await tester.pumpAndSettle(); + final hint = find.byKey(const ValueKey('sidebar-project-empty-other')); + expect(hint, findsOneWidget); + await tester.tap( + find.byKey(const ValueKey('sidebar-project-toggle-other')), + ); + await tester.pumpAndSettle(); + expect(hint, findsNothing); + await tester.tap( + find.byKey(const ValueKey('sidebar-project-other')), + buttons: kSecondaryMouseButton, + ); + await tester.pumpAndSettle(); + expect(find.text('Remove from sidebar'), findsOneWidget); + }, + ); + + testWidgets('project header more is inert and project rows switch projects', ( + tester, + ) async { + tester.view.physicalSize = const Size(1200, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + await tester.pumpWidget( + ProviderScope( + overrides: [ + deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop), + conversationRepositoryProvider.overrideWith( + (ref) async => EmptyConversationRepository(), + ), + projectsProvider.overrideWith(_GroupedProjects.new), + ], + child: const CutdexApp(), + ), + ); + await tester.pumpAndSettle(); + final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse); + await mouse.addPointer(location: Offset.zero); + await mouse.moveTo( + tester.getCenter(find.byKey(const Key('projects-heading'))), + ); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('projects-more'))); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('project-popover')), findsNothing); + await tester.tap(find.byKey(const ValueKey('sidebar-project-other'))); + await tester.pumpAndSettle(); + expect( + tester + .widget(find.byKey(const ValueKey('sidebar-project-other'))) + .selected, + isTrue, + ); + await tester.tap(find.byKey(const ValueKey('sidebar-project-project'))); + await tester.pumpAndSettle(); + expect( + tester + .widget( + find.byKey(const ValueKey('sidebar-project-project')), + ) + .selected, + isTrue, + ); + await mouse.removePointer(); + }); + + test('dark workspace uses the configured panel palette', () { + final theme = EditorTheme.penDark; + expect(theme.colorScheme.surface, const Color(0xFF111111)); + expect(theme.colorScheme.surfaceContainerLow, const Color(0xFF151515)); + expect( + theme.colorScheme.outlineVariant, + const Color(0xFFFCFCFC).withValues(alpha: 0.084), + ); + expect( + theme.extension()!.composerBackground, + const Color(0xFF2F2F2F), + ); + expect( + theme.extension()!.popoverBackground, + const Color(0xFF242424), + ); + }); + + testWidgets('project context menu renames its item', (tester) async { + tester.platformDispatcher.localesTestValue = const [Locale('zh')]; + addTearDown(tester.platformDispatcher.clearLocalesTestValue); + tester.view.physicalSize = const Size(1200, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final container = ProviderContainer( + overrides: [ + deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop), + conversationRepositoryProvider.overrideWith( + (ref) async => EmptyConversationRepository(), + ), + projectsProvider.overrideWith(_TestProjects.new), + ], + ); + addTearDown(container.dispose); + await tester.pumpWidget( + UncontrolledProviderScope(container: container, child: const CutdexApp()), + ); + await tester.pumpAndSettle(); + + Future rename(Finder target, String value) async { + await tester.tap(target, buttons: kSecondaryMouseButton); + await tester.pumpAndSettle(); + await tester.tap(find.text('重命名').last); + await tester.pumpAndSettle(); + await tester.enterText(find.byType(TextFormField), value); + await tester.tap(find.widgetWithText(FilledButton, '重命名')); + await tester.pumpAndSettle(); + } + + await rename( + find.byKey(const ValueKey('sidebar-project-project')), + '重命名项目', + ); + expect( + tester + .widget(find.byKey(const Key('workspace-project-title'))) + .data, + '重命名项目', + ); + }); + + testWidgets( + 'switching timelines preserves the project workspace and its layout', + (tester) async { + tester.platformDispatcher.localesTestValue = const [Locale('zh')]; + addTearDown(tester.platformDispatcher.clearLocalesTestValue); + tester.view.physicalSize = const Size(1440, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final container = ProviderContainer( + overrides: [ + deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop), + conversationRepositoryProvider.overrideWith( + (ref) async => EmptyConversationRepository(), + ), + projectsProvider.overrideWith(_SwitchProjects.new), + ], + ); + await tester.pumpWidget( + UncontrolledProviderScope( + container: container, + child: const CutdexApp(), + ), + ); + await tester.pumpAndSettle(); + expect( + find.byKey(const ValueKey('timeline-tab-project')), + findsOneWidget, + ); + expect( + tester.getSize(find.byKey(const Key('timeline-tabs-bar'))).height, + 26, + ); + expect( + find.descendant( + of: find.byKey(const Key('timeline-tabs-bar')), + matching: find.byType(VerticalDivider), + ), + findsNothing, + ); + expect( + find.descendant( + of: find.byKey(const Key('timeline-tabs-bar')), + matching: find.byType(ShaderMask), + ), + findsOneWidget, + ); + expect( + tester + .widget( + find.byKey(const ValueKey('timeline-tab-project')), + ) + .style! + .textStyle! + .resolve({})! + .fontSize, + 12, + ); + final projectTabFinder = find.byKey( + const ValueKey('timeline-tab-project'), + ); + final selectedInk = Theme.of(tester.element(projectTabFinder)) + .colorScheme + .onSurface; + expect( + tester + .widget(projectTabFinder) + .style! + .backgroundColor! + .resolve({}), + selectedInk.withValues(alpha: .05), + ); + expect(find.byKey(const ValueKey('timeline-tab-second')), findsOneWidget); + final tabs = find.byKey(const Key('timeline-tabs-list')); + final tabsScrollable = tester.state( + find.descendant(of: tabs, matching: find.byType(Scrollable)), + ); + expect(tabsScrollable.position.maxScrollExtent, greaterThan(0)); + await tester.sendEventToBinding( + PointerScrollEvent( + position: tester.getCenter(tabs), + scrollDelta: const Offset(0, 120), + ), + ); + await tester.pump(); + expect(tabsScrollable.position.pixels, greaterThan(0)); + tabsScrollable.position.jumpTo(0); + await tester.pump(); + await tester.tap(find.byKey(const Key('timeline-list-button'))); + await tester.pumpAndSettle(); + expect( + find.byKey(const ValueKey('timeline-menu-project')), + findsOneWidget, + ); + expect( + find.byKey(const ValueKey('timeline-menu-timeline-20')), + findsOneWidget, + ); + await tester.tap(find.byKey(const ValueKey('timeline-menu-timeline-3'))); + await tester.pumpAndSettle(); + expect( + tester + .widget(find.byType(EditorTimelinePanel)) + .timelineId, + 'timeline-3', + ); + final navigation = tester.element( + find.byKey(const Key('projects-heading')), + ); + final workspace = tester.element(find.byType(EditorWorkspace)); + await tester.tap(find.byKey(const Key('editor-media-button'))); + await tester.tap(find.byKey(const Key('editor-properties-button'))); + await tester.pumpAndSettle(); + final timelineListButton = find.byKey(const Key('timeline-list-button')); + await tester.tap(timelineListButton); + await tester.pumpAndSettle(); + final timelineMenuPanel = find.byWidgetPredicate( + (widget) => widget.runtimeType.toString() == '_MenuPanel', + ); + expect(timelineMenuPanel, findsOneWidget); + expect( + tester.getRect(timelineMenuPanel).right, + closeTo(tester.getRect(timelineListButton).right, 1), + ); + final menuRect = tester.getRect(timelineMenuPanel); + final buttonRect = tester.getRect(timelineListButton); + expect( + (menuRect.top - buttonRect.bottom - 4).abs() < 1 || + (menuRect.bottom - buttonRect.top + 4).abs() < 1, + isTrue, + ); + await tester.tap(timelineListButton); + await tester.pumpAndSettle(); + final editorHeader = tester.element( + find.byKey(const Key('editor-content-header')), + ); + final mediaPanel = tester.element(find.byType(MediaPanel)); + final propertiesPanel = tester.element( + find.byType(EditorPropertiesPanel), + ); + await tester.drag( + find.byKey(const Key('editor-timeline-resize')), + const Offset(0, -60), + ); + await tester.pumpAndSettle(); + final timelineHeight = tester + .getSize(find.byType(EditorTimelinePanel)) + .height; + final taskButtonFinder = find.byKey( + const ValueKey('background-tasks-button'), + ); + final taskButton = tester.element(taskButtonFinder); + expect(tester.widget(taskButtonFinder).onPressed, isNotNull); + for (final id in ['second', 'project', 'second']) { + final previousPreview = tester.element(find.byType(EditorPreviewPanel)); + final previousTimeline = tester.element( + find.byType(EditorTimelinePanel), + ); + await container + .read(projectsProvider.notifier) + .openTimeline('project', id); + await tester.pumpAndSettle(); + expect( + tester.element(find.byKey(const Key('projects-window-header'))), + isNotNull, + ); + expect( + tester.element(find.byKey(const Key('projects-heading'))), + same(navigation), + ); + expect(tester.element(find.byType(EditorWorkspace)), same(workspace)); + expect( + tester.element(find.byKey(const Key('editor-content-header'))), + same(editorHeader), + ); + expect( + tester.element(find.byType(EditorPreviewPanel)), + same(previousPreview), + ); + expect( + tester.element(find.byType(EditorTimelinePanel)), + same(previousTimeline), + ); + expect(tester.element(find.byType(MediaPanel)), same(mediaPanel)); + expect( + tester.element(find.byType(EditorPropertiesPanel)), + same(propertiesPanel), + ); + expect(tester.element(taskButtonFinder), same(taskButton)); + expect( + tester.widget(taskButtonFinder).onPressed, + isNotNull, + ); + expect(find.byKey(const Key('editor-media-region')), findsOneWidget); + expect( + find.byKey(const Key('editor-properties-region')), + findsOneWidget, + ); + expect( + tester.getSize(find.byType(EditorTimelinePanel)).height, + timelineHeight, + ); + expect( + tester + .widget(find.byType(EditorTimelinePanel)) + .timelineId, + id, + ); + expect( + tester + .widget(find.byKey(const Key('workspace-project-title'))) + .data, + '测试项目', + ); + expect( + tester + .widget(find.byKey(ValueKey('timeline-tab-$id'))) + .onPressed, + isNotNull, + ); + expect(tester.takeException(), isNull); + } + await tester.tap(find.byKey(const Key('timeline-list-button'))); + await tester.pumpAndSettle(); + await tester.ensureVisible( + find.byKey(const ValueKey('timeline-menu-timeline-20')), + ); + await tester.tap(find.byKey(const ValueKey('timeline-menu-timeline-20'))); + await tester.pumpAndSettle(); + final selectedTab = tester.getRect( + find.byKey(const ValueKey('timeline-tab-timeline-20')), + ); + final tabsViewport = tester.getRect(tabs); + expect(selectedTab.left, greaterThanOrEqualTo(tabsViewport.left)); + expect(selectedTab.right, lessThanOrEqualTo(tabsViewport.right)); + expect(tabsScrollable.position.pixels, greaterThan(0)); + await tester.tap(find.byKey(const Key('timeline-list-button'))); + await tester.pumpAndSettle(); + final selectedMenuItem = find.byKey( + const ValueKey('timeline-menu-timeline-20'), + ); + final menuScrollView = find + .ancestor( + of: selectedMenuItem, + matching: find.byType(SingleChildScrollView), + ) + .first; + expect( + tester.getRect(selectedMenuItem).bottom, + lessThanOrEqualTo(tester.getRect(menuScrollView).bottom), + ); + expect( + tester + .state( + find.descendant( + of: menuScrollView, + matching: find.byType(Scrollable), + ), + ) + .position + .pixels, + greaterThan(0), + ); + await tester.tap(find.byKey(const Key('timeline-list-button'))); + await tester.pumpAndSettle(); + final previousTabOffset = tabsScrollable.position.pixels; + await container + .read(projectsProvider.notifier) + .openTimeline('project', 'timeline-19'); + await tester.pumpAndSettle(); + expect(tabsScrollable.position.pixels, previousTabOffset); + final nearbyTab = tester.getRect( + find.byKey(const ValueKey('timeline-tab-timeline-19')), + ); + expect(nearbyTab.left, greaterThanOrEqualTo(tabsViewport.left)); + expect(nearbyTab.right, lessThanOrEqualTo(tabsViewport.right)); + await tester.pumpWidget(const SizedBox()); + container.dispose(); + }, + ); + + testWidgets('timeline tab context menu pins, renames, and deletes', ( + tester, + ) async { + tester.platformDispatcher.localesTestValue = const [Locale('zh')]; + addTearDown(tester.platformDispatcher.clearLocalesTestValue); + tester.view.physicalSize = const Size(1200, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final container = ProviderContainer( + overrides: [ + deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop), + conversationRepositoryProvider.overrideWith( + (ref) async => EmptyConversationRepository(), + ), + projectsProvider.overrideWith(_SwitchProjects.new), + ], + ); + addTearDown(container.dispose); + await tester.pumpWidget( + UncontrolledProviderScope(container: container, child: const CutdexApp()), + ); + await tester.pumpAndSettle(); + + Future openMenu() async { + await tester.tap( + find.byKey(const ValueKey('timeline-tab-second')), + buttons: kSecondaryMouseButton, + ); + await tester.pumpAndSettle(); + } + + await openMenu(); + await tester.tap(find.byKey(const ValueKey('timeline-pin-second'))); + await tester.pumpAndSettle(); + expect( + container.read(projectsProvider).requireValue.timelines.first.id, + 'second', + ); + expect( + container.read(projectsProvider).requireValue.timelines.first.pinned, + isTrue, + ); + + await openMenu(); + await tester.tap(find.byKey(const ValueKey('timeline-rename-second'))); + await tester.pumpAndSettle(); + await tester.enterText(find.byType(TextFormField), '已重命名时间线'); + await tester.tap(find.widgetWithText(FilledButton, '重命名')); + await tester.pumpAndSettle(); + expect( + container.read(projectsProvider).requireValue.timelines.first.name, + '已重命名时间线', + ); + + await openMenu(); + await tester.tap(find.byKey(const ValueKey('timeline-delete-second'))); + await tester.pumpAndSettle(); + expect(find.textContaining('已重命名时间线'), findsWidgets); + await tester.tap(find.widgetWithText(FilledButton, '删除')); + await tester.pumpAndSettle(); + expect( + container + .read(projectsProvider) + .requireValue + .timelines + .any((item) => item.id == 'second'), + isFalse, + ); + }); + + testWidgets('timeline limit is enforced and explained on click', ( + tester, + ) async { + tester.platformDispatcher.localesTestValue = const [Locale('zh')]; + addTearDown(tester.platformDispatcher.clearLocalesTestValue); + tester.view.physicalSize = const Size(1200, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final container = ProviderContainer( + overrides: [ + deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop), + conversationRepositoryProvider.overrideWith( + (ref) async => EmptyConversationRepository(), + ), + projectsProvider.overrideWith(_TimelineLimitProjects.new), + ], + ); + await tester.pumpWidget( + UncontrolledProviderScope(container: container, child: const CutdexApp()), + ); + await tester.pumpAndSettle(); + + expect( + container.read(projectsProvider).requireValue.timelines, + hasLength(Projects.maxTimelineCount), + ); + expect( + await container.read(projectsProvider.notifier).createTimeline(), + isFalse, + ); + final addButton = find.byKey(const Key('timeline-add-button')); + expect(tester.widget(addButton).onPressed, isNotNull); + await tester.tap(addButton); + await tester.pump(); + expect(find.text('每个项目最多可创建 50 条时间线。'), findsOneWidget); + + await tester.pumpWidget(const SizedBox()); + container.dispose(); + }); + + testWidgets('macOS single editing surface integrates native controls', ( + tester, + ) async { + tester.platformDispatcher.localesTestValue = const [Locale('zh')]; + addTearDown(tester.platformDispatcher.clearLocalesTestValue); + debugDefaultTargetPlatformOverride = TargetPlatform.macOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + tester.view.physicalSize = const Size(1200, 800); + tester.view.devicePixelRatio = 1; + tester.view.padding = const FakeViewPadding(top: 28); + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + addTearDown(tester.view.resetPadding); + const channel = MethodChannel('cutdex_native/window'); + final calls = []; + final closeModes = []; + const controlsChannel = MethodChannel('cutdex_native/window_controls'); + final controlRegions = {}; + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + messenger.setMockMethodCallHandler(channel, (call) async { + final enabled = (call.arguments as Map)['enabled'] as bool; + calls.add(enabled); + if (enabled) { + closeModes.add((call.arguments as Map)['interceptClose'] as bool); + } + return enabled; + }); + addTearDown(() => messenger.setMockMethodCallHandler(channel, null)); + messenger.setMockMethodCallHandler(controlsChannel, (call) async { + final arguments = call.arguments as Map; + final id = arguments['id'] as String; + final rect = arguments['rect'] as Map?; + if (rect == null) { + controlRegions.remove(id); + } else { + controlRegions[id] = Rect.fromLTWH( + (rect['x'] as num).toDouble(), + (rect['y'] as num).toDouble(), + (rect['width'] as num).toDouble(), + (rect['height'] as num).toDouble(), + ); + } + return null; + }); + addTearDown( + () => messenger.setMockMethodCallHandler(controlsChannel, null), + ); + await tester.pumpWidget( + ProviderScope( + overrides: [ + deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop), + conversationRepositoryProvider.overrideWith( + (ref) async => EmptyConversationRepository(), + ), + projectsProvider.overrideWith(_TestProjects.new), + ], + child: const CutdexApp(), + ), + ); + await tester.pumpAndSettle(); + expect( + tester.getTopLeft(find.byKey(const Key('projects-window-header'))).dy, + 0, + ); + expect( + tester.getTopLeft(find.byKey(const Key('sidebar-mode-trigger'))).dy, + AppControlSize.panelHeader, + ); + expect( + tester.getSize(find.byKey(const Key('native-window-controls-space'))), + const Size(88, AppControlSize.panelHeader), + ); + expect( + tester.getSize(find.byKey(const Key('project-sidebar-separator'))).width, + 1, + ); + final sidebarSeparator = tester.widget( + find.byKey(const Key('project-sidebar-separator')), + ); + expect( + sidebarSeparator.color, + Theme.of( + tester.element(find.byKey(const Key('project-sidebar-separator'))), + ).colorScheme.outlineVariant, + ); + expect( + tester.getSize(find.byKey(const Key('project-sidebar-separator'))).height, + tester.getSize(find.byType(EditorWorkspace)).height, + ); + final sidebarToggle = find.byKey(const Key('project-sidebar-toggle')); + expect( + tester.getRect(sidebarToggle).center.dy, + AppControlSize.panelHeader / 2, + ); + final projectSettings = find.byKey(const Key('project-settings-button')); + final backgroundTasks = find.byKey( + const ValueKey('background-tasks-button'), + ); + expect(projectSettings, findsOneWidget); + expect(backgroundTasks, findsOneWidget); + expect( + tester.getRect(sidebarToggle).right + AppSpacing.tiny, + tester.getRect(projectSettings).left, + ); + expect( + tester.getRect(projectSettings).center.dy, + AppControlSize.panelHeader / 2, + ); + expect(tester.getTopLeft(sidebarToggle).dx, 88); + await tester.tap(sidebarToggle); + await tester.pump(); + expect(find.byKey(const ValueKey('open-project-project')), findsNothing); + expect(find.byTooltip('展开侧边栏'), findsOneWidget); + expect(projectSettings, findsOneWidget); + expect(backgroundTasks, findsOneWidget); + final timelineTitle = find.byKey(const Key('workspace-project-title')); + expect( + tester.getRect(backgroundTasks).right + AppSpacing.compact, + lessThanOrEqualTo(tester.getRect(timelineTitle).left), + ); + expect( + tester.getTopLeft(find.byType(EditorPreviewPanel)).dx, + tester.getRect(find.byType(AgentChatPanel)).right, + ); + expect(sidebarToggle, findsOneWidget); + await tester.tap(sidebarToggle); + await tester.pump(); + expect(find.byKey(const Key('projects-heading')), findsOneWidget); + expect(find.byTooltip('收起侧边栏'), findsOneWidget); + await _hoverProjectHeader(tester); + await tester.tap(find.byKey(const Key('projects-more'))); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('project-popover')), findsNothing); + expect( + find.byKey(const ValueKey('sidebar-project-project')), + findsOneWidget, + ); + expect(find.byKey(const ValueKey('open-timeline-project')), findsNothing); + expect( + tester + .getSize(find.byKey(const ValueKey('sidebar-project-project'))) + .height, + 30, + ); + final projectTitle = tester.widget( + find.descendant( + of: find.byKey(const ValueKey('sidebar-project-project')), + matching: find.text('测试项目'), + ), + ); + expect(projectTitle.style?.fontSize, 14); + final projectRow = find.byKey(const ValueKey('sidebar-project-project')); + expect( + find.descendant(of: projectRow, matching: find.byIcon(Icons.add)), + findsNothing, + ); + expect(find.byKey(const Key('projects-section-header')), findsNothing); + expect(find.byKey(const Key('projects-more')), findsOneWidget); + expect( + tester.getSize(find.byKey(const Key('create-project'))), + const Size.square(24), + ); + expect( + tester.getRect(find.byKey(const Key('projects-heading'))).right + + AppSpacing.tiny, + tester.getRect(find.byKey(const Key('projects-more'))).left, + ); + expect( + find.descendant(of: projectRow, matching: find.byIcon(Icons.add)), + findsNothing, + ); + expect( + tester.getTopLeft(find.byKey(const Key('project-sidebar-resize'))).dx, + 256, + ); + expect( + tester.getTopLeft(find.byType(EditorPreviewPanel)).dy, + AppControlSize.panelHeader, + ); + expect(find.byKey(const Key('editor-content-header')), findsOneWidget); + final editingTopDivider = find.byKey(const Key('editing-top-divider')); + expect(editingTopDivider, findsOneWidget); + expect( + tester.getRect(editingTopDivider).top, + tester.getRect(find.byType(EditorPreviewPanel)).top, + ); + expect( + tester.getRect(editingTopDivider).left, + tester.getRect(find.byType(EditorPreviewPanel)).left, + ); + tester.view.physicalSize = const Size(500, 450); + await tester.pumpAndSettle(); + final navigationButton = find.byKey(const Key('project-sidebar-toggle')); + expect( + controlRegions.values.any( + (region) => region.contains(tester.getCenter(navigationButton)), + ), + isTrue, + reason: 'AppKit must forward navigation clicks instead of dragging.', + ); + await tester.tap(navigationButton); + await tester.pumpAndSettle(); + expect( + find.byKey(const ValueKey('sidebar-project-project')), + findsOneWidget, + ); + final closeNavigation = find.byTooltip('关闭'); + expect(tester.getRect(closeNavigation).left, greaterThanOrEqualTo(88)); + expect( + controlRegions.values.any( + (region) => region.contains(tester.getCenter(closeNavigation)), + ), + isTrue, + ); + await tester.tap(closeNavigation); + await tester.pumpAndSettle(); + expect( + tester.getRect(find.byKey(const Key('agent-content-header'))).left, + 0, + ); + final reply = Completer(); + messenger.handlePlatformMessage( + channel.name, + const StandardMethodCodec().encodeMethodCall( + const MethodCall('requestClose'), + ), + reply.complete, + ); + expect( + const StandardMethodCodec().decodeEnvelope((await reply.future)!), + isFalse, + ); + await tester.pumpAndSettle(); + expect(find.textContaining('测试项目'), findsWidgets); + expect(calls, [true]); + expect(closeModes, [false]); + expect( + tester.getTopLeft(find.byKey(const Key('agent-content-header'))).dy, + 0, + ); + expect(tester.takeException(), isNull); + debugDefaultTargetPlatformOverride = null; + }); + + testWidgets('editing page keeps sidebar and editing workspace', ( + tester, + ) async { + tester.platformDispatcher.localesTestValue = const [Locale('zh')]; + addTearDown(tester.platformDispatcher.clearLocalesTestValue); + tester.view.physicalSize = const Size(1440, 900); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + await tester.pumpWidget( + ProviderScope( + overrides: [ + deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop), + conversationRepositoryProvider.overrideWith( + (ref) async => EmptyConversationRepository(), + ), + projectsProvider.overrideWith(_TestProjects.new), + ], + child: const CutdexApp(), + ), + ); + await tester.pumpAndSettle(); + final projectHeading = find.byKey(const Key('projects-heading')); + final createProjectButton = find.byKey(const Key('create-project')); + expect(projectHeading, findsOneWidget); + expect(createProjectButton, findsOneWidget); + expect( + tester.getRect(projectHeading).right + AppSpacing.tiny, + tester.getRect(find.byKey(const Key('projects-more'))).left, + ); + expect(find.byKey(const ValueKey('open-project-project')), findsNothing); + expect(find.byKey(const ValueKey('open-timeline-project')), findsNothing); + expect(find.byType(AgentChatPanel), findsOneWidget); + final upperSidebar = find.byKey( + const Key('sidebar-projects-conversations'), + ); + final chatDivider = find.byKey(const Key('sidebar-chat-divider')); + expect(upperSidebar, findsOneWidget); + expect(chatDivider, findsOneWidget); + expect( + tester.getRect(upperSidebar).right, + tester.getRect(chatDivider).left, + ); + expect( + tester.getRect(find.byType(AgentChatPanel)).left, + tester.getRect(chatDivider).right, + ); + expect( + tester.getRect(find.byKey(const Key('agent-composer'))).bottom, + lessThanOrEqualTo(tester.getRect(find.byType(AgentChatPanel)).bottom), + ); + expect( + tester.getRect(find.byType(AgentChatPanel)).right, + lessThanOrEqualTo(tester.getRect(find.byType(EditorWorkspace)).left), + ); + await _hoverProjectHeader(tester); + await tester.tap(find.byKey(const Key('projects-more'))); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('projects-section-header')), findsNothing); + expect(find.byKey(const Key('project-popover')), findsNothing); + expect(find.byKey(const ValueKey('open-timeline-project')), findsNothing); + expect(find.byKey(const Key('editor-content-header')), findsOneWidget); + expect(find.byKey(const Key('editor-media-button')), findsOneWidget); + expect(find.byKey(const Key('timeline-tabs-bar')), findsOneWidget); + expect(find.byKey(const Key('timeline-add-button')), findsOneWidget); + expect(find.byKey(const ValueKey('timeline-tab-project')), findsOneWidget); + await tester.tap(find.byKey(const Key('timeline-add-button'))); + await tester.pumpAndSettle(); + expect(find.text('时间线 1'), findsWidgets); + expect( + find.byKey(const ValueKey('timeline-tab-created-1')), + findsOneWidget, + ); + final timelineTitleOffset = + tester.getRect(find.byKey(const Key('workspace-project-title'))).left - + tester.getRect(find.byType(EditorWorkspace)).left; + expect( + timelineTitleOffset, + lessThan( + tester.getRect(find.byKey(const Key('editor-media-button'))).left - + tester.getRect(find.byType(EditorWorkspace)).left, + ), + ); + final sidebarDivider = find.byKey(const Key('project-sidebar-resize')); + final sidebarLeftBefore = tester.getTopLeft(sidebarDivider).dx; + await tester.drag(sidebarDivider, const Offset(80, 0)); + await tester.pumpAndSettle(); + expect( + tester.getTopLeft(sidebarDivider).dx, + greaterThan(sidebarLeftBefore), + ); + final agentWidth = tester.getSize(find.byType(AgentChatPanel)).width; + await tester.drag(sidebarDivider, const Offset(2000, 0)); + await tester.pumpAndSettle(); + expect( + tester + .getSize(find.byKey(const Key('sidebar-projects-conversations'))) + .width, + 360, + ); + expect(tester.getSize(find.byType(AgentChatPanel)).width, agentWidth); + final preview = tester.getTopLeft(find.byType(EditorPreviewPanel)); + final timeline = tester.getTopLeft(find.byType(EditorTimelinePanel)); + final editingTopDivider = find.byKey(const Key('editing-top-divider')); + expect(editingTopDivider, findsOneWidget); + expect(timeline.dx, tester.getTopLeft(find.byType(EditorPreviewPanel)).dx); + expect(timeline.dy, greaterThan(preview.dy)); + expect(find.byType(AgentChatPanel), findsOneWidget); + expect(find.byKey(const Key('agent-top-divider')), findsNothing); + expect(find.byType(EditorPropertiesPanel), findsNothing); + final editingPropertiesButton = find.byKey( + const Key('editor-properties-button'), + ); + expect(editingPropertiesButton, findsOneWidget); + await tester.tap(editingPropertiesButton); + await tester.pumpAndSettle(); + expect(find.byType(EditorPropertiesPanel), findsOneWidget); + await tester.tap(editingPropertiesButton); + await tester.pumpAndSettle(); + expect(find.byType(EditorPropertiesPanel), findsNothing); + expect(tester.takeException(), isNull); + + final timelineResize = find.byKey(const Key('editor-timeline-resize')); + final timelineHeightBefore = tester + .getSize(find.byType(EditorTimelinePanel)) + .height; + await tester.drag(timelineResize, const Offset(0, -80)); + await tester.pumpAndSettle(); + expect( + tester.getSize(find.byType(EditorTimelinePanel)).height, + greaterThan(timelineHeightBefore), + ); + + final mediaButton = find.byKey(const Key('editor-media-button')); + final propertiesButton = find.byKey(const Key('editor-properties-button')); + expect( + tester.getRect(mediaButton).right + AppSpacing.tiny, + tester.getRect(propertiesButton).left, + ); + expect( + find.descendant( + of: find.byKey(const Key('editor-media-button')), + matching: find.byIcon(Icons.perm_media_outlined), + ), + findsOneWidget, + ); + expect(find.byKey(const Key('workspace-layout-menu')), findsNothing); + expect(find.byKey(const Key('editor-editing-toggle')), findsNothing); + expect(find.byKey(const Key('agent-editing-divider')), findsNothing); + expect( + tester.getTopLeft(find.byType(EditorTimelinePanel)).dy, + greaterThan(tester.getTopLeft(find.byType(EditorPreviewPanel)).dy), + ); + + await tester.tap(find.byKey(const Key('editor-media-button'))); + await tester.pumpAndSettle(); + expect(find.byType(MediaPanel), findsOneWidget); + expect(tester.widget(mediaButton).isSelected, isTrue); + expect(find.byType(Dialog), findsNothing); + expect(find.byKey(const Key('media-panel-header')), findsOneWidget); + expect(find.byKey(const Key('media-panel-body')), findsOneWidget); + final mediaRegion = find.byKey(const Key('editor-media-region')); + expect(mediaRegion, findsOneWidget); + expect(find.byKey(const Key('editor-properties-region')), findsNothing); + expect( + tester.getRect(find.byType(MediaPanel)), + tester.getRect(mediaRegion), + ); + expect( + tester.getRect(mediaRegion).left, + lessThan(tester.getRect(find.byType(EditorPreviewPanel)).left), + ); + expect( + tester.getRect(mediaRegion).right, + lessThanOrEqualTo(tester.getRect(find.byType(EditorPreviewPanel)).left), + ); + await tester.tap(find.byKey(const Key('media-layout-toggle'))); + await tester.pumpAndSettle(); + expect(find.byTooltip('宫格布局'), findsOneWidget); + await tester.tap(find.byKey(const Key('editor-properties-button'))); + await tester.pumpAndSettle(); + final propertiesRegion = find.byKey(const Key('editor-properties-region')); + expect(mediaRegion, findsOneWidget); + expect(find.byType(MediaPanel), findsOneWidget); + expect(propertiesRegion, findsOneWidget); + expect(find.byType(EditorPropertiesPanel), findsOneWidget); + expect( + tester.getRect(mediaRegion).right, + lessThanOrEqualTo(tester.getRect(find.byType(EditorPreviewPanel)).left), + ); + expect( + tester.getRect(propertiesRegion).left, + greaterThanOrEqualTo( + tester.getRect(find.byType(EditorPreviewPanel)).right, + ), + ); + await tester.tap(find.byKey(const Key('editor-media-button'))); + await tester.pumpAndSettle(); + expect(mediaRegion, findsNothing); + expect(propertiesRegion, findsOneWidget); + await tester.tap(find.byKey(const Key('editor-media-button'))); + await tester.pumpAndSettle(); + expect(mediaRegion, findsOneWidget); + expect(propertiesRegion, findsOneWidget); + expect(find.byTooltip('宫格布局'), findsOneWidget); + await tester.tap(find.byKey(const Key('editor-media-button'))); + await tester.pumpAndSettle(); + expect(mediaRegion, findsNothing); + expect(propertiesRegion, findsOneWidget); + expect(tester.widget(mediaButton).isSelected, isFalse); + expect(tester.takeException(), isNull); + }); + + for (final locale in const [ + Locale('en'), + Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hans'), + Locale.fromSubtags(languageCode: 'zh', scriptCode: 'Hant'), + Locale('ja'), + Locale('ko'), + Locale('fr'), + Locale('de'), + Locale('es'), + Locale('pt'), + Locale('it'), + Locale('ru'), + ]) { + testWidgets('small editor viewport fits in $locale', (tester) async { + tester.platformDispatcher.localesTestValue = [locale]; + addTearDown(tester.platformDispatcher.clearLocalesTestValue); + tester.view.physicalSize = const Size(600, 450); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + await tester.pumpWidget( + ProviderScope( + overrides: [ + deviceExperienceProvider.overrideWithValue( + DeviceExperience.desktop, + ), + conversationRepositoryProvider.overrideWith( + (ref) async => EmptyConversationRepository(), + ), + projectsProvider.overrideWith(_TestProjects.new), + ], + child: const CutdexApp(), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const Key('sidebar-mode-trigger'))); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(const ValueKey('sidebar-mode-cut'))); + await tester.pumpAndSettle(); + expect( + find.ancestor( + of: find.byType(EditorTimelinePanel), + matching: find.byType(SingleChildScrollView), + ), + findsNothing, + ); + expect(find.text('视频预览'), findsNothing); + expect(find.text('属性'), findsNothing); + final timeline = tester.getRect(find.byType(EditorTimelinePanel)); + expect(timeline.right, lessThanOrEqualTo(600)); + expect(timeline.bottom, lessThanOrEqualTo(450)); + final shellContext = tester.element(find.byType(EditorTimelinePanel)); + expect(Directionality.of(shellContext), TextDirection.ltr); + expect(tester.takeException(), isNull); + addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue); + for (final scale in [1.5, 2.0]) { + tester.platformDispatcher.textScaleFactorTestValue = scale; + await tester.pumpAndSettle(); + final scaledTimeline = tester.getRect(find.byType(EditorTimelinePanel)); + expect(scaledTimeline.right, lessThanOrEqualTo(600)); + expect(scaledTimeline.bottom, lessThanOrEqualTo(450)); + expect(tester.takeException(), isNull); + } + }); + } + + testWidgets('unknown project can return home without a navigation stack', ( + tester, + ) async { + tester.platformDispatcher.localesTestValue = const [Locale('zh')]; + addTearDown(tester.platformDispatcher.clearLocalesTestValue); + final container = ProviderContainer( + overrides: [ + deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop), + conversationRepositoryProvider.overrideWith( + (ref) async => EmptyConversationRepository(), + ), + projectsProvider.overrideWith(_TestProjects.new), + ], + ); + addTearDown(container.dispose); + container.read(appRouterProvider).go('/projects/missing'); + await tester.pumpWidget( + UncontrolledProviderScope(container: container, child: const CutdexApp()), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('返回剪辑')); + await tester.pumpAndSettle(); + expect(find.textContaining('测试项目'), findsWidgets); + }); +} + +class _EmptyConversationRepository extends ConversationRepository { + _EmptyConversationRepository(super.root); + + @override + Future> list( + String projectId, { + bool trash = false, + }) async => []; + + @override + Future selected(String projectId) async => null; +} + +class _GroupedConversationRepository extends ConversationRepository { + _GroupedConversationRepository(this.groups) : super(Directory('/unused')); + + final Map> groups; + + @override + Future> list( + String projectId, { + bool trash = false, + }) async => trash ? [] : groups[projectId] ?? []; + + @override + Future selected(String projectId) async => + groups[projectId]?.firstOrNull?.id; + + @override + Future update(ConversationMetadata item) async { + final conversations = groups[item.projectId]!; + final index = conversations.indexWhere((entry) => entry.id == item.id); + conversations[index] = item; + return item; + } +} + +class _GroupedProjects extends _TestProjects { + @override + Future build() async { + final state = await super.build(); + return state.copyWith( + recent: [ + ...state.recent, + const RecentProject( + id: 'other', + name: 'Other Project', + path: '/test/Other.cutdex', + ), + ], + ); + } + + @override + Future open( + String path, { + String? name, + String? expectedId, + String? timelineId, + String? initialTimelineName, + bool Function()? isCurrent, + }) async { + final current = state.requireValue; + final project = current.recent.firstWhere((item) => item.id == expectedId); + state = AsyncData(current.copyWith(activeProject: project)); + return true; + } +} + +class _SwitchProjects extends _TestProjects { + @override + Future build() async => (await super.build()).copyWith( + timelines: [ + const TimelineSummary(id: 'project', name: '测试项目', revision: 1), + const TimelineSummary(id: 'second', name: '第二条时间线', revision: 1), + for (var i = 3; i <= 20; i++) + TimelineSummary(id: 'timeline-$i', name: '时间线 $i', revision: 1), + ], + assets: [ + for (var i = 0; i < 30; i++) + AssetDocument( + id: 'image-$i', + name: 'Image $i.png', + storage: AssetStorage.external, + location: 'file:///image-$i.png', + metadata: const {'kind': 'image'}, + ), + ], + ); + + @override + Future openTimeline(String projectId, String timelineId) async { + state = AsyncData( + state.requireValue.copyWith( + timeline: TimelineDocument( + id: timelineId, + name: timelineId, + sequences: [], + ), + ), + ); + return true; + } + + @override + Future setTimelinePinned(String timelineId, bool pinned) async { + final current = state.requireValue; + final updated = [ + for (final item in current.timelines) + TimelineSummary( + id: item.id, + name: item.name, + revision: item.revision, + pinned: item.id == timelineId ? pinned : item.pinned, + ), + ]; + state = AsyncData( + current.copyWith( + timelines: [ + ...updated.where((item) => item.pinned), + ...updated.where((item) => !item.pinned), + ], + ), + ); + return true; + } + + @override + Future renameTimeline( + RecentProject project, + String timelineId, + String name, + ) async { + final current = state.requireValue; + state = AsyncData( + current.copyWith( + timelines: [ + for (final item in current.timelines) + TimelineSummary( + id: item.id, + name: item.id == timelineId ? name : item.name, + revision: item.revision, + pinned: item.pinned, + ), + ], + ), + ); + return true; + } + + @override + Future deleteTimeline(String timelineId) async { + final current = state.requireValue; + final timelines = current.timelines + .where((item) => item.id != timelineId) + .toList(); + state = AsyncData( + current.copyWith( + timelines: timelines, + timeline: current.timeline?.id == timelineId + ? TimelineDocument( + id: timelines.first.id, + name: timelines.first.name, + sequences: [], + ) + : current.timeline, + ), + ); + return true; + } +} + +class _TimelineLimitProjects extends Projects { + @override + Future build() async { + const project = RecentProject( + id: 'project', + name: '测试项目', + path: '/test/Project.cutdex', + ); + return ProjectState( + activeProject: project, + recent: const [project], + timeline: TimelineDocument(id: 'project', name: '测试时间线', sequences: []), + timelines: [ + const TimelineSummary(id: 'project', name: '测试时间线', revision: 1), + for (var i = 2; i <= Projects.maxTimelineCount; i++) + TimelineSummary(id: 'timeline-$i', name: '时间线 $i', revision: 1), + ], + ); + } +} + +class _LoadingProjects extends Projects { + @override + Future build() => Completer().future; +} + +class _BusyProjects extends _TestProjects { + @override + Future build() async => + (await super.build()).copyWith(projectBusy: true); +} + +class _TestProjects extends Projects { + @override + Future build() async { + const project = RecentProject( + id: 'project', + name: '测试项目', + path: '/test/Project.cutdex', + ); + return ProjectState( + activeProject: project, + recent: [project], + timelines: [ + const TimelineSummary(id: 'project', name: '测试时间线', revision: 1), + ], + timeline: TimelineDocument(id: 'project', name: '测试时间线', sequences: []), + ); + } + + @override + Future open( + String path, { + String? name, + String? expectedId, + String? timelineId, + String? initialTimelineName, + bool Function()? isCurrent, + }) async => true; + + @override + Future renameProject(RecentProject project, String name) async { + final current = state.requireValue; + final renamed = project.copyWith(name: name); + state = AsyncData( + current.copyWith(activeProject: renamed, recent: [renamed]), + ); + return true; + } + + @override + Future renameTimeline( + RecentProject project, + String timelineId, + String name, + ) async { + final current = state.requireValue; + state = AsyncData( + current.copyWith( + timelines: [TimelineSummary(id: timelineId, name: name, revision: 1)], + timeline: TimelineDocument(id: timelineId, name: name, sequences: []), + ), + ); + return true; + } + + @override + Future createTimeline({String? name}) async { + final current = state.requireValue; + final index = current.timelines.length; + final id = 'created-$index'; + final created = TimelineSummary( + id: id, + name: name ?? 'Timeline $index', + revision: 1, + ); + state = AsyncData( + current.copyWith( + timelines: [...current.timelines, created], + timeline: TimelineDocument(id: id, name: created.name, sequences: []), + ), + ); + return true; + } +} + +class _MemoryWorkspaceViewSettings implements WorkspaceViewSettingsRepository { + WorkspaceViewSettingsData value = const WorkspaceViewSettingsData(); + + @override + Future load() async => value; + + @override + Future save(WorkspaceViewSettingsData settings) async => + value = settings; +} + +class _UnselectedProjects extends _TestProjects { + @override + Future build() async { + final initial = await super.build(); + return ProjectState(recent: initial.recent); + } + + @override + Future open( + String path, { + String? name, + String? expectedId, + String? timelineId, + String? initialTimelineName, + bool Function()? isCurrent, + }) async { + state = AsyncData(await super.build()); + return true; + } +} + +class _DelayedProjects extends _GroupedProjects { + final requests = <(String, Completer)>[]; + + @override + Future build() async { + final initial = await super.build(); + return initial.copyWith( + recent: [ + ...initial.recent, + const RecentProject( + id: 'third', + name: 'Third Project', + path: '/test/Third.cutdex', + ), + ], + ); + } + + @override + Future open( + String path, { + String? name, + String? expectedId, + String? timelineId, + String? initialTimelineName, + bool Function()? isCurrent, + }) async { + final completion = Completer(); + requests.add((expectedId!, completion)); + state = AsyncData(state.requireValue.copyWith(projectBusy: true)); + final completed = await completion.future; + final success = completed && (isCurrent?.call() ?? true); + final current = state.requireValue; + state = AsyncData( + current.copyWith( + projectBusy: false, + activeProject: success + ? current.recent.firstWhere((project) => project.id == expectedId) + : current.activeProject, + ), + ); + return success; + } +} diff --git a/test/windows_media_import_test.dart b/test/windows_media_import_test.dart new file mode 100644 index 0000000..3ee2b63 --- /dev/null +++ b/test/windows_media_import_test.dart @@ -0,0 +1,116 @@ +import 'support/creation_names.dart'; + +import 'dart:convert'; +import 'dart:io'; + +import 'package:cutdex/workspace/media_file_extensions.dart'; +import 'package:cutdex/workspace/media_import.dart'; +import 'package:cutdex/workspace/persistence/project_workspace.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as p; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + const channel = MethodChannel('windows-import-test'); + late Directory root; + late ProjectWorkspace workspace; + late String projectId; + final requests = >[]; + var videoTracks = 1; + var protected = false; + var probeFails = false; + + setUp(() async { + debugDefaultTargetPlatformOverride = TargetPlatform.windows; + requests.clear(); + videoTracks = 1; + protected = false; + probeFails = false; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (call) async { + expect(call.method, 'request'); + final request = jsonDecode( + (call.arguments as Map)['request'] as String, + ) as Map; + requests.add(request); + expect(request['method'], 'probe'); + if (probeFails) throw PlatformException(code: 'unsupported'); + return jsonEncode({ + 'value': { + 'duration': {'numerator': '2', 'denominator': 1}, + 'videoTrackCount': videoTracks, + 'audioTrackCount': 0, + 'videoTrackIds': List.generate(videoTracks, (index) => index), + 'audioTrackIds': [], + 'isProtected': protected, + 'audioTracks': [], + }, + }); + }); + root = await Directory.systemTemp.createTemp('cutdex-windows-import-'); + workspace = ProjectWorkspace( + creationNames: testCreationNames, + runtime: CutdexRuntime(channel: channel), + ); + await workspace.open(p.join(root.path, 'Test.cutdex'), name: 'Import'); + projectId = workspace.project!.info.id; + }); + tearDown(() async { + debugDefaultTargetPlatformOverride = null; + await workspace.close(); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, null); + await root.delete(recursive: true); + }); + + test( + 'Windows ISO picker and import use backend capability, not file magic', + () async { + expect(selectableVideoFileExtensions, contains('iso')); + final file = await File(p.join(root.path, '中文 空格.ISO')) + .writeAsBytes(List.filled(64, 0)); + expect(mediaKindForPath(file.path), 'video'); + final result = await workspace.importExternalMedia(projectId, [ + ExternalMediaFile(path: file.path), + ]); + expect(result.failures, isEmpty); + expect(result.added, 1); + expect(requests, hasLength(1)); + expect((requests.single['media'] as Map)['uri'], file.uri.toString()); + expect(await file.readAsBytes(), List.filled(64, 0)); + expect( + await Directory(p.join(workspace.project!.directory.path, 'media')) + .exists(), + false, + ); + }, + skip: !Platform.isWindows, + ); + + for (final reason in ['no video', 'protected', 'probe failure']) { + test('unreadable ISO is rejected: $reason', () async { + videoTracks = reason == 'no video' ? 0 : 1; + protected = reason == 'protected'; + probeFails = reason == 'probe failure'; + final file = await File(p.join(root.path, 'disk.iso')).writeAsBytes([0]); + final result = await workspace.importExternalMedia(projectId, [ + ExternalMediaFile(path: file.path), + ]); + expect(result.added, 0); + expect(result.failures, hasLength(1)); + expect(await workspace.project!.listAssets(), isEmpty); + }, skip: !Platform.isWindows); + } + + test('ordinary imports retain lazy probing', () async { + final file = await File(p.join(root.path, 'video.mp4')).writeAsBytes([0]); + final result = await workspace.importExternalMedia(projectId, [ + ExternalMediaFile(path: file.path), + ]); + expect(result.added, 1); + expect(requests, isEmpty); + }); +} diff --git a/test/workspace/external_media_import_test.dart b/test/workspace/external_media_import_test.dart new file mode 100644 index 0000000..5670a8a --- /dev/null +++ b/test/workspace/external_media_import_test.dart @@ -0,0 +1,200 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:cutdex/workspace/external_media_import.dart'; +import 'package:cutdex/workspace/media_import.dart'; +import 'package:cutdex/workspace/project_state.dart'; +import 'package:cutdex/workspace/projects.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter_test/flutter_test.dart'; + +const _project = RecentProject( + id: 'project', + name: 'Project', + path: '/project', +); +AssetDocument _asset(String id, String path) => AssetDocument( + id: id, + name: id, + storage: AssetStorage.external, + location: Uri.file(path).toString(), +); + +class _Projects extends Projects { + @visibleForTesting + int importCalls = 0; + @override + Future build() async => ProjectState( + activeProject: _project, + assets: [_asset('existing', '/existing.mov')], + ); + @override + Future importExternalMedia( + String projectId, + List files, { + bool Function()? isCancelled, + }) async { + importCalls++; + final assets = [ + ...state.requireValue.assets, + for (final file in files) _asset(file.localPath!, file.localPath!), + ]; + state = AsyncData(state.requireValue.copyWith(assets: assets)); + return MediaImportResult( + assets: assets, + added: files.length, + duplicates: 0, + failures: [], + ); + } + + void leaveProject() => + state = AsyncData(state.requireValue.copyWith(activeProject: null)); +} + +class _DelayedResolver extends MediaFileResolver { + final started = Completer(); + final release = Completer>>(); + @override + Future>> resolve( + List files, + List assets, + ) { + started.complete(); + return release.future; + } +} + +class _ManagedProjects extends _Projects { + @override + Future build() async => ProjectState( + activeProject: _project, + assets: [ + AssetDocument( + id: 'managed', + name: 'clip.mp4', + storage: AssetStorage.managed, + location: 'media/originals/managed/source.mp4', + metadata: {mediaSourceUriKey: 'content://provider/document/42'}, + ), + ], + ); +} + +void main() { + test('generated media has no inferred external source identity', () { + final generated = AssetDocument( + id: 'generated', + name: 'Generated', + storage: AssetStorage.managed, + location: 'media/originals/generated/source.wav', + ); + expect(mediaSourceLocation(generated), isNull); + }); + + test( + 'external media identity comes from its URI rather than source metadata', + () { + final external = AssetDocument( + id: 'external', + name: 'External', + storage: AssetStorage.external, + location: 'file:///original.wav', + metadata: {mediaSourceUriKey: 'content://provider/document/42'}, + ); + expect(mediaSourceLocation(external), 'file:///original.wav'); + }, + ); + + test('provider re-selection resolves to the managed original without importing again', () async { + final container = ProviderContainer( + overrides: [projectsProvider.overrideWith(_ManagedProjects.new)], + ); + addTearDown(container.dispose); + await container.read(projectsProvider.future); + final result = await container + .read(externalMediaImportProvider('project').notifier) + .importFiles([ + ExternalMediaFile.content( + uri: Uri.parse('content://provider/document/42'), + name: 'clip.mp4', + ), + ]); + expect(result!.selected.single.id, 'managed'); + expect(result.result, isNull); + expect( + (container.read( + projectsProvider.notifier, + ) as _ManagedProjects).importCalls, + 0, + ); + }); + test('resolving a symlink includes its canonical location and preserves missing files', () async { + final root = await Directory.systemTemp.createTemp('cutdex-resolver-'); + addTearDown(() => root.delete(recursive: true)); + final source = await File('${root.path}/source.mov').writeAsString('media'); + final alias = await Link('${root.path}/alias.mov').create(source.path); + final files = [ + ExternalMediaFile(path: alias.path), + ExternalMediaFile(path: '${root.path}/missing.mov'), + ]; + final locations = await const MediaFileResolver().resolve(files, []); + expect( + locations[files.first], + contains(Uri.file(await source.resolveSymbolicLinks()).toString()), + ); + expect(locations[files.last], {files.last.sourceUri.toString()}); + }); + + test('an import selects existing and new files while only importing missing sources', () async { + final container = ProviderContainer( + overrides: [projectsProvider.overrideWith(_Projects.new)], + ); + addTearDown(container.dispose); + await container.read(projectsProvider.future); + final result = await container + .read(externalMediaImportProvider('project').notifier) + .importFiles([ + const ExternalMediaFile(path: '/existing.mov'), + const ExternalMediaFile(path: '/new.mov'), + ]); + expect(result!.selected.map((asset) => asset.id), ['existing', '/new.mov']); + expect(result.result!.added, 1); + expect( + (container.read(projectsProvider.notifier) as _Projects).importCalls, + 1, + ); + }); + + test('switching project during resolution prevents an import and releases busy state', () async { + final resolver = _DelayedResolver(); + final container = ProviderContainer( + overrides: [ + projectsProvider.overrideWith(_Projects.new), + mediaFileResolverProvider.overrideWithValue(resolver), + ], + ); + addTearDown(container.dispose); + await container.read(projectsProvider.future); + final provider = externalMediaImportProvider('project'); + final subscription = container.listen(provider, (_, _) {}); + addTearDown(subscription.close); + final operation = container.read(provider.notifier); + const file = ExternalMediaFile(path: '/new.mov'); + final pending = operation.importFiles([file]); + await resolver.started.future; + expect(await operation.importFiles([file]), isNull); + (container.read(projectsProvider.notifier) as _Projects).leaveProject(); + resolver.release.complete({ + file: {file.sourceUri.toString()}, + }); + expect(await pending, isNull); + expect(container.read(provider).isLoading, isFalse); + expect( + (container.read(projectsProvider.notifier) as _Projects).importCalls, + 0, + ); + }); +} diff --git a/test/workspace/media_selection_entry_points_test.dart b/test/workspace/media_selection_entry_points_test.dart new file mode 100644 index 0000000..791525d --- /dev/null +++ b/test/workspace/media_selection_entry_points_test.dart @@ -0,0 +1,90 @@ +import 'package:cutdex/features/assistant/agent_composer_store.dart'; +import 'package:cutdex/features/media/media_browser_controller.dart'; +import 'package:cutdex/integrations/platform/file_picker.dart'; +import 'package:cutdex/integrations/platform/native_file_drop_policy.dart'; +import 'package:cutdex/workspace/media_file_extensions.dart'; +import 'package:cutdex/workspace/media_import.dart'; +import 'package:cutdex/workspace/project_state.dart'; +import 'package:cutdex/workspace/projects.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +class _Projects extends Projects { + @override + Future build() async => const ProjectState( + activeProject: RecentProject( + id: 'project', + name: 'Project', + path: '/project', + ), + ); +} + +class _Picker extends AppFilePicker { + final selections = >[]; + + @override + Future> pickFiles({ + required List allowedExtensions, + }) async { + selections.add(List.of(allowedExtensions)); + return []; + } +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + tearDown(() => debugDefaultTargetPlatformOverride = null); + + for (final platform in TargetPlatform.values) { + test( + '$platform file selectors and native timeline filters agree', + () async { + debugDefaultTargetPlatformOverride = platform; + final picker = _Picker(); + final container = ProviderContainer( + overrides: [ + projectsProvider.overrideWith(_Projects.new), + filePickerProvider.overrideWithValue(picker), + ], + ); + addTearDown(container.dispose); + await container.read(projectsProvider.future); + final browserProvider = mediaBrowserProvider('project'); + container.listen(browserProvider, (_, _) {}); + await container.read(browserProvider).pickFiles(); + await container + .read(agentComposerStoreProvider) + .composer('project', 'draft') + .pickAttachments(); + expect(picker.selections, hasLength(2)); + expect(picker.selections[0], orderedEquals(picker.selections[1])); + final timeline = NativeFileDropPolicy.timeline.allowedExtensions!; + for (final extension in ['mp4', 'wav', 'iso', 'png', 'unknown']) { + final file = ExternalMediaFile( + path: '/source.${extension.toUpperCase()}', + ); + final kind = mediaKindForPath(file.displayName); + expect(picker.selections[0].contains(extension), kind != null); + expect( + timeline.contains(extension), + kind == 'video' || kind == 'audio', + ); + expect( + NativeFileDropPolicy.timeline.accepts([file]), + timeline.contains(extension), + ); + } + expect( + picker.selections[0].contains('iso'), + platform == TargetPlatform.windows, + ); + expect(timeline.contains('iso'), platform == TargetPlatform.windows); + expect(NativeFileDropPolicy.timeline.maximumFileCount, 1); + expect(NativeFileDropPolicy.mediaLibrary.allowedExtensions, isNull); + expect(NativeFileDropPolicy.attachments.allowedExtensions, isNull); + }, + ); + } +} diff --git a/test/workspace/media_timeline_duration_test.dart b/test/workspace/media_timeline_duration_test.dart new file mode 100644 index 0000000..b1ec16e --- /dev/null +++ b/test/workspace/media_timeline_duration_test.dart @@ -0,0 +1,99 @@ +import 'package:cutdex/errors/app_failure.dart'; +import 'package:cutdex/workspace/media_timeline_duration.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + test( + 'microsecond and 2997/100 container timebases lose less than one tick', + () { + for (final (source, ticks) in [ + (MediaTime(5853355833, 1000000), 8260255751529), + (MediaTime(70170000, 11988), 8260252252252), + ]) { + final result = mediaTimelineDuration(source); + final original = RationalTime(source.numerator, source.denominator); + expect(TimelineClock.standard.toTicks(result), ticks); + expect(result, lessThanOrEqualTo(original)); + expect(original - result, lessThan(RationalTime.timelineTicks(1))); + } + }, + ); + + test('native MPG duration is representable without exceeding the source', () { + final source = MediaTime(64737467444, 10000000); + expect( + () => TimelineClock.standard.toTicks( + RationalTime(source.numerator, source.denominator), + ), + throwsArgumentError, + ); + final duration = mediaTimelineDuration(source); + final ticks = TimelineClock.standard.toTicks(duration); + expect(ticks, 9135751405697); + // Check exact integers: discarded time is nonnegative and below one tick. + final remainder = + BigInt.from(source.numerator) * + BigInt.from(TimelineClock.ticksPerSecond) - + BigInt.from(ticks) * BigInt.from(source.denominator); + expect(remainder, BigInt.from(2800000)); + expect(remainder >= BigInt.zero, isTrue); + expect(remainder < BigInt.from(source.denominator), isTrue); + }); + + test('exact seconds, NTSC frames and audio samples retain their times', () { + for (final source in [ + MediaTime(5, 1), + MediaTime(1001, 30000), + MediaTime(1, 48000), + MediaTime(1, 44100), + MediaTime(1, 24), + MediaTime(1, 25), + MediaTime(1, 30), + MediaTime(1, 384000), + MediaTime(1, TimelineClock.ticksPerSecond), + ]) { + expect( + mediaTimelineDuration(source), + RationalTime(source.numerator, source.denominator), + ); + } + }); + + test('nonpositive and sub-tick durations cannot create empty clips', () { + for (final source in [ + MediaTime(0, 1), + MediaTime(-1, 1), + MediaTime(1, 0xffffffff), + ]) { + expect(() => mediaTimelineDuration(source), throwsStateError); + } + }); + + test('large intermediates remain exact; out-of-range ticks are rejected', () { + const maximum = 0x7fffffffffffffff; + expect( + TimelineClock.standard.toTicks( + mediaTimelineDuration(MediaTime(maximum, 0xffffffff)), + ), + 3030528924763199999, + ); + expect( + TimelineClock.standard.toTicks( + mediaTimelineDuration(MediaTime(maximum, TimelineClock.ticksPerSecond)), + ), + maximum, + ); + expect( + () => mediaTimelineDuration(MediaTime(maximum, 1)), + throwsA( + isA().having( + (error) => error.failure.code, + 'code', + AppErrorCode.mediaDurationOutOfRange, + ), + ), + ); + }); +} diff --git a/test/workspace/prepared_media_entry_points_test.dart b/test/workspace/prepared_media_entry_points_test.dart new file mode 100644 index 0000000..d8b2c30 --- /dev/null +++ b/test/workspace/prepared_media_entry_points_test.dart @@ -0,0 +1,171 @@ +import 'package:cutdex/errors/app_failure.dart'; + +import '../support/creation_names.dart'; + +import 'dart:convert'; +import 'dart:io'; + +import 'package:cutdex/workspace/persistence/project_workspace.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + const channel = MethodChannel('prepared-workspace-test'); + late Directory directory; + late ProjectWorkspace workspace; + late String projectId; + late Map response; + var probes = 0; + setUp(() async { + probes = 0; + response = { + 'duration': {'numerator': '64737467444', 'denominator': 10000000}, + 'videoTrackCount': 1, + 'audioTrackCount': 1, + 'videoTrackIds': [0], + 'audioTrackIds': [1], + 'audioTracks': [ + { + 'start': {'numerator': '1', 'denominator': 3}, + 'duration': {'numerator': '2', 'denominator': 3}, + }, + ], + 'isProtected': false, + }; + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (call) async { + if (call.method == 'request') { + final request = jsonDecode( + (call.arguments as Map)['request'] as String, + ); + expect(request['method'], 'probe'); + } else { + expect(call.method, 'probe'); + } + probes++; + return call.method == 'request' + ? jsonEncode({'value': response}) + : response; + }); + directory = await Directory.systemTemp.createTemp('cutdex-prepared-media-'); + workspace = ProjectWorkspace( + creationNames: testCreationNames, + runtime: CutdexRuntime(channel: channel), + ); + await workspace.open( + '${directory.path}/Test.cutdex', + name: 'Prepared media', + ); + projectId = workspace.project!.info.id; + final source = await File('${directory.path}/source.mpg').writeAsBytes([0]); + await workspace.project!.saveAsset( + AssetDocument( + id: 'media', + name: 'Source', + storage: AssetStorage.external, + location: source.uri.toString(), + ), + ); + }); + tearDown(() async { + await workspace.close(); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, null); + await directory.delete(recursive: true); + }); + + test( + 'ordinary insertion keeps the same MPG duration and original audio timing', + () async { + final prepared = await workspace.prepareMedia(projectId, 'media'); + expect(TimelineClock.standard.toTicks(prepared.duration), 9135751405697); + expect(prepared.kind, EditorMediaKind.video); + expect(prepared.hasAudio, isTrue); + expect(prepared.audioTracks.single.start.toMap(), { + 'numerator': '1', + 'denominator': 3, + }); + expect(prepared.audioTracks.single.duration.toMap(), { + 'numerator': '2', + 'denominator': 3, + }); + expect(probes, 1); + expect(await File('${directory.path}/source.mpg').readAsBytes(), [0]); + }, + ); + + test('ordinary audio-only insertion uses the validated audio kind', () async { + response = {...response, 'videoTrackCount': 0, 'videoTrackIds': []}; + final prepared = await workspace.prepareMedia(projectId, 'media'); + expect(prepared.kind, EditorMediaKind.audio); + expect(prepared.hasAudio, isTrue); + expect(prepared.audioTracks, hasLength(1)); + }); + + test( + 'ordinary image insertion keeps five seconds without native probing', + () async { + final asset = (await workspace.project!.listAssets()).single; + await workspace.project!.saveAsset( + AssetDocument( + id: asset.id, + name: asset.name, + storage: asset.storage, + location: asset.location, + metadata: {'kind': 'image'}, + ), + ); + final prepared = await workspace.prepareMedia(projectId, 'media'); + expect(prepared.kind, EditorMediaKind.image); + expect(prepared.duration, RationalTime.seconds(5)); + expect(prepared.hasAudio, isFalse); + expect(prepared.audioTracks, isEmpty); + expect(probes, 0); + }, + ); + + test( + 'ordinary insertion rejects overflowing duration with the shared error', + () async { + response = { + ...response, + 'duration': {'numerator': '9223372036854775807', 'denominator': 1}, + }; + await expectLater( + workspace.prepareMedia(projectId, 'media'), + throwsA( + isA().having( + (error) => error.failure.code, + 'code', + AppErrorCode.mediaDurationOutOfRange, + ), + ), + ); + }, + ); + + test( + 'ordinary insertion rejects sub-tick duration and protected media', + () async { + final original = response; + response = { + ...original, + 'duration': {'numerator': '1', 'denominator': 0xffffffff}, + }; + await expectLater( + workspace.prepareMedia(projectId, 'media'), + throwsStateError, + ); + response = {...original, 'isProtected': true}; + await expectLater( + workspace.prepareMedia(projectId, 'media'), + throwsStateError, + ); + }, + ); +} diff --git a/test/workspace/prepared_media_metadata_test.dart b/test/workspace/prepared_media_metadata_test.dart new file mode 100644 index 0000000..a946c83 --- /dev/null +++ b/test/workspace/prepared_media_metadata_test.dart @@ -0,0 +1,99 @@ +import 'package:cutdex/errors/app_failure.dart'; +import 'package:cutdex/workspace/prepared_media_metadata.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter_test/flutter_test.dart'; + +MediaInfo _info({ + MediaTime? duration, + int videoTracks = 1, + List audioTracks = const [], + bool protected = false, +}) => MediaInfo( + duration: duration ?? MediaTime(64737467444, 10000000), + videoTrackCount: videoTracks, + audioTrackCount: audioTracks.length, + videoTrackIds: List.generate(videoTracks, (index) => index), + audioTrackIds: List.generate(audioTracks.length, (index) => index + 10), + isProtected: protected, + audioTracks: audioTracks, +); + +void main() { + test( + 'video normalization preserves source audio timings and floors once', + () { + final tracks = [ + MediaTrackTiming(start: MediaTime(1, 3), duration: MediaTime(2, 3)), + MediaTrackTiming(start: MediaTime(0, 1), duration: MediaTime(0, 1)), + ]; + final info = _info(audioTracks: tracks); + final prepared = PreparedMediaMetadata.fromInfo(info); + expect(prepared.kind, EditorMediaKind.video); + expect(prepared.hasAudio, isTrue); + expect(TimelineClock.standard.toTicks(prepared.duration), 9135751405697); + expect(prepared.audioTracks, orderedEquals(info.audioTracks)); + expect(prepared.audioTracks.first.start.toMap(), MediaTime(1, 3).toMap()); + expect( + prepared.audioTracks.first.duration.toMap(), + MediaTime(2, 3).toMap(), + ); + expect(prepared.audioTracks.clear, throwsUnsupportedError); + expect(info.duration.toMap(), MediaTime(64737467444, 10000000).toMap()); + }, + ); + + test( + 'silent video, audio-only and images have consistent insertion fields', + () { + final silent = PreparedMediaMetadata.fromInfo(_info()); + expect(silent.kind, EditorMediaKind.video); + expect(silent.hasAudio, isFalse); + expect(silent.audioTracks, isEmpty); + final audio = PreparedMediaMetadata.fromInfo( + _info( + videoTracks: 0, + duration: MediaTime(1, 48000), + audioTracks: [ + MediaTrackTiming( + start: MediaTime(0, 1), + duration: MediaTime(1, 48000), + ), + ], + ), + ); + expect(audio.kind, EditorMediaKind.audio); + expect(audio.hasAudio, isTrue); + expect(audio.duration, RationalTime(1, 48000)); + final image = PreparedMediaMetadata.image(); + expect(image.kind, EditorMediaKind.image); + expect(image.duration, RationalTime.seconds(5)); + expect(image.hasAudio, isFalse); + expect(image.audioTracks, isEmpty); + }, + ); + + test('unusable sources cannot produce prepared insertion metadata', () { + for (final info in [ + _info(protected: true), + _info(videoTracks: 0), + _info(duration: MediaTime(0, 1)), + _info(duration: MediaTime(1, 0xffffffff)), + ]) { + expect(() => PreparedMediaMetadata.fromInfo(info), throwsStateError); + } + expect( + () => PreparedMediaMetadata.fromInfo( + _info(duration: MediaTime(0x7fffffffffffffff, 1)), + ), + throwsA( + isA().having( + (error) => error.failure.code, + 'code', + AppErrorCode.mediaDurationOutOfRange, + ), + ), + ); + }); +} diff --git a/test_driver/integration_test.dart b/test_driver/integration_test.dart new file mode 100644 index 0000000..aad856a --- /dev/null +++ b/test_driver/integration_test.dart @@ -0,0 +1,6 @@ +import 'package:integration_test/integration_test_driver.dart'; + +Future main() => integrationDriver( + timeout: const Duration(minutes: 40), + writeResponseOnFailure: true, +); diff --git a/tool/README.md b/tool/README.md new file mode 100644 index 0000000..5293ea2 --- /dev/null +++ b/tool/README.md @@ -0,0 +1,101 @@ +# 仓库工具 + +使用 Python 3.11 或更新版本,在 cutdex 仓库根目录运行下列入口。通用检查为 `python3 tool/check.py`;可用 `FLUTTER` 指定 Flutter 可执行文件。它检查 Python/Shell 语法、Python 业务/CLI 单测及 macOS Swift 辅助工具回归和 `lib test integration_test test_driver tool` 的 Dart 静态分析,只会在临时目录编译 Swift 测试辅助程序并生成测试密钥,不执行应用打包、签名、上传或真实模型推理。Windows 没有 bash 时会明确跳过 Shell 语法检查。 + +## 源码检查 + +`python3 tool/check_public_repository.py` 无需 Flutter 或私有依赖,检查待提交源码中的常见凭据、本地产物和文档本地链接。它已接入 `check.py`;检查范围与限制见 [测试指南](../docs/testing.md)。 + +## 稳定客户端入口 + +`dart run tool/mcp_stdio.dart` 由外部 MCP 客户端启动,通过 `CUTDEX_MCP_PORT` 和 `CUTDEX_MCP_TOKEN` 连接正在运行的 Cutdex。客户端配置见 [MCP 连接指南](../docs/mcp-connection.md),可用工具与参数由客户端连接后发现。 + +## macOS + +| 脚本 | 责任 | +| --- | --- | +| macos/build_macos_release.sh | 检查 processing 包、构建 production、签名、审计、生成 ZIP/DMG;可按配置公证 | +| macos/check_macos_build_target.sh | 拒绝覆盖正在运行的目标 App;Xcode 构建阶段直接调用 | +| macos/check_macos_release.py | 检查 arm64、macOS 14 最低版本约束、动态依赖、签名与 worker | +| macos/sign_macos_app.sh | 处理引擎搜索路径并统一签名嵌套二进制与 App | +| macos/create_macos_dmg.sh | 从现有 App 生成安装磁盘映像 | +| macos/set_macos_file_icon.swift | DMG 脚本调用的文件图标辅助程序 | +| macos/macos_updates.py | 配置更新源并生成应用更新产物 | +| macos/test_macos_release.py | 构建独立 smoke App,搬迁后验证无模型及有模型启动 | +| macos/test_check_macos_release.py | 需要真实 processing 包的发布审计故障注入测试 | +| macos/test_macos_updates_unit.py | 更新配置、版本与发布规则的纯 Python 单测 | +| macos/test_macos_updates.py | 本地更新模拟与测试服务器,需 App/Sparkle 工具 | +| macos/sparkle_test_key.swift | 更新模拟专用临时密钥工具,不写系统钥匙串 | + +正常应用打包入口: + +```sh +bash tool/macos/build_macos_release.sh /absolute/path/to/processing-runtime +``` + +默认输出到 `dist/macos/`,第二个参数可指定输出目录。`FLUTTER`、`PYTHON` 可指定工具;最终签名使用 `CUTDEX_CODESIGN_IDENTITY`,公证使用 `CUTDEX_NOTARY_PROFILE`。开发签名配置见 [开发指南](../docs/development.md)。 + +发布验证使用 `check_macos_release.py` 和 `test_macos_release.py`,参数见 `--help`。后者构建独立测试入口,完成后重新打包正常应用;搬迁启动不能代替干净 Mac 上的安装验证。 + +## Windows + +| 脚本 | 责任 | +| --- | --- | +| windows/package_windows_release.py | 校验 processing 哈希,组装便携发行包 | +| windows/check_windows_release.py | 检查 PE 依赖和发行包完整性;真实审计需 pefile | +| windows/test_check_windows_release.py | 注入依赖读取器验证缺库与系统库规则 | +| windows/prepare_windows_sandbox.py | 生成 Windows Sandbox 配置并部署对应测试脚本 | +| windows/test_windows_release.ps1 | 在干净 Windows 环境执行发布 smoke 测试 | +| windows/windows_updates.py | 生成应用更新产物,或启动本地测试更新源 | +| windows/test_windows_updates.py | 独立构建两个测试版本,验证损坏包拒绝、重试、安装和重启 | +| windows/test_windows_updates_unit.py | 发布版本递增、包身份与审计后完整性规则测试 | + +正常发行包组装入口,构建机还需安装 `pefile`: + +```powershell +flutter build windows --release --flavor production +python tool/windows/package_windows_release.py ` + --app build/windows/x64/production/runner/Release ` + --processing D:\packages\processing ` + --output D:\packages\Cutdex +``` + +提供完整 Release 目录和 processing 包,输出必须是新目录。依赖审计后再在独立 Windows 环境验证;`prepare_windows_sandbox.py --help` 提供 Sandbox 入口。真实界面检查需交互桌面,不能用 SSH 构建或进程存活代替。 + +## 应用更新产物 + +Cutdex 的更新构建配置为 macOS 的 `CUTDEX_UPDATE_FEED_URL` / `CUTDEX_UPDATE_PUBLIC_KEY`,Windows 的 `CUTDEX_WINDOWS_UPDATE_URL`;在构建前设置正式 HTTPS 更新源。 + +生成更新产物的应用入口: + +```sh +python3 tool/macos/macos_updates.py publish --help +python3 tool/windows/windows_updates.py pack --help +``` + +提升应用构建号,保留当前线上更新索引供版本检查;development 与 production 使用独立发布目录。脚本只生成产物,不上传。完整升级模拟使用各平台的 `test_*_updates.py`,参数见 `--help`,测试包不用于分发。 + +## 诊断与共享测试入口 + +- `diagnostics/frame_budget.py`:读取 `CUTDEX_FRAME_TIMINGS` JSONL,可带阶段标记文件;报告帧耗时。 +- `diagnostics/benchmark_diagnostic_store.dart`:无输入数据,比较逐条刷盘与默认批写策略的合成日志突发;`--samples=7` 设置测量轮数,JSON 输出包含同步记录耗时、排空耗时、定时器间隔与持久化追加次数。可先 `dart compile exe tool/diagnostics/benchmark_diagnostic_store.dart -o /tmp/cutdex-diagnostic-benchmark` 再运行可执行文件,排除 JIT 预热影响;不测量实际剪辑帧率。合成突发使用 320 项队列容量,其中 40 项预留给错误。 +- `diagnostics/benchmark_agent_context.dart`:读取第一个参数指定的 AgentMessage JSON 数组,比较完整历史和 Harness 投影的估算 token/字节量。 +- `testing/release_smoke.dart`:macOS/Windows 发布测试共用的 Flutter 入口,验证导出、翻译和资源配置。测试 App 不得分发;结束后使用 `lib/main.dart` 重建正式 App。 + +构建前退出相同构建目录中的运行实例。真实发布/更新/处理测试可能构建应用、启动 worker 或本地服务器,按脚本参数入口运行,不由通用检查隐式执行。 + +## 语言与入口约定 + +- Shell 负责系统命令编排与临时资源清理;JSON、XML、依赖和发布规则集中在 Python。签名脚本中的文件筛选与命令排序属于签名流程,保持单一实现。 +- Swift 处理原生能力;PowerShell 处理 Windows 桌面与进程环境;Dart 入口用于应用连接与 Flutter 测试。 +- 普通 Python、Shell、Swift 和 Dart 诊断入口支持 `--help`(Shell/Swift/Dart 也支持 `-h`),帮助不启动构建、服务器或发布操作。PowerShell 使用 `Get-Help <脚本> -Full`。 +- 普通 CLI:成功/帮助为 0,参数格式或数量错误为 2,工具主动判定的运行失败为 1。外部子命令失败保留其非零状态,不承诺所有第三方退出码均为 1;调用方按非零失败处理。 +- 人类诊断写 stderr;JSON、报告路径等结果写 stdout 或显式报告文件;密钥和凭据不得出现在输出中。 +- `mcp_stdio.dart` 是协议服务入口,stdout 专用于协议,保留其环境配置错误码 64;`release_smoke.dart` 与 Swift 窗口测试是测试进程入口,不套用交互 CLI 参数规范。 +- Python 同语言测试放在所属平台目录;跨语言入口契约测试在 `tool/tests/`,统一由 `tool/check.py` 执行。缺少宿主能力时明确显示 skip,不将其当作通过。 + +内部 UI/native 包边界由 `check_package_boundaries.py` 检查依赖声明与源码引用;应用使用包的公开入口。`check.py` 同时分析 workspace 成员、检查包内脚本语法并运行包内测试。 + +桌面原生标题栏回归工具由 [cutdex_native](../packages/cutdex_native/README.md#原生回归) 维护。 + +Flutter 侧使用 `flutter test test/editor_window_chrome_test.dart test/adaptive_workspace_test.dart test/localization_resources_test.dart`。Windows 构建和 Flutter 测试请顺序运行,避免测试进程占用构建需要替换的 SQLite DLL。 diff --git a/tool/check.py b/tool/check.py new file mode 100644 index 0000000..2278e10 --- /dev/null +++ b/tool/check.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 +"""Check repository tooling without building, signing, or publishing an app.""" +import argparse +import ast +import os +from pathlib import Path +import shutil +import subprocess +import sys + +ROOT = Path(__file__).resolve().parent.parent + + +def run(command): + print('+ ' + ' '.join(map(str, command)), flush=True) + subprocess.run(command, cwd=ROOT, check=True) + + +def main(): + argparse.ArgumentParser(description=__doc__).parse_args() + if sys.version_info < (3, 11): + raise SystemExit('Python 3.11 or newer is required for repository tooling.') + tool_roots = [ROOT / 'tool', *(ROOT / 'packages').glob('*/tool')] + for path in sorted(path for directory in tool_roots for path in directory.rglob('*.py')): + ast.parse(path.read_text(encoding='utf-8'), filename=str(path)) + print('Python syntax: passed', flush=True) + bash = shutil.which('bash') + if bash: + for path in sorted(path for directory in tool_roots for path in directory.rglob('*.sh')): + run([bash, '-n', str(path)]) + else: + print('Shell syntax: skipped (bash unavailable)', flush=True) + python = sys.executable + run([python, 'tool/check_public_repository.py']) + run([python, 'tool/check_package_boundaries.py']) + for directory, pattern in [ + ('tool/macos', '*_unit.py'), + ('tool/tests', '*_test.py'), + ('tool/windows', 'test_check_windows_release.py'), + ('tool/windows', '*_unit.py'), + ]: + run([python, '-m', 'unittest', 'discover', '-s', directory, '-p', pattern]) + flutter = os.environ.get('FLUTTER') or shutil.which('flutter') + if not flutter: + raise SystemExit('Flutter is required; set FLUTTER to its executable path.') + run([flutter, 'analyze', 'lib', 'test', 'integration_test', 'test_driver', 'tool', 'packages']) + package_tests = sorted(str(path.relative_to(ROOT)) for path in (ROOT / 'packages').glob('*/test')) + if package_tests: + run([flutter, 'test', *package_tests]) + + +if __name__ == '__main__': + main() diff --git a/tool/check_package_boundaries.py b/tool/check_package_boundaries.py new file mode 100644 index 0000000..e764d44 --- /dev/null +++ b/tool/check_package_boundaries.py @@ -0,0 +1,126 @@ +#!/usr/bin/env python3 +"""Check declared dependencies and public imports across workspace boundaries.""" +from pathlib import Path +import posixpath +import re +from urllib.parse import unquote + +ROOT = Path(__file__).resolve().parent.parent +RUNTIME = { + 'cutdex_native': {'flutter', 'path'}, + 'cutdex_ui': {'flutter', 'cutdex_native', 'freezed_annotation'}, +} +DEVELOPMENT = { + 'cutdex_native': {'flutter_test', 'flutter_lints'}, + 'cutdex_ui': {'flutter_test', 'flutter_lints', 'build_runner', 'freezed'}, +} +TOKENS = re.compile( + r"//[^\n]*|/\*.*?\*/|" + r"(?Pr?(?:\"\"\".*?\"\"\"|'''.*?'''|" + r"\"(?:\\.|[^\"\\])*\"|'(?:\\.|[^'\\])*'))|" + r"(?P\w+)|(?P[^\s])", + re.DOTALL, +) + + +def directives(source): + """Read URI strings in each directive, including conditional alternatives.""" + tokens = [token for token in TOKENS.finditer(source) if token.lastgroup] + index = 0 + while index < len(tokens): + token = tokens[index] + kind = token.group() + index += 1 + if token.lastgroup != 'word' or kind not in ('import', 'export', 'part'): + continue + if index >= len(tokens) or tokens[index].lastgroup != 'string': + continue + while index < len(tokens) and tokens[index].group() != ';': + token = tokens[index] + index += 1 + if token.lastgroup == 'string': + value = token.group() + if value.startswith('r'): + value = value[1:] + quote = value[0] * (3 if value[:3] == value[0] * 3 else 1) + yield kind, value[len(quote):-len(quote)] + + +def package_uri(uri): + dependency, _, path = uri.removeprefix('package:').partition('/') + return dependency, posixpath.normpath(unquote(path)) + + +def dependency_names(manifest, section): + """Read the flat dependency keys used by our workspace manifests.""" + match = re.search(rf'^{section}:\s*\n(.*?)(?=^\S|\Z)', manifest, + flags=re.MULTILINE | re.DOTALL) + if not match: + return set() + return set(re.findall(r'^ ([\w]+):', match.group(1), re.MULTILINE)) + + +def check(root): + errors = [] + + def reject(source, message): + errors.append(f'{source.relative_to(root)}: {message}') + + for package, allowed in RUNTIME.items(): + directory = root / 'packages' / package + manifest_path = directory / 'pubspec.yaml' + manifest = manifest_path.read_text() + dependencies = dependency_names(manifest, 'dependencies') + dev_dependencies = dependency_names(manifest, 'dev_dependencies') + for dependency in sorted(dependencies - allowed): + reject(manifest_path, f'forbidden dependency {dependency}') + for dependency in sorted(dev_dependencies - DEVELOPMENT[package]): + reject(manifest_path, f'forbidden dev_dependency {dependency}') + for key, value in [('name', package), ('resolution', 'workspace'), ('publish_to', 'none')]: + if not re.search(rf'^{key}:\s*{value}\s*$', manifest, re.MULTILINE): + reject(manifest_path, f'expected {key}: {value}') + for area in ['lib', 'test', 'tool']: + declared = dependencies | {package} + if area != 'lib': + declared |= dev_dependencies + for source in (directory / area).rglob('*.dart'): + for kind, uri in directives(source.read_text()): + if uri.startswith('package:'): + dependency, path = package_uri(uri) + if dependency not in declared: + reject(source, f'undeclared {kind} {uri}') + if dependency != package and (path == 'src' or path.startswith('src/')): + reject(source, f'private {kind} {uri}') + elif not uri.startswith('dart:'): + target = (source.parent / uri).resolve() + boundary = directory / ('lib' if area == 'lib' else '') + if not target.is_relative_to(boundary.resolve()): + reject(source, f'escaping {kind} {uri}') + + for area in ['lib', 'test', 'integration_test', 'test_driver', 'tool']: + for source in (root / area).rglob('*.dart'): + for kind, uri in directives(source.read_text()): + if uri.startswith('package:'): + dependency, path = package_uri(uri) + if dependency != 'cutdex' and (path == 'src' or path.startswith('src/')): + reject(source, f'private {kind} {uri}') + elif not uri.startswith('dart:'): + target = (source.parent / uri).resolve() + boundary = root / ('lib' if area == 'lib' else '') + if not target.is_relative_to(boundary.resolve()): + reject(source, f'escaping {kind} {uri}') + if any(target.is_relative_to((root / 'packages' / package).resolve()) + for package in RUNTIME): + reject(source, f'relative workspace {kind} {uri}') + return errors + + +def main(): + errors = check(ROOT) + if errors: + raise SystemExit('\n'.join(errors)) + print('Internal package boundaries: passed') + + +if __name__ == '__main__': + main() diff --git a/tool/check_public_repository.py b/tool/check_public_repository.py new file mode 100644 index 0000000..7ddd561 --- /dev/null +++ b/tool/check_public_repository.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python3 +"""Check publishable source files without Flutter or private dependencies. + +Uses tracked and non-ignored untracked files, leaving local inputs untouched. +Credential checks cover recognizable formats, not arbitrary passwords or history. +""" +from pathlib import Path +import re +import subprocess +from urllib.parse import unquote, urlsplit + +ROOT = Path(__file__).resolve().parent.parent +LOCAL_DIRECTORIES = { + '.local', '.dart_tool', '.gradle', '.build', '.swiftpm', '__pycache__', + 'build', 'coverage', 'Pods', 'ephemeral', 'xcuserdata', +} +PRIVATE_SUFFIXES = {'.pem', '.key', '.p8', '.p12', '.pfx', '.keystore', '.jks', + '.mobileprovision', '.provisionprofile'} +CREDENTIALS = re.compile( + r'-----BEGIN (?:RSA |EC |OPENSSH |DSA )?PRIVATE KEY-----|' + r'gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|' + r'sk-[A-Za-z0-9_-]{24,}|AKIA[0-9A-Z]{16}' +) +MARKDOWN_LINK = re.compile(r'!?\[[^\]]*\]\(([^\s)]+)\)') + + +def git_files(root, *arguments): + result = subprocess.check_output(['git', 'ls-files', '-z', *arguments], cwd=root) + return sorted(set(result.decode('utf-8').split('\0')) - {''}) + + +def check_files(root, names): + errors = [] + root = root.resolve() + for name in names: + path = root / name + if not path.exists() and not path.is_symlink(): + continue # Worktree deletions are absent from the next source snapshot. + if not path.resolve().is_relative_to(root): + errors.append(f'{name}: symlink escapes repository') + continue + if not path.is_file(): + continue + if (LOCAL_DIRECTORIES.intersection(path.relative_to(root).parts) + or name.startswith(('validation/', 'test-results/', 'dist/')) + or any(part.endswith('.cutdex') for part in path.relative_to(root).parts) + or path.name in {'.DS_Store', 'pubspec_overrides.yaml', 'key.properties'} + or path.suffix in PRIVATE_SUFFIXES + or path.name == '.env' + or (path.name.startswith('.env.') + and not path.name.endswith(('.example', '.sample')))): + errors.append(f'{name}: local artifact or credential configuration') + if path.stat().st_size > 50 * 1024 * 1024: + errors.append(f'{name}: source file exceeds 50 MiB') + continue + try: + source = path.read_text(encoding='utf-8') + except UnicodeError: + continue + for number, line in enumerate(source.splitlines(), 1): + if CREDENTIALS.search(line): + # Never echo the matched credential. + errors.append(f'{name}:{number}: possible credential; review locally') + if path.suffix == '.md': + for match in MARKDOWN_LINK.finditer(source): + target = urlsplit(match.group(1).strip('<>')) + if target.scheme or target.netloc or not target.path: + continue + linked = (path.parent / unquote(target.path)).resolve() + if not linked.is_relative_to(root) or not linked.exists(): + errors.append(f'{name}: missing or external local link {target.path}') + return errors + + +def main(): + names = git_files(ROOT, '-co', '--exclude-standard') + errors = check_files(ROOT, names) + for name in git_files(ROOT, '-ci', '--exclude-standard'): + if (ROOT / name).exists(): + errors.append(f'{name}: ignored file is already tracked') + if errors: + raise SystemExit('\n'.join(errors)) + print(f'Public repository source checks: passed ({len(names)} paths considered)') + + +if __name__ == '__main__': + main() diff --git a/tool/diagnostics/benchmark_agent_context.dart b/tool/diagnostics/benchmark_agent_context.dart new file mode 100644 index 0000000..a9020b6 --- /dev/null +++ b/tool/diagnostics/benchmark_agent_context.dart @@ -0,0 +1,39 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:cutdex_agent/cutdex_agent.dart'; + +void main(List args) { + const usage = + 'Usage: dart run tool/diagnostics/benchmark_agent_context.dart '; + if (args.length == 1 && (args.single == '--help' || args.single == '-h')) { + stdout.writeln(usage); + return; + } + if (args.length != 1) { + stderr.writeln(usage); + exitCode = 2; + return; + } + final history = (jsonDecode(File(args[0]).readAsStringSync()) as List) + .map( + (m) => AgentMessage.fromJson( + Map.from(m as Map), + ), + ) + .toList(); + final builder = HarnessContextBuilder(); + final current = builder.projectHistory(history); + final result = { + 'messages': history.length, + 'fullHistoryTokens': builder.measureInput(system: '', history: history), + 'projectedHistoryTokens': builder.measureInput( + system: '', + history: current, + ), + 'originalBytes': jsonEncode(history.map((m) => m.toJson()).toList()).length, + 'projectedBytes': jsonEncode(current.map((m) => m.toJson()).toList()) + .length, + }; + stdout.writeln(const JsonEncoder.withIndent(' ').convert(result)); +} diff --git a/tool/diagnostics/benchmark_diagnostic_store.dart b/tool/diagnostics/benchmark_diagnostic_store.dart new file mode 100644 index 0000000..245ac1b --- /dev/null +++ b/tool/diagnostics/benchmark_diagnostic_store.dart @@ -0,0 +1,190 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:math' as math; + +import 'package:cutdex/diagnostics/diagnostic_store.dart'; + +const _usage = + 'Usage: dart run tool/diagnostics/benchmark_diagnostic_store.dart [--samples=7]'; + +Future main(List args) async { + if (args.contains('--help') || args.contains('-h')) { + stdout.writeln(_usage); + return; + } + var samples = 7; + if (args.isNotEmpty) { + samples = args.length == 1 && args.single.startsWith('--samples=') + ? int.tryParse(args.single.substring('--samples='.length)) ?? 0 + : 0; + if (samples < 1 || samples > 100) { + stderr.writeln(_usage); + exitCode = 2; + return; + } + } + final root = await Directory.systemTemp.createTemp('cutdex-log-benchmark-'); + try { + final output = []; + for (final workload in ['edit', 'error']) { + final count = workload == 'edit' ? 256 : 64; + final measured = >>{ + for (final mode in ['disabled', 'perEventFlush', 'batched']) mode: [], + }; + // Warm the serializer and file APIs before collecting samples; alternate order. + for (var round = -2; round < samples; round++) { + final modes = measured.keys.toList(); + if (round.isOdd) { + modes.setAll(0, modes.reversed.toList()); + } + for (final mode in modes) { + final result = await _sample( + root, + '$workload-$mode-$round', + workload, + count, + mode, + ); + if (round >= 0) measured[mode]!.add(result); + } + } + output.add({ + 'workload': workload, + 'records': count, + 'modes': { + for (final mode in measured.entries) + mode.key: { + for (final key in mode.value.first.keys) + key: _median(mode.value.map((sample) => sample[key]!).toList()), + }, + }, + }); + } + stdout.writeln( + const JsonEncoder.withIndent(' ').convert({ + 'runtime': Platform.version, + 'os': Platform.operatingSystem, + 'samples': samples, + 'warmupRounds': 2, + 'maxPending': 320, + 'errorReserveRecords': 40, + 'maxPendingBytes': 1024 * 1024, + 'errorReserveBytes': 256 * 1024, + 'method': 'Synthetic diagnostic record bursts, same store with batchSize=1 versus defaults; disabled measures harness overhead. No Flutter frames or media decoding measured.', + 'results': output, + }), + ); + } catch (error) { + stderr.writeln('Diagnostic benchmark failed: $error'); + exitCode = 1; + } finally { + await root.delete(recursive: true); + } +} + +Future> _sample( + Directory root, + String id, + String workload, + int count, + String mode, +) async { + final directory = Directory('${root.path}/$id'); + final store = mode == 'disabled' + ? null + : DiagnosticStore( + directory, + maxPending: 320, + batchSize: mode == 'perEventFlush' ? 1 : 32, + ); + final records = [ + for (var i = 0; i < count; i++) + { + 'at': '2026-10-05T00:00:00.000Z', + 'sessionId': 'session', + 'level': workload == 'edit' ? 'info' : 'error', + 'component': 'editor', + 'operation': 'split', + 'environment': { + 'platform': 'macos', + 'appVersion': '1.0.0', + 'buildMode': 'release', + }, + 'context': { + 'operationId': 'operation-$i', + 'timelineId': 'timeline', + 'sequenceId': 'sequence', + 'clipIds': ['clip'], + 'playheadTick': 5000000, + 'versionBefore': 'before', + 'versionAfter': 'after', + }, + if (workload == 'error') ...{ + 'error': { + 'type': 'StateError', + 'message': 'Decoder rejected the requested frame', + }, + 'stackTrace': List.generate( + 24, + (line) => '#$line editor.dart:120', + ).join('\n'), + 'stderr': 'decoder failure at selected frame\n' * 256, + }, + }, + ]; + final clock = Stopwatch()..start(); + var previousTick = 0; + var maxTimerGapUs = 0; + final timer = Timer.periodic(const Duration(milliseconds: 1), (_) { + final now = clock.elapsedMicroseconds; + maxTimerGapUs = math.max(maxTimerGapUs, now - previousTick); + previousTick = now; + }); + final latencies = []; + final enqueueStart = clock.elapsedMicroseconds; + for (final record in records) { + final start = clock.elapsedMicroseconds; + store?.record(record); + latencies.add(clock.elapsedMicroseconds - start); + } + final enqueueUs = clock.elapsedMicroseconds - enqueueStart; + final drainStart = clock.elapsedMicroseconds; + await store?.flush(); + final drainUs = clock.elapsedMicroseconds - drainStart; + timer.cancel(); + if (store != null) { + var persisted = 0; + await for (final entity in directory.list()) { + if (entity is File && entity.path.endsWith('.jsonl')) { + for (final line in await entity.readAsLines()) { + jsonDecode(line); + persisted++; + } + } + } + if (persisted != count || store.dropped != 0 || store.writeFailures != 0) { + throw StateError( + 'Invalid sample: expected $count, persisted $persisted, dropped ${store.dropped}, failures ${store.writeFailures}', + ); + } + } + latencies.sort(); + return { + 'enqueueUs': enqueueUs, + 'recordP95Us': latencies[(count * .95).ceil() - 1], + 'drainUs': drainUs, + 'totalUs': enqueueUs + drainUs, + 'maxTimerGapUs': maxTimerGapUs, + 'durableEventAppends': store?.eventFlushes ?? 0, + 'eventBytesWritten': store?.eventBytesWritten ?? 0, + }; +} + +num _median(List values) { + values.sort(); + final middle = values.length ~/ 2; + return values.length.isOdd + ? values[middle] + : (values[middle - 1] + values[middle]) / 2; +} diff --git a/tool/diagnostics/frame_budget.py b/tool/diagnostics/frame_budget.py new file mode 100644 index 0000000..e9dab59 --- /dev/null +++ b/tool/diagnostics/frame_budget.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python3 +"""Summarize opt-in Release FrameTiming JSONL and optional UTC phase markers. + +Build/raster budget misses are reported separately. Total pipeline latency is +not a dropped-frame count. Engine timestamps are not display-present evidence. +""" + +import argparse +import datetime +import json + + +def read_jsonl(path): + with open(path, encoding="utf-8-sig") as source: + return [json.loads(line) for line in source if line.strip()] + + +def seconds(timestamp): + return datetime.datetime.fromisoformat(timestamp.replace("Z", "+00:00")).timestamp() + + +def summarize(name, frames): + if not frames: + return {"name": name, "frames": 0} + result = {"name": name, "frames": len(frames)} + for column, stage in [(1, "build"), (2, "raster"), (3, "total")]: + values = sorted(frame[column] / 1000 for frame in frames) + result[stage] = { + f"p{int(percentile * 100)}Ms": round( + values[int((len(values) - 1) * percentile)], 3 + ) + for percentile in [0.5, 0.95, 0.99] + } + result[stage].update( + maxMs=max(values), + over60Hz=sum(value > 1000 / 60 for value in values), + over120Hz=sum(value > 1000 / 120 for value in values), + ) + return result + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("frames", help="CUTDEX_FRAME_TIMINGS output file") + parser.add_argument("phases", nargs="?", help="Optional UTC scenario marker JSONL") + args = parser.parse_args() + batches = read_jsonl(args.frames) + overall = summarize("all", [frame for batch in batches for frame in batch["frames"]]) + overall["droppedDiagnosticSamples"] = sum(batch.get("dropped", 0) for batch in batches) + print(json.dumps(overall)) + if args.phases: + phases = {entry["phase"]: seconds(entry["at"]) for entry in read_jsonl(args.phases)} + for name in ["scrub", "zoom", "drag", "clip", "trim", "pan", "play"]: + start, end = phases.get(f"{name}-start"), phases.get(f"{name}-end") + if start is None or end is None: + continue + # Allow for the two-second asynchronous reporting batch boundary. + frames = [ + frame + for batch in batches + if start + 2.2 < seconds(batch["at"]) < end + for frame in batch["frames"] + ] + print(json.dumps(summarize(name, frames))) + + +if __name__ == "__main__": + main() diff --git a/tool/macos/build_macos_release.sh b/tool/macos/build_macos_release.sh new file mode 100755 index 0000000..0dfc438 --- /dev/null +++ b/tool/macos/build_macos_release.sh @@ -0,0 +1,85 @@ +#!/bin/bash + +set -euo pipefail + +if [ "$#" -eq 1 ] && { [ "$1" = "--help" ] || [ "$1" = "-h" ]; }; then + echo "Usage: $0 [output-directory]" + exit 0 +fi + +if [[ $# -lt 1 || $# -gt 2 ]]; then + echo "Usage: $0 [output-directory]" >&2 + exit 2 +fi + +repo_root="$(cd "$(dirname "$0")/../.." && pwd)" +runtime_root="$(cd "$1" && pwd)" +output_root="${2:-$repo_root/dist/macos}" +signing_identity="${CUTDEX_CODESIGN_IDENTITY:--}" +python="${PYTHON:-python3}" +flutter="${FLUTTER:-flutter}" +app="$repo_root/build/macos/Build/Products/Release-production/cutdex.app" +resources="$app/Contents/Resources" +embedded_runtime="$resources/processing" +mkdir -p "$output_root" +output_root="$(cd "$output_root" && pwd)" +archive="$output_root/cutdex-macos14-arm64.zip" +dmg="$output_root/cutdex-macos14-arm64.dmg" + +if [[ -n "${CUTDEX_NOTARY_PROFILE:-}" && "$signing_identity" == "-" ]]; then + echo "CUTDEX_NOTARY_PROFILE requires a Developer ID signing identity" >&2 + exit 1 +fi + +if [[ -n "${CUTDEX_UPDATE_FEED_URL:-}${CUTDEX_UPDATE_PUBLIC_KEY:-}" ]]; then + if [[ -z "${CUTDEX_UPDATE_FEED_URL:-}" || -z "${CUTDEX_UPDATE_PUBLIC_KEY:-}" ]]; then + echo "Set both CUTDEX_UPDATE_FEED_URL and CUTDEX_UPDATE_PUBLIC_KEY" >&2 + exit 1 + fi +fi + +# Fail before the Flutter build if a worker or a transitive library is missing. +"$python" "$repo_root/tool/macos/check_macos_release.py" --runtime "$runtime_root" + +cd "$repo_root" +bash "$repo_root/tool/macos/check_macos_build_target.sh" "$app/Contents/MacOS/cutdex" +rm -rf "$embedded_runtime" +"$flutter" build macos --release --flavor production \ + --split-debug-info=build/symbols/macos + +mkdir -p "$resources" "$output_root" +ditto "$runtime_root" "$embedded_runtime" + +if [[ -n "${CUTDEX_UPDATE_FEED_URL:-}" ]]; then + "$python" "$repo_root/tool/macos/macos_updates.py" configure --app "$app" \ + --feed "$CUTDEX_UPDATE_FEED_URL" --public-key "$CUTDEX_UPDATE_PUBLIC_KEY" +fi + +bash "$repo_root/tool/macos/sign_macos_app.sh" "$app" +"$python" "$repo_root/tool/macos/check_macos_release.py" --app "$app" \ + --report "$output_root/package-check.json" + +rm -f "$archive" +ditto -c -k --sequesterRsrc --keepParent "$app" "$archive" + +if [[ -n "${CUTDEX_NOTARY_PROFILE:-}" ]]; then + xcrun notarytool submit "$archive" \ + --keychain-profile "$CUTDEX_NOTARY_PROFILE" --wait + xcrun stapler staple "$app" + rm -f "$archive" + ditto -c -k --sequesterRsrc --keepParent "$app" "$archive" +fi + +bash "$repo_root/tool/macos/create_macos_dmg.sh" "$app" "$dmg" +if [[ -n "${CUTDEX_NOTARY_PROFILE:-}" ]]; then + xcrun notarytool submit "$dmg" \ + --keychain-profile "$CUTDEX_NOTARY_PROFILE" --wait + xcrun stapler staple "$dmg" + xcrun stapler validate "$dmg" +fi + +echo "App: $app" +echo "Archive: $archive" +shasum -a 256 "$archive" +echo "DMG: $dmg" +shasum -a 256 "$dmg" diff --git a/tool/macos/check_macos_build_target.sh b/tool/macos/check_macos_build_target.sh new file mode 100644 index 0000000..48eb78d --- /dev/null +++ b/tool/macos/check_macos_build_target.sh @@ -0,0 +1,19 @@ +#!/bin/sh +set -eu + +if [ "$#" -eq 1 ] && { [ "$1" = "--help" ] || [ "$1" = "-h" ]; }; then + echo "Usage: $0 " + exit 0 +fi + +# Replacing native assets under a live Flutter process can load a second SQLite +# image on a later lazy FFI lookup, mixing its globals with existing handles. +# Check the exact build product, not other installed copies of the application. +if [ "$#" -ne 1 ]; then + echo 'usage: check_macos_build_target.sh ' >&2 + exit 2 +fi +if /bin/ps -axo comm= | /usr/bin/grep -Fx -- "$1" >/dev/null; then + echo 'error: Cutdex is running from this build target. Save your edits and quit it (or stop the debugger), then rebuild. Hot reload does not require a native rebuild.' >&2 + exit 1 +fi diff --git a/tool/macos/check_macos_release.py b/tool/macos/check_macos_release.py new file mode 100644 index 0000000..8eceb07 --- /dev/null +++ b/tool/macos/check_macos_release.py @@ -0,0 +1,115 @@ +"""Audit a relocatable arm64 macOS app or processing runtime, without models.""" +import argparse +import json +import os +from pathlib import Path +import plistlib +import re +import struct +import subprocess +import tempfile + + +REQUIRED = ( + 'bin/cutdex-processing-worker', 'bin/ffmpeg', 'bin/ffprobe', + 'workers/asr/cutdex-asr-worker', 'workers/audio/cutdex-audio-worker', + 'workers/translation/cutdex-m2m100-worker', +) + + +def output(*args, **kwargs): + return subprocess.check_output(args, text=True, timeout=60, **kwargs) + + +def system(path): + return path.startswith(('/System/Library/', '/usr/lib/')) + + +def audit(root, app=False): + root = root.resolve() + runtime = root / 'Contents/Resources/processing' if app else root + for name in REQUIRED: + path = runtime / name + if not path.is_file() or not os.access(path, os.X_OK): + raise RuntimeError(f'Missing executable: {path}') + executable = runtime / REQUIRED[0] + if app: + info = plistlib.loads((root / 'Contents/Info.plist').read_bytes()) + executable = root / 'Contents/MacOS' / info['CFBundleExecutable'] + assets = root / 'Contents/Frameworks/App.framework/Resources/flutter_assets' + if not executable.is_file() or not assets.is_dir(): + raise RuntimeError('Missing app executable or Flutter assets') + output('/usr/bin/codesign', '--verify', '--deep', '--strict', str(root)) + # Check actual contents, not only the native files declared by a manifest. + native = {} + for path in root.rglob('*'): + if path.is_symlink() and not path.resolve().is_relative_to(root): + raise RuntimeError(f'Symlink escapes bundle: {path}') + if not path.is_file() or path.is_symlink(): + continue + with path.open('rb') as stream: + magic = stream.read(4) + if magic not in (b'\xcf\xfa\xed\xfe', b'\xfe\xed\xfa\xcf', b'\xca\xfe\xba\xbe', b'\xbe\xba\xfe\xca'): + continue + arch = output('/usr/bin/lipo', '-archs', str(path)).strip().split() + if 'arm64' not in arch: + raise RuntimeError(f'Missing arm64 slice: {path}: {arch}') + commands = output('/usr/bin/otool', '-arch', 'arm64', '-l', str(path)) + versions = re.findall(r'\bminos ([\d.]+)', commands) + versions += re.findall(r'LC_VERSION_MIN_MACOSX\s+cmdsize \d+\s+version ([\d.]+)', commands) + if not versions or any(tuple((list(map(int, v.split('.'))) + [0, 0])[:3]) > (14, 0, 0) for v in versions): + raise RuntimeError(f'Minimum macOS exceeds 14.0: {path}: {versions}') + rpaths = re.findall(r'LC_RPATH\s+cmdsize \d+\s+path (.*?) \(offset', commands) + for entry in rpaths: + if not system(entry) and not entry.startswith(('@loader_path/', '@executable_path/')): + raise RuntimeError(f'External runtime search path: {path}: {entry}') + imports = output('/usr/bin/otool', '-arch', 'arm64', '-L', str(path)).splitlines()[1:] + identity = output('/usr/bin/otool', '-arch', 'arm64', '-D', str(path)).splitlines()[1:] + native[path] = (rpaths, [line.strip().split(' (compatibility version')[0] for line in imports if line.strip().split(' (compatibility version')[0] not in identity]) + if executable.resolve() not in native: + raise RuntimeError(f'Not a Mach-O executable: {executable}') + for path, (rpaths, dependencies) in native.items(): + def expand(entry, owner): + return Path(entry.replace('@loader_path', str(owner.parent)).replace('@executable_path', str(executable.parent))) + search = [expand(p, path) for p in rpaths] + search += [expand(p, executable) for p in native[executable.resolve()][0]] + for dependency in dependencies: + if system(dependency): + continue + if dependency.startswith('@rpath/'): + candidates = [p / dependency[len('@rpath/'):] for p in search] + elif dependency.startswith(('@loader_path/', '@executable_path/')): + candidates = [expand(dependency, path)] + else: + raise RuntimeError(f'External native dependency: {path}: {dependency}') + if not any(p.resolve().is_relative_to(root) and p.is_file() for p in candidates): + raise RuntimeError(f'Unresolved bundled dependency: {path}: {dependency}') + with tempfile.TemporaryDirectory(prefix='cutdex-package-check-') as temporary: + env = {'PATH': '/usr/bin:/bin', 'HOME': temporary, 'TMPDIR': temporary} + descriptors = json.loads(output(str(runtime / REQUIRED[0]), '--capabilities', env=env)) + operations = {op for d in descriptors if d['available'] for op in d['operations']} + if not {'transcribeAudio', 'translateSubtitles', 'separateVocals'}.issubset(operations): + raise RuntimeError('Bundled processing capabilities unavailable') + for name in REQUIRED[1:3]: + output(str(runtime / name), '-version', env=env) + for name in REQUIRED[3:5]: + output(str(runtime / name), '--self-test', env=env) + result = subprocess.check_output([str(runtime / REQUIRED[5]), '--self-test'], env=env, timeout=60) + payload = '你好\r\n\x1a!'.encode('utf-8') + if result != struct.pack(' " + exit 0 +fi + +if [[ $# -ne 2 ]]; then + echo "Usage: $0 " >&2 + exit 2 +fi + +app="$(cd "$(dirname "$1")" && pwd)/$(basename "$1")" +output="$2" + +if [[ ! -f "$app/Contents/Info.plist" ]]; then + echo "Missing macOS application: $app" >&2 + exit 1 +fi +icon="$app/Contents/Resources/AppIcon.icns" +if [[ ! -f "$icon" ]]; then + echo "Missing application icon: $icon" >&2 + exit 1 +fi +if [[ "$output" != *.dmg ]]; then + echo "Output must have a .dmg extension: $output" >&2 + exit 2 +fi + +mkdir -p "$(dirname "$output")" +output="$(cd "$(dirname "$output")" && pwd)/$(basename "$output")" +stage="$(mktemp -d "${TMPDIR:-/tmp}/cutdex-dmg.XXXXXX")" +source="$stage/source" +mount="$stage/mounted" +mounted=false +cleanup() { + if [[ "$mounted" == true ]]; then + hdiutil detach -quiet "$mount" || true + fi + rm -rf "$stage" +} +trap cleanup EXIT + +mkdir "$source" "$mount" +ditto "$app" "$source/$(basename "$app")" +ln -s /Applications "$source/Applications" +ditto "$icon" "$source/.VolumeIcon.icns" +hdiutil create -quiet -format UDRW -volname Cutdex -srcfolder "$source" "$stage/uncompressed.dmg" +hdiutil attach -quiet -readwrite -nobrowse -mountpoint "$mount" "$stage/uncompressed.dmg" +mounted=true +xcrun SetFile -a C "$mount" +hdiutil detach -quiet "$mount" +mounted=false +hdiutil convert -quiet "$stage/uncompressed.dmg" -format UDZO -o "$output" -ov +hdiutil verify -quiet "$output" +swift "$(dirname "$0")/set_macos_file_icon.swift" "$icon" "$output" + +echo "DMG: $output" +shasum -a 256 "$output" diff --git a/tool/macos/macos_updates.py b/tool/macos/macos_updates.py new file mode 100644 index 0000000..b45f52f --- /dev/null +++ b/tool/macos/macos_updates.py @@ -0,0 +1,157 @@ +#!/usr/bin/env python3 +"""Configure Sparkle before signing and prepare full-only update publications.""" +import argparse +import base64 +from pathlib import Path +import plistlib +import re +import shutil +import subprocess +import tempfile +from urllib.parse import urlsplit +import xml.etree.ElementTree as ET + +SPARKLE = 'http://www.andymatuschak.org/xml-namespaces/sparkle' + + +def validate_url(value, local=False): + url = urlsplit(value) + if not url.hostname or url.username or url.password or url.fragment or url.query: + raise ValueError('Use an absolute update URL without credentials, query or fragment') + if url.scheme != 'https' and not ( + local and url.scheme == 'http' and url.hostname == 'localhost' + ): + raise ValueError('Updates require HTTPS (local testing permits http://localhost only)') + return value + + +def validate_key(value): + if len(base64.b64decode(value, validate=True)) != 32: + raise ValueError('Sparkle requires a base64-encoded 32-byte public key') + return value + + +def configure(app, feed, public_key, local=False): + info_path = app / 'Contents/Info.plist' + info = plistlib.loads(info_path.read_bytes()) + if local and info['CFBundleIdentifier'] != 'app.cutdex.desktop.dev': + raise ValueError('Local updates are restricted to the development app') + info['DeskupAllowLocalHTTP'] = bool(local) + info['SUFeedURL'] = validate_url(feed, local) + info['SUPublicEDKey'] = validate_key(public_key) + info['SUEnableAutomaticChecks'] = False + info['SUAllowsAutomaticUpdates'] = False + info['SUAutomaticallyUpdate'] = False + if local: + # Narrow ATS exception: no arbitrary network loads, never in production. + ats = info.setdefault('NSAppTransportSecurity', {}) + ats.setdefault('NSExceptionDomains', {})['localhost'] = { + 'NSExceptionAllowsInsecureHTTPLoads': True, + 'NSIncludesSubdomains': False, + } + info_path.write_bytes(plistlib.dumps(info)) + + +def validate_app(app, local=False): + info = plistlib.loads((app / 'Contents/Info.plist').read_bytes()) + validate_url(info['SUFeedURL'], local) + validate_key(info['SUPublicEDKey']) + expected_id = 'app.cutdex.desktop.dev' if local else 'app.cutdex.desktop' + if info['CFBundleIdentifier'] != expected_id: + raise ValueError('Wrong application identity for this update channel') + if not re.fullmatch(r'[0-9]+(?:\.[0-9]+){0,2}', info['CFBundleVersion']): + raise ValueError('Use a monotonically increasing numeric build version') + framework = app / 'Contents/Frameworks/Sparkle.framework' + for file in ['Sparkle', 'Autoupdate', 'Updater.app/Contents/MacOS/Updater']: + if not (framework / file).is_file(): + raise ValueError(f'Missing Sparkle component: {file}') + subprocess.run(['codesign', '--verify', '--deep', '--strict', str(app)], check=True) + if not local: + subprocess.run(['xcrun', 'stapler', 'validate', str(app)], check=True) + subprocess.run(['spctl', '--assess', '--type', 'execute', str(app)], check=True) + return info + + + +def version_key(version): + if not re.fullmatch(r'[0-9]+(?:\.[0-9]+){0,2}', version): + raise ValueError(f'Invalid numeric build version: {version}') + parts = tuple(map(int, version.split('.'))) + return parts + (0,) * (3 - len(parts)) + + +def require_newer_build(output, version): + feed = output / 'appcast.xml' + if not feed.exists(): + return + items = ET.parse(feed).findall('./channel/item') + for item in items: + current = item.findtext(f'{{{SPARKLE}}}version') + if current is None: + enclosure = item.find('enclosure') + current = None if enclosure is None else enclosure.get(f'{{{SPARKLE}}}version') + if current is None: + raise ValueError('Existing appcast item is missing its build version') + if version_key(version) <= version_key(current): + raise ValueError(f'New build {version} must be newer than published build {current}') + + +def publish(app, output, base_url, tools, key_file=None, local=False): + """Stage a complete publication; never mutate an existing version archive.""" + validate_url(base_url, local) + info = validate_app(app, local) + output.mkdir(parents=True, exist_ok=True) + require_newer_build(output, info['CFBundleVersion']) + filename = f"cutdex-{info['CFBundleVersion']}-macos-arm64.zip" + archive = output / filename + if archive.exists(): + raise ValueError(f'Refusing to replace published archive: {archive}') + with tempfile.TemporaryDirectory(prefix='cutdex-update-') as directory: + stage = Path(directory) + subprocess.run(['ditto', '-c', '-k', '--sequesterRsrc', '--keepParent', + str(app), str(stage / filename)], check=True) + command = [str(tools / 'generate_appcast'), '--maximum-deltas', '0', + '--download-url-prefix', base_url.rstrip('/') + '/', + '-o', str(stage / 'appcast.xml')] + if key_file: + command.extend(['--ed-key-file', str(key_file)]) + subprocess.run([*command, str(stage)], check=True) + tree = ET.parse(stage / 'appcast.xml') + if tree.findall(f'.//{{{SPARKLE}}}deltas'): + raise ValueError('This release pipeline only permits full updates') + enclosures = tree.findall('.//enclosure') + if len(enclosures) != 1 or not enclosures[0].get(f'{{{SPARKLE}}}edSignature'): + raise ValueError('Expected exactly one signed full update') + # Upload archive first, appcast last. Local replacement is atomic too. + shutil.copy2(stage / filename, archive) + pending = output / 'appcast.xml.pending' + shutil.copy2(stage / 'appcast.xml', pending) + pending.replace(output / 'appcast.xml') + return archive + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest='command', required=True) + config = commands.add_parser('configure') + config.add_argument('--app', type=Path, required=True) + config.add_argument('--feed', required=True) + config.add_argument('--public-key', required=True) + config.add_argument('--local', action='store_true') + release = commands.add_parser('publish') + release.add_argument('--app', type=Path, required=True) + release.add_argument('--output', type=Path, required=True) + release.add_argument('--base-url', required=True) + release.add_argument('--tools', type=Path, required=True, help='Sparkle bin directory') + release.add_argument('--key-file', type=Path) + release.add_argument('--local', action='store_true') + args = parser.parse_args() + if args.command == 'configure': + configure(args.app, args.feed, args.public_key, args.local) + else: + print(publish(args.app, args.output, args.base_url, args.tools.resolve(), + args.key_file, args.local)) + + +if __name__ == '__main__': + main() diff --git a/tool/macos/set_macos_file_icon.swift b/tool/macos/set_macos_file_icon.swift new file mode 100644 index 0000000..b921bd3 --- /dev/null +++ b/tool/macos/set_macos_file_icon.swift @@ -0,0 +1,19 @@ +import AppKit +import Foundation + +let arguments = Array(CommandLine.arguments.dropFirst()) +let usage = "Usage: swift set_macos_file_icon.swift \n" +if arguments == ["--help"] || arguments == ["-h"] { + print(usage, terminator: "") + exit(0) +} +guard arguments.count == 2 else { + fputs(usage, stderr) + exit(2) +} +guard FileManager.default.fileExists(atPath: arguments[1]), + let icon = NSImage(contentsOfFile: arguments[0]), + NSWorkspace.shared.setIcon(icon, forFile: arguments[1], options: []) else { + fputs("Failed to set file icon: verify the icon and target paths\n", stderr) + exit(1) +} diff --git a/tool/macos/sign_macos_app.sh b/tool/macos/sign_macos_app.sh new file mode 100644 index 0000000..af3ec7a --- /dev/null +++ b/tool/macos/sign_macos_app.sh @@ -0,0 +1,44 @@ +#!/bin/bash +set -euo pipefail + +if [ "$#" -eq 1 ] && { [ "$1" = "--help" ] || [ "$1" = "-h" ]; }; then + echo "Usage: $0 " + exit 0 +fi +if [[ $# != 1 ]]; then + echo "Usage: $0 " >&2 + exit 2 +fi +repo_root="$(cd "$(dirname "$0")/../.." && pwd)" +app="$1" +signing_identity="${CUTDEX_CODESIGN_IDENTITY:--}" +# Flutter's prebuilt engine carries an unused Homebrew search path. Remove it +# from our copy before signing; the audit rejects any remaining external paths. +engine="$app/Contents/Frameworks/FlutterMacOS.framework/Versions/A/FlutterMacOS" +if /usr/bin/otool -l "$engine" | grep -F 'path /usr/local/lib/. (offset' >/dev/null; then + /usr/bin/install_name_tool -delete_rpath /usr/local/lib/. "$engine" +fi +codesign_args=(--force --sign "$signing_identity") +if [[ "$signing_identity" == "-" ]]; then + codesign_args+=(--timestamp=none) +else + codesign_args+=(--timestamp --options runtime) +fi + +while IFS= read -r binary; do + if file "$binary" | grep -q 'Mach-O'; then + codesign "${codesign_args[@]}" --preserve-metadata=entitlements "$binary" + fi +done < <(find "$app/Contents" -type f -print | sort) + +# Every nested bundle must use the same identity as the outer app. Mixing the +# Xcode development signature with an ad-hoc or Developer ID signature causes +# dyld to reject FlutterMacOS.framework on a clean launch. +while IFS= read -r bundle; do + codesign "${codesign_args[@]}" --preserve-metadata=entitlements "$bundle" +done < <(find "$app/Contents" -type d \( \ + -name '*.framework' -o -name '*.appex' -o -name '*.xpc' -o -name '*.app' \ + \) -print | awk '{ print length, $0 }' | sort -rn | cut -d' ' -f2-) + +codesign "${codesign_args[@]}" \ + --entitlements "$repo_root/macos/Runner/Release.entitlements" "$app" diff --git a/tool/macos/sparkle_test_key.swift b/tool/macos/sparkle_test_key.swift new file mode 100644 index 0000000..d7ad490 --- /dev/null +++ b/tool/macos/sparkle_test_key.swift @@ -0,0 +1,44 @@ +// Local simulation only. Creates an isolated key file; never touches Keychain. +import CryptoKit +import Foundation + +let arguments = Array(CommandLine.arguments.dropFirst()) +let usage = "Usage: swift sparkle_test_key.swift \n" +if arguments == ["--help"] || arguments == ["-h"] { + print(usage, terminator: "") + exit(0) +} +guard arguments.count == 1 else { + fputs(usage, stderr) + exit(2) +} + +do { + let directory = URL(fileURLWithPath: arguments[0], isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, + attributes: [.posixPermissions: 0o700]) + let privateURL = directory.appendingPathComponent("private.key") + let key: Curve25519.Signing.PrivateKey + if FileManager.default.fileExists(atPath: privateURL.path) { + let encoded = try String(contentsOf: privateURL, encoding: .utf8) + guard let data = Data(base64Encoded: encoded) else { + fputs("Invalid test key file\n", stderr) + exit(1) + } + key = try Curve25519.Signing.PrivateKey(rawRepresentation: data) + } else { + key = Curve25519.Signing.PrivateKey() + guard FileManager.default.createFile(atPath: privateURL.path, + contents: key.rawRepresentation.base64EncodedData(), + attributes: [.posixPermissions: 0o600]) else { + fputs("Could not write test key file\n", stderr) + exit(1) + } + } + try key.publicKey.rawRepresentation.base64EncodedString().write( + to: directory.appendingPathComponent("public.key"), atomically: true, encoding: .utf8) +} catch { + // Do not print private key contents in diagnostics. + fputs("Could not create or read test key files\n", stderr) + exit(1) +} diff --git a/tool/macos/test_check_macos_release.py b/tool/macos/test_check_macos_release.py new file mode 100644 index 0000000..7da5d6d --- /dev/null +++ b/tool/macos/test_check_macos_release.py @@ -0,0 +1,56 @@ +"""Fault injection against a real extracted runtime; never modifies the source.""" +import argparse +import importlib.util +from pathlib import Path +import shutil +import subprocess +import tempfile + +spec = importlib.util.spec_from_file_location('release_check', Path(__file__).with_name('check_macos_release.py')) +check = importlib.util.module_from_spec(spec) +spec.loader.exec_module(check) + + +def rejected(root, expected): + try: + check.audit(root) + except RuntimeError as error: + if expected not in str(error): + raise + print(f'Correctly rejected: {expected}') + else: + raise AssertionError(f'Did not reject: {expected}') + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--runtime', type=Path, required=True) + args = parser.parse_args() + with tempfile.TemporaryDirectory(prefix='cutdex-audit-faults-') as temporary: + root = Path(temporary) / 'runtime' + shutil.copytree(args.runtime, root, symlinks=True) + worker = root / 'workers/asr/cutdex-asr-worker' + held = worker.with_suffix('.held') + worker.rename(held) + rejected(root, 'Missing executable') + held.rename(worker) + # Use the actual package's version instead of pinning FFmpeg's ABI. + library = next((root / 'lib').glob('libavcodec.*.dylib')) + saved = Path(temporary) / library.name + library.rename(saved) + rejected(root, 'Unresolved bundled dependency') + saved.rename(library) + link = root / 'external-library' + link.symlink_to('/usr/lib') + rejected(root, 'Symlink escapes bundle') + link.unlink() + backup = Path(temporary) / 'asr-backup' + shutil.copy2(worker, backup) + subprocess.run(['/usr/bin/install_name_tool', '-add_rpath', '/tmp/developer-libraries', str(worker)], check=True) + rejected(root, 'External runtime search path') + shutil.copy2(backup, worker) + print(check.audit(root)) + + +if __name__ == '__main__': + main() diff --git a/tool/macos/test_macos_release.py b/tool/macos/test_macos_release.py new file mode 100644 index 0000000..ab6e18b --- /dev/null +++ b/tool/macos/test_macos_release.py @@ -0,0 +1,82 @@ +"""Build and relocate a Release smoke app; exercise no-model and configured-model startup. + +The JSON config supplies WHISPER_SOURCE, M2M100_SOURCE, MELBAND_SOURCE and +CUTDEX_ASR_FIXTURE. Models are copied into the app-managed resource layout. +Run build_macos_release.sh afterwards to produce the normal application. +""" +import argparse +import json +import os +import shutil +from pathlib import Path +import subprocess +import tempfile + + +def run(command, **kwargs): + subprocess.run(list(map(str, command)), check=True, timeout=900, **kwargs) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--runtime', type=Path, required=True) + parser.add_argument('--config', type=Path, required=True) + parser.add_argument('--report', type=Path, required=True) + args = parser.parse_args() + repo = Path(__file__).resolve().parents[2] + config = json.loads(args.config.read_text()) + model_keys = ['WHISPER_SOURCE', 'M2M100_SOURCE', 'MELBAND_SOURCE'] + for key in model_keys + ['CUTDEX_ASR_FIXTURE']: + if not Path(config[key]).is_absolute() or not Path(config[key]).exists(): + raise ValueError(f'Missing absolute input path: {key}') + runtime = args.runtime.resolve() + run([os.environ.get('FLUTTER', 'flutter'), 'build', 'macos', '--release', + '--flavor=production', '--target=tool/testing/release_smoke.dart'], cwd=repo) + with tempfile.TemporaryDirectory(prefix='cutdex relocated release ') as temporary: + root = Path(temporary) + app = root / 'cutdex.app' + run(['/usr/bin/ditto', repo / 'build/macos/Build/Products/Release-production/cutdex.app', app]) + # A previous release build may have embedded a different runtime. + embedded = app / 'Contents/Resources/processing' + if embedded.exists(): + shutil.rmtree(embedded) + run(['/usr/bin/ditto', runtime, embedded]) + run(['/bin/bash', repo / 'tool/macos/sign_macos_app.sh', app]) + run([os.environ.get('PYTHON', 'python3'), repo / 'tool/macos/check_macos_release.py', '--app', app]) + results = [] + for configured in [False, True]: + home = root / ('with-models' if configured else 'without-models') + home.mkdir() + report = home / 'result.json' + env = {'PATH': '/usr/bin:/bin', 'HOME': str(home), 'TMPDIR': str(home), + 'CUTDEX_SMOKE_REPORT': str(report), 'CUTDEX_SMOKE_MODELS': str(int(configured)), + 'CUTDEX_SMOKE_MEDIA': config['CUTDEX_ASR_FIXTURE']} + # No CUTDEX_PROCESSING_ROOT: exercise the executable-relative Bundle default. + if configured: + processing = home / 'Documents/Cutdex/Resources/Processing' + shutil.copytree(config['WHISPER_SOURCE'], + processing / 'Transcription/whisper-turbo/1') + shutil.copytree(config['M2M100_SOURCE'], + processing / 'Translation/m2m100-418m/1') + vocals = processing / 'VocalSeparation/melband/1' + vocals.mkdir(parents=True) + shutil.copy2(config['MELBAND_SOURCE'], vocals / 'melband.pt') + with (home / 'app.log').open('w') as log: + try: + run([app / 'Contents/MacOS/cutdex'], env=env, stdout=log, stderr=subprocess.STDOUT) + except Exception: + print((home / 'app.log').read_text()) + if report.exists(): + print(report.read_text()) + raise + result = json.loads(report.read_text()) + if not result['passed']: + raise RuntimeError(result) + results.append(result) + args.report.parent.mkdir(parents=True, exist_ok=True) + args.report.write_text(json.dumps(results, indent=2) + '\n') + print('Release smoke passed: no models; three configured capabilities and real translation.') + + +if __name__ == '__main__': + main() diff --git a/tool/macos/test_macos_updates.py b/tool/macos/test_macos_updates.py new file mode 100644 index 0000000..4f9f73f --- /dev/null +++ b/tool/macos/test_macos_updates.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 +"""Prepare two development apps and serve a signed full update on localhost.""" +import argparse +from functools import partial +from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer +import os +from pathlib import Path +import plistlib +import subprocess + +from macos_updates import configure, publish + + +class UpdateHandler(SimpleHTTPRequestHandler): + def end_headers(self): + self.send_header('Cache-Control', 'no-store') + super().end_headers() + + def list_directory(self, path): + self.send_error(404) + return None + + +def prepare(source, root, tools, port): + repository = Path(__file__).resolve().parents[2] + root = root.resolve() + public = root / 'public' + keys = root / 'keys' + if (root / 'installed').exists() or public.exists(): + raise ValueError('Use a fresh output directory to preserve existing test installs') + subprocess.run(['swift', str(repository / 'tool/macos/sparkle_test_key.swift'), str(keys)], check=True) + public_key = (keys / 'public.key').read_text() + feed = f'http://localhost:{port}/appcast.xml' + info = plistlib.loads((source / 'Contents/Info.plist').read_bytes()) + if info['CFBundleIdentifier'] != 'app.cutdex.desktop.dev': + raise ValueError('Build with --flavor development first') + for folder, version in [('installed', '900001'), ('candidate', '900002')]: + app = root / folder / 'cutdex.app' + app.parent.mkdir(parents=True) + subprocess.run(['ditto', str(source), str(app)], check=True) + path = app / 'Contents/Info.plist' + bundle = plistlib.loads(path.read_bytes()) + bundle['CFBundleVersion'] = version + path.write_bytes(plistlib.dumps(bundle)) + configure(app, feed, public_key, local=True) + subprocess.run(['bash', str(repository / 'tool/macos/sign_macos_app.sh'), str(app)], + env={**os.environ, 'CUTDEX_CODESIGN_IDENTITY': '-'}, check=True) + publish(root / 'candidate/cutdex.app', public, f'http://localhost:{port}', + tools.resolve(), keys / 'private.key', local=True) + print(f'Open: {root / "installed/cutdex.app"}', flush=True) + print('Settings → Check for updates: 900001 → 900002 (full ZIP)', flush=True) + return public + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--app', type=Path, help='Built development app') + parser.add_argument('--tools', type=Path, help='Sparkle bin directory') + parser.add_argument('--output', type=Path, default=Path('.local/update-test')) + parser.add_argument('--port', type=int, default=8765) + parser.add_argument('--serve-only', action='store_true') + args = parser.parse_args() + if args.serve_only: + public = args.output.resolve() / 'public' + else: + if not args.app or not args.tools: + parser.error('--app and --tools are required unless --serve-only') + public = prepare(args.app, args.output, args.tools, args.port) + if not (public / 'appcast.xml').is_file(): + parser.error('No prepared appcast.xml') + # Only public artifacts are served. Private keys live outside this root. + server = ThreadingHTTPServer(('127.0.0.1', args.port), + partial(UpdateHandler, directory=str(public))) + print(f'Serving http://localhost:{args.port}/appcast.xml', flush=True) + try: + server.serve_forever() + except KeyboardInterrupt: + pass + finally: + server.server_close() + + +if __name__ == '__main__': + main() diff --git a/tool/macos/test_macos_updates_unit.py b/tool/macos/test_macos_updates_unit.py new file mode 100644 index 0000000..f42d84e --- /dev/null +++ b/tool/macos/test_macos_updates_unit.py @@ -0,0 +1,82 @@ +"""Release channel isolation and full update validation regression tests.""" +import base64 +from pathlib import Path +import plistlib +import tempfile +import unittest +from unittest.mock import patch + +from macos_updates import configure, validate_url, publish, SPARKLE + + +class UpdateConfigurationTests(unittest.TestCase): + def test_production_rejects_local_feed(self): + with self.assertRaises(ValueError): + validate_url('http://localhost:8765/appcast.xml') + with self.assertRaises(ValueError): + validate_url('http://example.com/appcast.xml', local=True) + with self.assertRaises(ValueError): + validate_url('https://user:password@example.com/appcast.xml') + + def test_local_configuration_is_scoped_to_development(self): + with tempfile.TemporaryDirectory() as directory: + app = Path(directory) / 'cutdex.app' + (app / 'Contents').mkdir(parents=True) + path = app / 'Contents/Info.plist' + key = base64.b64encode(bytes(range(32))).decode() + original = {'CFBundleIdentifier': 'app.cutdex.desktop'} + path.write_bytes(plistlib.dumps(original)) + with self.assertRaises(ValueError): + configure(app, 'http://localhost:8765/appcast.xml', key, local=True) + self.assertEqual(plistlib.loads(path.read_bytes()), original) + original['CFBundleIdentifier'] += '.dev' + path.write_bytes(plistlib.dumps(original)) + configure(app, 'http://localhost:8765/appcast.xml', key, local=True) + info = plistlib.loads(path.read_bytes()) + self.assertFalse(info['SUAllowsAutomaticUpdates']) + self.assertFalse(info['SUEnableAutomaticChecks']) + self.assertNotIn('NSAllowsArbitraryLoads', info['NSAppTransportSecurity']) + self.assertEqual(set(info['NSAppTransportSecurity']['NSExceptionDomains']), {'localhost'}) + + def test_invalid_public_key_does_not_change_app(self): + with tempfile.TemporaryDirectory() as directory: + app = Path(directory) + (app / 'Contents').mkdir() + path = app / 'Contents/Info.plist' + original = plistlib.dumps({'CFBundleIdentifier': 'app.cutdex.desktop'}) + path.write_bytes(original) + with self.assertRaises(ValueError): + configure(app, 'https://updates.example.com/appcast.xml', 'YQ==') + self.assertEqual(path.read_bytes(), original) + + +class PublicationVersionTests(unittest.TestCase): + def test_older_or_equivalent_build_cannot_replace_current_feed(self): + for current, candidate in [('900002', '900001'), ('2', '2.0'), ('2.10', '2.9')]: + with self.subTest(current=current, candidate=candidate), tempfile.TemporaryDirectory() as directory: + output = Path(directory) + feed = output / 'appcast.xml' + original = (f'' + f'{current}' + '').encode() + feed.write_bytes(original) + def generate(command, **kwargs): + if command[0] == 'ditto': + Path(command[-1]).write_bytes(b'archive') + else: + Path(command[command.index('-o') + 1]).write_text( + f'' + f'{candidate}' + '' + '') + with patch('macos_updates.validate_app', return_value={'CFBundleVersion': candidate}), \ + patch('macos_updates.subprocess.run', side_effect=generate) as run: + with self.assertRaisesRegex(ValueError, 'newer'): + publish(Path('app'), output, 'https://example.com/', Path('tools')) + run.assert_not_called() + self.assertEqual(feed.read_bytes(), original) + self.assertEqual(list(output.glob('*.zip')), []) + + +if __name__ == '__main__': + unittest.main() diff --git a/tool/mcp_stdio.dart b/tool/mcp_stdio.dart new file mode 100644 index 0000000..1b7a064 --- /dev/null +++ b/tool/mcp_stdio.dart @@ -0,0 +1,47 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +/// Launch this from an MCP client while the configured Cutdex editor is open. +Future main() async { + final port = int.tryParse(Platform.environment['CUTDEX_MCP_PORT'] ?? ''); + final token = Platform.environment['CUTDEX_MCP_TOKEN']; + if (port == null || + port < 1 || + port > 65535 || + token == null || + token.length < 32 || + token.length > 1024 || + token.contains('\n') || + token.contains('\r')) { + stderr.writeln( + 'Set CUTDEX_MCP_PORT and CUTDEX_MCP_TOKEN to match the running app.', + ); + exitCode = 64; + return; + } + Socket? socket; + StreamSubscription>? input; + try { + final connection = await Socket.connect( + InternetAddress.loopbackIPv4, + port, + timeout: const Duration(seconds: 5), + ); + socket = connection; + connection.add(utf8.encode('$token\n')); + input = stdin.listen( + connection.add, + onDone: connection.destroy, + onError: (Object _) => connection.destroy(), + ); + await stdout.addStream(connection); + await stdout.flush(); + } catch (_) { + stderr.writeln('Could not connect to the Cutdex MCP endpoint.'); + exitCode = 1; + } finally { + await input?.cancel(); + socket?.destroy(); + } +} diff --git a/tool/testing/release_smoke.dart b/tool/testing/release_smoke.dart new file mode 100644 index 0000000..88a55a1 --- /dev/null +++ b/tool/testing/release_smoke.dart @@ -0,0 +1,226 @@ +// A separate Release test entrypoint. Never included in the distributed app. +import 'dart:convert'; +import 'dart:io'; +import 'dart:ui' as ui; + +import 'package:cutdex/integrations/runtime/processing_configuration.dart'; +import 'package:cutdex/workspace/persistence/project_workspace.dart'; +import 'package:cutdex/workspace/persistence/timeline_creation_names.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/preview.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter/rendering.dart'; + +void require(bool condition, String message) { + if (!condition) throw StateError(message); +} + +Future waitFor(bool Function() complete) async { + final timer = Stopwatch()..start(); + while (!complete()) { + if (timer.elapsed > const Duration(minutes: 2)) { + throw StateError('Release smoke test timed out'); + } + await Future.delayed(const Duration(milliseconds: 30)); + } +} + +Future main() async { + WidgetsFlutterBinding.ensureInitialized(); + final report = File(Platform.environment['CUTDEX_SMOKE_REPORT']!); + final root = await Directory.systemTemp.createTemp('cutdex-release-smoke-'); + ProjectWorkspace? workspace; + PreviewController? preview; + var code = 1; + try { + final config = ProcessingConfiguration.configured( + resourcesRoot: Platform.environment['CUTDEX_SMOKE_RESOURCES'], + ); + require(config != null, 'Bundled processing runtime was not found'); + final models = Platform.environment['CUTDEX_SMOKE_MODELS'] == '1'; + require( + (config!.transcriptionModel != null) == models, + 'ASR configuration', + ); + require( + (config.translationModel != null) == models, + 'Translation configuration', + ); + require( + (config.vocalSeparationModel != null) == models, + 'Vocals configuration', + ); + workspace = ProjectWorkspace( + processing: config, + creationNames: const TimelineCreationNames( + timeline: 'Timeline 1', + sequence: 'Main sequence', + storyline: 'Main storyline', + ), + ); + await workspace.open('${root.path}/Smoke.cutdex', name: 'Release smoke'); + final timelines = await workspace.createTimeline('Playback'); + final project = workspace.project!; + final source = File(Platform.environment['CUTDEX_SMOKE_MEDIA']!); + final video = Platform.environment['CUTDEX_SMOKE_VIDEO'] == '1'; + final asset = await project.importFile(source, name: 'Audio'); + final document = await workspace.loadTimeline( + project.info.id, + timelines.last.id, + ); + final session = await workspace.openTimelineSession( + project.info.id, + document, + ); + final media = await workspace + .prepareMedia(project.info.id, asset.id) + .timeout(const Duration(minutes: 2)); + session.insertAsset( + sequenceId: session.activeSequenceId!, + assetId: asset.id, + assetName: 'Audio', + uri: media.uri, + duration: media.duration, + position: 0, + kind: video ? 'video' : 'audio', + hasAudio: true, + clipId: ElementId('audio'), + ); + for (final operation in [ + EditorOperation.startTranscription, + EditorOperation.startSubtitleTranslation, + EditorOperation.startVocalSeparation, + ]) { + require( + session.supportedCommandOperations.contains(operation) == models, + 'Capability: $operation', + ); + } + preview = PreviewController( + timeline: session, + activeSequence: () => session.activeSequenceId, + viewForSequence: session.view, + runtime: CutdexRuntime(), + ); + await preview.initialize(); + require( + preview.ready && preview.error == null, + 'Native preview initialization', + ); + final canvasKey = GlobalKey(); + if (video) { + runApp( + ProviderScope( + child: Directionality( + textDirection: TextDirection.ltr, + child: RepaintBoundary( + key: canvasKey, + child: RuntimePreview(session: preview.session!), + ), + ), + ), + ); + } + final activePreview = preview; + await preview.controlPreview(session.activeSequenceId!, PreviewAction.play); + await waitFor( + () => + activePreview.positionTick > TimelineClock.ticksPerSecond ~/ 5 || + activePreview.error != null, + ); + require(preview.error == null, 'Native playback: ${preview.error}'); + await preview.controlPreview( + session.activeSequenceId!, + PreviewAction.pause, + ); + if (video) { + await WidgetsBinding.instance.endOfFrame.timeout( + const Duration(seconds: 20), + ); + final boundary = + canvasKey.currentContext!.findRenderObject()! + as RenderRepaintBoundary; + final image = await boundary.toImage(); + try { + final rgba = await image.toByteData(); + final pixels = rgba!.buffer.asUint8List(); + final colors = {}; + for (var i = 0; i < pixels.length; i += 4) { + colors.add((pixels[i] << 16) | (pixels[i + 1] << 8) | pixels[i + 2]); + if (colors.length > 32) break; + } + require(colors.length > 32, 'Preview is blank or has too few colors'); + final png = await image.toByteData(format: ui.ImageByteFormat.png); + await File('${report.path}.png') + .writeAsBytes(png!.buffer.asUint8List()); + } finally { + image.dispose(); + } + final output = await session.exports.start( + session.activeSequenceId!, + ExportProject(destination: '${report.path}.mp4'), + ); + final exported = await CutdexRuntime().probe( + MediaReference(id: 'exported', uri: output), + ); + require(exported.videoTrackCount == 1, 'Exported video track'); + require(exported.audioTrackCount == 1, 'Exported audio track'); + require( + (exported.duration.seconds - media.duration.seconds).abs() < .2, + 'Exported duration', + ); + } + if (models) { + final subtitles = File('${root.path}/subtitles.json'); + await subtitles.writeAsString( + jsonEncode({ + 'schemaVersion': 1, + 'language': 'en', + 'cues': [ + { + 'startMs': 0, + 'endMs': 1000, + 'text': 'Hello, welcome to the video.', + }, + ], + }), + ); + final task = await session.transcriptions!.startTranslation( + StartSubtitleTranslation( + source: subtitles.path, + sourceLanguage: 'en', + targetLanguage: 'zh', + threads: 2, + ), + ); + await waitFor(() => task.terminal); + require( + task.status == TranscriptionStatus.succeeded, + 'Translation: ${task.error}', + ); + require(task.result!.document.cues.isNotEmpty, 'Translated cues'); + } + await report.writeAsString( + jsonEncode({ + 'passed': true, + 'models': models, + 'videoPreviewAndExport': video, + 'playbackTick': preview.positionTick, + 'executable': Platform.resolvedExecutable, + }), + ); + code = 0; + } catch (error, stack) { + await report.writeAsString( + jsonEncode({'passed': false, 'error': '$error', 'stack': '$stack'}), + ); + } finally { + await preview?.close(); + await workspace?.close(); + await root.delete(recursive: true); + } + exit(code); +} diff --git a/tool/testing/windows_update_smoke.dart b/tool/testing/windows_update_smoke.dart new file mode 100644 index 0000000..6af2681 --- /dev/null +++ b/tool/testing/windows_update_smoke.dart @@ -0,0 +1,86 @@ +// Dedicated test app: never distribute its release packages. +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +const channel = MethodChannel('deskup'); +const smokeRoot = String.fromEnvironment('CUTDEX_UPDATE_SMOKE_ROOT'); + +void main() { + WidgetsFlutterBinding.ensureInitialized(); + // The isolated smoke fixture depends only on Flutter, without Riverpod. + // ignore: riverpod_lint/missing_provider_scope + runApp( + const MaterialApp( + home: Scaffold(body: Center(child: Text('Cutdex update test'))), + ), + ); + unawaited(runSmoke()); +} + +Future> status() async => + await channel.invokeMapMethod('status') ?? {}; + +Future> waitFor( + bool Function(Map) predicate, +) async { + final deadline = DateTime.now().add(const Duration(minutes: 3)); + while (DateTime.now().isBefore(deadline)) { + final value = await status(); + if (predicate(value)) return value; + await Future.delayed(const Duration(milliseconds: 100)); + } + throw StateError( + 'Timed out waiting for native update state: ${await status()}', + ); +} + +Future record(String name, Object value) async { + await File('$smokeRoot/$name.json') + .writeAsString(jsonEncode(value), flush: true); +} + +Future runSmoke() async { + if (smokeRoot.isEmpty) { + throw StateError('Set CUTDEX_UPDATE_SMOKE_ROOT for this test app'); + } + try { + await channel.invokeMethod('ready'); + final initial = await waitFor( + (value) => value['configured'] == true && value['canCheck'] == true, + ); + await channel.invokeMethod('check'); + var checked = await waitFor((value) => value['canCheck'] == true); + if (initial['build'] == '900002') { + if (checked['phase'] != 'current') { + throw StateError('Updated version was offered again: $checked'); + } + await record('after', checked); + exit(0); + } + if (checked['phase'] != 'available' || + checked['availableVersion'] != '1.0.0-build.900002') { + throw StateError('Expected version 1.0.0-build.900002: $checked'); + } + await channel.invokeMethod('download'); + final rejected = await waitFor((value) => value['canCheck'] == true); + if (rejected['phase'] == 'ready' || rejected['error'] == '') { + throw StateError('Corrupted package was not rejected: $rejected'); + } + await record('corrupt-rejected', rejected); + await channel.invokeMethod('download'); + checked = await waitFor((value) => value['canCheck'] == true); + if (checked['phase'] != 'ready' || checked['error'] != '') { + throw StateError('Could not download valid update: $checked'); + } + await record('before', checked); + await channel.invokeMethod('validateInstall'); + await channel.invokeMethod('install'); + } catch (error, stack) { + await record('failure', {'error': '$error', 'stack': '$stack'}); + exit(1); + } +} diff --git a/tool/tests/cli_test.py b/tool/tests/cli_test.py new file mode 100644 index 0000000..2bc28e5 --- /dev/null +++ b/tool/tests/cli_test.py @@ -0,0 +1,96 @@ +"""CLI contracts: help/invalid arguments must not start builds or publish files.""" +import json +from pathlib import Path +import shutil +import subprocess +import sys +import tempfile +import unittest + +ROOT = Path(__file__).resolve().parents[2] + + +class CliTests(unittest.TestCase): + def test_python_help_and_unknown_option(self): + scripts = [ + 'check.py', 'macos/check_macos_release.py', 'macos/macos_updates.py', + 'macos/test_macos_release.py', 'macos/test_macos_updates.py', + 'macos/test_check_macos_release.py', 'windows/check_windows_release.py', + 'windows/package_windows_release.py', 'windows/prepare_windows_sandbox.py', + 'windows/windows_updates.py', 'windows/test_windows_updates.py', + 'diagnostics/frame_budget.py', + ] + for name in scripts: + for flag, code in [('--help', 0), ('--invalid-option', 2)]: + with self.subTest(script=name, flag=flag): + result = subprocess.run([sys.executable, str(ROOT / 'tool' / name), flag], + capture_output=True, text=True, timeout=30) + self.assertEqual(result.returncode, code, result.stderr) + self.assertIn('usage:', (result.stdout + result.stderr).lower()) + + @unittest.skipUnless(shutil.which('dart'), 'Dart SDK unavailable') + def test_context_diagnostic_arguments_and_json_output(self): + command = [shutil.which('dart'), 'run', + str(ROOT / 'tool/diagnostics/benchmark_agent_context.dart')] + for arguments, code in [(['--help'], 0), ([], 2)]: + result = subprocess.run(command + arguments, cwd=ROOT, capture_output=True, + text=True, timeout=60) + self.assertEqual(result.returncode, code, result.stderr) + self.assertIn('Usage:', result.stdout + result.stderr) + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / 'history.json' + path.write_text('[]') + result = subprocess.run(command + [str(path)], cwd=ROOT, capture_output=True, + text=True, timeout=60) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(json.loads(result.stdout)['messages'], 0) + + @unittest.skipUnless(shutil.which('bash'), 'bash unavailable') + def test_shell_help_and_argument_count(self): + for script in (ROOT / 'tool/macos').glob('*.sh'): + with self.subTest(script=script.name): + result = subprocess.run(['bash', str(script), '--help'], + capture_output=True, text=True, timeout=10) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn('Usage:', result.stdout) + result = subprocess.run(['bash', str(script), 'one', 'two', 'three'], + capture_output=True, text=True, timeout=10) + self.assertEqual(result.returncode, 2, result.stderr) + + +@unittest.skipUnless(sys.platform == 'darwin' and shutil.which('swiftc'), 'macOS Swift required') +class NativeCliTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.temp = tempfile.TemporaryDirectory(prefix='cutdex-cli-') + cls.addClassCleanup(cls.temp.cleanup) + cls.root = Path(cls.temp.name) + for name in ['set_macos_file_icon', 'sparkle_test_key']: + subprocess.run(['swiftc', str(ROOT / f'tool/macos/{name}.swift'), + '-o', str(cls.root / name)], check=True, capture_output=True, timeout=120) + + def test_help_and_missing_arguments(self): + for name in ['set_macos_file_icon', 'sparkle_test_key']: + for arguments, code in [(['--help'], 0), ([], 2)]: + with self.subTest(script=name, arguments=arguments): + result = subprocess.run([str(self.root / name), *arguments], capture_output=True) + self.assertEqual(result.returncode, code, result.stderr) + + def test_test_key_reuse_and_invalid_file(self): + path = self.root / 'keys with spaces' + command = [str(self.root / 'sparkle_test_key'), str(path)] + subprocess.run(command, check=True, capture_output=True) + original = (path / 'private.key').read_bytes() + subprocess.run(command, check=True, capture_output=True) + self.assertEqual((path / 'private.key').read_bytes(), original) + self.assertEqual((path / 'private.key').stat().st_mode & 0o777, 0o600) + (path / 'private.key').write_text('invalid key') + result = subprocess.run(command, capture_output=True) + self.assertEqual(result.returncode, 1) + self.assertNotIn(b'invalid key', result.stderr) + + def test_missing_icon_returns_failure(self): + result = subprocess.run([str(self.root / 'set_macos_file_icon'), + str(self.root / 'missing.png'), str(self.root / 'missing.dmg')], + capture_output=True) + self.assertEqual(result.returncode, 1) diff --git a/tool/tests/package_boundaries_test.py b/tool/tests/package_boundaries_test.py new file mode 100644 index 0000000..c59af5e --- /dev/null +++ b/tool/tests/package_boundaries_test.py @@ -0,0 +1,97 @@ +"""Catch dependencies that Dart's shared workspace resolution can hide.""" +import importlib.util +from pathlib import Path +import tempfile +import unittest + +spec = importlib.util.spec_from_file_location( + 'boundaries', Path(__file__).resolve().parents[1] / 'check_package_boundaries.py') +boundaries = importlib.util.module_from_spec(spec) +spec.loader.exec_module(boundaries) + + +class PackageBoundaryTests(unittest.TestCase): + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.root = Path(temp.name) + for package in boundaries.RUNTIME: + self.write(f'packages/{package}/pubspec.yaml', f'''name: {package} +resolution: workspace +publish_to: none +dependencies: + flutter: + sdk: flutter +dev_dependencies: + flutter_test: + sdk: flutter +''') + + def write(self, path, content): + target = self.root / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(content) + + def test_reverse_dependency_is_rejected_even_when_unused(self): + path = self.root / 'packages/cutdex_native/pubspec.yaml' + path.write_text(path.read_text().replace('dependencies:\n', + 'dependencies:\n cutdex: any\n', 1)) + self.assertTrue(any('forbidden dependency cutdex' in error + for error in boundaries.check(self.root))) + + def test_workspace_resolution_does_not_authorize_transitive_imports(self): + self.write('packages/cutdex_ui/lib/component.dart', "import 'package:path/path.dart';") + self.assertTrue(any('undeclared import package:path/' in error + for error in boundaries.check(self.root))) + + def test_application_requires_public_package_entrypoints(self): + self.write('lib/app.dart', "import 'package:cutdex_ui/src/widgets/app_item.dart';") + self.write('test/app_test.dart', "import '../packages/cutdex_native/lib/cutdex_native.dart';") + errors = boundaries.check(self.root) + self.assertEqual(len(errors), 2, errors) + + def test_integration_tests_cannot_import_sdk_implementation(self): + self.write('integration_test/save_test.dart', + "import 'package:cutdex_project/src/persistence/timeline_codec.dart';") + self.assertTrue(any('private import' in error + for error in boundaries.check(self.root))) + + def test_package_tests_cannot_escape_the_package(self): + self.write('packages/cutdex_ui/test/component_test.dart', + "import '../../../lib/app.dart';") + self.assertTrue(any('escaping import' in error + for error in boundaries.check(self.root))) + + def test_application_cannot_import_sibling_repository_sources(self): + self.write('lib/bridge.dart', "export '../../cutdex_sdk/lib/editor.dart';") + self.write('integration_test/save_test.dart', + "import '../../cutdex_sdk/packages/project/lib/cutdex_project.dart';") + self.assertEqual(len(boundaries.check(self.root)), 2) + + def test_application_library_cannot_import_test_or_tool_sources(self): + self.write('lib/bridge.dart', "import '../test/support/fake.dart';") + self.write('lib/tool.dart', "export '../tool/testing/fixture.dart';") + self.assertEqual(len(boundaries.check(self.root)), 2) + + def test_public_imports_and_own_implementation_are_allowed(self): + self.write('lib/app.dart', "import 'package:cutdex_ui/widgets.dart';") + self.write('packages/cutdex_ui/lib/widgets.dart', "export 'src/widget.dart';") + self.write('packages/cutdex_ui/test/widget_test.dart', + "import 'package:cutdex_ui/widgets.dart';\nimport 'package:flutter_test/flutter_test.dart';") + self.assertEqual(boundaries.check(self.root), []) + + def test_conditional_imports_and_exports_cannot_hide_private_sources(self): + self.write('lib/app.dart', "import 'stub.dart' if (dart.library.io) 'package:cutdex_ui/src/widgets/app_item.dart';") + self.write('lib/export.dart', "export 'stub.dart' if (dart.library.io) 'package:cutdex_native/src/file_drop.dart';") + self.assertEqual(len(boundaries.check(self.root)), 2) + + def test_normalized_package_uris_cannot_hide_private_sources(self): + self.write('lib/app.dart', "import 'package:cutdex_ui/public/../src/widgets/app_item.dart';") + self.assertTrue(any('private import' in error for error in boundaries.check(self.root))) + + def test_fixture_strings_and_comments_are_not_imports(self): + self.write('lib/app.dart', '''// import 'package:cutdex_ui/src/fake.dart'; +/* export 'package:cutdex_ui/src/fake.dart'; */ +const fixture = "import 'package:cutdex_ui/src/fake.dart';"; +''') + self.assertEqual(boundaries.check(self.root), []) diff --git a/tool/tests/public_repository_test.py b/tool/tests/public_repository_test.py new file mode 100644 index 0000000..aa392ae --- /dev/null +++ b/tool/tests/public_repository_test.py @@ -0,0 +1,58 @@ +import importlib.util +from pathlib import Path +import tempfile +import unittest + +SPEC = importlib.util.spec_from_file_location( + 'public_repository', Path(__file__).resolve().parents[1] / 'check_public_repository.py') +CHECKER = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(CHECKER) + + +class PublicRepositoryTest(unittest.TestCase): + def setUp(self): + self.temporary = tempfile.TemporaryDirectory() + self.addCleanup(self.temporary.cleanup) + self.root = Path(self.temporary.name) + + def write(self, name, text='local value'): + path = self.root / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text) + + def test_credential_report_does_not_echo_secret(self): + secret = 'gh' + 'p_' + 'a' * 40 + self.write('config.txt', 'token=' + secret) + errors = CHECKER.check_files(self.root, ['config.txt']) + self.assertEqual(len(errors), 1) + self.assertIn('config.txt:1', errors[0]) + self.assertNotIn(secret, errors[0]) + + def test_local_inputs_are_rejected_but_examples_are_allowed(self): + names = ['.env', '.env.production', 'android/key.properties', + '.local/config.json', 'nested/build/output.txt', + 'example.cutdex/project.json', 'signing.p12'] + for name in names + ['.env.example', '.env.production.sample']: + self.write(name) + self.assertEqual(len(CHECKER.check_files(self.root, names)), len(names)) + self.assertEqual(CHECKER.check_files( + self.root, ['.env.example', '.env.production.sample']), []) + + def test_links_allow_urls_fragments_and_relative_files(self): + self.write('docs/guide.md', '[file](../LICENSE) [section](#intro) ' + '[web](https://example.com) [missing](missing.md)') + self.write('LICENSE') + errors = CHECKER.check_files(self.root, ['docs/guide.md']) + self.assertEqual(errors, ['docs/guide.md: missing or external local link missing.md']) + + def test_symlinks_cannot_publish_external_files(self): + (self.root / 'external').symlink_to(self.root.parent) + self.assertEqual(CHECKER.check_files(self.root, ['external']), + ['external: symlink escapes repository']) + + def test_deleted_worktree_file_is_not_published(self): + self.assertEqual(CHECKER.check_files(self.root, ['deleted.txt']), []) + + +if __name__ == '__main__': + unittest.main() diff --git a/tool/windows/check_windows_release.py b/tool/windows/check_windows_release.py new file mode 100644 index 0000000..491c2ef --- /dev/null +++ b/tool/windows/check_windows_release.py @@ -0,0 +1,91 @@ +"""Audit Windows x64 PE imports without trusting the build host's System32. + +Build-host dependency: pefile==2024.8.26. The target computer needs no Python. +This is a static dependency gate, not a substitute for a clean Windows VM run. +""" +import argparse +import json +from pathlib import Path + +# Inbox components on supported, fully updated Windows 10/11 (non-N editions). +# Never infer this list from files installed on the developer's machine. +SYSTEM_DLLS = set(''' +advapi32 avicap32 avrt bcrypt bcryptprimitives cfgmgr32 combase comctl32 comdlg32 +crypt32 d2d1 d3d11 d3d12 d3d9 d3dcompiler_47 dbghelp dnsapi dwmapi dwrite dxgi +gdi32 imagehlp imm32 iphlpapi kernel32 mf mfplat mfplay mfreadwrite msimg32 +ncrypt ntdll ole32 oleacc oleaut32 opengl32 propsys psapi rpcrt4 secur32 +setupapi shell32 shlwapi uiautomationcore user32 userenv usp10 winmm wintrust +ws2_32 ucrtbase version +'''.split()) +SYSTEM_DLLS = {name + '.dll' for name in SYSTEM_DLLS} +REQUIRED = ( + 'cutdex.exe', 'flutter_windows.dll', 'cutdex_runtime_plugin.dll', + 'deskup_plugin.dll', 'velopack_libc.dll', + 'cutdex_windows_ffi.dll', 'sqlite3.dll', 'data/app.so', 'data/icudtl.dat', + 'processing/bin/cutdex-processing-worker.exe', + 'processing/bin/cutdex_processing_ffi.dll', 'processing/bin/ffmpeg.exe', + 'processing/bin/ffprobe.exe', 'processing/bin/onnxruntime.dll', + 'processing/bin/DirectML.dll', + 'processing/workers/asr/cutdex-asr-worker.exe', + 'processing/workers/audio/cutdex-audio-worker.exe', + 'processing/workers/translation/cutdex-m2m100-worker.exe', +) + + +def system_dependency(name): + name = name.lower() + return name in SYSTEM_DLLS or name.startswith(('api-ms-win-', 'ext-ms-win-')) + + +def pe_imports(path): + import pefile + with pefile.PE(str(path), fast_load=True) as pe: + if pe.FILE_HEADER.Machine != 0x8664: + raise ValueError(f'Not an x64 PE: {path}') + pe.parse_data_directories(directories=[1, 13]) + return sorted({item.dll.decode('ascii').lower() for attribute in + ('DIRECTORY_ENTRY_IMPORT', 'DIRECTORY_ENTRY_DELAY_IMPORT') + for item in getattr(pe, attribute, [])}) + + +def audit(root, read_imports=pe_imports): + root = Path(root).resolve() + missing = [name for name in REQUIRED if not (root / name).is_file()] + if missing: + raise ValueError(f'Missing release files: {missing}') + if not (root / 'data/flutter_assets').is_dir(): + raise ValueError('Missing Flutter assets') + report = {} + unresolved = [] + for binary in sorted(root.rglob('*')): + if binary.suffix.lower() not in ('.dll', '.exe'): + continue + if binary.is_symlink(): + raise ValueError(f'External/symlink binary: {binary}') + # Each worker is a separate process. A DLL in another worker directory + # (or only in the main app directory) does not satisfy its dependency. + local = {p.name.lower() for p in binary.parent.iterdir() if p.is_file()} + names = read_imports(binary) + report[binary.relative_to(root).as_posix()] = names + for name in names: + if name.lower() not in local and not system_dependency(name): + unresolved.append(f'{binary.relative_to(root)} -> {name}') + if unresolved: + raise ValueError('Unbundled dependencies: ' + '; '.join(unresolved)) + return {'architecture': 'x64', 'imports': report, 'unresolved': [], + 'cleanSystemValidated': False} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--app', type=Path, required=True) + parser.add_argument('--report', type=Path, required=True) + args = parser.parse_args() + result = audit(args.app) + args.report.parent.mkdir(parents=True, exist_ok=True) + args.report.write_text(json.dumps(result, indent=2) + '\n', encoding='utf-8') + print(f'Windows dependency gate passed: {len(result["imports"])} PE files') + + +if __name__ == '__main__': + main() diff --git a/tool/windows/package_windows_release.py b/tool/windows/package_windows_release.py new file mode 100644 index 0000000..5fa32db --- /dev/null +++ b/tool/windows/package_windows_release.py @@ -0,0 +1,50 @@ +"""Stage an audited portable Windows x64 app from a normal Flutter Release build. + +Requires pefile on the build host. Models remain separate from the application. +""" +import argparse +import hashlib +import json +from pathlib import Path +import shutil + +from check_windows_release import audit + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--app', type=Path, required=True) + parser.add_argument('--processing', type=Path, required=True) + parser.add_argument('--output', type=Path, required=True) + args = parser.parse_args() + source, runtime, output = [p.resolve() for p in (args.app, args.processing, args.output)] + if output.exists() or output.is_relative_to(source) or output.is_relative_to(runtime): + raise ValueError('Output must be a new directory outside the source packages') + if not (source / 'cutdex.exe').is_file() or not (runtime / 'checksums.json').is_file(): + raise ValueError('Provide a complete Release directory and processing package') + checksums = json.loads((runtime / 'checksums.json').read_text(encoding='utf-8-sig')) + for name, expected in checksums.items(): + path = (runtime / name).resolve() + if not path.is_relative_to(runtime): + raise ValueError(f'Invalid processing manifest path: {name}') + with path.open('rb') as stream: + actual = hashlib.file_digest(stream, 'sha256').hexdigest() + if actual.lower() != expected.lower(): + raise ValueError(f'Processing checksum mismatch: {name}') + # Older Flutter builds can retain the unused JNI plugin from Android's + # path_provider dependency. Windows has its own provider and needs no JVM. + shutil.copytree(source, output, ignore=shutil.ignore_patterns('processing', '*.pdb', '*.lib', '*.exp', 'dartjni.dll')) + shutil.copytree(runtime, output / 'processing') + result = audit(output) + (output / 'dependency-audit.json').write_text(json.dumps(result, indent=2) + '\n', encoding='utf-8') + manifest = {} + for path in sorted(output.rglob('*')): + if path.is_file(): + with path.open('rb') as stream: + manifest[path.relative_to(output).as_posix()] = hashlib.file_digest(stream, 'sha256').hexdigest() + (output / 'checksums.json').write_text(json.dumps(manifest, indent=2) + '\n', encoding='utf-8') + print(f'Portable package staged: {output} ({len(manifest)} files)') + + +if __name__ == '__main__': + main() diff --git a/tool/windows/prepare_windows_sandbox.py b/tool/windows/prepare_windows_sandbox.py new file mode 100644 index 0000000..e8eb520 --- /dev/null +++ b/tool/windows/prepare_windows_sandbox.py @@ -0,0 +1,59 @@ +"""Create a Windows Sandbox launch file; no developer tools are mapped into it. + +Inputs must contain fixture.mp4 (short SDR H.264 + AAC). Model folders are mapped +read-only; the vocals folder must contain melband.pt. Only results are writable. +""" +import argparse +import json +from pathlib import Path +import xml.etree.ElementTree as ET + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + for name in ('app', 'smoke', 'inputs', 'whisper', 'translation', 'vocals', 'results', 'output'): + parser.add_argument('--' + name, type=Path, required=True) + args = parser.parse_args() + paths = {name: getattr(args, name).resolve() for name in + ('app', 'smoke', 'inputs', 'whisper', 'translation', 'vocals', 'results')} + for name in ('app', 'smoke'): + if not (paths[name] / 'checksums.json').is_file(): + raise ValueError(f'Not an audited package: {paths[name]}') + for name in ('inputs', 'whisper', 'translation', 'vocals'): + if not paths[name].is_dir(): + raise ValueError(f'Missing directory: {paths[name]}') + if not (paths['inputs'] / 'fixture.mp4').is_file() or not (paths['vocals'] / 'melband.pt').is_file(): + raise ValueError('Missing fixture.mp4 or vocals/melband.pt') + paths['results'].mkdir(parents=True, exist_ok=True) + config = ET.Element('Configuration') + ET.SubElement(config, 'VGpu').text = 'Enable' + ET.SubElement(config, 'MemoryInMB').text = '8192' + ET.SubElement(config, 'Networking').text = 'Disable' + folders = ET.SubElement(config, 'MappedFolders') + # Copy just the standalone guest script; never map the source/build tool tree. + script = Path(__file__).with_name('test_windows_release.ps1') + (paths['inputs'] / script.name).write_bytes(script.read_bytes()) + mapping = {'app': r'C:\Cutdex', 'smoke': r'C:\Smoke', 'inputs': r'C:\Inputs', + 'whisper': r'C:\Models\whisper', 'translation': r'C:\Models\translation', + 'vocals': r'C:\Models\vocals', 'results': r'C:\Results'} + for name, guest in mapping.items(): + folder = ET.SubElement(folders, 'MappedFolder') + ET.SubElement(folder, 'HostFolder').text = str(paths[name]) + ET.SubElement(folder, 'SandboxFolder').text = guest + ET.SubElement(folder, 'ReadOnly').text = 'false' if name == 'results' else 'true' + (paths['inputs'] / 'models.json').write_text(json.dumps({ + 'whisper': mapping['whisper'], + 'translation': mapping['translation'], + 'vocals': mapping['vocals'] + r'\melband.pt', + }, indent=2), encoding='utf-8') + command = ET.SubElement(config, 'LogonCommand') + ET.SubElement(command, 'Command').text = ( + 'powershell.exe -NoProfile -ExecutionPolicy Bypass -File C:\\Inputs\\test_windows_release.ps1 ' + '-App C:\\Cutdex -SmokeApp C:\\Smoke -Inputs C:\\Inputs -Results C:\\Results') + ET.indent(config) + args.output.write_text(ET.tostring(config, encoding='unicode') + '\n', encoding='utf-8') + print(f'Log into Windows, then open {args.output}. Results: {paths["results"]}') + + +if __name__ == '__main__': + main() diff --git a/tool/windows/test_check_windows_release.py b/tool/windows/test_check_windows_release.py new file mode 100644 index 0000000..40a4d28 --- /dev/null +++ b/tool/windows/test_check_windows_release.py @@ -0,0 +1,46 @@ +import tempfile +import unittest +from pathlib import Path + +from check_windows_release import REQUIRED, audit + + +class DependencyGateTest(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + for name in REQUIRED: + path = self.root / name + path.parent.mkdir(parents=True, exist_ok=True) + path.touch() + (self.root / 'data/flutter_assets').mkdir() + + def test_vc_runtime_in_another_worker_does_not_satisfy_app(self): + (self.root / 'processing/workers/asr/vcruntime140.dll').touch() + with self.assertRaisesRegex(ValueError, 'cutdex.exe -> vcruntime140.dll'): + audit(self.root, lambda p: ['vcruntime140.dll'] if p.name == 'cutdex.exe' else []) + + def test_unknown_dependency_is_not_assumed_to_be_a_system_dll(self): + with self.assertRaisesRegex(ValueError, 'vendor.dll'): + audit(self.root, lambda p: ['vendor.dll']) + + def test_local_runtime_and_inbox_api_sets_pass(self): + (self.root / 'VCRUNTIME140.dll').touch() + result = audit(self.root, lambda p: ['vcruntime140.dll', 'KERNEL32.dll', + 'VERSION.dll', 'COMCTL32.dll', 'api-ms-win-crt-runtime-l1-1-0.dll'] if p.name == 'cutdex.exe' else []) + self.assertEqual(result['unresolved'], []) + self.assertFalse(result['cleanSystemValidated']) + + def test_missing_flutter_aot_is_rejected(self): + (self.root / 'data/app.so').unlink() + with self.assertRaisesRegex(ValueError, 'data/app.so'): + audit(self.root, lambda p: []) + + def test_jvm_is_not_assumed_to_be_a_system_dependency(self): + with self.assertRaisesRegex(ValueError, 'jvm.dll'): + audit(self.root, lambda p: ['jvm.dll'] if p.name == 'cutdex.exe' else []) + + +if __name__ == '__main__': + unittest.main() diff --git a/tool/windows/test_windows_release.ps1 b/tool/windows/test_windows_release.ps1 new file mode 100644 index 0000000..939fa62 --- /dev/null +++ b/tool/windows/test_windows_release.ps1 @@ -0,0 +1,100 @@ +<# +.SYNOPSIS +Validates a normal and smoke release package on an interactive Windows desktop. +.DESCRIPTION +Requires App, SmokeApp, Inputs and Results paths. Writes result.json and process +logs to Results. Returns a nonzero status on failure; does not publish packages. +.EXAMPLE +Get-Help ./tool/windows/test_windows_release.ps1 -Full +.EXAMPLE +./tool/windows/test_windows_release.ps1 -App C:\Cutdex -SmokeApp C:\Smoke -Inputs C:\Inputs -Results C:\Results +#> +param( + [Parameter(Mandatory=$true)][string]$App, + [Parameter(Mandatory=$true)][string]$SmokeApp, + [Parameter(Mandatory=$true)][string]$Inputs, + [Parameter(Mandatory=$true)][string]$Results +) +$ErrorActionPreference = 'Stop' +New-Item -ItemType Directory -Force $Results | Out-Null +$report = @{ passed = $false; sandbox = ($env:USERNAME -eq 'WDAGUtilityAccount'); sessionId = (Get-Process -Id $PID).SessionId } +$normal = $null +try { + if ($report.sessionId -eq 0) { throw 'Interactive Windows desktop required; SSH Session 0 is not a display test.' } + foreach ($folder in @($App, $SmokeApp)) { + $manifest = Get-Content (Join-Path $folder 'checksums.json') -Raw | ConvertFrom-Json + foreach ($entry in $manifest.PSObject.Properties) { + if ((Get-FileHash -LiteralPath (Join-Path $folder $entry.Name) -Algorithm SHA256).Hash -ne $entry.Value) { + throw "Package checksum mismatch: $($entry.Name)" + } + } + } + Get-ChildItem Env:CUTDEX_* | Remove-Item + $env:PATH = "$env:SystemRoot\System32;$env:SystemRoot" + $env:PATHEXT = '.COM;.EXE;.BAT;.CMD' + $normal = Start-Process (Join-Path $App 'cutdex.exe') -WorkingDirectory $App -PassThru -RedirectStandardOutput (Join-Path $Results 'app.stdout.log') -RedirectStandardError (Join-Path $Results 'app.stderr.log') + Start-Sleep -Seconds 5 + $normal.Refresh() + if ($normal.HasExited -or $normal.MainWindowHandle -eq 0) { throw 'Normal app did not create a window.' } + $loaded = @{} + foreach ($module in $normal.Modules) { + if ($module.ModuleName -match '^(msvcp140|vcruntime140(_1)?)\.dll$') { + $loaded[$module.ModuleName] = $module.FileName + if ([IO.Path]::GetFullPath([IO.Path]::GetDirectoryName($module.FileName)) -ne [IO.Path]::GetFullPath($App)) { + throw "VC runtime loaded outside app: $($module.FileName)" + } + } + } + foreach ($name in @('msvcp140.dll','vcruntime140.dll','vcruntime140_1.dll')) { + if (!$loaded.ContainsKey($name)) { throw "VC runtime module missing: $name" } + } + $report.loadedVcRuntime = $loaded + Stop-Process -Id $normal.Id + $normal = $null + & "$env:SystemRoot\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -ExecutionPolicy Bypass -File (Join-Path $App 'processing\verify.ps1') -Report (Join-Path $Results 'processing.json') + if ($LASTEXITCODE -ne 0) { throw 'Processing package verification failed.' } + $config = Get-Content (Join-Path $Inputs 'models.json') -Raw | ConvertFrom-Json + foreach ($configured in @($false, $true)) { + Get-ChildItem Env:CUTDEX_* | Remove-Item + $name = if ($configured) { 'with-models' } else { 'without-models' } + $caseDirectory = Join-Path $Results $name + New-Item -ItemType Directory -Force $caseDirectory | Out-Null + $env:LOCALAPPDATA = $caseDirectory + $env:APPDATA = $caseDirectory + $env:USERPROFILE = $caseDirectory + $env:CUTDEX_SMOKE_REPORT = Join-Path $caseDirectory 'result.json' + $env:CUTDEX_SMOKE_MODELS = [int]$configured + $env:CUTDEX_SMOKE_VIDEO = '1' + $env:CUTDEX_SMOKE_MEDIA = Join-Path $Inputs 'fixture.mp4' + if ($configured) { + $processing = Join-Path $caseDirectory 'Documents\Cutdex\Resources\Processing' + $whisperTarget = Join-Path $processing 'Transcription\whisper-turbo\1' + $translationTarget = Join-Path $processing 'Translation\m2m100-418m\1' + New-Item -ItemType Directory -Force $whisperTarget, $translationTarget | Out-Null + Copy-Item -Recurse -Force (Join-Path $config.whisper '*') $whisperTarget + Copy-Item -Recurse -Force (Join-Path $config.translation '*') $translationTarget + New-Item -ItemType Directory -Force (Join-Path $processing 'VocalSeparation\melband\1') | Out-Null + Copy-Item -Force $config.vocals (Join-Path $processing 'VocalSeparation\melband\1\melband.pt') + } + $process = Start-Process (Join-Path $SmokeApp 'cutdex.exe') -WorkingDirectory $SmokeApp -PassThru -RedirectStandardOutput (Join-Path $caseDirectory 'stdout.log') -RedirectStandardError (Join-Path $caseDirectory 'stderr.log') + # Retain the process handle before it exits so PowerShell 5.1 can read + # ExitCode after WaitForExit instead of returning null. + $null = $process.Handle + try { + if (!$process.WaitForExit(600000)) { throw "Smoke timed out: $name" } + if ($process.ExitCode -ne 0) { throw "Smoke failed: $name ($($process.ExitCode))" } + $result = Get-Content $env:CUTDEX_SMOKE_REPORT -Raw | ConvertFrom-Json + if (!$result.passed -or !$result.videoPreviewAndExport) { throw "Incomplete smoke: $name" } + $report[$name] = $result + } finally { + if (!$process.HasExited) { Stop-Process -Id $process.Id } + } + } + $report.passed = $true +} catch { + $report.error = $_.ToString() + throw +} finally { + if ($normal -and !$normal.HasExited) { Stop-Process -Id $normal.Id } + $report | ConvertTo-Json -Depth 12 | Set-Content -Encoding UTF8 (Join-Path $Results 'result.json') +} diff --git a/tool/windows/test_windows_updates.py b/tool/windows/test_windows_updates.py new file mode 100644 index 0000000..c858cea --- /dev/null +++ b/tool/windows/test_windows_updates.py @@ -0,0 +1,128 @@ +"""Build two disposable Flutter apps and verify updates through a Python HTTP server. + +Uses Cutdex.Dev only. Tests checksum rejection, retry, install, relaunch and no-op +checks. Requires Flutter, the pinned vpk tool and Windows. Never uploads releases. +""" +import argparse +from functools import partial +from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer +import json +import os +from pathlib import Path +import shutil +import subprocess +import sys +import threading +import time + +from windows_updates import DESKUP_VERSION, ROOT, check_tool, pack_release, update_version, vpk_command + + +class TestHandler(SimpleHTTPRequestHandler): + corrupt = True + + def do_GET(self): + if self.path.endswith('.nupkg') and type(self).corrupt: + type(self).corrupt = False + file = Path(self.directory) / self.path.lstrip('/') + payload = bytearray(file.read_bytes()) + payload[len(payload) // 2] ^= 1 + self.send_response(200) + self.send_header('Content-Length', str(len(payload))) + self.end_headers() + self.wfile.write(payload) + else: + super().do_GET() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--vpk', type=Path, required=True) + parser.add_argument('--flutter', default=shutil.which('flutter')) + parser.add_argument('--work', type=Path, default=ROOT / '.local/windows-update-test') + parser.add_argument('--port', type=int, default=8765) + parser.add_argument('--offline', action='store_true', help='Use already cached Flutter packages') + args = parser.parse_args() + if sys.platform != 'win32': + parser.error('This test requires Windows') + work = args.work.resolve() + if work.exists(): + parser.error('Use a new work directory so previous reports cannot pass this test') + work.mkdir(parents=True) + command = vpk_command(args.vpk) + check_tool(command) + definitions = work / 'defines.json' + definitions.write_text(json.dumps({'CUTDEX_UPDATE_SMOKE_ROOT': work.as_posix()}), encoding='utf-8') + environment = dict(os.environ, CUTDEX_WINDOWS_UPDATE_URL=f'http://127.0.0.1:{args.port}', + CUTDEX_UPDATE_TEST_HTTP='1') + # Isolate Flutter caches, generated runner files and output from live builds. + source = work / 'source' + source.mkdir() + for name in ['windows']: + shutil.copytree(ROOT / name, source / name, + ignore=shutil.ignore_patterns('ephemeral', 'build', '__pycache__')) + # Exercise the real Runner/update bridge with a small Flutter test entry. + # Media processing is covered separately and need not be rebuilt here. + (source / 'pubspec.yaml').write_text( + 'name: cutdex_update_smoke\nversion: 1.0.0+1\n' + 'environment:\n sdk: ^3.13.2\n' + 'dependencies:\n flutter:\n sdk: flutter\n' + f' deskup: {DESKUP_VERSION}\n' + 'flutter:\n uses-material-design: true\n', encoding='utf-8') + entry = source / 'tool/testing/windows_update_smoke.dart' + entry.parent.mkdir(parents=True) + shutil.copyfile(ROOT / 'tool/testing/windows_update_smoke.dart', entry) + subprocess.run([args.flutter, 'pub', 'get'] + (['--offline'] if args.offline else []), + cwd=source, env=environment, check=True) + # Keep test packages separate from the app's normal release output. + for build in [900001, 900002]: + subprocess.run([args.flutter, 'build', 'windows', '--no-pub', '--release', '--flavor', 'development', + '--target', 'tool/testing/windows_update_smoke.dart', '--build-name', '1.0.0', + '--build-number', str(build), '--dart-define-from-file', str(definitions)], + cwd=source, env=environment, check=True) + app = source / 'build/windows/x64/development/runner/Release' + release = work / ('baseline' if build == 900001 else 'public') + pack_release(command, app=app, output=release, package_id='Cutdex.Dev', + version=update_version('1.0.0', build), title='Cutdex update test') + verify_update(work, args.port) + + +def verify_update(work, port): + reports = ['corrupt-rejected', 'before', 'after', 'failure'] + if any((work / f'{name}.json').exists() for name in reports): + raise ValueError('Previous reports must not pass this test; use a fresh work directory') + portable = next((work / 'baseline').glob('*Portable.zip')) + if not (work / 'installed').exists(): + shutil.unpack_archive(portable, work / 'installed') + TestHandler.corrupt = True + server = ThreadingHTTPServer(('127.0.0.1', port), + partial(TestHandler, directory=str(work / 'public'))) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + # Hide the helper process console; the test app itself shows its test window. + app = work / 'installed/Cutdex update test.exe' + process = None + try: + process = subprocess.Popen([str(app)], cwd=app.parent, creationflags=subprocess.CREATE_NO_WINDOW) + deadline = time.monotonic() + 240 + while time.monotonic() < deadline: + if (work / 'failure.json').exists(): + raise RuntimeError((work / 'failure.json').read_text()) + if (work / 'after.json').exists(): + break + time.sleep(0.2) + else: + raise TimeoutError('Update did not relaunch within 240 seconds') + for report in ['corrupt-rejected', 'before', 'after']: + print(report + ': ' + (work / f'{report}.json').read_text()) + process.wait(timeout=20) + print(f'Velopack end-to-end update passed: {work}') + finally: + if process is not None and process.poll() is None: + process.terminate() + server.shutdown() + server.server_close() + + +if __name__ == '__main__': + main() diff --git a/tool/windows/test_windows_updates_unit.py b/tool/windows/test_windows_updates_unit.py new file mode 100644 index 0000000..5f94785 --- /dev/null +++ b/tool/windows/test_windows_updates_unit.py @@ -0,0 +1,121 @@ +import hashlib +import json +from pathlib import Path +from unittest.mock import patch +import tempfile +import unittest + +from windows_updates import resolved_deskup, numeric_version, pack_release, update_version, validate_previous, verify_manifest + + +class UpdatePublicationTests(unittest.TestCase): + def test_deskup_is_located_from_resolved_package_config(self): + with tempfile.TemporaryDirectory(prefix='deskup package ') as directory: + root = Path(directory) + config = root / '.dart_tool/package_config.json' + config.parent.mkdir() + package = root / 'cache/deskup-0.1.0' + for uri in ['../cache/deskup-0.1.0/', package.as_uri() + '/']: + config.write_text(json.dumps({'packages': [ + {'name': 'deskup', 'rootUri': uri}, + ]}), encoding='utf-8') + with patch('windows_updates.ROOT', root): + self.assertEqual(resolved_deskup().resolve(), package.resolve()) + + def test_missing_package_config_requests_pub_get(self): + with tempfile.TemporaryDirectory() as directory: + with patch('windows_updates.ROOT', Path(directory)): + with self.assertRaisesRegex(ValueError, 'flutter pub get'): + resolved_deskup() + + def test_display_version_conversion_is_shared_and_ordered(self): + self.assertEqual(update_version('1.2.3', '42'), '1.2.3-build.42') + self.assertEqual(update_version('1.2.3', '0042'), '1.2.3-build.42') + for version, build in [('1.2', 1), ('1.2.3', -1), ('1.2.3', 'beta')]: + with self.assertRaises(ValueError): + update_version(version, build) + + def test_invalid_pack_version_never_starts_vpk(self): + with patch('windows_updates.subprocess.run') as run: + with self.assertRaises(ValueError): + pack_release(['vpk'], app=Path('app'), output=Path('release'), + package_id='Cutdex', version='1.0.0.42', title='Cutdex') + run.assert_not_called() + + def test_build_number_participates_in_version_order(self): + self.assertLess(numeric_version('1.0.0-build.1'), numeric_version('1.0.0-build.2')) + self.assertLess(numeric_version('1.0.0-build.9'), numeric_version('1.0.0-build.10')) + self.assertLess(numeric_version('1.0.0-build.999'), numeric_version('1.0.1-build.1')) + self.assertLess(numeric_version('1.0.0-build.999'), numeric_version('1.0.0')) + for version in ['1.0', '1.0.0+2', '1.0.0.2', '1.0.0-build.02', '1.0.0-beta', '../1.0.0']: + with self.assertRaises(ValueError): + numeric_version(version) + + def test_reused_build_and_mixed_identity_are_rejected(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / 'releases.win-x64.json').write_text(json.dumps({ + 'Assets': [{'PackageId': 'Cutdex', 'Version': '1.0.0-build.2'}]})) + for candidate in ['1.0.0-build.1', '1.0.0-build.2']: + with self.assertRaises(ValueError): + validate_previous(root, 'Cutdex', candidate) + with self.assertRaises(ValueError): + validate_previous(root, 'Cutdex.Dev', '1.0.0-build.3') + validate_previous(root, 'Cutdex', '1.0.0-build.3') + + def test_post_audit_tampering_and_added_files_are_rejected(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / 'cutdex.exe').write_bytes(b'app') + (root / 'processing').mkdir() + (root / 'processing/checksums.json').write_text('{}') + manifest = {name: hashlib.sha256((root / name).read_bytes()).hexdigest() + for name in ['cutdex.exe', 'processing/checksums.json']} + (root / 'checksums.json').write_text(json.dumps(manifest)) + verify_manifest(root) + (root / 'cutdex.exe').write_bytes(b'changed') + with self.assertRaises(ValueError): + verify_manifest(root) + (root / 'cutdex.exe').write_bytes(b'app') + (root / 'injected.dll').write_bytes(b'new') + with self.assertRaises(ValueError): + verify_manifest(root) + + def test_escaping_manifest_path_is_rejected(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / 'checksums.json').write_text(json.dumps({'../outside.exe': '0' * 64})) + with self.assertRaises(ValueError): + verify_manifest(root) + + def test_relative_staging_directory_is_normalized(self): + with tempfile.TemporaryDirectory(dir=Path.cwd()) as directory: + root = Path(directory).relative_to(Path.cwd()) + (root / 'cutdex.exe').write_bytes(b'app') + (root / 'checksums.json').write_text(json.dumps({ + 'cutdex.exe': hashlib.sha256(b'app').hexdigest(), + })) + verify_manifest(root) + + def test_symlink_inside_staging_directory_is_rejected(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + original = root / 'cutdex.exe' + original.write_bytes(b'app') + try: + (root / 'linked.exe').symlink_to(original) + except OSError as error: + if getattr(error, 'winerror', None) != 1314: + raise + self.skipTest(f'Symlinks unavailable: {error}') + digest = hashlib.sha256(b'app').hexdigest() + (root / 'checksums.json').write_text(json.dumps({ + 'cutdex.exe': digest, + 'linked.exe': digest, + })) + with self.assertRaisesRegex(ValueError, 'Invalid manifest path'): + verify_manifest(root) + + +if __name__ == '__main__': + unittest.main() diff --git a/tool/windows/windows_updates.py b/tool/windows/windows_updates.py new file mode 100644 index 0000000..62d1ad8 --- /dev/null +++ b/tool/windows/windows_updates.py @@ -0,0 +1,184 @@ +"""Package audited Windows releases with Velopack, or serve a loopback test feed.""" +import argparse +from functools import partial +import hashlib +from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer +import json +from pathlib import Path +import re +import subprocess +import sys +from urllib.parse import urljoin, urlparse +from urllib.request import url2pathname + +from check_windows_release import audit + +ROOT = Path(__file__).resolve().parents[2] +def resolved_deskup(): + config = ROOT / '.dart_tool/package_config.json' + if not config.is_file(): + raise ValueError('Run flutter pub get before using Windows update tools') + packages = json.loads(config.read_text(encoding='utf-8'))['packages'] + package = next(item for item in packages if item['name'] == 'deskup') + uri = urlparse(urljoin(config.as_uri(), package['rootUri'])) + if uri.scheme != 'file' or uri.netloc: + raise ValueError('Expected a local resolved deskup package') + return Path(url2pathname(uri.path)) + + +DESKUP_ROOT = resolved_deskup() +DESKUP_VERSION = re.search(r'^version: ([^\s]+)', + (DESKUP_ROOT / 'pubspec.yaml').read_text(encoding='utf-8'), + re.MULTILINE).group(1) +SDK_VERSION = re.search(r'set\(DESKUP_VELOPACK_VERSION "([^"]+)"\)', + (DESKUP_ROOT / 'windows/velopack.cmake').read_text(encoding='utf-8')).group(1) + + +def vpk_command(path): + path = Path(path).resolve() + if path.suffix.lower() == '.dll': + # Useful with a locally extracted official vpk tool package. + return ['dotnet', str(path), '--legacyConsole', '--skip-updates'] + return [str(path), '--legacyConsole', '--skip-updates'] + + +def check_tool(command): + result = subprocess.run(command + ['--help'], capture_output=True, text=True, + encoding='utf-8', errors='replace', check=True, timeout=30) + if not re.search(rf'(?= candidate: + raise ValueError('Update version must be greater than every previously published version') + + +def verify_manifest(app): + app = app.resolve() + manifest = json.loads((app / 'checksums.json').read_text(encoding='utf-8-sig')) + actual_files = {file.relative_to(app).as_posix() for file in app.rglob('*') + if file.is_file() and file.name != 'checksums.json'} + # The processing subtree has its own checksum manifest, which is included + # as a file in the outer app manifest. + actual_files.update(file.relative_to(app).as_posix() for file in app.rglob('checksums.json') + if file != app / 'checksums.json') + if set(manifest) != actual_files: + raise ValueError('Release files differ from the audited staging manifest') + for name, expected in manifest.items(): + candidate = app / name + file = candidate.resolve() + if not file.is_relative_to(app) or candidate.is_symlink(): + raise ValueError(f'Invalid manifest path: {name}') + with file.open('rb') as stream: + if hashlib.file_digest(stream, 'sha256').hexdigest().lower() != expected.lower(): + raise ValueError(f'Release checksum mismatch: {name}') + + +def package(args): + app, output = args.app.resolve(), args.output.resolve() + if output == app or output.is_relative_to(app) or app.is_relative_to(output): + raise ValueError('Release output must be outside the staged app') + audit(app) + verify_manifest(app) + sdk_dll = app / 'velopack_libc.dll' + if not sdk_dll.is_file(): + raise ValueError('Rebuild the app with the Velopack integration before packaging') + command = vpk_command(args.vpk) + check_tool(command) + version = file_version(app) + package_id = 'Cutdex.Dev' if args.development else 'Cutdex' + # The expected identity is compiled into the runner and must match the package. + identity = package_id.encode('ascii') + b'\0' + if identity not in (app / 'cutdex.exe').read_bytes(): + raise ValueError('Package identity does not match the Flutter build flavor') + validate_previous(output, package_id, version) + output.mkdir(parents=True, exist_ok=True) + pack_release(command, app=app, output=output, package_id=package_id, version=version, + title='Cutdex Dev' if args.development else 'Cutdex') + print(json.dumps({'version': version, 'packageId': package_id, 'output': str(output)})) + + +def serve(directory, port): + directory = directory.resolve() + if not directory.is_dir(): + raise ValueError('Provide an existing Velopack release directory') + with ThreadingHTTPServer(('127.0.0.1', port), + partial(SimpleHTTPRequestHandler, directory=str(directory))) as server: + print(f'Test update source: http://127.0.0.1:{server.server_port}', flush=True) + server.serve_forever() + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + commands = parser.add_subparsers(dest='command', required=True) + pack = commands.add_parser('pack', help='Package a complete audited release; never uploads') + pack.add_argument('--app', type=Path, required=True) + pack.add_argument('--output', type=Path, required=True) + pack.add_argument('--vpk', type=Path, required=True) + pack.add_argument('--development', action='store_true') + server = commands.add_parser('serve', help='Serve a test feed on 127.0.0.1 only') + server.add_argument('--directory', type=Path, required=True) + server.add_argument('--port', type=int, default=8765) + args = parser.parse_args() + try: + if args.command == 'pack': + package(args) + else: + serve(args.directory, args.port) + except KeyboardInterrupt: + return + except (ValueError, OSError) as error: + print(str(error), file=sys.stderr) + raise SystemExit(1) from error + except subprocess.CalledProcessError as error: + raise SystemExit(error.returncode) from error + + +if __name__ == '__main__': + main() diff --git a/web/favicon.png b/web/favicon.png new file mode 100644 index 0000000..f9d091e Binary files /dev/null and b/web/favicon.png differ diff --git a/web/icons/Icon-192.png b/web/icons/Icon-192.png new file mode 100644 index 0000000..dc079d1 Binary files /dev/null and b/web/icons/Icon-192.png differ diff --git a/web/icons/Icon-512.png b/web/icons/Icon-512.png new file mode 100644 index 0000000..fdc11ed Binary files /dev/null and b/web/icons/Icon-512.png differ diff --git a/web/icons/Icon-maskable-192.png b/web/icons/Icon-maskable-192.png new file mode 100644 index 0000000..c5eae8a Binary files /dev/null and b/web/icons/Icon-maskable-192.png differ diff --git a/web/icons/Icon-maskable-512.png b/web/icons/Icon-maskable-512.png new file mode 100644 index 0000000..36e535a Binary files /dev/null and b/web/icons/Icon-maskable-512.png differ diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..859cca5 --- /dev/null +++ b/web/index.html @@ -0,0 +1,46 @@ + + + + + + + + + + + + + + + + + + + + cutdex + + + + + + + diff --git a/web/manifest.json b/web/manifest.json new file mode 100644 index 0000000..e48ea65 --- /dev/null +++ b/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "cutdex", + "short_name": "cutdex", + "start_url": ".", + "display": "standalone", + "background_color": "#0175C2", + "theme_color": "#0175C2", + "description": "A new Flutter project.", + "orientation": "portrait-primary", + "prefer_related_applications": false, + "icons": [ + { + "src": "icons/Icon-192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "icons/Icon-512.png", + "sizes": "512x512", + "type": "image/png" + }, + { + "src": "icons/Icon-maskable-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "maskable" + }, + { + "src": "icons/Icon-maskable-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + } + ] +} diff --git a/windows/.gitignore b/windows/.gitignore new file mode 100644 index 0000000..d492d0d --- /dev/null +++ b/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt new file mode 100644 index 0000000..969e4de --- /dev/null +++ b/windows/CMakeLists.txt @@ -0,0 +1,129 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(cutdex LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "cutdex") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(VERSION 3.14...3.25) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +# JNI is pulled in by path_provider_android. Windows uses path_provider_windows +# and never starts a JVM; do not let a build-host JDK add dartjni.dll to the app. +set(CMAKE_DISABLE_FIND_PACKAGE_JNI TRUE) +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") +install(CODE "file(REMOVE \"${INSTALL_BUNDLE_LIB_DIR}/dartjni.dll\")" + COMPONENT Runtime) + +# App-local VC++ runtime: a Release bundle must not rely on Visual Studio or +# vc_redist having been installed on the target machine. Windows 10/11 supply +# the UCRT; debug CRTs are not redistributable. +set(CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS_SKIP TRUE) +set(CMAKE_INSTALL_DEBUG_LIBRARIES FALSE) +include(InstallRequiredSystemLibraries) +if(NOT CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS) + message(FATAL_ERROR "Visual C++ redistributable libraries were not found") +endif() +install(PROGRAMS ${CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS} + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + CONFIGURATIONS Profile Release COMPONENT Runtime) + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Copy the native assets provided by the build.dart from all packages. +set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") +install(DIRECTORY "${NATIVE_ASSETS_DIR}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) + +# deskup is registered by generated_plugins.cmake above. +target_link_libraries(${BINARY_NAME} PRIVATE deskup_startup) diff --git a/windows/flutter/CMakeLists.txt b/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..903f489 --- /dev/null +++ b/windows/flutter/CMakeLists.txt @@ -0,0 +1,109 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# Set fallback configurations for older versions of the flutter tool. +if (NOT DEFINED FLUTTER_TARGET_PLATFORM) + set(FLUTTER_TARGET_PLATFORM "windows-x64") +endif() + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + ${FLUTTER_TARGET_PLATFORM} $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..e181429 --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,26 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + +#include +#include +#include +#include +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + CutdexNativePluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("CutdexNativePluginCApi")); + CutdexRuntimePluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("CutdexRuntimePluginCApi")); + DeskupPluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("DeskupPluginCApi")); + FilegatePluginCApiRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FilegatePluginCApi")); + FlutterSecureStorageWindowsPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FlutterSecureStorageWindowsPlugin")); +} diff --git a/windows/flutter/generated_plugin_registrant.h b/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..dc139d8 --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..337347c --- /dev/null +++ b/windows/flutter/generated_plugins.cmake @@ -0,0 +1,29 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + cutdex_native + cutdex_runtime + deskup + filegate + flutter_secure_storage_windows +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST + jni +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/windows/runner/CMakeLists.txt b/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..7150a3b --- /dev/null +++ b/windows/runner/CMakeLists.txt @@ -0,0 +1,66 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Configure native runner branding for the selected Flutter flavor. Flutter +# exposes FLUTTER_APP_FLAVOR after windows/flutter has been added by the +# top-level CMakeLists.txt. +set(RUNNER_APP_ICON "production.ico") +set(WINDOW_TITLE "Cutdex") +if(DEFINED FLUTTER_APP_FLAVOR) + if(FLUTTER_APP_FLAVOR STREQUAL "development") + set(RUNNER_APP_ICON "development.ico") + set(WINDOW_TITLE "Cutdex Dev") + elseif(FLUTTER_APP_FLAVOR STREQUAL "production") + set(RUNNER_APP_ICON "production.ico") + set(WINDOW_TITLE "Cutdex") + endif() +endif() + +configure_file( + "${CMAKE_CURRENT_SOURCE_DIR}/main.cpp.in" + "${CMAKE_CURRENT_SOURCE_DIR}/main.cpp" + @ONLY +) +configure_file( + "${CMAKE_CURRENT_SOURCE_DIR}/Runner.rc.in" + "${CMAKE_CURRENT_SOURCE_DIR}/Runner.rc" + @ONLY +) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") +include("${CMAKE_CURRENT_SOURCE_DIR}/update_configuration.cmake") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/windows/runner/Runner.rc.in b/windows/runner/Runner.rc.in new file mode 100644 index 0000000..44c9c1f --- /dev/null +++ b/windows/runner/Runner.rc.in @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\@RUNNER_APP_ICON@" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "com.example" "\0" + VALUE "FileDescription", "@WINDOW_TITLE@" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "cutdex" "\0" + VALUE "LegalCopyright", "Copyright (C) 2026 com.example. All rights reserved." "\0" + VALUE "OriginalFilename", "cutdex.exe" "\0" + VALUE "ProductName", "@WINDOW_TITLE@" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/windows/runner/flutter_window.cpp b/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..f0fdb1a --- /dev/null +++ b/windows/runner/flutter_window.cpp @@ -0,0 +1,78 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_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()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + flutter_controller_->engine()->SetNextFrameCallback([&]() { + this->Show(); + }); + + // Flutter can complete the first frame before the "show window" callback is + // registered. The following call ensures a frame is pending to ensure the + // window is shown. It is a no-op if the first frame hasn't completed yet. + flutter_controller_->ForceRedraw(); + + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_GETMINMAXINFO: { + Win32Window::MessageHandler(hwnd, message, wparam, lparam); + const UINT dpi = GetDpiForWindow(hwnd); + auto limits = reinterpret_cast(lparam); + limits->ptMinTrackSize.x = MulDiv(400, static_cast(dpi), 96); + limits->ptMinTrackSize.y = MulDiv(300, static_cast(dpi), 96); + return 0; + } + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/windows/runner/flutter_window.h b/windows/runner/flutter_window.h new file mode 100644 index 0000000..6da0652 --- /dev/null +++ b/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/windows/runner/main.cpp.in b/windows/runner/main.cpp.in new file mode 100644 index 0000000..ea5e94b --- /dev/null +++ b/windows/runner/main.cpp.in @@ -0,0 +1,56 @@ +#include +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +// Hybrid graphics drivers consult these process-wide hints before Flutter or +// native media creates a D3D device. Keep both texture producers on the same +// preferred adapter; explicit Windows graphics preferences still take priority. +extern "C" { +__declspec(dllexport) DWORD NvOptimusEnablement = 1; +__declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1; +} + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Handle installation hooks before initializing Flutter, COM or media. + // Applying a pending update requires an explicit user action in Cutdex. + DeskupRunStartup(); + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.Create(L"@WINDOW_TITLE@", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + window.Show(); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/windows/runner/resource.h b/windows/runner/resource.h new file mode 100644 index 0000000..66a65d1 --- /dev/null +++ b/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/windows/runner/resources/development.ico b/windows/runner/resources/development.ico new file mode 100644 index 0000000..1691967 Binary files /dev/null and b/windows/runner/resources/development.ico differ diff --git a/windows/runner/resources/production.ico b/windows/runner/resources/production.ico new file mode 100644 index 0000000..2c287fd Binary files /dev/null and b/windows/runner/resources/production.ico differ diff --git a/windows/runner/runner.exe.manifest b/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..153653e --- /dev/null +++ b/windows/runner/runner.exe.manifest @@ -0,0 +1,14 @@ + + + + + PerMonitorV2 + + + + + + + + + diff --git a/windows/runner/update_configuration.cmake b/windows/runner/update_configuration.cmake new file mode 100644 index 0000000..33671ee --- /dev/null +++ b/windows/runner/update_configuration.cmake @@ -0,0 +1,18 @@ +# Configuration is baked into the binary; a user's environment cannot redirect it. +set(CUTDEX_WINDOWS_UPDATE_URL "$ENV{CUTDEX_WINDOWS_UPDATE_URL}") +set(CUTDEX_UPDATE_PACKAGE_ID "Cutdex") +set(CUTDEX_UPDATE_TEST_HTTP 0) +if(FLUTTER_APP_FLAVOR STREQUAL "development") + set(CUTDEX_UPDATE_PACKAGE_ID "Cutdex.Dev") + if("$ENV{CUTDEX_UPDATE_TEST_HTTP}" STREQUAL "1") + set(CUTDEX_UPDATE_TEST_HTTP 1) + endif() +endif() +# deskup validates feed URLs; the host limits local HTTP to development. +if(DEFINED ENV{CUTDEX_VELOPACK_ARCHIVE}) + set(ENV{DESKUP_VELOPACK_ARCHIVE} "$ENV{CUTDEX_VELOPACK_ARCHIVE}") +endif() +set(DESKUP_WINDOWS_UPDATE_URL "${CUTDEX_WINDOWS_UPDATE_URL}" PARENT_SCOPE) +set(DESKUP_UPDATE_PACKAGE_ID "${CUTDEX_UPDATE_PACKAGE_ID}" PARENT_SCOPE) +set(DESKUP_PREFERENCE_ROOT "Software\\\\Cutdex\\\\" PARENT_SCOPE) +set(DESKUP_ALLOW_LOCAL_HTTP "${CUTDEX_UPDATE_TEST_HTTP}" PARENT_SCOPE) diff --git a/windows/runner/utils.cpp b/windows/runner/utils.cpp new file mode 100644 index 0000000..3cb7146 --- /dev/null +++ b/windows/runner/utils.cpp @@ -0,0 +1,69 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + // First, find the length of the string with a safe upper bound (CWE-126). + // UNICODE_STRING_MAX_CHARS (32767) is the maximum length of a UNICODE_STRING. + int input_length = static_cast(wcsnlen(utf16_string, UNICODE_STRING_MAX_CHARS)); + // Now use that bounded length to determine the required buffer size. + // When an explicit length is passed, WideCharToMultiByte does not include + // the null terminator in its returned size. + int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, nullptr, 0, nullptr, nullptr); + std::string utf8_string; + if (target_length == 0 || static_cast(target_length) > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + input_length, utf8_string.data(), target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/windows/runner/utils.h b/windows/runner/utils.h new file mode 100644 index 0000000..3879d54 --- /dev/null +++ b/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/windows/runner/win32_window.cpp b/windows/runner/win32_window.cpp new file mode 100644 index 0000000..60608d0 --- /dev/null +++ b/windows/runner/win32_window.cpp @@ -0,0 +1,288 @@ +#include "win32_window.h" + +#include +#include + +#include "resource.h" + +namespace { + +/// Window attribute that enables dark mode window decorations. +/// +/// Redefined in case the developer's machine has a Windows SDK older than +/// version 10.0.22000.0. +/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute +#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE +#define DWMWA_USE_IMMERSIVE_DARK_MODE 20 +#endif + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +/// Registry key for app theme preference. +/// +/// A value of 0 indicates apps should use dark mode. A non-zero or missing +/// value indicates apps should use light mode. +constexpr const wchar_t kGetPreferredBrightnessRegKey[] = + L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; +constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + } + FreeLibrary(user32_module); +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registrar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::Create(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + UpdateTheme(window); + + return OnCreate(); +} + +bool Win32Window::Show() { + return ShowWindow(window_handle_, SW_SHOWNORMAL); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + + case WM_DWMCOLORIZATIONCOLORCHANGED: + UpdateTheme(hwnd); + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} + +void Win32Window::UpdateTheme(HWND const window) { + DWORD light_mode; + DWORD light_mode_size = sizeof(light_mode); + LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, + kGetPreferredBrightnessRegValue, + RRF_RT_REG_DWORD, nullptr, &light_mode, + &light_mode_size); + + if (result == ERROR_SUCCESS) { + BOOL enable_dark_mode = light_mode == 0; + DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, + &enable_dark_mode, sizeof(enable_dark_mode)); + } +} diff --git a/windows/runner/win32_window.h b/windows/runner/win32_window.h new file mode 100644 index 0000000..e901dde --- /dev/null +++ b/windows/runner/win32_window.h @@ -0,0 +1,102 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates a win32 window with |title| that is positioned and sized using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size this function will scale the inputted width and height as + // as appropriate for the default monitor. The window is invisible until + // |Show| is called. Returns true if the window was created successfully. + bool Create(const std::wstring& title, const Point& origin, const Size& size); + + // Show the current window. Returns true if the window was successfully shown. + bool Show(); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + // Update the window frame's theme to match the system theme. + static void UpdateTheme(HWND const window); + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_