9 Commits
346 changed files with 48687 additions and 3431 deletions

No files matched your search

+33
View File
@@ -0,0 +1,33 @@
# Copy to .env.local and uncomment only the overrides needed on this machine.
# Existing process environment variables take precedence.
# Values are literal: no shell commands, interpolation or escape expansion.
# Use quotes for spaces; Windows paths may use / or literal backslashes.
# Windows native source development (requires Rust and FFMPEG_DIR).
# CUTDEX_WINDOWS_PATH=D:/workspace/cutdex_windows
# FFMPEG_DIR=D:/tools/ffmpeg
# Alternatively, use an extracted Windows native package. Choose only one path.
# CUTDEX_WINDOWS_PACKAGE_PATH=D:/packages/cutdex-windows
# macOS / iOS native source development.
# CUTDEX_APPLE_PATH=/Users/your-name/workspace/cutdex_apple
# Android native source development (Gradle composite build).
# CUTDEX_ANDROID_PATH=D:/workspace/cutdex-project/cutdex_android
# Optional processing workers directory.
# CUTDEX_PROCESSING_ROOT=D:/packages/cutdex-processing
# Optional authentication for private native packages.
# Token owner's authentication account (not the workflow trigger user).
# GITEA_ACTOR=your-account
# CUTDEX_GITEA_TOKEN=
# Optional macOS release signing and notarization.
# CUTDEX_CODESIGN_IDENTITY=Developer ID Application: Your Name (TEAMID)
# CUTDEX_NOTARY_PROFILE=your-notary-keychain-profile
# Optional macOS update feed. Set both values together.
# CUTDEX_UPDATE_FEED_URL=https://updates.example.com/cutdex/appcast.xml
# CUTDEX_UPDATE_PUBLIC_KEY=your-update-public-key
+3
View File
@@ -0,0 +1,3 @@
{
"flutter": "3.47.5"
}
+19 -6
View File
@@ -1,6 +1,6 @@
# Gitea Windows and Android builds
The Windows x64 host runner needs Flutter 3.47.5, Python, Node, Visual Studio C++,
The Windows x64 host runner needs the Flutter version pinned in `.fvmrc`, Python, Node, Visual Studio C++,
JDK 21 and Android SDK 36. The native cutdex_windows Release and cutdex_android
Maven packages must be published before building this app. The SDK Git dependency
is pinned to Gitea; the runner account needs SSH access to that private repository.
@@ -13,13 +13,26 @@ shipping a production signed Android release. The Windows ZIP includes the whole
Flutter Release directory and passes the PE dependency audit. Processing workers
and optional models are separate; these four repositories contain no worker bundle.
PR/main CI analyzes and tests the app, builds both platforms, and uploads
cutdex-release-packages including SHA256SUMS and a release manifest. It also saves
CI and local checks share `tool/check.py` suites for analysis, app/package tests
and repository/tool tests. Local tooling loads `.env.local` with the project FVM
SDK; CI uses its version-verified preinstalled SDK and ignores that file. Both
use `tool/build.py` production/release presets for platform compilation.
CI always analyzes and tests the app. Ordinary code PRs also compile both
platforms, but skip Windows packaging, artifact uploads and final assembly.
Documentation-only PRs skip platform compilation as well. PR changes to CI,
tooling, native platform configuration, package dependencies or app update code
run the complete pipeline. `ci_scope.py` compares the PR base and head using Git
history, including deleted files; a failed comparison fails code checks.
Main pushes and manual CI runs always execute the complete pipeline and upload
cutdex-release-packages including SHA256SUMS and a release manifest. They also save
cutdex-release-metadata containing only the manifest, checksums, Windows update
index and audit report. Platform, complete and metadata artifacts retain 30 days. Protect main
with `Gitea CI / Gitea CI passed (pull_request)`.
with `Gitea CI / Gitea CI passed (pull_request)`. This required check validates
every expected job and permits skipped jobs only when the selected scope
explicitly excludes them; failures, cancellations and unexpected skips fail it.
Windows compilation and packaging are separate jobs. Compilation saves the
Windows compilation and packaging are separate jobs. Full-pipeline compilation saves the
unpackaged Release directory as `cutdex-windows-app` for 30 days; packaging
downloads it and runs the existing PE audit and Velopack tools. Rerunning a failed
packaging job reuses this app without recompiling. Assembly and Release jobs
@@ -62,7 +75,7 @@ operator attention. Published Releases are never overwritten. The built-in
GITEA_TOKEN handles release writes and Actions artifact reads; no separate
release-write PAT is required. Do not commit credentials or keystores.
PR/main CI produces Actions artifacts without creating Releases. If a tag is pushed
Full-pipeline CI produces Actions artifacts without creating Releases. If a tag is pushed
before main CI succeeds, release preparation fails without creating a draft; retry
the Release workflow once CI has finished. This design overlaps platform uploads,
not main CI builds with Release uploads. There is no legacy whole-archive
+54 -1
View File
@@ -1,6 +1,22 @@
# CI build performance
The workflow runs checks first, then Android and Windows compilation concurrently.
The workflow runs checks first, then Android and Windows compilation concurrently
when compilation is required. Ordinary code PRs stop after compilation and native
SDK validation; they skip artifact transfers, Windows packaging and assembly.
Documentation-only PRs run checks without compiling either platform. Changes to
CI, tooling, native platform configuration, dependencies, `.fvmrc` and app update code
force the full pipeline. Main pushes and manual CI runs always use the full
pipeline, preserving the exact-commit artifacts needed by Release.
Scope selection uses the complete PR base/head history in the quality checkout.
Other checkouts retain their default shallow fetch. Git comparisons include
deleted paths and disable rename detection, so moving a packaging file into docs
cannot hide its deletion. Unknown paths compile both platforms; empty PR diffs
run the full pipeline. Scope selection errors fail CI instead of skipping jobs.
The final required check requires success for selected jobs and `skipped` for
excluded jobs, and always requires successful code checks.
In the full pipeline,
Windows compilation saves `cutdex-windows-app`; an independent Windows job
downloads that app, audits it and creates Velopack packages. Packaging needs
neither Flutter dependencies nor another Windows compilation. The Android job
@@ -14,6 +30,43 @@ enabled for CI. Do not clear these caches between runs. Each job must have its o
checkout; do not share a Flutter `build/` or `.dart_tool/` directory between jobs.
With an ephemeral runner, these user directories must be persisted separately.
The Windows compilation job runs `tool/windows/native_cache.py` after locked Pub
resolution. It reads the Velopack version and SHA256 from the resolved deskup
package and persists its ZIP in `%LOCALAPPDATA%/Cutdex/ci-tools/native/`, keyed by
both values. Every reuse verifies the digest; corrupt files are replaced only
after a verified download. OS file locks coordinate concurrent jobs, and atomic
replacement prevents interrupted downloads from becoming cache hits. Temporary
network failures retry at most three times. `DESKUP_VELOPACK_ARCHIVE` points CMake
at the verified local ZIP, where the SDK performs its own hash check again.
An explicitly supplied offline archive is validated and can populate this cache.
Version or hash changes use a separate file; no checkout-local `_deps` directory
is shared. Persist this user cache too when using ephemeral runners.
The local `prepare-flutter` action owns cache setup, Flutter version validation,
optional Java configuration and locked dependency resolution for the quality,
Android and Windows compilation jobs. `.fvmrc` is the shared local/CI Flutter
version source; the action verifies the preinstalled runner SDK against it, without
installing FVM or resolving a second SDK. Quality checks also run the Flutter
Python version guard and local launcher regression tests. The guard reads `.fvmrc`
before probing the runner SDK and requires no PowerShell-specific implementation.
Local and CI checks share
`tool/check.py --suite analyze|flutter|tools`, including fatal-info analysis,
app/package tests, repository hygiene and portable tooling regressions. Each suite
remains a separate CI step. `tool/build.py` owns production/release defaults and
Android architectures; SDK selection and environment loading use the shared Dart
launcher through its Python adapter. The runner continues using its verified
preinstalled SDK rather than requiring a project FVM link. Platform builds clear their
local native source path environment overrides and never read `.env.local`.
The separate `prepare-windows-packaging` action owns the user .NET
installation and packaging tool setup, so packaging retries do not resolve
Flutter dependencies. Individual setup steps remain visible within each action.
Workflow-level environment variables contain only shared nonsecret settings.
The SDK token is limited to quality and platform compilation jobs. The fixed
Maven account name is set only on the Android build step, matching the SDK token
owner rather than the user who triggered CI. Assembly needs no SDK credentials;
Release credentials remain confined to the Release workflow's publishing jobs.
Build commands keep Flutter's default Pub preparation after the explicit locked
resolution. Do not use `--no-pub`: Flutter also regenerates release plugin
registrants in that preparation, removing dev-only plugins such as integration_test.
+28
View File
@@ -0,0 +1,28 @@
name: Prepare Flutter build environment
description: Configure persistent caches, verify Flutter and resolve locked dependencies.
inputs:
configure-java:
description: Configure Flutter to use the runner's JAVA_HOME
default: 'false'
runs:
using: composite
steps:
- name: Configure persistent build caches
shell: pwsh
run: ./tool/gitea/prepare-build-cache.ps1
- name: Verify Flutter version
shell: pwsh
run: python tool/gitea/verify_flutter_version.py
- name: Configure Flutter Java
if: ${{ inputs.configure-java == 'true' }}
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
if (-not $env:JAVA_HOME) { throw 'JAVA_HOME is required for Flutter JDK setup.' }
flutter config --jdk-dir=$env:JAVA_HOME
if ($LASTEXITCODE -ne 0) { throw 'Flutter JDK setup failed.' }
- name: Resolve locked Flutter dependencies
shell: pwsh
run: |
flutter pub get --enforce-lockfile
if ($LASTEXITCODE -ne 0) { throw 'Locked Flutter dependency resolution failed.' }
@@ -0,0 +1,20 @@
name: Prepare Windows packaging environment
description: Reuse the user .NET installation and pinned packaging tools independently of Flutter.
runs:
using: composite
steps:
- name: Configure user .NET installation
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$directory = Join-Path $env:LOCALAPPDATA 'Cutdex/ci-tools/dotnet'
[IO.Directory]::CreateDirectory($directory) | Out-Null
"DOTNET_INSTALL_DIR=$directory" | Out-File -LiteralPath $env:GITHUB_ENV -Encoding utf8 -Append
"DOTNET_ROOT=$directory" | Out-File -LiteralPath $env:GITHUB_ENV -Encoding utf8 -Append
- name: Set up .NET SDK
uses: https://github.com/actions/setup-dotnet@26b0ec14cb23fa6904739307f278c14f94c95bf1
with:
dotnet-version: '10.0.x'
- name: Prepare pinned packaging tools
shell: pwsh
run: ./tool/gitea/prepare-package-tools.ps1
+73 -59
View File
@@ -12,6 +12,7 @@ concurrency:
group: app-${{ gitea.ref }}
cancel-in-progress: true
env:
CI: 'true'
PYTHONUTF8: '1'
CUTDEX_GITEA_INTERNAL_URL: http://127.0.0.1:3000
GIT_CONFIG_COUNT: '2'
@@ -23,8 +24,10 @@ jobs:
quality:
name: Check code and tests
runs-on: cutdex-windows-x64
outputs:
build-app: ${{ steps.scope.outputs.build-app }}
package-app: ${{ steps.scope.outputs.package-app }}
env:
GITEA_ACTOR: lingjhf
CUTDEX_GITEA_TOKEN: ${{ secrets.CUTDEX_GITEA_TOKEN }}
steps:
- name: Check out source
@@ -32,33 +35,33 @@ jobs:
with:
persist-credentials: false
github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
- name: Configure persistent build caches
run: ./tool/gitea/prepare-build-cache.ps1
- name: Verify Flutter version and configure Java
fetch-depth: 0
- name: Select compilation and packaging scope
id: scope
env:
CI_EVENT_NAME: ${{ gitea.event_name }}
CI_PR_BASE_SHA: ${{ gitea.event.pull_request.base.sha }}
CI_PR_HEAD_SHA: ${{ gitea.event.pull_request.head.sha }}
run: |
$version = flutter --version --machine | ConvertFrom-Json
if ($version.frameworkVersion -ne '3.47.5') { throw 'Flutter 3.47.5 required.' }
flutter config --jdk-dir=$env:JAVA_HOME
if ($LASTEXITCODE -ne 0) { throw 'Flutter JDK setup failed.' }
- name: Resolve locked Flutter dependencies
run: flutter pub get --enforce-lockfile
python tool/gitea/ci_scope.py
if ($LASTEXITCODE -ne 0) { throw 'CI scope selection failed.' }
- name: Prepare Flutter environment
uses: ./.gitea/actions/prepare-flutter
with:
configure-java: 'true'
- name: Analyze Dart code
run: dart analyze --fatal-infos
run: python tool/check.py --suite analyze
- name: Run Flutter tests
run: flutter test --reporter expanded test packages/cutdex_ui/test packages/cutdex_native/test
- name: Test update and release tools
run: |
python -m unittest discover -s tool/gitea -p 'test_*.py'
if ($LASTEXITCODE -ne 0) { throw 'Release tooling tests failed.' }
python -m unittest discover -s tool/windows -p '*_unit.py'
if ($LASTEXITCODE -ne 0) { throw 'Update tooling tests failed.' }
run: python tool/check.py --suite flutter
- name: Check repository and tool tests
run: python tool/check.py --suite tools
android:
name: Build Android APK
needs: quality
if: ${{ needs.quality.outputs.build-app == 'true' }}
runs-on: cutdex-windows-x64
env:
GITEA_ACTOR: lingjhf
CUTDEX_GITEA_TOKEN: ${{ secrets.CUTDEX_GITEA_TOKEN }}
steps:
- name: Check out source
@@ -66,24 +69,24 @@ jobs:
with:
persist-credentials: false
github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
- name: Configure persistent build caches
run: ./tool/gitea/prepare-build-cache.ps1
- name: Verify Flutter version and configure Java
run: |
$version = flutter --version --machine | ConvertFrom-Json
if ($version.frameworkVersion -ne '3.47.5') { throw 'Flutter 3.47.5 required.' }
flutter config --jdk-dir=$env:JAVA_HOME
if ($LASTEXITCODE -ne 0) { throw 'Flutter JDK setup failed.' }
- name: Resolve locked Flutter dependencies
run: flutter pub get --enforce-lockfile
- name: Prepare Flutter environment
uses: ./.gitea/actions/prepare-flutter
with:
configure-java: 'true'
- name: Configure Gradle memory and build cache
run: |
$file = 'android/gradle.properties'
$properties = [IO.File]::ReadAllText($file).Replace('-Xmx8G', '-Xmx3G').Replace('MaxMetaspaceSize=4G', 'MaxMetaspaceSize=768m')
[IO.File]::WriteAllText($file, $properties + "`norg.gradle.workers.max=4`norg.gradle.caching=true`n")
- name: Build production Android APK
run: flutter build apk --release --flavor production --target-platform android-arm64,android-x64
env:
GITEA_ACTOR: lingjhf
run: |
Remove-Item Env:CUTDEX_ANDROID_PATH -ErrorAction SilentlyContinue
python tool/build.py android
if ($LASTEXITCODE -ne 0) { throw 'Android build failed.' }
- name: Upload Android CI artifact
if: ${{ needs.quality.outputs.package-app == 'true' }}
uses: ./.gitea/actions/upload-artifact
with:
name: cutdex-android-build
@@ -94,9 +97,9 @@ jobs:
windows-build:
name: Build Windows x64 app
needs: quality
if: ${{ needs.quality.outputs.build-app == 'true' }}
runs-on: cutdex-windows-x64
env:
GITEA_ACTOR: lingjhf
CUTDEX_GITEA_TOKEN: ${{ secrets.CUTDEX_GITEA_TOKEN }}
steps:
- name: Check out source
@@ -104,24 +107,23 @@ jobs:
with:
persist-credentials: false
github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
- name: Configure persistent build caches
run: ./tool/gitea/prepare-build-cache.ps1
- name: Verify Flutter version
- name: Prepare Flutter environment
uses: ./.gitea/actions/prepare-flutter
- name: Reuse verified Velopack native archive
run: |
$version = flutter --version --machine | ConvertFrom-Json
if ($version.frameworkVersion -ne '3.47.5') { throw 'Flutter 3.47.5 required.' }
- name: Resolve locked Flutter dependencies
run: flutter pub get --enforce-lockfile
python tool/windows/native_cache.py
if ($LASTEXITCODE -ne 0) { throw 'Windows native archive cache preparation failed.' }
- name: Build production Windows app
run: |
Remove-Item Env:CUTDEX_WINDOWS_PATH, Env:CUTDEX_WINDOWS_PACKAGE_PATH -ErrorAction SilentlyContinue
flutter build windows --release --flavor production
python tool/build.py windows
if ($LASTEXITCODE -ne 0) { throw 'Windows build failed.' }
- name: Verify native SDK matches pinned packaging tools
run: |
python tool/windows/windows_updates.py verify-sdk
if ($LASTEXITCODE -ne 0) { throw 'Windows native SDK version validation failed.' }
- name: Save Windows app for independent packaging retries
if: ${{ needs.quality.outputs.package-app == 'true' }}
uses: ./.gitea/actions/upload-artifact
with:
name: cutdex-windows-app
@@ -137,7 +139,8 @@ jobs:
windows:
name: Audit and package Windows x64
needs: windows-build
needs: [quality, windows-build]
if: ${{ needs.quality.outputs.package-app == 'true' }}
runs-on: cutdex-windows-x64
steps:
- name: Check out source
@@ -152,18 +155,8 @@ jobs:
with:
name: cutdex-windows-app
path: build/windows/x64/production/runner/Release/
- name: Configure user .NET installation
run: |
$directory = Join-Path $env:LOCALAPPDATA 'Cutdex/ci-tools/dotnet'
[IO.Directory]::CreateDirectory($directory) | Out-Null
"DOTNET_INSTALL_DIR=$directory" | Out-File -LiteralPath $env:GITHUB_ENV -Encoding utf8 -Append
"DOTNET_ROOT=$directory" | Out-File -LiteralPath $env:GITHUB_ENV -Encoding utf8 -Append
- name: Set up .NET SDK
uses: https://github.com/actions/setup-dotnet@26b0ec14cb23fa6904739307f278c14f94c95bf1
with:
dotnet-version: '10.0.x'
- name: Prepare pinned packaging tools
run: ./tool/gitea/prepare-package-tools.ps1
- name: Prepare Windows packaging environment
uses: ./.gitea/actions/prepare-windows-packaging
- name: Audit and package Windows release
run: |
& $env:PACKAGE_PYTHON tool/gitea/package-app.py --platform windows --vpk $env:VPK_PATH
@@ -178,11 +171,9 @@ jobs:
build:
name: Assemble and validate CI artifacts
needs: [android, windows]
needs: [quality, android, windows]
if: ${{ needs.quality.outputs.package-app == 'true' }}
runs-on: cutdex-windows-x64
env:
GITEA_ACTOR: lingjhf
CUTDEX_GITEA_TOKEN: ${{ secrets.CUTDEX_GITEA_TOKEN }}
steps:
- name: Check out source
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
@@ -224,11 +215,34 @@ jobs:
checks:
name: Gitea CI passed
if: always()
needs: build
needs: [quality, android, windows-build, windows, build]
runs-on: cutdex-windows-x64
steps:
- name: Verify CI result
env:
RESULT: ${{ needs.build.result }}
QUALITY_RESULT: ${{ needs.quality.result }}
BUILD_APP: ${{ needs.quality.outputs.build-app }}
PACKAGE_APP: ${{ needs.quality.outputs.package-app }}
# The local runner omits results for jobs excluded by their condition.
# Required jobs still fail below if this becomes 'skipped'.
ANDROID_RESULT: ${{ needs.android.result || 'skipped' }}
WINDOWS_BUILD_RESULT: ${{ needs.windows-build.result || 'skipped' }}
WINDOWS_PACKAGE_RESULT: ${{ needs.windows.result || 'skipped' }}
ASSEMBLY_RESULT: ${{ needs.build.result || 'skipped' }}
run: |
if ($env:RESULT -ne 'success') { throw "App build: $env:RESULT" }
if ($env:QUALITY_RESULT -ne 'success') { throw "Code checks: $env:QUALITY_RESULT" }
if ($env:BUILD_APP -notin @('true', 'false') -or $env:PACKAGE_APP -notin @('true', 'false')) {
throw 'Missing or invalid CI scope outputs.'
}
if ($env:PACKAGE_APP -eq 'true' -and $env:BUILD_APP -ne 'true') { throw 'Packaging requires compilation.' }
$compileResult = if ($env:BUILD_APP -eq 'true') { 'success' } else { 'skipped' }
$packageResult = if ($env:PACKAGE_APP -eq 'true') { 'success' } else { 'skipped' }
$jobs = @(
@{ Name = 'Android compilation'; Result = $env:ANDROID_RESULT; Expected = $compileResult },
@{ Name = 'Windows compilation'; Result = $env:WINDOWS_BUILD_RESULT; Expected = $compileResult },
@{ Name = 'Windows packaging'; Result = $env:WINDOWS_PACKAGE_RESULT; Expected = $packageResult },
@{ Name = 'Artifact assembly'; Result = $env:ASSEMBLY_RESULT; Expected = $packageResult }
)
foreach ($job in $jobs) {
if ($job.Result -ne $job.Expected) { throw "$($job.Name): $($job.Result), expected $($job.Expected)." }
}
+4
View File
@@ -101,3 +101,7 @@ pubspec_overrides.yaml
*.aab
.vscode/*
!.vscode/launch.json
!.vscode/settings.json
# FVM Version Cache
.fvm/
+27 -1
View File
@@ -5,7 +5,33 @@
"name": "Cutdex",
"request": "launch",
"type": "dart",
"program": "lib/main.dart"
"program": "lib/main.dart",
"customTool": "${workspaceFolder}/tool/flutter-local.sh",
"windows": {
"customTool": "${workspaceFolder}/tool/flutter-local.bat"
}
},
{
"name": "Cutdex (Profile)",
"request": "launch",
"type": "dart",
"program": "lib/main.dart",
"flutterMode": "profile",
"customTool": "${workspaceFolder}/tool/flutter-local.sh",
"windows": {
"customTool": "${workspaceFolder}/tool/flutter-local.bat"
}
},
{
"name": "Cutdex (Release)",
"request": "launch",
"type": "dart",
"program": "lib/main.dart",
"flutterMode": "release",
"customTool": "${workspaceFolder}/tool/flutter-local.sh",
"windows": {
"customTool": "${workspaceFolder}/tool/flutter-local.bat"
}
}
]
}
+3
View File
@@ -0,0 +1,3 @@
{
"dart.flutterSdkPath": ".fvm/versions/3.47.5"
}
+8
View File
@@ -53,6 +53,14 @@ Cutdex 是一款视频剪辑应用。你可以在时间线上编辑视频、音
“设置 → 通用”可以切换语言、明暗主题和存储位置。桌面版还提供软件更新入口,是否可用取决于安装包的更新配置。
配色方案提供石墨灰与蓝色、柔灰与紫色、暖灰与青绿三种选择。每种方案都有浅色和深色版本,也可跟随系统外观;配色方案与明暗选择分别保存。
桌面剪辑工作区采用独立的控件与布局尺寸:素材、预览和属性分别成面板,下方时间线横跨编辑区,播放栏固定在预览底部。时间线标签、编辑命令和标尺分层排列,窄面板中的次要命令收进更多菜单。顶部可展开或收起聊天,草稿会保留;聊天区域宽度和时间线高度支持拖动并保存。手机和平板继续使用各自的页面与工具面板。
桌面窗口顶部以标签页切换已打开的项目,“+”菜单可新建、打开或选择最近项目。左侧只展示当前项目的聊天,会话历史与新建聊天位于聊天区头部;素材库属于当前项目,放在编辑区内,可独立收起并保留浏览状态。关闭标签不会删除项目,切换项目会保留各自的聊天草稿。
桌面素材区提供紧凑卡片和列表视图,可按名称搜索,并按导入顺序或名称升降序排列。视频、图片和音频共用选中状态,时长来自实际素材信息;缺失素材保留名称并标明原因。搜索、排序和视图选择按项目保留。
遇到编辑、保存、预览或后台任务错误时,可在“设置 → 通用 → 诊断”中导出诊断包,协助定位问题。分享前请检查内容,移除不希望公开的信息。
需要连接外部 AI 工具时,可查看 [MCP 连接指南](docs/mcp-connection.md)。
+13 -1
View File
@@ -33,6 +33,8 @@ android {
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId = "com.example.cutdex"
manifestPlaceholders["cutdexPreviewReverseCacheMiB"] = "0"
manifestPlaceholders["cutdexNativeSurfacePreview"] = "false"
// You can update the following values to match your application needs.
// For more information, see: https://flutter.dev/to/review-gradle-config.
minSdk = 31
@@ -50,7 +52,17 @@ android {
create("development") {
dimension = "environment"
applicationIdSuffix = ".dev"
resValue("string", "app_name", "Cutdex Dev")
// Device validation can coexist with an app signed on another machine.
val validationId = providers.gradleProperty("cutdexValidationApplicationId")
.orElse(providers.environmentVariable("CUTDEX_VALIDATION_APPLICATION_ID")).orNull
if (validationId != null) applicationId = validationId
resValue("string", "app_name", if (validationId == null) "Cutdex Dev" else "Cutdex Decoder Test")
manifestPlaceholders["cutdexPreviewReverseCacheMiB"] = providers
.gradleProperty("cutdexPreviewReverseCacheMiB")
.orElse(providers.environmentVariable("CUTDEX_PREVIEW_REVERSE_CACHE_MIB")).getOrElse("0")
manifestPlaceholders["cutdexNativeSurfacePreview"] = providers
.gradleProperty("cutdexNativeSurfacePreview")
.orElse(providers.environmentVariable("CUTDEX_NATIVE_SURFACE_PREVIEW")).getOrElse("false")
}
create("production") {
dimension = "environment"
+4
View File
@@ -3,6 +3,10 @@
android:label="@string/app_name"
android:name="${applicationName}"
android:icon="@mipmap/cutdex_launcher">
<meta-data android:name="dev.cutdex.previewReverseCacheMiB"
android:value="${cutdexPreviewReverseCacheMiB}" />
<meta-data android:name="dev.cutdex.nativeSurfacePreview"
android:value="${cutdexNativeSurfacePreview}" />
<activity
android:name=".MainActivity"
android:exported="true"
+4 -1
View File
@@ -26,7 +26,10 @@ plugins {
include(":app")
// Native source development is opt-in; default resolution uses Gitea Maven packages.
providers.gradleProperty("cutdex.android.path").orNull?.let { nativePath ->
val nativeAndroidPath = providers.gradleProperty("cutdex.android.path")
.orElse(providers.environmentVariable("CUTDEX_ANDROID_PATH"))
.orNull
nativeAndroidPath?.takeIf { it.isNotBlank() }?.let { nativePath ->
includeBuild(nativePath) {
dependencySubstitution {
substitute(module("dev.cutdex:cutdex-android")).using(project(":cutdex-android"))
+52 -8
View File
@@ -4,20 +4,55 @@
## 准备环境
使用满足 `pubspec.yaml` 约束的 Flutter 与 Dart 工具链,并安装目标平台的开发工具。仓库脚本使用 Python 3.11+。
安装 FVM,在仓库根目录运行 `fvm use`,使用 `.fvmrc` 固定的 Flutter 版本,
并准备目标平台的开发工具。CI 按同一文件校验 SDK。`.fvmrc` 提交到仓库,生成的
`.fvm/` SDK 链接与缓存不提交。仓库脚本使用 Python 3.11+。
应用依赖与版本以 `pubspec.yaml`、`pubspec.lock` 为准,通过 `flutter pub get` 获取。依赖的访问权限、配置和工具链要求按各依赖自身的文档准备;依赖未就绪时无法完成应用构建。
应用依赖与版本以 `pubspec.yaml`、`pubspec.lock` 为准,通过 `fvm dart tool/flutter_local.dart pub get` 获取。依赖的访问权限、配置和工具链要求按各依赖自身的文档准备;依赖未就绪时无法完成应用构建。
本地联调其他包时,可参考 `pubspec_overrides.yaml.example` 创建覆盖配置。覆盖文件只用于本机开发,不提交。
## 运行应用
本地路径与原生包认证统一放在应用根目录的 `.env.local`。复制
[配置示例](../.env.example),按需取消注释并填写本机路径;文件已忽略,不提交、
不作为应用资源打包。没有配置时,SDK 使用固定版本的已发布原生包。
Windows 可用 `CUTDEX_WINDOWS_PATH` 联调本地源码(需要 Rust 和 `FFMPEG_DIR`),
或用 `CUTDEX_WINDOWS_PACKAGE_PATH` 指定已解压的离线包,两者只选其一。
macOS/iOS 可用 `CUTDEX_APPLE_PATH` 指定本地源码。
Android 可用 `CUTDEX_ANDROID_PATH` 指向 `cutdex_android` 工程根目录,Gradle 会用
本地源码替换 Maven 原生依赖;未配置或留空时使用已发布包。
已有 Gradle 属性 `cutdex.android.path` 优先于该环境变量,显式空属性会关闭本地替换。
`CUTDEX_PROCESSING_ROOT` 指定处理 worker 目录;Android 私有 Maven 认证可填写
`GITEA_ACTOR` 和 `CUTDEX_GITEA_TOKEN`。这里的 `GITEA_ACTOR` 是令牌所属的认证
账号,CI 中也按令牌账号设置,与触发工作流的用户无关。
VS Code 的 Debug、Profile、Release 启动项与下述命令共用
`tool/flutter_local.dart` 加载规则。VS Code 的项目 SDK 设置由 `fvm use` 自动同步,
启动入口通过 `.fvm/flutter_sdk` 使用同一项目版本,不通过 `FLUTTER` 环境变量或
全局 PATH 选择 Flutter。
未准备项目 SDK 时先运行 `fvm use`。现有进程环境变量优先于文件,包括显式空值。
文件支持 `KEY=value`、单双引号和注释;值按字面读取,不执行命令,不展开变量或
反斜杠转义。格式错误会在构建前报错,不输出配置值。
Flutter 启动入口、Python 构建/检查入口和 macOS 打包共用同一个 Dart 加载器,
配置注入整个工具流水线的子进程环境,不修改系统环境或 SDK 文件。
检测到 `CI`、`GITEA_ACTIONS` 或 `GITHUB_ACTIONS` 为 true/1/yes 时,不读取本地文件。
现有 CI 继续使用工作流配置与 Secrets。直接执行 `fvm flutter` 不加载此文件。
更换 Windows 原生路径后,若 CMake 仍缓存旧路径,先退出应用并运行 `fvm dart tool/flutter_local.dart clean`。
Flutter 自带的 `--dart-define-from-file` 也支持 `.env` 格式,但生成的是 Dart 编译期
配置,由 `String.fromEnvironment` 读取,不会设置 CMake、Gradle 或 Swift 读取的
进程环境。原生依赖路径与认证使用上述启动入口;应用自身的编译期选项可继续使用
`--dart-define` 或 `--dart-define-from-file`,不要把原生包认证文件作为 Dart define 输入。
在 Cutdex 根目录运行:
```sh
flutter pub get
dart run build_runner build
flutter run -d macos --flavor development
fvm dart tool/flutter_local.dart pub get
fvm dart run build_runner build
fvm dart tool/flutter_local.dart run -d macos --flavor development
```
Android、macOS、Windows 配置了 development 与 production flavor,默认是 development。按目标平台替换设备参数。iOS 使用 `Runner` scheme。构建或集成测试前,退出占用同一构建目录的应用。
@@ -25,7 +60,7 @@ Android、macOS、Windows 配置了 development 与 production flavor,默认
Android 支持 ARM64 和 x86_64。按架构拆分 APK 时显式指定目标:
```sh
flutter build apk --flavor development --split-per-abi --target-platform android-arm64,android-x64
python3 tool/build.py android --flavor development --split-per-abi
```
字幕、翻译和抠像的功能验证需要相应资源。按应用提示准备资源,并使用合成或允许再分发的素材;不要把个人媒体、模型服务凭据或项目文件提交到仓库。
@@ -48,9 +83,9 @@ flutter build apk --flavor development --split-per-abi --target-platform android
## 文案与代码生成
修改需要生成代码的模型后,在所属包目录运行 `dart run build_runner build`,将生成文件与源码一起提交。
修改需要生成代码的模型后,在所属包目录运行 `fvm dart run build_runner build`,将生成文件与源码一起提交。
修改文案时更新 `lib/l10n/` 中的 ARB,再运行 `flutter gen-l10n`。简体中文同时维护 `app_zh.arb` 和 `app_zh_Hans.arb`;增加界面语言时更新语言选择与 Apple bundle 声明。
修改文案时更新 `lib/l10n/` 中的 ARB,再运行 `fvm dart tool/flutter_local.dart gen-l10n`。简体中文同时维护 `app_zh.arb` 和 `app_zh_Hans.arb`;增加界面语言时更新语言选择与 Apple bundle 声明。
执行 [测试指南](testing.md) 中适用的检查。界面改动还需检查桌面、平板和手机布局,以及明暗主题和不同语言下的表现。
@@ -64,6 +99,15 @@ flutter build apk --flavor development --split-per-abi --target-platform android
构建、打包和更新验证入口见 [仓库工具](../tool/README.md)。完成集成测试后,使用 `lib/main.dart` 重建正式应用,避免分发测试入口。
`python3 tool/build.py android|windows|macos` 与 CI 共用 production/release 预设,
额外 Flutter 参数放在 `--` 后。仅构建 macOS 应用时使用此入口;完整 ZIP/DMG
打包、processing 嵌入、签名和公证使用 `build_macos_release.py`。
环境文件合并时进程变量优先,包括空值。原生构建仍遵循所属 SDK 的覆盖规则:
Android Gradle 属性先于环境变量;Windows CMake 已缓存的非空路径先于环境变量,
修改后需 clean;processing 的非空 Dart define 先于进程环境,再使用随包默认路径。
`CUTDEX_GITEA_TOKEN` 用于依赖访问,Release 的 `GITEA_TOKEN` 用于发布和 CI 产物读取。
Android release 当前使用调试签名,正式分发前需配置发布签名;production flavor 本身不提供发布证书。
macOS 默认 ad-hoc 签名。开发证书配置放在 `macos/Runner/Configs/Signing.local.xcconfig`;iOS 真机的 Team 设置放在 `ios/Flutter/Signing.local.xcconfig`。这些文件已忽略,凭据与私钥保留在本地或 CI 私密配置中。
+1 -1
View File
@@ -7,7 +7,7 @@
MCP 默认关闭,在设置中启用并获取端口和访问令牌。外部客户端设置 `CUTDEX_MCP_PORT`、`CUTDEX_MCP_TOKEN`,以本仓库为工作目录运行:
```sh
dart run tool/mcp_stdio.dart
fvm dart run tool/mcp_stdio.dart
```
连接通过本机端口访问正在运行的 Cutdex。工具范围由当前工作区和可用功能决定,参数以客户端发现结果为准。
+8 -6
View File
@@ -13,9 +13,7 @@ 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
fvm dart tool/flutter_local.dart pub get
# Python 3.11+
python3 tool/check.py
```
@@ -27,15 +25,19 @@ python3 tool/check.py
| [integration_test](../integration_test/README.md) | 对应平台上的真实预览、媒体编辑与处理任务 |
| [tool](../tool/README.md) | 脚本检查、发布包验证和平台诊断 |
本地完整检查与 CI 共用相同的套件,可用 `python3 tool/check.py --suite analyze`、
`--suite flutter` 或 `--suite tools` 单独执行或重试。静态分析启用 `--fatal-infos`;
Flutter 套件同时运行应用与内部包测试。所有入口使用项目 SDK 和相同环境加载规则。
App 测试验证宿主行为,底层算法、协议及插件生命周期在所属包测试。普通测试通过不代表真实播放或模型质量已经验证。
## 生成文件
```sh
dart run build_runner build
fvm dart run build_runner build
# UI 模型修改后,在 packages/cutdex_ui 中运行相同生成命令
flutter gen-l10n
flutter test test/generated_code_test.dart test/localization_resources_test.dart
fvm dart tool/flutter_local.dart gen-l10n
fvm dart tool/flutter_local.dart test test/generated_code_test.dart test/localization_resources_test.dart
```
生成文件应与源码一同提交。生成校验会重新生成应用与 UI 包并比较前后内容,同时检查应用生成文件的跟踪状态;不要暂存无关文件来掩盖失败。
+5 -1
View File
@@ -59,7 +59,7 @@ development 包身份为 `Cutdex.Dev`,默认不配置更新源。
开发更新源通过编译期 Dart defines 配置,修改后需重新构建。例如本地测试:
```powershell
flutter build windows --release --flavor development `
python tool/build.py windows --flavor development -- `
--dart-define=CUTDEX_WINDOWS_UPDATE_SOURCE=web `
--dart-define=CUTDEX_WINDOWS_UPDATE_URL=http://127.0.0.1:8765 `
--dart-define=CUTDEX_UPDATE_TEST_HTTP=true
@@ -68,6 +68,10 @@ flutter build windows --release --flavor development `
Gitea 开发仓库使用 `CUTDEX_WINDOWS_UPDATE_SOURCE=gitea` 和仓库 URL。
仅设置进程环境变量不会配置 Dart 更新源。正式版忽略开发 defines。
原生 SDK 离线缓存仍通过 `DESKUP_VELOPACK_ARCHIVE` 环境变量指定。
CI 会按已解析 deskup 的版本和 SHA256,将原生 ZIP 缓存到
`%LOCALAPPDATA%/Cutdex/ci-tools/native/`,后续构建校验后直接复用。
本地可运行 `python tool/windows/native_cache.py` 预热同一缓存;命令会输出
可供 `DESKUP_VELOPACK_ARCHIVE` 使用的文件路径。
```powershell
python -m unittest discover -s tool/gitea -p 'test_*.py'
+131 -19
View File
@@ -2,10 +2,84 @@
`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;
`fvm dart tool/flutter_local.dart 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`.
## Android navigation and playhead measurements
`android_decoder_material_performance_test.dart` extends the production workspace
benchmark to other source rates and variable timestamps. Supply
`CUTDEX_TEST_SOURCE_PTS` as an independent, sorted list of original frame PTS
(one integer source tick per line), with `CUTDEX_TEST_SOURCE_TIMESCALE` set to
that clock's denominator, such as 90000. The default timescale is 1000000 for
existing integer-microsecond fixtures; preserve original source ticks for frame
boundaries that cannot be represented in microseconds. `CUTDEX_TEST_FRAME_STEP_US`
is the nominal frame period rounded to microseconds. Its eight `matchedSeeks` use
the standalone benchmark's exact request sequence. Full-source ruler drags and
20-frame local drags use the production timeline and are reported separately;
their inputs differ from the standalone source replay.
`CUTDEX_TEST_CALIBRATE=true` explicitly runs native/software calibration before
opening the workspace and verifies both sets against the external PTS list.
It asserts the admitted backend throughout later navigation and gestures.
The application opens no calibration workload automatically.
If the device's installed application has a different signing certificate,
build the development flavor with
`CUTDEX_VALIDATION_APPLICATION_ID=com.example.cutdex.decoder_validation`.
This creates `com.example.cutdex.decoder_validation.dev`, labeled
`Cutdex Decoder Test`, while preserving the installed application and its data.
For a cache baseline, set `CUTDEX_PREVIEW_REVERSE_CACHE_MIB=24`;
set it to `0` for normal device policy. These properties affect development only.
Use matching private file paths and retain the app between runs.
`android_navigation_performance_test.dart` mounts the production `EditorWorkspace`
with real `Projects`, preview and native playback providers. Its project and
application database are isolated. Supply a complete original video through
`CUTDEX_TEST_SOURCE` and an app-writable JSON path through `CUTDEX_TEST_REPORT`.
The test keeps production audible-skimming policy and uses touch input on real
timeline tabs and the timeline ruler. It measures cold/cached selection, rapid
selection replacement, exact seeks, full-source fit-to-viewport and local
20-frame drags, and both immediate release and a one-second stationary hold.
The source-frame containment checks currently require an untrimmed CFR
2997/100 fps source.
Use `--dart-define=CUTDEX_TEST_DECODER=ffmpeg` to assert the actual decoder
from initial load through seeks, both drag directions and final release.
Reports retain per-layer backend and selection-reason diagnostics.
```powershell
fvm dart tool/flutter_local.dart drive --profile --flavor development -d DEVICE_ID --keep-app-running `
--driver=test_driver/integration_test.dart `
--target=integration_test/android_navigation_performance_test.dart `
--dart-define=CUTDEX_TEST_SOURCE=/data/user/0/com.example.cutdex.dev/files/cutdex-validation/source.mp4 `
--dart-define=CUTDEX_TEST_REPORT=/data/user/0/com.example.cutdex.dev/files/cutdex-validation/results.json
```
The pinned SDK uses the published Android 0.1.3 Maven artifacts. Use explicit SDK
and Android source overrides only when comparing unpublished changes. Calibration
requires a `--debug` build; profile/production hosts do not register its channel.
UI timing ends at the
target workspace's post-frame callback. Native diagnostics record queued output
frames/content timestamps and backend seek/reuse counters; those do not measure
physical display refresh. The planned drag input rate is 60 Hz; retain actual
input timestamps and report achieved input cadence. The test uses `fullyLive`
frame scheduling and does not pump a Flutter frame for every pointer input.
Native polling has at most
one outstanding request, so decoder latency cannot accumulate diagnostic reads.
Source PTS is distinct from the requested timeline sample. A stationary release
must preserve source PTS, output-frame count and seek count; the final source
frame must cover the target tick. These counters measure queued native output,
not physical scanout. A cached timeline's nonzero frame counter alone does not
prove that its new Surface has displayed the retained frame.
Rebuild/install the normal `lib/main.dart` entry point after testing. Do not clear
app data or uninstall merely to obtain a cold sample.
Always pass `--keep-app-running`: Flutter drive otherwise uninstalls the Android
application during cleanup, which also deletes its application data.
On devices that deny access to ADB-created external app directories, copy the
fixture into the installed debuggable development app's internal files using
`run-as`, and export its report with `adb exec-out run-as PACKAGE cat PATH`.
## Desktop plugin registration
`native_desktop_plugins_test.dart` checks the real application's registration of
@@ -13,7 +87,7 @@ window chrome, dynamically configured file destinations, and the macOS fullscree
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
fvm dart tool/flutter_local.dart test integration_test/native_desktop_plugins_test.dart -d macos --flavor development
```
Use `-d windows` on Windows. Rebuild the normal application entry point afterwards.
@@ -29,7 +103,7 @@ 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 \
fvm dart tool/flutter_local.dart test integration_test/processing_e2e_test.dart -d macos --flavor development \
--dart-define-from-file=/absolute/path/to/processing-e2e.json
```
@@ -53,7 +127,7 @@ fault-injection checks with real media and native playback, not evidence that th
native backend itself produced these failures.
```sh
flutter drive --profile -d macos --flavor production \
fvm dart tool/flutter_local.dart 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 \
@@ -76,7 +150,7 @@ 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 \
CUTDEX_PREVIEW_CADENCE_DIAGNOSTICS=1 fvm dart tool/flutter_local.dart 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 \
@@ -99,7 +173,7 @@ source clock, source duration and undo. No playback backend is mocked. ISO impor
when the native backend can probe an unprotected video stream.
```powershell
flutter test integration_test/windows_real_media_test.dart -d windows `
fvm dart tool/flutter_local.dart 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'
```
@@ -112,10 +186,10 @@ 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
`fvm dart tool/flutter_local.dart 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
defines: `fvm dart tool/flutter_local.dart 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
@@ -162,10 +236,10 @@ not play or export every frame of the original movies.
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`.
`test_driver/integration_test.dart` entry point using `fvm dart tool/flutter_local.dart drive --profile`.
```powershell
flutter drive --profile --flavor production -d windows `
fvm dart tool/flutter_local.dart 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' `
@@ -187,7 +261,7 @@ 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 `
fvm dart tool/flutter_local.dart 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
```
@@ -225,19 +299,19 @@ 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
fvm dart tool/flutter_local.dart 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 \
fvm dart tool/flutter_local.dart 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.
reports. With `fvm dart tool/flutter_local.dart 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
@@ -291,7 +365,7 @@ 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 \
fvm dart tool/flutter_local.dart 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
@@ -335,7 +409,7 @@ Use an unlocked developer-enabled iPhone and a valid signing team. Select the iO
other platforms. First install the test host using the shared empty-timeline test:
```sh
flutter test integration_test/preview_startup_test.dart -d <iphone-udid> \
fvm dart tool/flutter_local.dart test integration_test/preview_startup_test.dart -d <iphone-udid> \
--flavor Runner --no-uninstall \
--plain-name 'opening a timeline initializes native preview through App providers'
```
@@ -349,7 +423,7 @@ xcrun devicectl device copy to --device <iphone-udid> \
--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 <iphone-udid> \
fvm dart tool/flutter_local.dart test integration_test/ios_device_test.dart -d <iphone-udid> \
--flavor Runner --no-uninstall --reporter expanded \
--dart-define=CUTDEX_TEST_SOURCE_DOCUMENT=cutdex-validation-source.mp4 \
--dart-define=CUTDEX_TEST_OUTPUT=ios-keyframes
@@ -379,7 +453,7 @@ 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 \
fvm dart tool/flutter_local.dart 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
@@ -396,7 +470,7 @@ 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 \
fvm dart tool/flutter_local.dart drive --debug --keep-app-running \
--driver=test_driver/integration_test.dart \
--target=integration_test/android_document_import_test.dart \
-d DEVICE_SERIAL --flavor development \
@@ -416,3 +490,41 @@ 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.
## Android native Surface preview comparison
The development build can enable the experimental native source with the Gradle
property `cutdexNativeSurfacePreview=true` or environment variable
`CUTDEX_NATIVE_SURFACE_PREVIEW=true`. Production and default development builds
leave it disabled. `android_decoder_material_performance_test.dart` uses the real
EditorWorkspace with the whole original clip fitted into the timeline viewport.
Set `CUTDEX_TEST_DECODER=media3-surface` to fail if the source falls back; use
`ffmpeg` for the paired baseline. `CUTDEX_TEST_PLAYBACK=true` additionally records
three seconds of unique frame changes, play/pause acknowledgments and a frozen
paused frame. The existing seek/drag assertions independently check every observed
frame against original rational packet PTS and require zero extra release seek
or presentation for an already precise held picture.
Use a separate validation application ID to preserve the installed development
application and its projects. Supply media and PTS files inside that validation
app's sandbox; no personal fixture or benchmark report is committed here.
For example, an explicitly admitted 60 fps / 90000 Hz source can be measured with:
```powershell
$env:CUTDEX_VALIDATION_APPLICATION_ID = 'com.example.cutdex.decoder_validation'
$env:CUTDEX_NATIVE_SURFACE_PREVIEW = 'true'
fvm dart tool/flutter_local.dart drive --profile --flavor development -d DEVICE_ID --keep-app-running `
--driver=test_driver/integration_test.dart `
--target=integration_test/android_decoder_material_performance_test.dart `
--dart-define=CUTDEX_TEST_SOURCE=/data/user/0/com.example.cutdex.decoder_validation.dev/files/source.mp4 `
--dart-define=CUTDEX_TEST_SOURCE_PTS=/data/user/0/com.example.cutdex.decoder_validation.dev/files/source-pts.txt `
--dart-define=CUTDEX_TEST_SOURCE_TIMESCALE=90000 --dart-define=CUTDEX_TEST_FRAME_STEP_US=16667 `
--dart-define=CUTDEX_TEST_DECODER=media3-surface --dart-define=CUTDEX_TEST_PLAYBACK=true `
--dart-define=CUTDEX_TEST_REPORT=/data/user/0/com.example.cutdex.decoder_validation.dev/files/native-results.json
```
Repeat with `CUTDEX_NATIVE_SURFACE_PREVIEW=false`, `CUTDEX_TEST_DECODER=ffmpeg`
and another report path for the software baseline. Restore the default environment
and normal application entry point after testing. Record first-source indexing
separately from warm seek timings. Only compare inputs with matching source clocks,
targets, drag trajectories, audio/UI workloads and achieved input cadence.
@@ -0,0 +1,730 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:cutdex/app/editor_theme.dart';
import 'package:cutdex/features/editor/editor_page.dart';
import 'package:cutdex/features/preview/preview_panel.dart';
import 'package:cutdex/integrations/platform/device_experience.dart';
import 'package:cutdex/l10n/app_localizations.dart';
import 'package:cutdex/persistence/app_database.dart';
import 'package:cutdex/workspace/project_state.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/project.dart';
import 'package:cutdex_sdk/runtime.dart';
import 'package:cutdex_sdk/timeline/layout.dart';
import 'package:cutdex_sdk/timeline/model.dart';
import 'package:cutdex_sdk/timeline_ui.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 '../test/support/preview_fixture.dart';
void main() {
final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();
binding.framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.fullyLive;
const source = String.fromEnvironment('CUTDEX_TEST_SOURCE');
const output = String.fromEnvironment('CUTDEX_TEST_REPORT');
const ptsFile = String.fromEnvironment('CUTDEX_TEST_SOURCE_PTS');
const sourceStepUs = int.fromEnvironment('CUTDEX_TEST_FRAME_STEP_US');
const sourceTimescale = int.fromEnvironment(
'CUTDEX_TEST_SOURCE_TIMESCALE',
defaultValue: 1000000,
);
testWidgets(
'Android material decoder production workspace performance',
(tester) async {
expect(Platform.isAndroid, isTrue);
final file = File(source);
final before = await file.stat();
expect(before.size, greaterThan(0));
expect(sourceStepUs, greaterThan(0));
expect(sourceTimescale, greaterThan(0));
final report = File(output);
await report.parent.create(recursive: true);
final result = <String, Object?>{
'status': 'running',
'source': source,
'sourceBytes': before.size,
'buildMode': const bool.fromEnvironment('dart.vm.product')
? 'release'
: const bool.fromEnvironment('dart.vm.profile')
? 'profile'
: 'debug',
'scope': 'Production EditorWorkspace, Projects, preview and real touch ruler input; isolated project/database',
'measurement': 'Native queued-frame counters and content timestamp, not physical display scanout',
'switches': <Map<String, Object?>>[],
'seeks': <Map<String, Object?>>[],
'drags': <Map<String, Object?>>[],
'heldRelease': <Map<String, Object?>>[],
};
void save() => report.writeAsStringSync(
const JsonEncoder.withIndent(' ').convert(result),
);
save();
final runtime = CutdexRuntime();
final info = await runtime.probe(
MediaReference(id: 'media', uri: file.uri),
);
result['durationSeconds'] = info.duration.seconds;
final sourcePtsTicks = (await File(
ptsFile,
).readAsLines()).map(int.parse).toList(growable: false);
double expectedSourceUs(int numerator, int denominator) {
final target = BigInt.from(numerator) * BigInt.from(sourceTimescale);
final divisor = BigInt.from(denominator);
var low = 0;
var high = sourcePtsTicks.length;
while (low < high) {
final middle = (low + high) ~/ 2;
if (BigInt.from(sourcePtsTicks[middle]) * divisor <= target) {
low = middle + 1;
} else {
high = middle;
}
}
expectSync(low, greaterThan(0));
return sourcePtsTicks[low - 1] * 1000000 / sourceTimescale;
}
result['independentSourcePtsCount'] = sourcePtsTicks.length;
result['sourcePtsTimescale'] = sourceTimescale;
if (const bool.fromEnvironment('CUTDEX_TEST_CALIBRATE')) {
const diagnostics = MethodChannel('cutdex_decoder_diagnostics');
const stepUs = sourceStepUs;
final calibrated = (await diagnostics.invokeMapMethod<String, dynamic>(
'calibrate',
{
'source': file.uri.toString(),
'targetsMicros': [
60000000,
2000000000,
2000000000 + stepUs,
2000000000 + stepUs * 2,
2000000000 + stepUs,
2000000000 + stepUs * 3,
120000567,
60000000,
],
},
))!;
result['calibration'] = calibrated;
save();
for (final sample in calibrated['samples'] as List) {
final requested = sample['requestedTime'] as Map;
final actual = sample['actualTime'] as Map;
final pts =
int.parse('${actual['numerator']}') /
(actual['denominator'] as num);
expect(
(pts * 1000000 -
expectedSourceUs(
int.parse('${requested['numerator']}'),
requested['denominator'] as int,
))
.abs(),
lessThanOrEqualTo(2),
);
}
}
final fixture = await createPreviewFixture(
file.uri,
hasAudio: info.audioTrackCount > 0,
clipDuration: RationalTime(
info.duration.numerator,
info.duration.denominator,
),
renderSize: {'width': 1280, 'height': 720},
);
final document = await fixture.workspace.project!.loadTimeline('project');
for (final id in ['cold', 'third']) {
await fixture.workspace.project!.saveTimeline(
TimelineDocument(
id: id,
name: id,
sequences: document.sequences,
defaultSequenceId: document.defaultSequenceId,
payloads: document.payloads,
settings: document.settings,
),
);
}
await fixture.workspace.close();
final database = AppDatabase(NativeDatabase.memory());
final container = ProviderContainer(
overrides: [appDatabaseProvider.overrideWithValue(database)],
);
final projects = container.read(projectsProvider.notifier);
Future<void> until(
bool Function() ready,
String label, {
int seconds = 60,
}) async {
final clock = Stopwatch()..start();
while (!ready()) {
if (clock.elapsed.inSeconds >= seconds) throw TimeoutException(label);
await tester.pump();
await Future<void>.delayed(const Duration(milliseconds: 16));
}
await tester.pump();
}
Future<void> advance(int milliseconds) async {
final clock = Stopwatch()..start();
while (clock.elapsedMilliseconds < milliseconds) {
await tester.pump();
await Future<void>.delayed(const Duration(milliseconds: 16));
}
}
PreviewController? activePreview() {
final state = container.read(projectsProvider).value;
if (state?.timeline == null || state!.openingTimelineId != null) {
return null;
}
return container
.read(
editorPreviewProvider(
state.activeProject!.id,
state.timeline!.id,
),
)
.value;
}
const nativeChannel = MethodChannel('cutdex_runtime');
const configuredDecoder = String.fromEnvironment('CUTDEX_TEST_DECODER');
final calibration = result['calibration'] as Map?;
final expectedDecoder = configuredDecoder.isNotEmpty
? configuredDecoder
: calibration == null
? ''
: calibration['backend'] == 'NATIVE'
? 'mediaCodec'
: 'ffmpeg';
Future<Map<String, dynamic>> diagnostic(PreviewController preview) async {
final value = (await nativeChannel.invokeMapMethod<String, dynamic>(
'previewDiagnostics',
{'contractVersion': 1, 'sessionId': preview.session!.id},
))!;
if (expectedDecoder.isNotEmpty) {
final backends = value['decoderBackends'] as Map?;
// Diagnostics also run from a timer while WidgetTester.pump is active.
expectSync(value['executionBackend'], 'direct');
expectSync(backends, isNotEmpty);
expectSync(backends!.values, everyElement(expectedDecoder));
expectSync(value['decoderSelectionReasons'], isNotEmpty);
}
return value;
}
int frames(Map<String, dynamic> value) =>
int.tryParse('${value['presentedVideoFrameCount']}') ?? 0;
double sourcePts(Map<String, dynamic> value) {
final time = value['presentedSourceFrameTime'] as Map?;
expect(time, isNotNull, reason: 'Actual source PTS must be available');
return int.parse('${time!['numerator']}') /
(time['denominator'] as num);
}
void expectExactSource(Map<String, dynamic> value, int tick) {
final pts = sourcePts(value);
expect(
(pts * 1000000 - expectedSourceUs(tick, TimelineClock.ticksPerSecond))
.abs(),
lessThanOrEqualTo(2),
reason: 'Independent packet PTS must identify the exact source frame',
);
}
try {
await SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeLeft,
]);
expect(
await projects.open(
'${fixture.directory.path}/Preview.cutdex',
timelineId: 'project',
),
isTrue,
);
await tester.pumpWidget(
UncontrolledProviderScope(
container: container,
child: MaterialApp(
theme: EditorTheme.penDark,
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
locale: const Locale('zh'),
home: const Scaffold(body: _Workspace()),
),
),
);
await until(
() =>
activePreview()?.ready == true &&
activePreview()?.session != null,
'initial preview ready',
);
await until(
() =>
(activePreview()!.session!.snapshot?.presentedVideoFrameCount ??
0) >
0,
'initial native frame',
);
expect(activePreview()!.error, isNull);
result['initialNative'] = await diagnostic(activePreview()!);
save();
final projectId = container
.read(projectsProvider)
.requireValue
.activeProject!
.id;
final switches = result['switches']! as List<Map<String, Object?>>;
Future<void> switchTo(String id, String name) async {
final workspaceElement = find
.byType(EditorWorkspace)
.evaluate()
.single;
final clock = Stopwatch()..start();
double? dataMs, uiMs;
final startupTrace = <Map<String, Object?>>[];
final traceTimer = Timer.periodic(const Duration(milliseconds: 100), (
_,
) {
final controller = activePreview();
final views = find.byType(RuntimePreview).evaluate();
final row = <String, Object?>{
'ms': clock.elapsedMicroseconds / 1000,
'pending': container
.read(projectsProvider)
.value
?.openingTimelineId,
'controller': controller != null,
'ready': controller?.ready,
'durationTick': controller?.durationTick,
'session': controller?.session?.id,
'views': views
.map((e) => (e.widget as RuntimePreview).session.id)
.toList(),
};
startupTrace.add(row);
});
final subscription = container.listen(projectsProvider, (_, next) {
if (next.value?.timeline?.id == id &&
next.value?.openingTimelineId == null) {
dataMs ??= clock.elapsedMicroseconds / 1000;
}
});
void observeFrame(Duration _) {
final workspace = workspaceElement.widget as EditorWorkspace;
if (workspace.timelineId == id) {
uiMs ??= clock.elapsedMicroseconds / 1000;
}
if (uiMs == null && clock.elapsedMilliseconds < 60000) {
WidgetsBinding.instance.addPostFrameCallback(observeFrame);
WidgetsBinding.instance.scheduleFrame();
}
}
WidgetsBinding.instance.addPostFrameCallback(observeFrame);
try {
await tester.tap(find.byKey(ValueKey('timeline-tab-$id')));
await until(() => uiMs != null, 'selected UI $id');
await until(
() =>
dataMs != null &&
activePreview()?.ready == true &&
activePreview()?.session != null,
'metadata/preview $id',
);
result['switchBeforeFirstFrame'] = {
'timelineId': id,
'native': await diagnostic(activePreview()!),
};
save();
await until(
() =>
(activePreview()!
.session!
.snapshot
?.presentedVideoFrameCount ??
0) >
0,
'native frame $id',
);
switches.add({
'scenario': name,
'uiPostFrameMs': uiMs,
'dataMs': dataMs,
'nativeFrameObservedMs': clock.elapsedMicroseconds / 1000,
'startupTrace': startupTrace,
});
expect(activePreview()!.error, isNull);
save();
} finally {
traceTimer.cancel();
subscription.close();
}
}
await switchTo('cold', 'cold');
for (var i = 0; i < 3; i++) {
await switchTo('project', 'warm-return-$i');
await switchTo('cold', 'warm-target-$i');
}
final rapid = <String>[];
final rapidSub = container.listen(projectsProvider, (_, next) {
if (next.value?.visibleTimelineId case final id?) rapid.add(id);
});
for (final id in ['third', 'project', 'cold', 'project', 'cold']) {
await tester.tap(find.byKey(ValueKey('timeline-tab-$id')));
await tester.pump();
await Future<void>.delayed(const Duration(milliseconds: 16));
expect(
container.read(projectsProvider).requireValue.visibleTimelineId,
id,
);
}
await advance(1000);
rapidSub.close();
expect(
container.read(projectsProvider).requireValue.timeline!.id,
'cold',
);
result['rapidSelection'] = rapid;
await until(
() => activePreview()?.ready == true,
'preview after rapid selection',
);
final preview = activePreview()!;
final session = await container.read(
editorTimelineProvider(projectId, 'cold').future,
);
final sequence = session.activeSequenceId!;
final view = session.view(sequence);
Future<void> seek(int frame) => preview.controlPreview(
sequence,
PreviewAction.seek,
at: CommandTime(frame, 30),
);
final matchedSeeks = <Map<String, Object?>>[];
result['matchedSeeks'] = matchedSeeks;
for (final targetUs in [
60000000,
2000000000,
2000000000 + sourceStepUs,
2000000000 + sourceStepUs * 2,
2000000000 + sourceStepUs,
2000000000 + sourceStepUs * 3,
120000567,
60000000,
]) {
final timer = Stopwatch()..start();
await preview.session!.seek(MediaTime(targetUs, 1000000));
timer.stop();
final value = await diagnostic(preview);
matchedSeeks.add({
'targetUs': targetUs,
'latencyMs': timer.elapsedMicroseconds / 1000,
'sourcePtsUs': sourcePts(value) * 1000000,
'diagnostics': value,
});
save();
expect(
(sourcePts(value) * 1000000 - expectedSourceUs(targetUs, 1000000))
.abs(),
lessThanOrEqualTo(2),
);
}
final seeks = result['seeks']! as List<Map<String, Object?>>;
for (final frame in [1800, 60000, 60001, 60002, 60001]) {
final before = await diagnostic(preview);
final clock = Stopwatch()..start();
await seek(frame);
final after = await diagnostic(preview);
seeks.add({
'frame': frame,
'acknowledgmentMs': clock.elapsedMicroseconds / 1000,
'frames': frames(after) - frames(before),
'native': after,
});
expect(preview.error, isNull);
save();
}
final drags = result['drags']! as List<Map<String, Object?>>;
for (var round = 0; round < 2; round++) {
for (final local in [false, true]) {
view.fitTimeline();
await advance(200);
final rulerFinder = find.byType(TimelineRuler);
final ruler = tester.renderObject<RenderBox>(rulerFinder);
final viewport = TimelineViewportRect(
width: ruler.size.width,
height: ruler.size.height,
);
final durationFrames = (info.duration.seconds * 30).floor();
if (local) {
view.setCamera(
TimelineCamera(
baseTick: TimelineClock.standard.toTicks(
RationalTime(59980, 30),
),
pixelsPerTick:
4 / TimelineClock.standard.toTicks(RationalTime(1, 30)),
verticalOffset: view.camera.verticalOffset,
),
);
await advance(100);
}
Offset position(int frame) => ruler.localToGlobal(
Offset(
view.camera.screenXForTick(
TimelineClock.standard.toTicks(RationalTime(frame, 30)),
viewport,
),
ruler.size.height / 2,
),
);
final startFrame = local ? 60000 : (durationFrames * .05).round();
await seek(startFrame);
await advance(150);
var initial = await diagnostic(preview);
final observations = <Map<String, Object?>>[];
final inputs = <Map<String, Object?>>[];
final clock = Stopwatch()..start();
Future<void>? pending;
Object? sampleError;
void sample() {
if (pending != null) return;
pending = diagnostic(preview)
.then((d) {
observations.add({
'ms': clock.elapsedMicroseconds / 1000,
...d,
});
})
.catchError((Object e) {
sampleError = e;
})
.whenComplete(() => pending = null);
}
final gesture = await tester.startGesture(
position(startFrame),
kind: PointerDeviceKind.touch,
);
// Acquire the real ruler's drag recognizer before measuring movement.
await gesture.moveBy(const Offset(30, 0));
await tester.pump();
expect(view.isScrubbing, isTrue);
await gesture.moveTo(position(startFrame));
await advance(350);
initial = await diagnostic(preview);
clock.reset();
final timer = Timer.periodic(
const Duration(milliseconds: 20),
(_) => sample(),
);
for (var i = 0; i < 120; i++) {
final dueUs = (i * 1000000 / 60).round();
final remaining = dueUs - clock.elapsedMicroseconds;
if (remaining > 0) {
await Future<void>.delayed(Duration(microseconds: remaining));
}
final phase = i < 60 ? i : 119 - i;
final target = local
? 60000 + (i % 40 < 20 ? i % 40 : 39 - i % 40)
: (durationFrames * (.05 + .9 * phase / 59)).round();
await gesture.moveTo(position(target));
inputs.add({
'ms': clock.elapsedMicroseconds / 1000,
'dueMs': dueUs / 1000,
'idealFrame': target,
'actualTick': view.playheadTick,
});
}
final releaseAt = clock.elapsedMicroseconds / 1000;
final finalTick = view.playheadTick;
await gesture.up();
await tester.pump();
await preview.waitForPendingPreview().timeout(
const Duration(seconds: 60),
);
final settled = await diagnostic(preview);
final settledMs = clock.elapsedMicroseconds / 1000;
await advance(500);
final frozen = await diagnostic(preview);
timer.cancel();
await pending;
expect(sampleError, isNull);
expect(preview.error, isNull);
final snapshot = await preview.session!.refresh();
final clockTick =
(BigInt.from(snapshot.position.numerator) *
BigInt.from(TimelineClock.ticksPerSecond) ~/
BigInt.from(snapshot.position.denominator))
.toInt();
expectExactSource(settled, finalTick);
expect(
(clockTick - finalTick).abs(),
lessThanOrEqualTo(TimelineClock.ticksPerSecond ~/ 1000000),
);
drags.add({
'round': round,
'scenario': local ? 'local-20-frame' : 'fit-entire-source',
'viewportWidth': ruler.size.width,
'inputs': inputs,
'observations': observations,
'before': initial,
'settled': settled,
'frozen': frozen,
'releaseAtMs': releaseAt,
'settledAtMs': settledMs,
'releaseWaitMs': settledMs - releaseAt,
'finalTick': finalTick,
'clockTick': clockTick,
'postSettleFrames': frames(frozen) - frames(settled),
});
save();
}
}
final ruler = tester.renderObject<RenderBox>(
find.byType(TimelineRuler),
);
final viewport = TimelineViewportRect(
width: ruler.size.width,
height: ruler.size.height,
);
Offset heldPosition(int frame) => ruler.localToGlobal(
Offset(
view.camera.screenXForTick(
TimelineClock.standard.toTicks(RationalTime(frame, 30)),
viewport,
),
ruler.size.height / 2,
),
);
await seek(60000);
final hold = await tester.startGesture(
heldPosition(60000),
kind: PointerDeviceKind.touch,
);
await hold.moveBy(const Offset(30, 0));
await tester.pump();
await hold.moveTo(heldPosition(60010));
await advance(1000);
final heldTick = view.playheadTick;
final heldBefore = await diagnostic(preview);
final releaseClock = Stopwatch()..start();
await hold.up();
await tester.pump();
await preview.waitForPendingPreview().timeout(
const Duration(seconds: 60),
);
final heldAfter = await diagnostic(preview);
final heldReleaseMs = releaseClock.elapsedMicroseconds / 1000;
await advance(500);
final heldFrozen = await diagnostic(preview);
(result['heldRelease']! as List<Map<String, Object?>>).add({
'holdMilliseconds': 1000,
'targetTick': heldTick,
'before': heldBefore,
'after': heldAfter,
'frozen': heldFrozen,
'releaseWaitMs': heldReleaseMs,
});
save();
expectExactSource(heldBefore, heldTick);
expectExactSource(heldAfter, heldTick);
expect(sourcePts(heldAfter), sourcePts(heldBefore));
expect(frames(heldAfter), frames(heldBefore));
expect(heldAfter['seekRequestCount'], heldBefore['seekRequestCount']);
expect(frames(heldFrozen), frames(heldAfter));
if (const bool.fromEnvironment('CUTDEX_TEST_PLAYBACK')) {
await preview.session!.seek(MediaTime(60000000, 1000000));
final beforePlay = await diagnostic(preview);
final clock = Stopwatch()..start();
await preview.session!.play();
final playAckMs = clock.elapsedMicroseconds / 1000;
await advance(3000);
final pauseClock = Stopwatch()..start();
await preview.session!.pause();
final pauseAckMs = pauseClock.elapsedMicroseconds / 1000;
final paused = await diagnostic(preview);
clock.stop();
await advance(250);
final frozen = await diagnostic(preview);
int unique(Map<String, dynamic> value) =>
int.parse('${value['uniquePresentedVideoFrameCount']}');
result['playback'] = {
'before': beforePlay,
'paused': paused,
'frozen': frozen,
'playAcknowledgmentMs': playAckMs,
'pauseAcknowledgmentMs': pauseAckMs,
'elapsedMs': clock.elapsedMicroseconds / 1000,
'uniqueFrameChanges': unique(paused) - unique(beforePlay),
'uniqueFramesPerSecond':
(unique(paused) - unique(beforePlay)) *
1000000 /
clock.elapsedMicroseconds,
};
save();
expect(unique(paused) - unique(beforePlay), greaterThan(30));
expect(frames(frozen), frames(paused));
expect(sourcePts(frozen), sourcePts(paused));
expect(paused['playbackError'], isNull);
}
expect(tester.takeException(), isNull);
final after = await file.stat();
expect(after.size, before.size);
expect(after.modified, before.modified);
result['status'] = 'passed';
result['sourceUnchanged'] = true;
save();
} catch (error, stack) {
result['status'] = 'failed';
result['error'] = '$error';
result['stack'] = '$stack';
save();
rethrow;
} finally {
await tester.pumpWidget(const SizedBox.shrink());
container.dispose();
await Future<void>.delayed(const Duration(milliseconds: 300));
await database.close();
await SystemChrome.setPreferredOrientations([]);
}
},
skip: source.isEmpty || output.isEmpty,
timeout: const Timeout(Duration(minutes: 15)),
);
}
class _Workspace extends ConsumerWidget {
const _Workspace();
@override
Widget build(BuildContext context, WidgetRef ref) {
final state = ref.watch(projectsProvider).requireValue;
return EditorWorkspace(
projectId: state.activeProject!.id,
projectName: state.activeProject!.name,
timelineId: state.visibleTimelineId!,
projectLoading: state.projectBusy,
timelineLoading: state.openingTimelineId != null,
integratedTitlebar: false,
headerLeading: const SizedBox.shrink(),
experience: DeviceExperience.tablet,
);
}
}
@@ -0,0 +1,589 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:cutdex/app/editor_theme.dart';
import 'package:cutdex/features/editor/editor_page.dart';
import 'package:cutdex/features/preview/preview_panel.dart';
import 'package:cutdex/integrations/platform/device_experience.dart';
import 'package:cutdex/l10n/app_localizations.dart';
import 'package:cutdex/persistence/app_database.dart';
import 'package:cutdex/workspace/project_state.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/project.dart';
import 'package:cutdex_sdk/runtime.dart';
import 'package:cutdex_sdk/timeline/layout.dart';
import 'package:cutdex_sdk/timeline/model.dart';
import 'package:cutdex_sdk/timeline_ui.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 '../test/support/preview_fixture.dart';
void main() {
final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();
binding.framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.fullyLive;
const source = String.fromEnvironment('CUTDEX_TEST_SOURCE');
const output = String.fromEnvironment('CUTDEX_TEST_REPORT');
testWidgets(
'Android production workspace navigation and exact-stop timing',
(tester) async {
expect(Platform.isAndroid, isTrue);
final file = File(source);
final before = await file.stat();
expect(before.size, greaterThan(0));
final report = File(output);
await report.parent.create(recursive: true);
final result = <String, Object?>{
'status': 'running',
'source': source,
'sourceBytes': before.size,
'buildMode': const bool.fromEnvironment('dart.vm.product')
? 'release'
: const bool.fromEnvironment('dart.vm.profile')
? 'profile'
: 'debug',
'scope': 'Production EditorWorkspace, Projects, preview and real touch ruler input; isolated project/database',
'measurement': 'Native queued-frame counters and content timestamp, not physical display scanout',
'switches': <Map<String, Object?>>[],
'seeks': <Map<String, Object?>>[],
'drags': <Map<String, Object?>>[],
'heldRelease': <Map<String, Object?>>[],
};
void save() => report.writeAsStringSync(
const JsonEncoder.withIndent(' ').convert(result),
);
save();
final runtime = CutdexRuntime();
final info = await runtime.probe(
MediaReference(id: 'media', uri: file.uri),
);
result['durationSeconds'] = info.duration.seconds;
final fixture = await createPreviewFixture(
file.uri,
hasAudio: info.audioTrackCount > 0,
clipDuration: RationalTime(
info.duration.numerator,
info.duration.denominator,
),
renderSize: {'width': 1280, 'height': 720},
);
final document = await fixture.workspace.project!.loadTimeline('project');
for (final id in ['cold', 'third']) {
await fixture.workspace.project!.saveTimeline(
TimelineDocument(
id: id,
name: id,
sequences: document.sequences,
defaultSequenceId: document.defaultSequenceId,
payloads: document.payloads,
settings: document.settings,
),
);
}
await fixture.workspace.close();
final database = AppDatabase(NativeDatabase.memory());
final container = ProviderContainer(
overrides: [appDatabaseProvider.overrideWithValue(database)],
);
final projects = container.read(projectsProvider.notifier);
Future<void> until(
bool Function() ready,
String label, {
int seconds = 60,
}) async {
final clock = Stopwatch()..start();
while (!ready()) {
if (clock.elapsed.inSeconds >= seconds) throw TimeoutException(label);
await tester.pump();
await Future<void>.delayed(const Duration(milliseconds: 16));
}
await tester.pump();
}
Future<void> advance(int milliseconds) async {
final clock = Stopwatch()..start();
while (clock.elapsedMilliseconds < milliseconds) {
await tester.pump();
await Future<void>.delayed(const Duration(milliseconds: 16));
}
}
PreviewController? activePreview() {
final state = container.read(projectsProvider).value;
if (state?.timeline == null || state!.openingTimelineId != null) {
return null;
}
return container
.read(
editorPreviewProvider(
state.activeProject!.id,
state.timeline!.id,
),
)
.value;
}
const nativeChannel = MethodChannel('cutdex_runtime');
const expectedDecoder = String.fromEnvironment('CUTDEX_TEST_DECODER');
Future<Map<String, dynamic>> diagnostic(PreviewController preview) async {
final value = (await nativeChannel.invokeMapMethod<String, dynamic>(
'previewDiagnostics',
{'contractVersion': 1, 'sessionId': preview.session!.id},
))!;
if (expectedDecoder.isNotEmpty) {
final backends = value['decoderBackends'] as Map?;
// Diagnostics also run from a timer while WidgetTester.pump is active.
expectSync(value['executionBackend'], 'direct');
expectSync(backends, isNotEmpty);
expectSync(backends!.values, everyElement(expectedDecoder));
expectSync(value['decoderSelectionReasons'], isNotEmpty);
}
return value;
}
int frames(Map<String, dynamic> value) =>
int.tryParse('${value['presentedVideoFrameCount']}') ?? 0;
double sourcePts(Map<String, dynamic> value) {
final time = value['presentedSourceFrameTime'] as Map?;
expect(time, isNotNull, reason: 'Actual source PTS must be available');
return int.parse('${time!['numerator']}') /
(time['denominator'] as num);
}
void expectExactSource(Map<String, dynamic> value, int tick) {
final target = tick / TimelineClock.ticksPerSecond;
final pts = sourcePts(value);
// This original is untrimmed CFR 2997/100, so the preceding source
// frame owns this sample. Allow only microsecond timestamp precision.
expect(pts, lessThanOrEqualTo(target + 0.000002));
expect(target - pts, lessThan(100 / 2997 + 0.000002));
}
try {
await SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeLeft,
]);
expect(
await projects.open(
'${fixture.directory.path}/Preview.cutdex',
timelineId: 'project',
),
isTrue,
);
await tester.pumpWidget(
UncontrolledProviderScope(
container: container,
child: MaterialApp(
theme: EditorTheme.penDark,
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
locale: const Locale('zh'),
home: const Scaffold(body: _Workspace()),
),
),
);
await until(
() =>
activePreview()?.ready == true &&
activePreview()?.session != null,
'initial preview ready',
);
await until(
() =>
(activePreview()!.session!.snapshot?.presentedVideoFrameCount ??
0) >
0,
'initial native frame',
);
expect(activePreview()!.error, isNull);
result['initialNative'] = await diagnostic(activePreview()!);
save();
final projectId = container
.read(projectsProvider)
.requireValue
.activeProject!
.id;
final switches = result['switches']! as List<Map<String, Object?>>;
Future<void> switchTo(String id, String name) async {
final workspaceElement = find
.byType(EditorWorkspace)
.evaluate()
.single;
final clock = Stopwatch()..start();
double? dataMs, uiMs;
final startupTrace = <Map<String, Object?>>[];
final traceTimer = Timer.periodic(const Duration(milliseconds: 100), (
_,
) {
final controller = activePreview();
final views = find.byType(RuntimePreview).evaluate();
final row = <String, Object?>{
'ms': clock.elapsedMicroseconds / 1000,
'pending': container
.read(projectsProvider)
.value
?.openingTimelineId,
'controller': controller != null,
'ready': controller?.ready,
'durationTick': controller?.durationTick,
'session': controller?.session?.id,
'views': views
.map((e) => (e.widget as RuntimePreview).session.id)
.toList(),
};
startupTrace.add(row);
});
final subscription = container.listen(projectsProvider, (_, next) {
if (next.value?.timeline?.id == id &&
next.value?.openingTimelineId == null) {
dataMs ??= clock.elapsedMicroseconds / 1000;
}
});
void observeFrame(Duration _) {
final workspace = workspaceElement.widget as EditorWorkspace;
if (workspace.timelineId == id) {
uiMs ??= clock.elapsedMicroseconds / 1000;
}
if (uiMs == null && clock.elapsedMilliseconds < 60000) {
WidgetsBinding.instance.addPostFrameCallback(observeFrame);
WidgetsBinding.instance.scheduleFrame();
}
}
WidgetsBinding.instance.addPostFrameCallback(observeFrame);
try {
await tester.tap(find.byKey(ValueKey('timeline-tab-$id')));
await until(() => uiMs != null, 'selected UI $id');
await until(
() =>
dataMs != null &&
activePreview()?.ready == true &&
activePreview()?.session != null,
'metadata/preview $id',
);
result['switchBeforeFirstFrame'] = {
'timelineId': id,
'native': await diagnostic(activePreview()!),
};
save();
await until(
() =>
(activePreview()!
.session!
.snapshot
?.presentedVideoFrameCount ??
0) >
0,
'native frame $id',
);
switches.add({
'scenario': name,
'uiPostFrameMs': uiMs,
'dataMs': dataMs,
'nativeFrameObservedMs': clock.elapsedMicroseconds / 1000,
'startupTrace': startupTrace,
});
expect(activePreview()!.error, isNull);
save();
} finally {
traceTimer.cancel();
subscription.close();
}
}
await switchTo('cold', 'cold');
for (var i = 0; i < 3; i++) {
await switchTo('project', 'warm-return-$i');
await switchTo('cold', 'warm-target-$i');
}
final rapid = <String>[];
final rapidSub = container.listen(projectsProvider, (_, next) {
if (next.value?.visibleTimelineId case final id?) rapid.add(id);
});
for (final id in ['third', 'project', 'cold', 'project', 'cold']) {
await tester.tap(find.byKey(ValueKey('timeline-tab-$id')));
await tester.pump();
await Future<void>.delayed(const Duration(milliseconds: 16));
expect(
container.read(projectsProvider).requireValue.visibleTimelineId,
id,
);
}
await advance(1000);
rapidSub.close();
expect(
container.read(projectsProvider).requireValue.timeline!.id,
'cold',
);
result['rapidSelection'] = rapid;
await until(
() => activePreview()?.ready == true,
'preview after rapid selection',
);
final preview = activePreview()!;
final session = await container.read(
editorTimelineProvider(projectId, 'cold').future,
);
final sequence = session.activeSequenceId!;
final view = session.view(sequence);
Future<void> seek(int frame) => preview.controlPreview(
sequence,
PreviewAction.seek,
at: CommandTime(frame, 30),
);
final seeks = result['seeks']! as List<Map<String, Object?>>;
for (final frame in [1800, 60000, 60001, 60002, 60001]) {
final before = await diagnostic(preview);
final clock = Stopwatch()..start();
await seek(frame);
final after = await diagnostic(preview);
seeks.add({
'frame': frame,
'acknowledgmentMs': clock.elapsedMicroseconds / 1000,
'frames': frames(after) - frames(before),
'native': after,
});
expect(preview.error, isNull);
save();
}
final drags = result['drags']! as List<Map<String, Object?>>;
for (var round = 0; round < 2; round++) {
for (final local in [false, true]) {
view.fitTimeline();
await advance(200);
final rulerFinder = find.byType(TimelineRuler);
final ruler = tester.renderObject<RenderBox>(rulerFinder);
final viewport = TimelineViewportRect(
width: ruler.size.width,
height: ruler.size.height,
);
final durationFrames = (info.duration.seconds * 30).floor();
if (local) {
view.setCamera(
TimelineCamera(
baseTick: TimelineClock.standard.toTicks(
RationalTime(59980, 30),
),
pixelsPerTick:
4 / TimelineClock.standard.toTicks(RationalTime(1, 30)),
verticalOffset: view.camera.verticalOffset,
),
);
await advance(100);
}
Offset position(int frame) => ruler.localToGlobal(
Offset(
view.camera.screenXForTick(
TimelineClock.standard.toTicks(RationalTime(frame, 30)),
viewport,
),
ruler.size.height / 2,
),
);
final startFrame = local ? 60000 : (durationFrames * .05).round();
await seek(startFrame);
await advance(150);
var initial = await diagnostic(preview);
final observations = <Map<String, Object?>>[];
final inputs = <Map<String, Object?>>[];
final clock = Stopwatch()..start();
Future<void>? pending;
Object? sampleError;
void sample() {
if (pending != null) return;
pending = diagnostic(preview)
.then((d) {
observations.add({
'ms': clock.elapsedMicroseconds / 1000,
...d,
});
})
.catchError((Object e) {
sampleError = e;
})
.whenComplete(() => pending = null);
}
final gesture = await tester.startGesture(
position(startFrame),
kind: PointerDeviceKind.touch,
);
// Acquire the real ruler's drag recognizer before measuring movement.
await gesture.moveBy(const Offset(30, 0));
await tester.pump();
expect(view.isScrubbing, isTrue);
await gesture.moveTo(position(startFrame));
await advance(350);
initial = await diagnostic(preview);
clock.reset();
final timer = Timer.periodic(
const Duration(milliseconds: 20),
(_) => sample(),
);
for (var i = 0; i < 120; i++) {
final dueUs = (i * 1000000 / 60).round();
final remaining = dueUs - clock.elapsedMicroseconds;
if (remaining > 0) {
await Future<void>.delayed(Duration(microseconds: remaining));
}
final phase = i < 60 ? i : 119 - i;
final target = local
? 60000 + (i % 40 < 20 ? i % 40 : 39 - i % 40)
: (durationFrames * (.05 + .9 * phase / 59)).round();
await gesture.moveTo(position(target));
inputs.add({
'ms': clock.elapsedMicroseconds / 1000,
'dueMs': dueUs / 1000,
'idealFrame': target,
'actualTick': view.playheadTick,
});
}
final releaseAt = clock.elapsedMicroseconds / 1000;
final finalTick = view.playheadTick;
await gesture.up();
await tester.pump();
await preview.waitForPendingPreview().timeout(
const Duration(seconds: 60),
);
final settled = await diagnostic(preview);
final settledMs = clock.elapsedMicroseconds / 1000;
await advance(500);
final frozen = await diagnostic(preview);
timer.cancel();
await pending;
expect(sampleError, isNull);
expect(preview.error, isNull);
final snapshot = await preview.session!.refresh();
final clockTick =
(BigInt.from(snapshot.position.numerator) *
BigInt.from(TimelineClock.ticksPerSecond) ~/
BigInt.from(snapshot.position.denominator))
.toInt();
expectExactSource(settled, finalTick);
expect(
(clockTick - finalTick).abs(),
lessThanOrEqualTo(TimelineClock.ticksPerSecond ~/ 1000000),
);
drags.add({
'round': round,
'scenario': local ? 'local-20-frame' : 'fit-entire-source',
'viewportWidth': ruler.size.width,
'inputs': inputs,
'observations': observations,
'before': initial,
'settled': settled,
'frozen': frozen,
'releaseAtMs': releaseAt,
'settledAtMs': settledMs,
'releaseWaitMs': settledMs - releaseAt,
'finalTick': finalTick,
'clockTick': clockTick,
'postSettleFrames': frames(frozen) - frames(settled),
});
save();
}
}
final ruler = tester.renderObject<RenderBox>(
find.byType(TimelineRuler),
);
final viewport = TimelineViewportRect(
width: ruler.size.width,
height: ruler.size.height,
);
Offset heldPosition(int frame) => ruler.localToGlobal(
Offset(
view.camera.screenXForTick(
TimelineClock.standard.toTicks(RationalTime(frame, 30)),
viewport,
),
ruler.size.height / 2,
),
);
await seek(60000);
final hold = await tester.startGesture(
heldPosition(60000),
kind: PointerDeviceKind.touch,
);
await hold.moveBy(const Offset(30, 0));
await tester.pump();
await hold.moveTo(heldPosition(60010));
await advance(1000);
final heldTick = view.playheadTick;
final heldBefore = await diagnostic(preview);
final releaseClock = Stopwatch()..start();
await hold.up();
await tester.pump();
await preview.waitForPendingPreview().timeout(
const Duration(seconds: 60),
);
final heldAfter = await diagnostic(preview);
final heldReleaseMs = releaseClock.elapsedMicroseconds / 1000;
await advance(500);
final heldFrozen = await diagnostic(preview);
(result['heldRelease']! as List<Map<String, Object?>>).add({
'holdMilliseconds': 1000,
'targetTick': heldTick,
'before': heldBefore,
'after': heldAfter,
'frozen': heldFrozen,
'releaseWaitMs': heldReleaseMs,
});
save();
expectExactSource(heldBefore, heldTick);
expectExactSource(heldAfter, heldTick);
expect(sourcePts(heldAfter), sourcePts(heldBefore));
expect(frames(heldAfter), frames(heldBefore));
expect(heldAfter['seekRequestCount'], heldBefore['seekRequestCount']);
expect(frames(heldFrozen), frames(heldAfter));
expect(tester.takeException(), isNull);
final after = await file.stat();
expect(after.size, before.size);
expect(after.modified, before.modified);
result['status'] = 'passed';
result['sourceUnchanged'] = true;
save();
} catch (error, stack) {
result['status'] = 'failed';
result['error'] = '$error';
result['stack'] = '$stack';
save();
rethrow;
} finally {
await tester.pumpWidget(const SizedBox.shrink());
container.dispose();
await Future<void>.delayed(const Duration(milliseconds: 300));
await database.close();
await SystemChrome.setPreferredOrientations([]);
}
},
skip: source.isEmpty || output.isEmpty,
timeout: const Timeout(Duration(minutes: 15)),
);
}
class _Workspace extends ConsumerWidget {
const _Workspace();
@override
Widget build(BuildContext context, WidgetRef ref) {
final state = ref.watch(projectsProvider).requireValue;
return EditorWorkspace(
projectId: state.activeProject!.id,
projectName: state.activeProject!.name,
timelineId: state.visibleTimelineId!,
projectLoading: state.projectBusy,
timelineLoading: state.openingTimelineId != null,
integratedTitlebar: false,
headerLeading: const SizedBox.shrink(),
experience: DeviceExperience.tablet,
);
}
}
@@ -12,6 +12,7 @@ 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:cutdex_ui/icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
@@ -161,9 +162,7 @@ void main() {
final panel = find.byType(EditorPreviewPanel);
await tester.tap(
find
.descendant(of: panel, matching: find.byIcon(Icons.play_arrow))
.first,
find.descendant(of: panel, matching: find.byIcon(AppIcons.play)).first,
);
await until(() => preview.playing, label: 'UI play');
await Future<void>.delayed(const Duration(milliseconds: 700));
@@ -173,7 +172,7 @@ void main() {
greaterThan(0),
);
await tester.tap(
find.descendant(of: panel, matching: find.byIcon(Icons.pause)).first,
find.descendant(of: panel, matching: find.byIcon(AppIcons.pause)).first,
);
await until(() => !preview.playing, label: 'UI pause');
mark('real play and pause buttons advanced native media clock');
@@ -1,6 +1,6 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
enum DesktopContent { workspace, library, settings }
enum DesktopContent { workspace, library, resourceLibrary, settings }
typedef DesktopContentSelection = ({
DesktopContent surface,
@@ -9,6 +9,7 @@ typedef DesktopContentSelection = ({
(String, String)? workspace,
bool settingsVisited,
bool resourcesSelected,
bool librarySelected,
});
final desktopContentProvider =
@@ -18,6 +19,8 @@ final desktopContentProvider =
/// Navigation changes visibility without disposing any visited content.
class DesktopContentController extends Notifier<DesktopContentSelection> {
DesktopContent _settingsReturnSurface = DesktopContent.workspace;
@override
DesktopContentSelection build() => (
surface: DesktopContent.workspace,
@@ -26,6 +29,7 @@ class DesktopContentController extends Notifier<DesktopContentSelection> {
workspace: null,
settingsVisited: false,
resourcesSelected: false,
librarySelected: false,
);
void select(DesktopContent surface) {
@@ -37,10 +41,14 @@ class DesktopContentController extends Notifier<DesktopContentSelection> {
settingsVisited:
state.settingsVisited || surface == DesktopContent.settings,
resourcesSelected: surface == DesktopContent.library,
librarySelected: surface == DesktopContent.resourceLibrary,
);
}
void showSettings({int? tab, (String, String)? workspace}) {
if (state.surface != DesktopContent.settings) {
_settingsReturnSurface = state.surface;
}
state = (
surface: DesktopContent.settings,
settingsTab: tab ?? state.settingsTab,
@@ -48,6 +56,13 @@ class DesktopContentController extends Notifier<DesktopContentSelection> {
workspace: workspace ?? state.workspace,
settingsVisited: true,
resourcesSelected: state.resourcesSelected,
librarySelected: state.librarySelected,
);
}
void closeSettings() {
if (state.surface == DesktopContent.settings) {
select(_settingsReturnSurface);
}
}
}
@@ -4,17 +4,49 @@ import 'package:flutter/foundation.dart';
class DesktopWorkspaceController extends ChangeNotifier {
double? _agentWidth;
bool _agentFullscreen = false;
bool _agentFloating = false;
bool _agentFloatingExpanded = false;
bool _agentVisible = false;
double? get agentWidth => _agentWidth;
bool get agentFullscreen => _agentFullscreen;
bool get agentFloating => _agentFloating;
bool get agentFloatingExpanded => _agentFloatingExpanded;
bool get agentVisible => _agentVisible;
void setAgentVisible(bool value) {
if (_agentVisible == value) return;
_agentVisible = value;
if (!value) {
_agentFloating = false;
_agentFullscreen = false;
_agentFloatingExpanded = false;
}
notifyListeners();
}
void toggleFloatingConversation() {
_agentFloatingExpanded = !_agentFloatingExpanded;
notifyListeners();
}
void setAgentWidth(double width) {
_agentWidth = width;
notifyListeners();
}
void setAgentFloating(bool value) {
if (_agentFloating == value) return;
_agentFloating = value;
_agentVisible = true;
if (!value) _agentFloatingExpanded = false;
if (value) _agentFullscreen = false;
notifyListeners();
}
void setAgentFullscreen(bool value) {
if (_agentFullscreen == value) return;
if (_agentFullscreen == value && !(value && _agentFloating)) return;
if (value) _agentFloating = false;
_agentFullscreen = value;
notifyListeners();
}
@@ -9,7 +9,7 @@ abstract final class WorkspaceLayoutPolicy {
width >=
WorkspaceLayoutMetrics.sidebarMinimumWidth +
WorkspaceLayoutMetrics.contentMinimumWidth +
1;
WorkspaceLayoutMetrics.desktopSpacing;
static bool showAgentBesideEditor(double width) =>
width >= WorkspaceLayoutMetrics.dualPaneMinimumWidth;
+14 -4
View File
@@ -11,17 +11,27 @@ import '../integrations/app_updates.dart';
import '../integrations/editor_tools.dart';
import '../features/settings/appearance_settings.dart';
import '../shared/widgets/error_notification_host.dart';
import '../integrations/platform/device_experience.dart';
class CutdexApp extends ConsumerWidget {
const CutdexApp({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
ref.watch(applicationMcpConnectionProvider);
ref.watch(appUpdateLifecycleProvider);
ref.watch(applicationMcpConnectionProvider.select((_) => null));
ref.watch(appUpdateLifecycleProvider.select((_) => null));
final appearance =
ref.watch(appearanceSettingsProvider).asData?.value ??
AppAppearance.system;
final palette =
ref.watch(paletteSettingsProvider).asData?.value ?? AppPalette.graphite;
final desktop =
ref.watch(deviceExperienceProvider) == DeviceExperience.desktop;
ThemeData theme(Brightness brightness) {
final base = EditorTheme.forPalette(palette, brightness);
return desktop ? EditorTheme.desktop(base) : base;
}
return MaterialApp.router(
builder: (context, child) =>
ErrorNotificationHost(child: child ?? const SizedBox.shrink()),
@@ -31,8 +41,8 @@ class CutdexApp extends ConsumerWidget {
supportedLocales: AppLocalizations.supportedLocales,
localeListResolutionCallback: resolveAppLocale,
debugShowCheckedModeBanner: false,
theme: EditorTheme.penLight,
darkTheme: EditorTheme.penDark,
theme: theme(Brightness.light),
darkTheme: theme(Brightness.dark),
themeMode: appearance.themeMode,
routerConfig: ref.watch(appRouterProvider),
);
+35 -6
View File
@@ -7,10 +7,39 @@ abstract final class EditorTheme {
static ThemeData get penLight => adapt(AppTheme.penLight);
static ThemeData get penDark => adapt(AppTheme.penDark);
static ThemeData forPalette(AppPalette palette, Brightness brightness) =>
adapt(AppTheme.forPalette(palette, brightness));
static ThemeData desktop(ThemeData theme) {
final desktop = AppTheme.desktopWorkspaceTheme(theme);
final timeline = desktop.extension<TimelineThemeData>();
if (timeline == null) return desktop;
return desktop.copyWith(
extensions: [
...desktop.extensions.values.where(
(value) => value is! TimelineThemeData,
),
timeline.copyWith(
rulerHeight: AppDesktopMetrics.timelineRuler,
rulerTextStyle: timeline.rulerTextStyle.copyWith(
fontSize: 12,
height: 16 / 12,
fontFeatures: const [FontFeature.tabularFigures()],
),
playheadColor: desktop.colorScheme.primary,
clipHeaderHeight: 20,
clipHeaderPadding: 4,
clipNameTextStyle: timeline.clipNameTextStyle.copyWith(
fontSize: 11,
height: 16 / 11,
),
),
],
);
}
static ThemeData adapt(ThemeData theme) {
final palette = theme.brightness == Brightness.dark
? AppColors.penDark
: AppColors.penLight;
final palette = AppColors.of(theme);
final dark = theme.brightness == Brightness.dark;
final text = theme.textTheme;
final timelineBorder = palette.divider;
@@ -27,8 +56,8 @@ abstract final class EditorTheme {
backgroundColor: palette.background,
primaryLaneBackgroundColor: palette.sidebar,
visualClipColor: palette.visualClip,
audioClipColor: palette.popover,
audioAccentColor: timelineSecondary,
audioClipColor: palette.audioClip,
audioAccentColor: palette.audioWaveform,
gapColor: timelineBorder,
gapBorderColor: timelineBorder,
containerAccentColor: timelineSecondary,
@@ -37,7 +66,7 @@ abstract final class EditorTheme {
connectionLineWidth: 3,
clipBorderColor: timelineBorder,
clipBorderWidth: 1,
selectionOutlineColor: palette.foreground,
selectionOutlineColor: palette.selection,
selectionOutlineWidth: 2,
keyframeColor: timelineSecondary,
keyframeBorderColor: palette.background,
+1 -1
View File
@@ -22,7 +22,7 @@ GoRouter appRouter(Ref ref) {
builder: (context, state) => SettingsPage(
initialTab:
(int.tryParse(state.uri.queryParameters['tab'] ?? '') ?? 0)
.clamp(0, 2),
.clamp(0, 3),
workspace: state.extra is (String, String)
? state.extra as (String, String)
: null,
+1 -1
View File
@@ -48,4 +48,4 @@ final class AppRouterProvider
}
}
String _$appRouterHash() => r'00e948f9d82c1f07ecdfc62b3c1ec833cb03edfe';
String _$appRouterHash() => r'ea1ed83ca5ca1f7079b268b1a94940d575b6ddf9';
+101 -35
View File
@@ -1,10 +1,12 @@
import 'package:cutdex_native/cutdex_native.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:flutter/material.dart';
import '../../integrations/platform/editor_window_chrome.dart';
import '../../l10n/l10n.dart';
import '../../shared/layout/workspace_layout_metrics.dart';
import '../../workspace/workspace_mode.dart';
import '../editor_theme.dart';
/// Keeps window chrome outside the shared workspace surface.
class DesktopWindowFrame extends StatelessWidget {
@@ -12,30 +14,40 @@ class DesktopWindowFrame extends StatelessWidget {
super.key,
required this.integratedTitlebar,
required this.headerControls,
required this.librarySelected,
this.projectTabs,
this.headerTrailing = const SizedBox.shrink(),
this.settingsSelected = false,
required this.onModeChanged,
required this.onLibraryPressed,
this.resourceLibrarySelected = false,
this.onResourceLibraryPressed,
required this.onHomePressed,
required this.onSettingsPressed,
required this.child,
});
static const railWidth = 44.0;
static const railButtonSize = 32.0;
static const railIconSize = 22.0;
static const headerHeight = 40.0;
static const contentInset = WorkspaceLayoutMetrics.desktopSpacing;
static const railIconSize = 20.0;
static const headerHeight = AppDesktopMetrics.windowHeader;
static const headerInset = (railWidth - AppControlSize.headerButton) / 2;
static const contentInset = WorkspaceLayoutMetrics.desktopOuterSpacing;
final bool integratedTitlebar;
final Widget headerControls;
final bool librarySelected;
final Widget? projectTabs;
final Widget headerTrailing;
final bool settingsSelected;
final ValueChanged<WorkspaceMode> onModeChanged;
final VoidCallback? onLibraryPressed;
final bool resourceLibrarySelected;
final VoidCallback? onResourceLibraryPressed;
final VoidCallback onHomePressed;
final VoidCallback onSettingsPressed;
final Widget child;
@override
Widget build(BuildContext context) => ColoredBox(
Widget build(BuildContext context) => Theme(
data: EditorTheme.desktop(Theme.of(context)),
child: Builder(builder: _buildFrame),
);
Widget _buildFrame(BuildContext context) => ColoredBox(
color: Theme.of(context).colorScheme.surfaceContainer,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
@@ -44,13 +56,53 @@ class DesktopWindowFrame extends StatelessWidget {
key: const Key('desktop-window-header'),
height: headerHeight,
child: WindowHeaderPadding(
child: SingleChildScrollView(
child: Row(
children: [
Expanded(
child: projectTabs != null
? LayoutBuilder(
builder: (context, constraints) =>
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: SizedBox(
width: constraints.maxWidth.clamp(
240.0,
double.infinity,
),
child: Row(
children: [
if (integratedTitlebar)
SizedBox(
key: const Key(
'native-window-controls-space',
),
width:
EditorWindowChrome.leadingWidth,
height: headerHeight,
),
headerControls,
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: headerInset,
),
child: projectTabs!,
),
),
],
),
),
),
)
: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
if (integratedTitlebar)
SizedBox(
key: const Key('native-window-controls-space'),
key: const Key(
'native-window-controls-space',
),
width: EditorWindowChrome.leadingWidth,
height: headerHeight,
),
@@ -59,10 +111,15 @@ class DesktopWindowFrame extends StatelessWidget {
),
),
),
headerTrailing,
],
),
),
),
Expanded(
child: Row(
children: [
if (projectTabs == null)
SizedBox(
key: const Key('desktop-navigation-rail'),
width: railWidth,
@@ -70,20 +127,23 @@ class DesktopWindowFrame extends StatelessWidget {
padding: const EdgeInsets.symmetric(vertical: 10),
child: Column(
children: [
for (final library in [false, true])
for (final section in [0, 2])
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: IconButton.filledTonal(
key: ValueKey(
library
? 'desktop-rail-library'
: 'desktop-rail-cut',
),
tooltip: library
? context.l10n.navigationLibrary
: context.l10n.navigationChat,
key: ValueKey(switch (section) {
0 => 'desktop-rail-home',
_ => 'desktop-rail-resources',
}),
tooltip: switch (section) {
0 => context.l10n.navigationHome,
_ => context.l10n.navigationLibrary,
},
isSelected:
!settingsSelected && library == librarySelected,
!settingsSelected &&
(section == 2
? resourceLibrarySelected
: !resourceLibrarySelected),
style: IconButton.styleFrom(
fixedSize: const Size.square(railButtonSize),
minimumSize: const Size.square(railButtonSize),
@@ -93,18 +153,20 @@ class DesktopWindowFrame extends StatelessWidget {
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
backgroundColor:
!settingsSelected &&
library == librarySelected
(section == 2
? resourceLibrarySelected
: !resourceLibrarySelected)
? null
: Colors.transparent,
),
onPressed: library
? onLibraryPressed
: () => onModeChanged(WorkspaceMode.cut),
icon: Icon(
library
? Icons.video_library_outlined
: Icons.chat_bubble_outline,
),
onPressed: switch (section) {
0 => onHomePressed,
_ => onResourceLibraryPressed,
},
icon: Icon(switch (section) {
0 => AppIcons.home,
_ => AppIcons.folder,
}),
),
),
const Spacer(),
@@ -121,7 +183,7 @@ class DesktopWindowFrame extends StatelessWidget {
iconSize: railIconSize,
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
icon: const Icon(Icons.settings_outlined),
icon: const Icon(AppIcons.settings),
),
],
),
@@ -129,14 +191,18 @@ class DesktopWindowFrame extends StatelessWidget {
),
Expanded(
child: Padding(
padding: const EdgeInsets.only(
padding: EdgeInsets.only(
left: projectTabs == null ? 0 : contentInset,
right: contentInset,
bottom: contentInset,
),
child: SizedBox(
key: const Key('desktop-content-container'),
child: WindowHeaderPane(
offset: const Offset(railWidth, headerHeight),
offset: Offset(
projectTabs == null ? railWidth : contentInset,
headerHeight,
),
child: LayoutBuilder(
builder: (context, constraints) =>
constraints.maxWidth < 200
+161 -7
View File
@@ -1,4 +1,8 @@
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import '../adaptive/desktop_workspace_controller.dart';
import '../adaptive/workspace_layout_policy.dart';
@@ -27,6 +31,7 @@ class DesktopWorkspaceShell extends StatefulWidget {
required this.editor,
required this.scaffoldKey,
required this.navigationDrawer,
this.projectTabsLayout = false,
});
static const gutterWidth = WorkspaceLayoutMetrics.desktopSpacing;
@@ -41,6 +46,7 @@ class DesktopWorkspaceShell extends StatefulWidget {
final Widget editor;
final GlobalKey<ScaffoldState> scaffoldKey;
final Widget navigationDrawer;
final bool projectTabsLayout;
@override
State<DesktopWorkspaceShell> createState() => _DesktopWorkspaceShellState();
@@ -93,15 +99,23 @@ class _DesktopWorkspaceShellState extends State<DesktopWorkspaceShell> {
);
@override
Widget build(BuildContext context) => LayoutBuilder(
Widget build(BuildContext context) => widget.projectTabsLayout
? _projectWorkspace(context)
: LayoutBuilder(
builder: (context, constraints) {
const gap = DesktopWorkspaceShell.gutterWidth;
final width = constraints.maxWidth;
final requestedFloating = widget.controller.agentFloating;
final showAgent =
widget.mode == WorkspaceMode.agent ||
widget.controller.agentVisible;
final navigationGap = widget.sidebarCollapsed ? 0.0 : gap;
final resolved = DesktopWorkspaceGeometry.resolve(
// The geometry policy accounts for a one-pixel divider; reserve gutters.
width: width - navigationGap - gap + 1,
mode: WorkspaceMode.agent,
mode: requestedFloating || !showAgent
? WorkspaceMode.cut
: WorkspaceMode.agent,
sidebarCollapsed: widget.sidebarCollapsed,
sidebarWidth: widget.sidebarWidth,
agentWidth: widget.controller.agentWidth,
@@ -110,7 +124,15 @@ class _DesktopWorkspaceShellState extends State<DesktopWorkspaceShell> {
final navigationSpace = widget.sidebarCollapsed
? 0.0
: resolved.sidebarWidth;
final floating =
requestedFloating ||
(showAgent &&
widget.mode == WorkspaceMode.cut &&
resolved.editorHidden &&
!widget.controller.agentFullscreen);
final agentHidden =
floating ||
!showAgent ||
resolved.editorHidden &&
widget.mode == WorkspaceMode.cut &&
!widget.controller.agentFullscreen;
@@ -126,7 +148,8 @@ class _DesktopWorkspaceShellState extends State<DesktopWorkspaceShell> {
final available = width - navigationSpace - navigationGap;
void expandEditor() {
final collapseNavigation =
available < 220 + gap + DesktopWorkspaceGeometry.editorMinimumWidth;
available <
220 + gap + DesktopWorkspaceGeometry.editorMinimumWidth;
if (collapseNavigation) widget.onSidebarCollapsedChanged(true);
widget.controller.setAgentFullscreen(false);
}
@@ -189,21 +212,57 @@ class _DesktopWorkspaceShellState extends State<DesktopWorkspaceShell> {
),
if (!agentHidden && !geometry.editorHidden)
const SizedBox(width: gap),
if (!agentHidden)
SizedBox(
if (!floating)
Offstage(
offstage: agentHidden,
child: ExcludeFocus(
excluding: agentHidden,
child: TickerMode(
enabled: !agentHidden,
child: SizedBox(
key: const Key('desktop-agent-slot'),
width: geometry.agentWidth,
width: agentHidden
? widget.controller.agentWidth ?? 320
: geometry.agentWidth,
child: _card(
'agent',
widget.agentBuilder(geometry, expandEditor),
),
),
),
),
),
],
),
if (floating)
Positioned(
key: const Key('agent-floating-window'),
right: 12,
bottom: 12,
width: math.min(560, math.max(0, available - 24)),
child: AppFloatingDialog(
key: const Key('floating-agent-dialog'),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(22),
),
backgroundColor: AppSurfaces.of(context)
.composerBackground,
child: ConstrainedBox(
constraints: BoxConstraints(
maxHeight: math.min(
640,
math.max(0, constraints.maxHeight - 24),
),
),
child: widget.agentBuilder(geometry, expandEditor),
),
),
),
if (!widget.sidebarCollapsed)
Positioned(
left:
navigationSpace - WorkspaceLayoutMetrics.desktopResizeSlop,
navigationSpace -
WorkspaceLayoutMetrics.desktopResizeSlop,
top: 0,
bottom: 0,
child: _gutter(
@@ -246,4 +305,99 @@ class _DesktopWorkspaceShellState extends State<DesktopWorkspaceShell> {
);
},
);
Widget _projectWorkspace(BuildContext context) => LayoutBuilder(
builder: (context, constraints) {
const gap = DesktopWorkspaceShell.gutterWidth;
final width = constraints.maxWidth;
final maximum = WorkspaceLayoutMetrics.sidebarMaximumWidth(width - gap);
final sidebarWidth =
(widget.sidebarWidth ?? WorkspaceLayoutMetrics.sidebarDefaultWidth)
.clamp(WorkspaceLayoutMetrics.sidebarMinimumWidth, maximum)
.toDouble();
final floating = widget.controller.agentFloating;
final collapsed = widget.sidebarCollapsed || floating;
final geometry = DesktopWorkspaceGeometry(
sidebarWidth: sidebarWidth,
agentWidth: 0,
editorHidden: false,
);
return Scaffold(
key: widget.scaffoldKey,
backgroundColor: Colors.transparent,
drawer: Drawer(
width: 320,
child: SafeArea(
// The drawer and floating panel share the conversation widget.
child: floating ? const SizedBox.shrink() : widget.navigationDrawer,
),
),
body: Stack(
key: const Key('desktop-workspace-shell'),
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (!collapsed) ...[
SizedBox(
width: sidebarWidth,
child: _card(
'chat',
widget.sidebarBuilder(geometry, () {}),
),
),
const SizedBox(width: gap),
],
Expanded(
child: SizedBox(
key: const Key('desktop-editor-card'),
child: widget.editor,
),
),
],
),
if (!collapsed)
Positioned(
left: sidebarWidth - WorkspaceLayoutMetrics.desktopResizeSlop,
top: 0,
bottom: 0,
child: _gutter(
name: 'project-sidebar',
initialWidth: sidebarWidth,
onResize: (value) => widget.onSidebarWidthChanged(
value.clamp(
WorkspaceLayoutMetrics.sidebarMinimumWidth,
maximum,
),
),
),
),
if (floating)
Positioned(
key: const Key('agent-floating-window'),
right: 12,
bottom: 12,
width: math.min(560, math.max(0, width - 24)),
child: AppFloatingDialog(
key: const Key('floating-agent-dialog'),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(22),
),
backgroundColor: AppSurfaces.of(context).composerBackground,
child: ConstrainedBox(
constraints: BoxConstraints(
maxHeight: math.min(
640,
math.max(0, constraints.maxHeight - 24),
),
),
child: widget.agentBuilder(geometry, () {}),
),
),
),
],
),
);
},
);
}
+3 -2
View File
@@ -1,3 +1,4 @@
import 'package:cutdex_ui/icons.dart';
import 'package:flutter/material.dart';
import '../../l10n/l10n.dart';
@@ -43,12 +44,12 @@ class PhoneWorkspaceShell extends StatelessWidget {
destinations: [
NavigationDestination(
key: const Key('workspace-agent-destination'),
icon: const Icon(Icons.chat_bubble_outline),
icon: const Icon(AppIcons.chat),
label: context.l10n.workspaceAgent,
),
NavigationDestination(
key: const Key('workspace-cut-destination'),
icon: const Icon(Icons.movie_outlined),
icon: const Icon(AppIcons.video),
label: context.l10n.workspaceCut,
),
],
+3 -2
View File
@@ -1,5 +1,6 @@
import 'dart:math' as math;
import 'package:cutdex_ui/icons.dart';
import 'package:flutter/material.dart';
import '../../l10n/l10n.dart';
@@ -55,14 +56,14 @@ class TabletWorkspaceShell extends StatelessWidget {
destinations: [
NavigationRailDestination(
icon: const Icon(
Icons.chat_bubble_outline,
AppIcons.chat,
key: Key('workspace-agent-destination'),
),
label: Text(context.l10n.workspaceAgent),
),
NavigationRailDestination(
icon: const Icon(
Icons.movie_outlined,
AppIcons.video,
key: Key('workspace-cut-destination'),
),
label: Text(context.l10n.workspaceCut),
+2 -1
View File
@@ -1,3 +1,4 @@
import 'package:cutdex_ui/icons.dart';
import 'package:flutter/material.dart';
import '../../integrations/platform/editor_window_chrome.dart';
@@ -45,7 +46,7 @@ class WorkspaceFrame extends StatelessWidget {
key: const Key('workspace-navigation-button'),
tooltip: context.l10n.expandSidebar,
onPressed: () => Scaffold.of(context).openDrawer(),
icon: const Icon(Icons.menu),
icon: const Icon(AppIcons.menu),
),
),
),
@@ -0,0 +1,24 @@
// Opt-in profiler of the existing full app; normal launches do no benchmark work.
import 'dart:async';
import 'dart:io';
import 'full_app_viewport_bench/config.dart';
import 'full_app_viewport_bench/runner.dart';
void startFullAppViewportBenchFromEnvironment() {
final output = Platform.environment['CUTDEX_FULL_APP_VIEWPORT_BENCH'];
if (output == null || output.isEmpty) return;
unawaited(_start(output));
}
Future<void> _start(String output) async {
try {
await runFullAppViewportBench(
ViewportBenchConfig.fromEnvironment(Platform.environment),
);
} catch (error, stack) {
final directory = Directory(output);
await directory.create(recursive: true);
await File('${directory.path}/error.txt').writeAsString('$error\n$stack');
}
}
@@ -0,0 +1,71 @@
# 完整编辑器拖拽实测
没有 `CUTDEX_FULL_APP_VIEWPORT_BENCH` 时入口立即返回。启用后使用正常持久化项目和时间线,通过真实播放头手势进入生产预览链路;不会加载素材夹具或替换页面。请先在正常编辑器打开待测素材所在的时间线并暂停播放。
代码职责:`config.dart` 校验配置,`workload.dart` 生成目标轨迹,`drag.dart` 投递实际手势并验证播放头,`diagnostics.dart` 校准 QPC/采样,`records.dart` 写出证据,`capture.dart` 管理可选捕获进程,`runner.dart` 编排和验证停止。
以下变量统一加 `CUTDEX_FULL_APP_VIEWPORT_` 前缀:
| 后缀 | 默认/含义 |
|---|---|
| `BENCH` | 必填输出目录;每次使用新目录 |
| `START_GATE` | 可选门文件路径;正常项目加载后创建文件,最多等待120秒 |
| `EXPECTED_FRAMES` | 可选预期时间线长度,容差2帧;未指定时从实际时间线读取 |
| `TIMELINE_FPS` | 30;目标坐标的时间基准,不是源视频帧率 |
| `ROUNDS` | 5 |
| `PAIRED` | 0;设为1比较全片5%–95%往返和局部往返 |
| `INPUT_HZ` / `INPUT_COUNT` | 60 / 360;配对模式每场景6秒,输入数量必须是至少6的偶数 |
| `LOCAL_START_FRAME` | 实际时间线长度的28%;可指定复现旧测试位置 |
| `LOCAL_SPAN_FRAMES` / `LOCAL_PIXELS_PER_FRAME` | 20 / 4 |
| `EDGE_MARGIN_FRAMES` | 900;旧五场景模式首尾边距,也用于检查时间线足够长;短素材需缩小 |
| `SAMPLE_INTERVAL_MS` | 16 |
| `NATIVE_ONLY` | 1;采样原生提交,不捕获桌面 |
| `CAPTURE_HELPER` | `NATIVE_ONLY=0` 时必填捕获工具绝对路径 |
| `SILENT` | 0;保持生产 audible policy,设为1仅用于明确要求的静音对照 |
MIDE旧测试配置:`PAIRED=1`、`ROUNDS=3`、`EXPECTED_FRAMES=214073.82`、`LOCAL_START_FRAME=60137`、`NATIVE_ONLY=1`,其余保持默认。
输出保留 `inputs.csv`、`phases.csv`、`native-samples.jsonl`、`meta.json` 和 `progress.json` 的既有字段,`meta.json.configuration` 增加实际配置。停止仅等待已有请求完成,不发出额外定位;最终时钟必须命中最后目标,之后观察冻结窗口。通过状态在采样与文件流完成后写出,异常写入 `error.txt`。
输入/阶段CSV里的帧数使用配置的时间基准。兼容元数据中名字含 `At30Hz` 的字段仍换算为30Hz。原生提交数不能当作DWM屏幕扫描帧数;正式分析还须校验GPU、输出尺寸、冻结期间源帧计数和最终提交相对松手的时刻。
## 时间线切换实测
`main.dart` 提供独立、默认关闭的完整应用切换测试,实现在
`../timeline_switch_bench.dart`。启动正常 Profile 程序前,将
`CUTDEX_TIMELINE_SWITCH_BENCH` 设置为新的输出目录。测试保持生产 provider
和编辑页面,通过 `GestureBinding` 点击真实时间线标签,输出
`results.json` 和 `done.json`。
初始时间线必须不同于 `CUTDEX_TIMELINE_SWITCH_TARGET`;不设置时选择项目中
第一个非当前时间线,因此项目至少需要两条时间线。测试等待初始预览控制器
完成初始化。可选的 `CUTDEX_TIMELINE_SWITCH_GATE` 文件允许先检查正常工作区,
创建该文件后才开始测量。`CUTDEX_TIMELINE_SWITCH_RAPID=1` 改为连续点击五次,
每次计划间隔 16 ms,并在最后一次点击后观察五秒,验证最新选择不被旧请求覆盖;
输出为 `rapid.json`。
UI 耗时记录到目标工作区的 post-frame 回调,数据耗时记录到 `Projects` 发布
准备好的文档。原生首帧采用异步 20 ms 诊断轮询,因此记录的是首次观察耗时;
缓存时间线的原生计数表示复用已有帧。首次打开对照必须使用新进程和未缓存的
目标会话。启动出错或正常切换测试缺少原生帧均判失败;`startup.json` 记录
初始状态。快速切换模式验证状态一致性,未单独计时原生首帧。普通启动应清除
上述测试环境变量。
## 触摸板缩放回放与驱动事件
`../timeline_gesture_bench.dart` 提供默认关闭的完整应用手势回放。启动正常
Profile 程序前设置 `CUTDEX_TIMELINE_GESTURE_BENCH` 为新输出目录,测试等待
六秒后向当前时间线发送原生 pan/zoom 协议及 Ctrl+滚轮输入。播放头应在
viewport 内,键盘修饰键应松开。输入走正常命中测试和手势识别路径,输出
`results.json`、`done.json`;异常输出 `error.txt`。回放结束恢复原相机,
不定位播放头、不修改时间线文档。回放不等同于物理触摸板操作。
可独立设置 `CUTDEX_TIMELINE_GESTURE_TRACE` 为 JSONL 文件路径,记录实际
`PointerPanZoom` 与 `PointerScroll` 事件以及 Ctrl/Meta 状态。`source` 区分
`protocol-replay` 与 `driver`,回放使用 device 7200。记录默认关闭,启用时
每秒刷新文件,可用于确认驱动是发送合并的 pan/scale,还是兼容滚轮输入。
普通启动应清除这两个环境变量。
独立测试入口 `tool/windows/native_preview_bench.dart` 要求显式设置
`CUTDEX_BENCH_SOURCE`、`CUTDEX_BENCH_DURATION_FRAMES`(30 Hz 时基下的正整数
时长)和 `CUTDEX_BENCH_CAPTURE_HELPER`;素材及桌面捕获工具保留在仓库外。
@@ -0,0 +1,62 @@
import 'dart:async';
import 'dart:io';
import 'config.dart';
/// Optional desktop capture process; its path is supplied explicitly.
class BenchCapture {
BenchCapture._(this.output, this.process);
final Directory output;
final Process process;
static Future<BenchCapture?> start(
ViewportBenchConfig config,
Directory output,
) async {
if (config.nativeOnly) return null;
final helper = config.captureHelper!;
final probe = await Process.run(helper, ['$pid']);
if (probe.exitCode != 0) {
throw StateError('Capture probe failed: ${probe.stderr}');
}
final line = probe.stdout
.toString()
.split('\n')
.singleWhere((s) => s.startsWith('CutdexD3D11Preview 1 '));
final rect = line.trim().split(' ').skip(2).map(int.parse).toList();
final process = await Process.start(helper, [
output.path,
'$pid',
'${rect[0] + 8}',
'${rect[1] + 8}',
'${rect[2] - 8}',
'${rect[3] - 8}',
]);
unawaited(process.stdout.drain<void>());
unawaited(process.stderr.drain<void>());
final capture = BenchCapture._(output, process);
for (
var i = 0;
!await File('${output.path}/capture-ready').exists() && i < 500;
i++
) {
await Future<void>.delayed(const Duration(milliseconds: 10));
}
if (!await File('${output.path}/capture-ready').exists()) {
await capture.stop();
throw StateError('Capture not ready');
}
return capture;
}
Future<void> stop() async {
await File('${output.path}/capture-stop').writeAsString('stop');
try {
final code = await process.exitCode.timeout(const Duration(seconds: 10));
if (code != 0) throw StateError('Capture exit $code');
} on TimeoutException {
process.kill();
rethrow;
}
}
}
@@ -0,0 +1,89 @@
/// Explicit inputs for the opt-in full-editor benchmark.
class ViewportBenchConfig {
ViewportBenchConfig.fromEnvironment(Map<String, String> environment)
: outputPath = environment['CUTDEX_FULL_APP_VIEWPORT_BENCH']!,
startGate = environment['CUTDEX_FULL_APP_VIEWPORT_START_GATE'],
expectedFrames = _number(environment, 'EXPECTED_FRAMES'),
rounds = _integer(environment, 'ROUNDS', 5),
paired = _flag(environment, 'PAIRED', false),
silent = _flag(environment, 'SILENT', false),
nativeOnly = _flag(environment, 'NATIVE_ONLY', true),
captureHelper = environment['CUTDEX_FULL_APP_VIEWPORT_CAPTURE_HELPER'],
timelineFps = _integer(environment, 'TIMELINE_FPS', 30),
inputHz = _integer(environment, 'INPUT_HZ', 60),
inputCount = _integer(environment, 'INPUT_COUNT', 360),
localStartFrame = _optionalInteger(environment, 'LOCAL_START_FRAME'),
localSpanFrames = _integer(environment, 'LOCAL_SPAN_FRAMES', 20),
localPixelsPerFrame = _number(environment, 'LOCAL_PIXELS_PER_FRAME') ?? 4,
edgeMarginFrames = _integer(environment, 'EDGE_MARGIN_FRAMES', 900),
sampleIntervalMs = _integer(environment, 'SAMPLE_INTERVAL_MS', 16) {
if (outputPath.isEmpty ||
rounds < 1 ||
timelineFps < 1 ||
inputHz < 1 ||
inputCount < 6 ||
inputCount.isOdd ||
localSpanFrames < 1 ||
localPixelsPerFrame <= 0 ||
edgeMarginFrames < 1 ||
sampleIntervalMs < 1 ||
(expectedFrames != null && expectedFrames! <= 0)) {
throw ArgumentError('Invalid viewport benchmark configuration');
}
if (!nativeOnly && (captureHelper == null || captureHelper!.isEmpty)) {
throw ArgumentError('CAPTURE_HELPER is required when NATIVE_ONLY=0');
}
}
final String outputPath;
final String? startGate;
final double? expectedFrames;
final int rounds, timelineFps, inputHz, inputCount, localSpanFrames;
final int edgeMarginFrames, sampleIntervalMs;
final int? localStartFrame;
final double localPixelsPerFrame;
final bool paired, silent, nativeOnly;
final String? captureHelper;
Map<String, Object?> toJson() => {
'expectedFrames': expectedFrames,
'rounds': rounds,
'paired': paired,
'timelineFps': timelineFps,
'inputHz': inputHz,
'inputCount': inputCount,
'localStartFrame': localStartFrame,
'localSpanFrames': localSpanFrames,
'localPixelsPerFrame': localPixelsPerFrame,
'edgeMarginFrames': edgeMarginFrames,
'sampleIntervalMs': sampleIntervalMs,
'nativeOnly': nativeOnly,
'captureHelper': captureHelper,
'silent': silent,
};
static int _integer(Map<String, String> env, String key, int fallback) =>
_optionalInteger(env, key) ?? fallback;
static int? _optionalInteger(Map<String, String> env, String key) {
final value = env['CUTDEX_FULL_APP_VIEWPORT_$key'];
return value == null ? null : int.parse(value);
}
static double? _number(Map<String, String> env, String key) {
final value = env['CUTDEX_FULL_APP_VIEWPORT_$key'];
if (value == null) return null;
final number = double.parse(value);
if (!number.isFinite) throw ArgumentError('Non-finite $key');
return number;
}
static bool _flag(Map<String, String> env, String key, bool fallback) {
final value = env['CUTDEX_FULL_APP_VIEWPORT_$key'];
return switch (value) {
null => fallback,
'1' => true,
'0' => false,
_ => throw ArgumentError('$key must be 0 or 1'),
};
}
}
@@ -0,0 +1,70 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/services.dart';
/// Native QPC clock calibration and bounded asynchronous diagnostics sampling.
class BenchDiagnostics {
BenchDiagnostics(this.sessionId, this.clock);
final String sessionId;
final Stopwatch clock;
static const _channel = MethodChannel('cutdex_runtime');
double uncertaintyMs = double.infinity, _offset = 0;
Timer? _timer;
Future<void>? _pending;
Object? _sampleError;
double now() => _offset + clock.elapsedMicroseconds / 1000;
Future<Map<String, dynamic>> read() async =>
(await _channel.invokeMapMethod<String, dynamic>('previewDiagnostics', {
'sessionId': sessionId,
}))!;
Future<void> calibrate() async {
for (var i = 0; i < 20; i++) {
final begin = clock.elapsedMicroseconds / 1000;
final diagnostic = await read();
final end = clock.elapsedMicroseconds / 1000;
if (end - begin < uncertaintyMs) {
uncertaintyMs = end - begin;
_offset = (diagnostic['qpcMs'] as num).toDouble() - (begin + end) / 2;
}
}
}
Future<void> until(double due) async {
while (now() < due) {
await Future<void>.delayed(
Duration(microseconds: ((due - now()) * 1000).ceil().clamp(1, 1000000)),
);
}
}
void startSamples(IOSink sink, int intervalMs) {
_timer = Timer.periodic(Duration(milliseconds: intervalMs), (_) {
if (_pending != null || _sampleError != null) return;
_pending = _sample(sink).whenComplete(() => _pending = null);
});
}
Future<void> _sample(IOSink sink) async {
try {
sink.writeln(jsonEncode(await read()));
} catch (error) {
_sampleError = error;
}
}
void check() {
if (_sampleError != null) {
throw StateError('Native sampler failed: $_sampleError');
}
}
Future<void> stopSamples() async {
_timer?.cancel();
await _pending;
check();
}
}
@@ -0,0 +1,138 @@
import 'package:cutdex_sdk/timeline/model.dart';
import 'package:cutdex_sdk/timeline/layout.dart';
import 'package:cutdex_sdk/timeline_ui.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
/// Real playhead gesture input, quantized to physical pixels like desktop input.
class BenchPlayheadDrag {
BenchPlayheadDrag({
required this.view,
required this.ruler,
required this.viewport,
required this.scale,
required this.clock,
required this.pointer,
required this.warmFrame,
required this.fps,
}) : camera = view.camera;
final TimelineViewController view;
final RenderBox ruler;
final TimelineViewportRect viewport;
final TimelineCamera camera;
final double scale;
final Stopwatch clock;
final int pointer, warmFrame, fps;
Offset _position = Offset.zero, _origin = Offset.zero;
bool _active = false;
int tick(int frame) =>
TimelineClock.standard.toTicks(RationalTime(frame, fps));
double get _pixelsPerFrame => camera.pixelsPerTick * tick(1);
int _delta(int frame) =>
((frame - warmFrame) * _pixelsPerFrame * scale).round();
int target(int frame) =>
(warmFrame + _delta(frame) / (_pixelsPerFrame * scale)).round();
Future<void> begin() async {
final point = ruler.localToGlobal(
Offset(
camera.screenXForTick(tick(warmFrame), viewport),
ruler.size.height / 2,
),
);
_position = Offset(
(point.dx * scale).round() / scale,
(point.dy * scale).round() / scale,
);
GestureBinding.instance.handlePointerEvent(
PointerAddedEvent(
pointer: pointer,
device: 42,
kind: PointerDeviceKind.mouse,
position: _position,
),
);
GestureBinding.instance.handlePointerEvent(
PointerDownEvent(
pointer: pointer,
device: 42,
kind: PointerDeviceKind.mouse,
buttons: kPrimaryButton,
position: _position,
timeStamp: clock.elapsed,
),
);
_active = true;
_move(_position + const Offset(40, 0));
await Future<void>.delayed(const Duration(milliseconds: 20));
if (!view.isScrubbing || view.playheadTick != tick(warmFrame)) {
throw StateError('Playhead drag warmup failed');
}
_origin = _position;
}
void moveTo(int frame) {
_move(_origin + Offset(_delta(frame) / scale, 0));
if (!view.isScrubbing || view.playheadTick != tick(target(frame))) {
throw StateError('Real playhead mismatch at input frame $frame');
}
}
void _move(Offset next) {
GestureBinding.instance.handlePointerEvent(
PointerMoveEvent(
pointer: pointer,
device: 42,
kind: PointerDeviceKind.mouse,
buttons: kPrimaryButton,
position: next,
delta: next - _position,
timeStamp: clock.elapsed,
),
);
_position = next;
}
void end() {
GestureBinding.instance.handlePointerEvent(
PointerUpEvent(
pointer: pointer,
device: 42,
kind: PointerDeviceKind.mouse,
position: _position,
timeStamp: clock.elapsed,
),
);
_remove();
if (view.isScrubbing || !identical(camera, view.camera)) {
throw StateError('Release/camera failure');
}
}
void cancel() {
if (!_active) return;
GestureBinding.instance.handlePointerEvent(
PointerCancelEvent(
pointer: pointer,
device: 42,
kind: PointerDeviceKind.mouse,
position: _position,
timeStamp: clock.elapsed,
),
);
_remove();
}
void _remove() {
GestureBinding.instance.handlePointerEvent(
PointerRemovedEvent(
pointer: pointer,
device: 42,
kind: PointerDeviceKind.mouse,
position: _position,
),
);
_active = false;
}
}
@@ -0,0 +1,64 @@
import 'dart:convert';
import 'dart:io';
/// Owns benchmark output streams and metadata, preserving the existing CSV schema.
class BenchRecords {
BenchRecords(this.output)
: inputs = File('${output.path}/inputs.csv').openWrite(),
phases = File('${output.path}/phases.csv').openWrite(),
samples = File('${output.path}/native-samples.jsonl').openWrite() {
inputs.writeln(
'round,scenario,index,target,qpc_ms,scheduled_ms,request_ms',
);
phases.writeln(
'round,scenario,start_ms,end_ms,release_begin_ms,final_frame,final_clock_frame,freeze_begin_ms,freeze_end_ms',
);
}
final Directory output;
final IOSink inputs, phases, samples;
Future<void>? _closing;
final stages = <Map<String, Object?>>[], checks = <Map<String, Object?>>[];
void input(
int round,
int scenario,
int index,
int target,
double begin,
double due,
double returned,
) => inputs.writeln(
'$round,$scenario,$index,$target,$begin,$due,${returned - begin}',
);
void phase(
int round,
int scenario,
double start,
double end,
double release,
int finalFrame,
double actual,
double frozenBegin,
double frozenEnd,
) => phases.writeln(
'$round,$scenario,$start,$end,$release,$finalFrame,$actual,$frozenBegin,$frozenEnd',
);
Future<void> progress(int round) =>
File('${output.path}/progress.json')
.writeAsString(jsonEncode({'completedRounds': round}));
Future<void> complete(Map<String, Object?> metadata) =>
File('${output.path}/meta.json').writeAsString(
jsonEncode({
...metadata,
'nativeDiagnostics': stages,
'checks': checks,
}),
);
Future<void> close() => _closing ??= _close();
Future<void> _close() async {
await samples.close();
await inputs.close();
await phases.close();
}
}
@@ -0,0 +1,259 @@
import 'dart:async';
import 'dart:io';
import 'package:cutdex/features/preview/preview_panel.dart';
import 'package:cutdex_sdk/editor.dart';
import 'package:cutdex_sdk/runtime.dart';
import 'package:cutdex_sdk/timeline/model.dart';
import 'package:cutdex_sdk/timeline/layout.dart';
import 'package:cutdex_sdk/timeline_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'capture.dart';
import 'config.dart';
import 'diagnostics.dart';
import 'drag.dart';
import 'records.dart';
import 'workload.dart';
Future<void> _sleep(int ms) => Future<void>.delayed(Duration(milliseconds: ms));
/// Orchestrates existing editor state, real input, exact-stop validation and output.
Future<void> runFullAppViewportBench(ViewportBenchConfig config) async {
final output = Directory(config.outputPath);
final clock = Stopwatch()..start();
BenchCapture? capture;
BenchDiagnostics? diagnostics;
BenchRecords? records;
BenchPlayheadDrag? activeDrag;
await output.create(recursive: true);
try {
await _sleep(6000);
if (config.startGate case final gatePath?) {
final gate = File(gatePath);
for (var i = 0; !await gate.exists() && i < 240; i++) {
await _sleep(500);
}
if (!await gate.exists()) {
throw StateError('Benchmark start gate timed out');
}
}
Element? previewElement;
TimelineViewport? timeline;
RenderBox? ruler;
void visit(Element element) {
if (element.widget is EditorPreviewPanel) previewElement = element;
if (element.widget is TimelineViewport) {
timeline = element.widget as TimelineViewport;
}
if (element.widget is TimelineRuler) {
ruler = element.findRenderObject() as RenderBox?;
}
element.visitChildElements(visit);
}
WidgetsBinding.instance.rootElement!.visitChildElements(visit);
if (previewElement == null || timeline == null || ruler == null) {
throw StateError('Full normal editor is not open');
}
final panel = previewElement!.widget as EditorPreviewPanel;
final container = ProviderScope.containerOf(previewElement!);
final preview = container
.read(editorPreviewProvider(panel.projectId, panel.timelineId))
.asData
?.value;
if (preview?.session == null || preview!.error != null) {
throw StateError('Normal preview unavailable');
}
final sequence = preview.activeSequence()!;
final view = timeline!.controller;
final endTime = TimelineClock.standard.fromTicks(view.contentEndTick);
final endFrame =
endTime.numerator * config.timelineFps / endTime.denominator;
final workloads = ViewportBenchWorkload.forTimeline(config, endFrame);
view.fitTimeline();
await _sleep(500);
final viewport = TimelineViewportRect(
width: ruler!.size.width,
height: ruler!.size.height,
);
final scale = View.of(previewElement!).devicePixelRatio;
final clipStart = view.camera.screenXForTick(0, viewport);
final clipEnd = view.camera.screenXForTick(view.contentEndTick, viewport);
if (clipStart < 0 || clipEnd > viewport.width) {
throw StateError('Clip outside viewport');
}
final native = diagnostics = BenchDiagnostics(preview.session!.id, clock);
await native.calibrate();
capture = await BenchCapture.start(config, output);
final record = records = BenchRecords(output);
native.startSamples(record.samples, config.sampleIntervalMs);
int tick(int frame) =>
TimelineClock.standard.toTicks(RationalTime(frame, config.timelineFps));
for (var round = 1; round <= config.rounds; round++) {
for (final workload in workloads) {
final scenario = workload.scenario;
if (config.paired) {
if (workload.local) {
view.setCamera(
TimelineCamera(
baseTick: tick(workload.cameraBaseFrame),
pixelsPerTick: config.localPixelsPerFrame / tick(1),
verticalOffset: view.camera.verticalOffset,
),
);
} else {
view.fitTimeline();
}
await _sleep(100);
}
final warm = workload.warmFrame;
final drag = activeDrag = BenchPlayheadDrag(
view: view,
ruler: ruler!,
viewport: viewport,
scale: scale,
clock: clock,
pointer: 100 + round * 10 + scenario,
warmFrame: warm,
fps: config.timelineFps,
);
await preview.controlPreview(
sequence,
PreviewAction.seek,
at: CommandTime(warm, config.timelineFps),
);
await _sleep(80);
if (config.silent) {
await preview.session!.beginSkimming(mode: SkimmingMode.silent);
}
await drag.begin();
drag.moveTo(workload.idealFrame(0));
await _sleep(350);
final before = await native.read();
final start = native.now();
for (var i = 0; i < workload.count; i++) {
final due = start + 1000 * i / workload.hz;
await native.until(due);
final begin = native.now();
final ideal = workload.idealFrame(i);
drag.moveTo(ideal);
record.input(
round,
scenario,
i,
drag.target(ideal),
begin,
due,
native.now(),
);
}
await native.until(start + workload.durationMs);
final end = native.now();
final release = native.now();
drag.end();
activeDrag = null;
await preview.waitForPendingPreview();
final settled = await preview.session!.refresh();
final settledAt = native.now();
await _sleep(350);
final frozenBegin = native.now();
await _sleep(350);
final snapshot = await preview.session!.refresh();
final after = await native.read();
record.stages.add({
'round': round,
'scenario': scenario,
'before': before,
'after': after,
'settledAtMs': settledAt,
'settledClock':
'${settled.position.numerator}/${settled.position.denominator}',
});
final actual =
snapshot.position.numerator *
config.timelineFps /
snapshot.position.denominator;
final finalTarget = drag.target(
workload.idealFrame(workload.count - 1),
);
if ((actual - finalTarget).abs() > .01 || preview.error != null) {
throw StateError('Final precision failure $actual');
}
native.check();
record.checks.add({
'round': round,
'scenario': scenario,
'finalClockFrame': actual,
'target': finalTarget,
'state': snapshot.state.name,
});
record.phase(
round,
scenario,
start,
end,
release,
finalTarget,
actual,
frozenBegin,
native.now(),
);
}
await record.progress(round);
}
await capture?.stop();
capture = null;
await native.stopSamples();
await record.close();
await record.complete({
'status': 'passed',
'entrypoint': 'lib/main.dart',
'fullApp': true,
'startGateUsed': config.startGate != null,
'configuration': config.toJson(),
'projectId': panel.projectId,
'timelineId': panel.timelineId,
'sequenceId': sequence.value,
'timelineEndFramesAt30Hz': endFrame * 30 / config.timelineFps,
'firstSampleFrameAt30Hz':
config.edgeMarginFrames * 30 / config.timelineFps,
'lastSampleFrameAt30Hz':
(endFrame.round() - config.edgeMarginFrames - 1) *
30 /
config.timelineFps,
'clipStartX': clipStart,
'clipEndX': clipEnd,
'viewportWidth': viewport.width,
'devicePixelRatio': scale,
'qpcCalibrationRoundTripMs': native.uncertaintyMs,
'inputRoute': 'GestureBinding -> real normal TimelineViewport playhead handle -> production preview/runtime/native presenter',
'physicalPixelInput': true,
'rounds': config.rounds,
'pairedWideLocal': config.paired,
'nativeOnly': config.nativeOnly,
'silentOverride': config.silent,
'skimmingPolicy': preview.policy.skimmingMode.name,
'canvas': {
'width': preview.canvas.width,
'height': preview.canvas.height,
},
'timelineSettings': preview.timeline.settings,
});
// Leave the normal editor paused with the complete clip visible.
view.fitTimeline();
} finally {
activeDrag?.cancel();
try {
await capture?.stop();
} finally {
try {
await diagnostics?.stopSamples();
} finally {
await records?.close();
}
}
}
}
@@ -0,0 +1,96 @@
import 'config.dart';
/// A deterministic input sequence; independent of Flutter, decoding and sampling.
class ViewportBenchWorkload {
const ViewportBenchWorkload({
required this.scenario,
required this.hz,
required this.count,
required this.firstFrame,
required this.lastFrame,
required this.steps,
required this.paired,
required this.localSpanFrames,
required this.timelineEndFrame,
});
final int scenario, hz, count, firstFrame, lastFrame, steps, localSpanFrames;
final bool paired;
final double timelineEndFrame;
bool get local => paired && scenario == 1;
double get durationMs => 1000 * count / hz;
int get warmFrame => idealFrame(0) - 1;
int get cameraBaseFrame => firstFrame - 17;
int idealFrame(int i) {
if (local) {
final phase = i % (2 * localSpanFrames);
return firstFrame +
(phase <= localSpanFrames ? phase : 2 * localSpanFrames - phase);
}
if (paired) {
final half = count ~/ 2;
final phase = i % count;
final index = phase < half ? phase : count - 1 - phase;
return (timelineEndFrame * (.05 + .9 * index / (half - 1))).round();
}
final period = 2 * (steps - 1);
final phase = i % period;
final index = switch (scenario) {
0 => i,
1 => steps - 1 - i,
_ => phase < steps ? phase : period - phase,
};
return (firstFrame * (steps - 1) +
(lastFrame - firstFrame) * index +
(steps - 1) ~/ 2) ~/
(steps - 1);
}
static List<ViewportBenchWorkload> forTimeline(
ViewportBenchConfig config,
double endFrame,
) {
if (!endFrame.isFinite ||
endFrame < 2 * config.edgeMarginFrames + 2 ||
(config.expectedFrames != null &&
(endFrame - config.expectedFrames!).abs() > 2)) {
throw StateError('Unexpected normal timeline length: $endFrame');
}
final localStart = config.localStartFrame ?? (endFrame * .28).round();
if (config.paired &&
(localStart < 18 || localStart + config.localSpanFrames >= endFrame)) {
throw StateError('Local benchmark range falls outside the timeline');
}
final steps = config.inputCount ~/ 3;
return List.generate(config.paired ? 2 : 5, (scenario) {
final hz = config.paired
? config.inputHz
: config.inputHz * [1, 2, 1, 2, 4][scenario];
final count = config.paired
? config.inputCount
: [
steps,
steps,
config.inputCount,
config.inputCount * 2,
config.inputCount * 4,
][scenario];
return ViewportBenchWorkload(
scenario: scenario,
hz: hz,
count: count,
firstFrame: config.paired
? (scenario == 0 ? (endFrame * .05).round() : localStart)
: config.edgeMarginFrames,
lastFrame: config.paired
? (endFrame * .95).round()
: endFrame.round() - config.edgeMarginFrames - 1,
steps: steps,
paired: config.paired,
localSpanFrames: config.localSpanFrames,
timelineEndFrame: endFrame,
);
});
}
}
+220
View File
@@ -0,0 +1,220 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:cutdex_sdk/timeline/layout.dart';
import 'package:cutdex_sdk/timeline_ui.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
bool _replayActive = false;
/// Replays trackpad input through the normal full-app timeline hit-test path.
/// An independent opt-in trace can also record physical driver events.
void startTimelineGestureBenchFromEnvironment() {
final trace = Platform.environment['CUTDEX_TIMELINE_GESTURE_TRACE'];
if (trace != null && trace.isNotEmpty) {
final file = File(trace)..parent.createSync(recursive: true);
final sink = file.openWrite(mode: FileMode.append);
Timer.periodic(const Duration(seconds: 1), (_) => unawaited(sink.flush()));
GestureBinding.instance.pointerRouter.addGlobalRoute((event) {
if (event is! PointerPanZoomStartEvent &&
event is! PointerPanZoomUpdateEvent &&
event is! PointerPanZoomEndEvent &&
event is! PointerScrollEvent) {
return;
}
sink.writeln(
jsonEncode({
'at': DateTime.now().toUtc().toIso8601String(),
'type': event.runtimeType.toString(),
'source': _replayActive ? 'protocol-replay' : 'driver',
'device': event.device,
'kind': event.kind.name,
'control': HardwareKeyboard.instance.isControlPressed,
'meta': HardwareKeyboard.instance.isMetaPressed,
if (event is PointerPanZoomUpdateEvent) ...{
'pan': [event.pan.dx, event.pan.dy],
'scale': event.scale,
},
if (event is PointerScrollEvent)
'scroll': [event.scrollDelta.dx, event.scrollDelta.dy],
}),
);
});
}
final output = Platform.environment['CUTDEX_TIMELINE_GESTURE_BENCH'];
if (output == null || output.isEmpty) return;
unawaited(
_run(output).catchError((Object error, StackTrace stack) async {
await Directory(output).create(recursive: true);
await File('$output/error.txt').writeAsString('$error\n$stack');
}),
);
}
Element? _surface() {
Element? result;
void visit(Element element) {
if (element.widget case TimelineInteractionRegion(ruler: false)) {
result = element;
}
element.visitChildElements(visit);
}
WidgetsBinding.instance.rootElement?.visitChildElements(visit);
return result;
}
Future<void> _run(String output) async {
await Directory(output).create(recursive: true);
await Future<void>.delayed(const Duration(seconds: 6));
final element = _surface();
if (element == null) throw StateError('Normal timeline surface is not open');
if (HardwareKeyboard.instance.logicalKeysPressed.isNotEmpty) {
throw StateError('Release keyboard modifiers before replay');
}
final region = element.widget as TimelineInteractionRegion;
final c = region.controller;
final box = element.findRenderObject()! as RenderBox;
final viewport = TimelineViewportRect(
width: box.size.width,
height: box.size.height,
);
final position = box.localToGlobal(
Offset(box.size.width * .8, box.size.height * .5),
);
final saved = c.camera;
final playhead = c.playheadTick;
final version = c.version;
final x = saved.screenXForTick(playhead, viewport);
if (x < 0 || x > viewport.width) throw StateError('Playhead must be visible');
final rows = <Map<String, Object?>>[];
const device = 7200;
void send(PointerEvent event) =>
GestureBinding.instance.handlePointerEvent(event);
void start(int pointer) => send(
PointerPanZoomStartEvent(
pointer: pointer,
device: device,
position: position,
),
);
void update(int pointer, Offset pan, double scale) => send(
PointerPanZoomUpdateEvent(
pointer: pointer,
device: device,
position: position,
pan: pan,
scale: scale,
),
);
void end(int pointer) => send(
PointerPanZoomEndEvent(
pointer: pointer,
device: device,
position: position,
),
);
void record(String name, {bool anchor = true}) {
final drift = c.camera.screenXForTick(playhead, viewport) - x;
final unchanged =
c.playheadTick == playhead && identical(c.version, version);
rows.add({
'scenario': name,
'playheadPixelDrift': drift,
'scaleRatio': c.camera.pixelsPerTick / saved.pixelsPerTick,
'verticalDrift': c.camera.verticalOffset - saved.verticalOffset,
'timelineUnchanged': unchanged,
'cameraBaseTick': c.camera.baseTick,
'savedCameraBaseTick': saved.baseTick,
});
File('$output/progress.json').writeAsStringSync(jsonEncode(rows));
if (!unchanged || (anchor && drift.abs() > .001)) {
throw StateError('$name changed the timeline or moved the zoom anchor');
}
}
try {
_replayActive = true;
send(
PointerAddedEvent(
device: device,
kind: PointerDeviceKind.trackpad,
position: position,
),
);
start(7201);
update(7201, const Offset(50, 30), 1.2);
await Future<void>.delayed(const Duration(milliseconds: 16));
update(7201, const Offset(100, 60), 1.5);
await WidgetsBinding.instance.endOfFrame;
record('native-pinch-with-translation');
final pinchCamera = c.camera;
update(7201, const Offset(140, 90), 1.5);
await WidgetsBinding.instance.endOfFrame;
record('pinch-scale-pauses');
if (c.camera != pinchCamera) throw StateError('Pinch tail became a pan');
end(7201);
c.setCamera(saved);
HardwareKeyboard.instance.handleKeyEvent(
const KeyDownEvent(
physicalKey: PhysicalKeyboardKey.controlLeft,
logicalKey: LogicalKeyboardKey.controlLeft,
timeStamp: Duration.zero,
),
);
try {
send(
PointerScrollEvent(
position: position,
scrollDelta: const Offset(0, -120),
),
);
} finally {
HardwareKeyboard.instance.handleKeyEvent(
const KeyUpEvent(
physicalKey: PhysicalKeyboardKey.controlLeft,
logicalKey: LogicalKeyboardKey.controlLeft,
timeStamp: Duration(milliseconds: 1),
),
);
}
await WidgetsBinding.instance.endOfFrame;
record('control-scroll-zoom');
c.setCamera(saved);
start(7202);
update(7202, const Offset(-30, 0), 1);
await Future<void>.delayed(const Duration(milliseconds: 16));
update(7202, const Offset(-70, 0), 1);
await WidgetsBinding.instance.endOfFrame;
record('plain-two-finger-pan', anchor: false);
end(7202);
if ((c.camera.screenXForTick(playhead, viewport) - x).abs() < 1 ||
c.camera.pixelsPerTick != saved.pixelsPerTick) {
throw StateError('Ordinary pan stopped working');
}
await File('$output/results.json').writeAsString(
jsonEncode({
'inputRoute':
'GestureBinding -> normal full-app TimelineInteractionRegion',
'inputKind': 'synthetic driver-protocol replay; not physical fingers',
'playheadTick': playhead,
'playheadScreenX': x,
'rows': rows,
}),
);
} finally {
send(
PointerRemovedEvent(
device: device,
kind: PointerDeviceKind.trackpad,
position: position,
),
);
c.setCamera(saved);
_replayActive = false;
}
await File('$output/done.json').writeAsString(jsonEncode({'complete': true}));
}
+311
View File
@@ -0,0 +1,311 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../features/editor/editor_page.dart';
import '../features/preview/preview_panel.dart';
import '../workspace/timeline_provider.dart';
import '../workspace/projects.dart';
import '../workspace/project_state.dart';
import '../workspace/preview_controller_registry.dart';
import 'full_app_viewport_bench/diagnostics.dart';
import 'app_diagnostics.dart';
/// Opt-in measurements through normal timeline tabs in the complete application.
void startTimelineSwitchBenchFromEnvironment() {
final output = Platform.environment['CUTDEX_TIMELINE_SWITCH_BENCH'];
if (output == null || output.isEmpty) return;
unawaited(
_run(output).catchError((Object error, StackTrace stack) async {
await Directory(output).create(recursive: true);
await File('$output/error.txt').writeAsString('$error\n$stack');
}),
);
}
Element? _find(bool Function(Widget) matches) {
Element? result;
void visit(Element element) {
if (matches(element.widget)) result = element;
element.visitChildElements(visit);
}
WidgetsBinding.instance.rootElement?.visitChildElements(visit);
return result;
}
Future<void> _run(String output) async {
await Directory(output).create(recursive: true);
final gate = Platform.environment['CUTDEX_TIMELINE_SWITCH_GATE'];
await Future<void>.delayed(const Duration(seconds: 6));
if (gate != null) {
for (var i = 0; !await File(gate).exists() && i < 600; i++) {
await Future<void>.delayed(const Duration(milliseconds: 200));
}
if (!await File(gate).exists()) throw StateError('Start gate timed out');
}
final element = _find((widget) => widget is EditorWorkspace);
if (element == null) throw StateError('Normal editor is not open');
final container = ProviderScope.containerOf(element);
final initial = container.read(projectsProvider).requireValue;
final projectId = initial.activeProject!.id;
final target =
Platform.environment['CUTDEX_TIMELINE_SWITCH_TARGET'] ??
initial.timelines.firstWhere((t) => t.id != initial.timeline!.id).id;
if (initial.timeline!.id == target) throw StateError('Target already active');
final initialSession = container
.read(projectsProvider.notifier)
.cachedTimelineSession(projectId, initial.timeline!.id)!;
final initialSequence = initialSession.activeSequenceId;
File('$output/startup.json').writeAsStringSync(
jsonEncode({
'initialTimelineId': initial.timeline!.id,
'editorError': container
.read(editorTimelineProvider(projectId, initial.timeline!.id))
.error
?.toString(),
'previewError': container
.read(editorPreviewProvider(projectId, initial.timeline!.id))
.error
?.toString(),
'diagnosticsDirectory': AppDiagnostics.instance?.store.directory.path,
}),
);
if (initialSequence != null &&
initialSession.sequenceDurationTicks(initialSequence) > 0) {
var ready = false;
for (var i = 0; i < 3000; i++) {
final editing = container.read(
editorTimelineProvider(projectId, initial.timeline!.id),
);
if (editing.hasError) {
throw StateError(
'Initial editor failed: ${editing.error}\n${editing.stackTrace}',
);
}
final previewState = container.read(
editorPreviewProvider(projectId, initial.timeline!.id),
);
if (previewState.hasError) {
throw StateError(
'Initial preview failed: ${previewState.error}\n${previewState.stackTrace}',
);
}
final preview = container.read(previewControllerRegistryProvider).cached((
projectId,
initial.timeline!.id,
));
if (preview?.session != null) {
ready = true;
break;
}
await Future<void>.delayed(const Duration(milliseconds: 20));
}
if (!ready) throw StateError('Initial preview is not ready');
}
final rows = <Map<String, Object?>>[];
var pointer = 500;
void tap(String id, Stopwatch clock) {
final button = _find(
(widget) => widget.key == ValueKey('timeline-tab-$id'),
);
final box = button?.findRenderObject() as RenderBox?;
if (box == null || !box.hasSize) throw StateError('Tab not laid out: $id');
final position = box.localToGlobal(box.size.center(Offset.zero));
final input = ++pointer;
GestureBinding.instance.handlePointerEvent(
PointerAddedEvent(
pointer: input,
device: 51,
kind: PointerDeviceKind.mouse,
position: position,
),
);
GestureBinding.instance.handlePointerEvent(
PointerDownEvent(
pointer: input,
device: 51,
kind: PointerDeviceKind.mouse,
buttons: kPrimaryButton,
position: position,
timeStamp: clock.elapsed,
),
);
GestureBinding.instance.handlePointerEvent(
PointerUpEvent(
pointer: input,
device: 51,
kind: PointerDeviceKind.mouse,
position: position,
timeStamp: clock.elapsed,
),
);
GestureBinding.instance.handlePointerEvent(
PointerRemovedEvent(
pointer: input,
device: 51,
kind: PointerDeviceKind.mouse,
position: position,
),
);
}
Future<void> measure(String id, String scenario) async {
final cached =
container
.read(projectsProvider.notifier)
.cachedTimelineSession(projectId, id) !=
null;
final clock = Stopwatch()..start();
double? dataMs, uiMs, firstFrameObservedMs;
final subscription = container.listen(projectsProvider, (_, next) {
if (next.value?.timeline?.id == id &&
next.value?.openingTimelineId == null) {
dataMs ??= clock.elapsedMicroseconds / 1000;
}
});
void observeFrame(Duration _) {
final workspace =
_find((w) => w is EditorWorkspace)?.widget as EditorWorkspace?;
if (workspace?.timelineId == id) {
uiMs ??= clock.elapsedMicroseconds / 1000;
}
if (uiMs == null && clock.elapsedMilliseconds < 60000) {
SchedulerBinding.instance.addPostFrameCallback(observeFrame);
SchedulerBinding.instance.scheduleFrame();
}
}
SchedulerBinding.instance.addPostFrameCallback(observeFrame);
tap(id, clock);
try {
for (var i = 0; i < 3000; i++) {
final preview = container
.read(previewControllerRegistryProvider)
.cached((projectId, id));
if (preview?.session != null && uiMs != null && dataMs != null) {
final diagnostic = await BenchDiagnostics(
preview!.session!.id,
clock,
).read().timeout(const Duration(seconds: 2));
if ((diagnostic['sourceSubmitted'] as num?) != null &&
(diagnostic['sourceSubmitted'] as num) > 0 &&
(diagnostic['presented'] as num?) != null &&
(diagnostic['presented'] as num) > 0) {
firstFrameObservedMs = clock.elapsedMicroseconds / 1000;
break;
}
}
await Future<void>.delayed(const Duration(milliseconds: 20));
}
if (uiMs == null || dataMs == null) {
throw StateError('Switch timed out: $scenario');
}
if (firstFrameObservedMs == null) {
final previewState = container.read(
editorPreviewProvider(projectId, id),
);
throw StateError(
'Native frame timed out: $scenario; ${previewState.error}\n${previewState.stackTrace}',
);
}
rows.add({
'scenario': scenario,
'timelineId': id,
'sessionCachedBeforeClick': cached,
'clickToUiPostFrameMs': uiMs,
'clickToDataMs': dataMs,
'clickToNativeFrameObservedMs': firstFrameObservedMs,
});
await File('$output/results.json').writeAsString(
jsonEncode({
'projectId': projectId,
'initialTimelineId': initial.timeline!.id,
'inputRoute':
'GestureBinding -> real timeline TextButton -> Projects',
'uiClock': 'Stopwatch until target EditorWorkspace post-frame',
'nativeClock':
'20 ms polling; cached frames are reuse, not new decode',
'rows': rows,
}),
);
} finally {
subscription.close();
}
}
if (Platform.environment['CUTDEX_TIMELINE_SWITCH_RAPID'] == '1') {
final third = initial.timelines
.firstWhere((t) => t.id != target && t.id != initial.timeline!.id)
.id;
final clock = Stopwatch()..start();
final inputs = <Map<String, Object?>>[];
final states = <Map<String, Object?>>[];
var latest = initial.timeline!.id;
final subscription = container.listen(projectsProvider, (_, next) {
final value = next.value!;
states.add({
'ms': clock.elapsedMicroseconds / 1000,
'latestInput': latest,
'visible': value.visibleTimelineId,
'loaded': value.timeline?.id,
'pending': value.openingTimelineId,
'error': value.error?.toString(),
});
});
try {
for (final id in [
target,
initial.timeline!.id,
third,
initial.timeline!.id,
target,
]) {
latest = id;
inputs.add({'ms': clock.elapsedMicroseconds / 1000, 'timelineId': id});
tap(id, clock);
await Future<void>.delayed(const Duration(milliseconds: 16));
}
await Future<void>.delayed(const Duration(seconds: 5));
final finalState = container.read(projectsProvider).requireValue;
if (finalState.timeline?.id != target ||
finalState.openingTimelineId != null ||
finalState.error != null ||
states.any((s) => s['visible'] != s['latestInput'])) {
throw StateError(
'Rapid navigation did not preserve the latest request',
);
}
await File('$output/rapid.json').writeAsString(
jsonEncode({
'inputRoute': 'GestureBinding -> real timeline tabs',
'inputs': inputs,
'states': states,
'finalTimelineId': finalState.timeline!.id,
'latestWins': true,
'stabilityWindowMs': 5000,
}),
);
await File('$output/done.json')
.writeAsString(jsonEncode({'complete': true}));
return;
} finally {
subscription.close();
}
}
await measure(target, 'cold-target');
for (var round = 1; round <= 3; round++) {
await Future<void>.delayed(const Duration(milliseconds: 200));
await measure(initial.timeline!.id, 'warm-return-$round');
await Future<void>.delayed(const Duration(milliseconds: 200));
await measure(target, 'warm-target-$round');
}
await File('$output/done.json').writeAsString(jsonEncode({'complete': true}));
}
+1
View File
@@ -18,6 +18,7 @@ enum AppErrorCode {
openMatchingProject,
openTimelineFailed,
projectMismatch,
projectAlreadyExists,
openProjectFirst,
localFilesOnly,
foldersUnsupported,
@@ -3,6 +3,7 @@ import 'package:flutter/material.dart';
import '../media/media_asset_cover.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import '../media/audio_asset_tile.dart';
@@ -25,13 +26,13 @@ class AgentAttachmentCard extends StatelessWidget {
fit: BoxFit.cover,
fallback: Center(
child: Icon(
kind == 'image' ? Icons.image_outlined : Icons.movie_outlined,
kind == 'image' ? AppIcons.image : AppIcons.video,
color: colors.onSurfaceVariant,
),
),
errorFallback: Center(
child: Icon(
Icons.broken_image_outlined,
AppIcons.imageUnavailable,
color: colors.onSurfaceVariant,
),
),
@@ -42,12 +43,7 @@ class AgentAttachmentCard extends StatelessWidget {
showName: false,
aspectRatio: 132 / 96,
),
_ => Center(
child: Icon(
Icons.insert_drive_file_outlined,
color: colors.onSurfaceVariant,
),
),
_ => Center(child: Icon(AppIcons.file, color: colors.onSurfaceVariant)),
};
return SizedBox(
width: 132,
@@ -93,7 +89,7 @@ class AgentAttachmentCard extends StatelessWidget {
backgroundColor: colors.surface,
foregroundColor: colors.onSurface,
),
icon: const Icon(Icons.close, size: 13),
icon: const Icon(AppIcons.close, size: 13),
),
),
],
@@ -0,0 +1,127 @@
import 'package:flutter/widgets.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../integrations/platform/platform_capabilities.dart';
import '../../integrations/platform/native_project_drop_region.dart';
import '../../integrations/platform/native_file_drop_policy.dart';
import '../../workspace/projects.dart';
import '../../workspace/media_import.dart';
import '../../workspace/external_media_import.dart';
import '../../shared/widgets/drop_to_add_overlay.dart';
import '../media/media_asset_drag.dart';
import 'agent_composer_controller.dart';
/// Shared attachment drop handling for docked and floating chat presentations.
class AgentAttachmentDropRegion extends ConsumerStatefulWidget {
const AgentAttachmentDropRegion({
super.key,
required this.projectId,
required this.composer,
required this.child,
this.shrinkWrap = false,
});
final String? projectId;
final AgentComposerController composer;
final Widget child;
final bool shrinkWrap;
@override
ConsumerState<AgentAttachmentDropRegion> createState() =>
_AgentAttachmentDropRegionState();
}
class _AgentAttachmentDropRegionState
extends ConsumerState<AgentAttachmentDropRegion> {
bool _hovering = false;
bool _canAttach(MediaAssetDrag drag) {
final workspace = ref.read(projectsProvider).value;
return widget.projectId == drag.projectId &&
workspace?.activeProject?.id == drag.projectId &&
!widget.composer.attachments.any((item) => item.id == drag.assetId) &&
workspace!.assets.any((asset) => asset.id == drag.assetId);
}
bool _canAttachFiles(List<ExternalMediaFile> files) {
if (files.isEmpty) return true;
final assets = ref.read(projectsProvider).value?.assets;
if (assets == null) return false;
final ids = {for (final item in widget.composer.attachments) item.id};
final locations = {
for (final asset in assets)
if (ids.contains(asset.id)) ?mediaSourceLocation(asset),
};
return files.any((file) => !locations.contains(file.sourceUri.toString()));
}
@override
Widget build(BuildContext context) {
final workspace = ref.watch(
projectsProvider.select(
(value) => value.value?.copyWith(
recent: const [],
timelines: const [],
error: null,
creatingTimeline: false,
),
),
);
final native = ref.watch(platformCapabilitiesProvider).nativeFileDrop;
final importing =
widget.composer.busy ||
widget.projectId != null &&
ref.watch(
externalMediaImportProvider(widget.projectId!)
.select((value) => value.isLoading),
);
final internal = DragTarget<MediaAssetDrag>(
key: const Key('agent-panel-drop-target'),
onWillAcceptWithDetails: (details) => _canAttach(details.data),
onAcceptWithDetails: (details) {
if (_canAttach(details.data)) {
widget.composer.attach(
ref
.read(projectsProvider)
.value!
.assets
.firstWhere((asset) => asset.id == details.data.assetId),
);
}
},
builder: (context, candidates, _) => Stack(
fit: widget.shrinkWrap ? StackFit.loose : StackFit.expand,
children: [
widget.child,
if (candidates.isNotEmpty || _hovering)
const Positioned.fill(
child: DropToAddOverlay(key: Key('agent-drop-overlay')),
),
],
),
);
if (!native) return internal;
return NativeProjectDropRegion(
regionId: 'attachments',
policy: NativeFileDropPolicy.attachments,
enabled:
widget.projectId != null &&
workspace?.activeProject?.id == widget.projectId &&
(workspace?.projectBusy == false || importing),
onEnter: (files) {
if (!importing && _canAttachFiles(files)) {
setState(() => _hovering = true);
}
},
onExit: () {
if (mounted && _hovering) setState(() => _hovering = false);
},
onDrop: (files) async {
setState(() => _hovering = false);
try {
await widget.composer.importAttachments(files);
} catch (_) {
/* Shared composer publishes import feedback. */
}
},
child: internal,
);
}
}
@@ -0,0 +1,41 @@
import 'package:flutter/widgets.dart';
import '../../l10n/l10n.dart';
import 'chat_state.dart';
import 'agent_composer_controller.dart';
import 'composer_document.dart';
import 'agent_message_codec.dart';
/// Consume one draft after the shared chat controller's send preconditions pass.
String takeAgentDraft(
ComposerDocumentController input,
AgentComposerController composer,
) {
final text = AgentComposerMessage.encodeDocument(
input.segments,
composer.attachments,
);
input.clearDocument();
composer.clear();
return text;
}
String agentChatErrorMessage(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,
};
+67 -188
View File
@@ -1,3 +1,5 @@
import 'agent_reply_region.dart';
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import '../../shared/layout/composer_layout.dart';
@@ -9,6 +11,8 @@ import 'package:cutdex_sdk/project.dart';
import '../../integrations/platform/platform_capabilities.dart';
import 'agent_composer_controller.dart';
import 'agent_attachment_drop_region.dart';
import 'agent_chat_actions.dart';
import 'agent_composer_store.dart';
import 'package:flutter/material.dart';
@@ -16,21 +20,17 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../integrations/agent/agent_provider.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import '../../shared/widgets/drop_to_add_overlay.dart';
import '../settings/settings_page.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';
@@ -97,8 +97,7 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
'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 _usingDraftModel => _composer.usingDraftModel;
bool get _importingAttachments =>
_composer.busy ||
widget.projectId != null &&
@@ -143,33 +142,12 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
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();
@@ -189,41 +167,6 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
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<ExternalMediaFile> 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<void> _dropExternalFiles(List<ExternalMediaFile> files) async {
setState(() => _dropHovering = false);
try {
await _composer.importAttachments(files);
} catch (_) {
// Feedback belongs to the composer even if this panel is hidden.
}
}
Future<void> _pickAttachments() async {
try {
await _composer.pickAttachments();
@@ -232,64 +175,27 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
}
}
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<MediaAssetDrag>(
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));
ref.watch(
settingsOperationProvider(_modelOperation)
.select((value) => value.isLoading),
);
if (widget.projectId != null) {
ref.watch(externalMediaImportProvider(widget.projectId!));
ref.watch(
externalMediaImportProvider(widget.projectId!)
.select((value) => value.isLoading),
);
}
final workspace = ref.watch(projectsProvider).asData?.value;
final workspace = ref.watch(
projectsProvider.select(
(value) => value.asData?.value.copyWith(
recent: const [],
error: null,
creatingTimeline: false,
),
),
);
final referenceValidator = ComposerReferenceValidator(
workspace: workspace,
projectId: widget.projectId,
@@ -305,7 +211,9 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
draftKey: widget.draftKey,
)
: null;
final state = provider == null ? const ChatState() : ref.watch(provider);
final state = provider == null
? const ChatState()
: ref.watch(provider.select(chatChrome));
final settings = ref.watch(agentSettingsProvider).asData?.value;
final available =
settings?.providers
@@ -360,7 +268,7 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
});
if (!mounted || !context.mounted) return;
if (saved) {
setState(() => _usingDraftModel = true);
_composer.useDraftModel();
} else {
ErrorNotificationHost.of(context).show(
ErrorNotification(
@@ -379,7 +287,7 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
key: const Key('agent-configure-model'),
style: compactButtonStyle,
onPressed: () => showSettingsPage(context, initialTab: 1),
icon: const Icon(Icons.tune, size: 16),
icon: const Icon(AppIcons.tune, size: 16),
label: Text(context.l10n.agentConfigureModel),
);
}
@@ -423,14 +331,14 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
),
),
const SizedBox(width: 4),
const Icon(Icons.expand_more, size: 14),
const Icon(AppIcons.expandMore, size: 14),
],
),
),
);
}
if (provider != null) {
if (provider != null && TickerMode.valuesOf(context).enabled) {
ref.listen(provider, (previous, next) {
if (_follow) {
WidgetsBinding.instance.addPostFrameCallback((_) {
@@ -453,12 +361,7 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
(_input.text.trim().isEmpty && _attachments.isEmpty)) {
return;
}
final text = AgentComposerMessage.encodeDocument(
_input.segments,
_attachments,
);
_input.clearDocument();
_composer.clear();
final text = takeAgentDraft(_input, _composer);
_follow = true;
ref
.read(provider.notifier)
@@ -471,8 +374,10 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
}
final theme = Theme.of(context);
final content = _agentDropRegion(
LayoutBuilder(
final content = AgentAttachmentDropRegion(
projectId: widget.projectId,
composer: _composer,
child: LayoutBuilder(
builder: (context, constraints) {
final panelWidth =
(constraints.maxWidth - ComposerLayout.horizontalInset * 2)
@@ -562,8 +467,8 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
),
),
Icon(
Icons
.chevron_right,
AppIcons
.chevronRight,
size: 14,
color:
AppTheme.chatMetaTextStyle(
@@ -575,7 +480,6 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
),
Divider(
height: 1,
thickness: 1,
color:
theme.dividerColor,
),
@@ -640,10 +544,13 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
in AgentComposerMessage.decode(
message.text,
).attachments)
if (ref
.watch(
projectsProvider,
)
Consumer(
builder: (context, ref, _) {
final asset = ref.watch(
projectsProvider.select(
(
value,
) => value
.asData
?.value
.assets
@@ -654,17 +561,21 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
asset.id ==
attachment.id,
)
.firstOrNull
case final asset?)
AgentAttachmentCard(
asset: asset,
)
else
Chip(
label: Text(
attachment
.name,
.firstOrNull,
),
);
return asset ==
null
? Chip(
label: Text(
attachment.name,
),
)
: AgentAttachmentCard(
asset:
asset,
);
},
),
],
),
@@ -681,44 +592,12 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
],
),
),
if (state.busy) ...[
if (state
.partialResponse
.isNotEmpty)
SelectableText(
state.partialResponse,
style:
AppTheme.chatMessageTextStyle(
context,
AgentReplyRegion(
projectId: widget.projectId,
conversationId:
widget.conversationId,
draftKey: widget.draftKey,
),
),
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,
),
],
],
),
),
@@ -751,7 +630,7 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
horizontal: AppSpacing.compact,
),
child: Text(
_errorMessage(context, error),
agentChatErrorMessage(context, error),
style: theme.textTheme.bodySmall,
),
),
@@ -1045,7 +924,7 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
? _pickAttachments
: null,
icon: const Icon(
Icons.add,
AppIcons.add,
),
),
const SizedBox(
@@ -1085,7 +964,7 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
)
.stop,
icon: const Icon(
Icons.stop,
AppIcons.stop,
),
)
else
@@ -1120,7 +999,7 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
? send
: null,
icon: const Icon(
Icons.arrow_upward,
AppIcons.arrowUp,
),
),
),
@@ -22,6 +22,14 @@ class AgentComposerController extends ChangeNotifier {
final List<AgentMediaAttachment> attachments;
final feedback = MediaImportFeedbackController();
bool _busy = false;
bool _usingDraftModel = false;
bool get usingDraftModel => _usingDraftModel;
void useDraftModel() {
if (_disposed) return;
_usingDraftModel = true;
notifyListeners();
}
bool _disposed = false;
bool get busy => _busy;
@@ -37,12 +37,24 @@ final class AgentComposerStore {
final AgentComposerController Function(String?) createComposer;
ComposerDocumentController _draft = ComposerDocumentController();
ComposerDocumentController get draft => _draft;
final _projectDrafts = <String?, ComposerDocumentController>{};
final _inputs = <(String?, String), ComposerDocumentController>{};
final _composers = <(String?, String), AgentComposerController>{};
ComposerDocumentController input(String? projectId, String? conversationId) =>
conversationId == null
? draft
ComposerDocumentController input(
String? projectId,
String? conversationId, {
bool projectScoped = false,
}) => conversationId == null
? projectScoped
? _projectDrafts.putIfAbsent(
projectId,
() => projectId == null
? ComposerDocumentController()
: _projectDrafts.remove(null) ??
ComposerDocumentController(),
)
: draft
: _inputs.putIfAbsent((
projectId,
conversationId,
@@ -57,8 +69,9 @@ final class AgentComposerStore {
void promoteDraft(String projectId, String draftKey, String conversationId) {
final destination = (projectId, conversationId);
_inputs.remove(destination)?.dispose();
_inputs[destination] = _draft;
_draft = ComposerDocumentController();
final scoped = _projectDrafts.remove(projectId);
_inputs[destination] = scoped ?? _draft;
if (scoped == null) _draft = ComposerDocumentController();
final composer = _composers.remove((projectId, draftKey));
if (composer != null) {
_composers.remove(destination)?.dispose();
@@ -77,6 +90,10 @@ final class AgentComposerStore {
void dispose() {
draft.dispose();
for (final input in _projectDrafts.values) {
input.dispose();
}
_projectDrafts.clear();
for (final input in _inputs.values) {
input.dispose();
}
@@ -0,0 +1,26 @@
import 'package:flutter/widgets.dart';
class AgentPanelPresentation extends InheritedWidget {
const AgentPanelPresentation({
super.key,
required this.compact,
this.expanded = false,
this.onToggleExpanded,
this.onDock,
required super.child,
});
final bool compact;
final bool expanded;
final VoidCallback? onToggleExpanded;
final VoidCallback? onDock;
static AgentPanelPresentation? of(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<AgentPanelPresentation>();
static bool compactOf(BuildContext context) =>
context
.dependOnInheritedWidgetOfExactType<AgentPanelPresentation>()
?.compact ??
false;
@override
bool updateShouldNotify(AgentPanelPresentation oldWidget) =>
compact != oldWidget.compact || expanded != oldWidget.expanded;
}
@@ -0,0 +1,70 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:cutdex_ui/theme.dart';
import '../../l10n/l10n.dart';
import 'chat_controller.dart';
import 'chat_state.dart';
/// Streaming output observes its conversation independently of history/composer.
class AgentReplyRegion extends ConsumerWidget {
const AgentReplyRegion({
super.key,
required this.projectId,
this.conversationId,
this.draftKey,
});
final String? projectId;
final String? conversationId;
final String? draftKey;
@override
Widget build(BuildContext context, WidgetRef ref) {
if (projectId == null) return const SizedBox.shrink();
final provider =
chatControllerProvider(
projectId!,
conversationId: conversationId,
draftKey: draftKey,
).select(
(state) => (
state.busy,
state.partialResponse,
state.stopping,
state.activity,
),
);
final state = TickerMode.valuesOf(context).enabled
? ref.watch(provider)
: ref.read(provider);
if (!state.$1) return const SizedBox.shrink();
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (state.$2.isNotEmpty)
SelectionArea(
child: Text(
state.$2,
style: AppTheme.chatMessageTextStyle(context),
),
),
Text(
state.$3
? context.l10n.stopping
: switch (state.$4) {
AgentChatActivity.compacting => context.l10n.agentCompacting,
AgentChatActivity.editing => context.l10n.agentEditing,
AgentChatActivity.verifying => context.l10n.agentVerifying,
AgentChatActivity.replying => context.l10n.replying,
},
style: Theme.of(context).textTheme.bodySmall,
),
],
);
}
}
/// Stable chrome/history snapshot; each streamed token belongs to reply region.
ChatState chatChrome(ChatState state) =>
state.copyWith(partialResponse: '', activity: AgentChatActivity.replying);
@@ -1,6 +1,7 @@
import 'package:flutter/material.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
part 'composer_document.freezed.dart';
@@ -322,8 +323,8 @@ class ComposerDocumentController extends TextEditingController {
padding: const EdgeInsets.only(right: 4),
child: Icon(
mark.reference.kind == ComposerReferenceKind.timeline
? Icons.view_timeline_outlined
: Icons.attach_file,
? AppIcons.timeline
: AppIcons.attachment,
size: 14,
color: color,
),
@@ -4,6 +4,7 @@ import '../../l10n/l10n.dart';
import '../../shared/layout/composer_layout.dart';
import '../../shared/theme/composer_style.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import '../../workspace/project_state.dart';
@@ -72,7 +73,7 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
if (selected == true) ...[
const SizedBox(width: ComposerLayout.menuIconGap),
Icon(
Icons.check,
AppIcons.check,
size: ComposerLayout.menuIconSize,
color: colors.onSurfaceVariant,
),
@@ -85,10 +86,7 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
Widget _separator() => const Padding(
padding: AppComposerStyle.menuSeparatorPadding,
child: Divider(
height: 1,
thickness: AppComposerStyle.menuSeparatorThickness,
),
child: Divider(height: 1),
);
@override
@@ -141,6 +139,8 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
controller: _search,
autofocus: true,
style: AppTheme.composerTextStyle(context),
cursorHeight: AppTheme.composerCursorHeight(context),
textAlignVertical: TextAlignVertical.center,
onChanged: (_) => setState(() {}),
decoration: AppComposerStyle.projectSearchDecoration(
context,
@@ -169,7 +169,7 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
_item(
key: ValueKey('composer-project-${project.id}'),
label: project.name,
icon: Icons.folder_outlined,
icon: AppIcons.folder,
selected: project.id == widget.selected?.id,
onPressed:
widget.busy || !project.availability.canOpen
@@ -188,7 +188,7 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
key: const Key('composer-new-project'),
secondary: true,
label: context.l10n.newProject,
icon: Icons.add,
icon: AppIcons.add,
onPressed: widget.busy || widget.onCreate == null
? null
: () {
@@ -209,7 +209,7 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
: controller.open(),
style: AppComposerStyle.projectTrigger(context),
icon: const Icon(
Icons.folder_outlined,
AppIcons.folder,
size: ComposerLayout.menuIconSize,
),
label: Text(
@@ -1,5 +1,6 @@
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:cutdex_sdk/project.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:flutter/material.dart';
import '../../l10n/app_localizations.dart';
@@ -62,10 +63,10 @@ abstract final class ComposerOptionCatalog {
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,
'video' => AppIcons.video,
'audio' => AppIcons.audio,
'image' => AppIcons.image,
_ => AppIcons.file,
},
group: ComposerOptionGroup.media,
reference: ComposerReference(
@@ -80,7 +81,7 @@ abstract final class ComposerOptionCatalog {
trigger: '@',
title: timeline.name,
subtitle: l10n.timelines,
icon: Icons.view_timeline_outlined,
icon: AppIcons.timeline,
group: ComposerOptionGroup.timeline,
reference: ComposerReference(
kind: ComposerReferenceKind.timeline,
@@ -0,0 +1,792 @@
import 'agent_reply_region.dart';
import '../../workspace/projects.dart';
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import '../../shared/layout/composer_layout.dart';
import '../../shared/theme/composer_style.dart';
import '../../shared/widgets/workspace_resize_handle.dart';
import '../../l10n/l10n.dart';
import '../../workspace/project_state.dart';
import '../../workspace/external_media_import.dart';
import '../../integrations/agent/agent_provider.dart';
import '../../integrations/agent/conversation_repository.dart';
import '../projects/conversation_sidebar.dart';
import '../media/media_browser_feedback.dart';
import '../settings/settings_page.dart';
import '../../settings/settings_operation.dart';
import '../../shared/widgets/error_notification_host.dart';
import 'agent_chat_actions.dart';
import 'agent_attachment_card.dart';
import 'agent_attachment_drop_region.dart';
import 'agent_composer_controller.dart';
import 'agent_message_codec.dart';
import 'breakable_selectable_text.dart';
import 'chat_controller.dart';
import 'chat_state.dart';
import 'composer_document.dart';
import 'composer_reference_validator.dart';
import 'composer_suggestion_surface.dart';
/// Independent floating presentation of the same conversation and draft stores.
class FloatingAgentPanel extends ConsumerStatefulWidget {
const FloatingAgentPanel({
super.key,
required this.state,
required this.selection,
required this.input,
required this.composer,
required this.expanded,
required this.onToggleExpanded,
required this.onDock,
required this.onConversationCreated,
required this.onConversationUpdated,
});
final ProjectState state;
final ConversationSelectionState selection;
final ComposerDocumentController input;
final AgentComposerController composer;
final bool expanded;
final VoidCallback onToggleExpanded;
final VoidCallback onDock;
final ValueChanged<ConversationMetadata> onConversationCreated;
final ValueChanged<ConversationMetadata> onConversationUpdated;
@override
ConsumerState<FloatingAgentPanel> createState() => _FloatingAgentPanelState();
}
class _FloatingAgentPanelState extends ConsumerState<FloatingAgentPanel>
with SingleTickerProviderStateMixin {
final _scroll = ScrollController();
late final AnimationController _reveal;
bool _resizing = false;
void _animateReveal(bool expanded) {
_reveal.animateTo(expanded ? 1 : 0, curve: Curves.easeOutCubic);
}
void _startResize() {
_reveal.stop();
setState(() => _resizing = true);
}
void _finishResize() {
if (!_resizing) return;
final expanded = _reveal.value >= .35;
setState(() => _resizing = false);
if (expanded != widget.expanded) {
widget.onToggleExpanded();
} else {
_animateReveal(expanded);
}
}
void _changed() {
if (mounted) setState(() {});
}
@override
void initState() {
super.initState();
_reveal = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 220),
value: widget.expanded ? 1 : 0,
);
widget.composer.addListener(_changed);
}
@override
void didUpdateWidget(FloatingAgentPanel oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.expanded != oldWidget.expanded) {
_animateReveal(widget.expanded);
}
if (oldWidget.input != widget.input) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted && _scroll.hasClients) {
_scroll.jumpTo(_scroll.position.maxScrollExtent);
}
});
}
if (oldWidget.composer != widget.composer) {
oldWidget.composer.removeListener(_changed);
widget.composer.addListener(_changed);
}
}
@override
void dispose() {
widget.composer.removeListener(_changed);
_reveal.dispose();
_scroll.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final assets =
ref.watch(
projectsProvider.select(
(value) =>
value.asData?.value.activeProject?.id ==
widget.state.activeProject?.id
? value.asData?.value.assets
: null,
),
) ??
widget.state.assets;
final workspace = widget.state.copyWith(assets: assets);
final projectId = workspace.activeProject?.id;
final timelineId = widget.state.timeline?.id;
final selection = widget.selection;
final provider = projectId == null
? null
: chatControllerProvider(
projectId,
conversationId: selection.selectedId,
draftKey: selection.selectedId == null ? selection.draftKey : null,
);
final chat = provider == null
? const ChatState()
: ref.watch(provider.select(chatChrome));
final settings = ref.watch(agentSettingsProvider).value;
final available =
settings?.providers
.where(
(p) =>
p.enabled &&
AgentApiType.values.any((type) => type.name == p.apiType) &&
p.models.isNotEmpty,
)
.toList() ??
[];
final conversation = chat.conversation;
final providerId = conversation?.providerId ?? settings?.selectedProviderId;
final modelId = conversation?.modelId ?? settings?.selectedModelId;
final selectedProvider = available
.where((p) => p.id == providerId)
.firstOrNull;
final selectedModel = selectedProvider?.models
.where((m) => m.id == modelId)
.firstOrNull;
final configured =
conversation != null ||
(selection.selectedId != null && !widget.composer.usingDraftModel)
? conversation != null &&
settings?.enabled == true &&
selectedModel != null
: ref.watch(agentRuntimeProvider).value != null;
final importing =
widget.composer.busy ||
(projectId != null &&
ref.watch(
externalMediaImportProvider(projectId)
.select((value) => value.isLoading),
));
final operation =
'agent-model-$projectId-${selection.selectedId ?? selection.draftKey}';
final choosingModel = ref.watch(
settingsOperationProvider(operation).select((value) => value.isLoading),
);
final validator = ComposerReferenceValidator(
workspace: workspace,
projectId: projectId,
);
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) validator.validate(widget.input);
});
if (provider != null && TickerMode.valuesOf(context).enabled) {
ref.listen(provider, (old, next) {
if (_scroll.hasClients && _scroll.position.extentAfter < 80) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted && _scroll.hasClients) {
_scroll.jumpTo(_scroll.position.maxScrollExtent);
}
});
}
});
}
void send() {
validator.validate(widget.input);
if (provider == null ||
timelineId == null ||
!configured ||
choosingModel ||
chat.busy ||
importing ||
widget.input.hasInvalidReferences ||
(widget.input.text.trim().isEmpty &&
widget.composer.attachments.isEmpty)) {
return;
}
final text = takeAgentDraft(widget.input, widget.composer);
if (!widget.expanded) widget.onToggleExpanded();
unawaited(
ref
.read(provider.notifier)
.send(
text,
timelineId: timelineId,
onCreated: widget.onConversationCreated,
onUpdated: widget.onConversationUpdated,
),
);
}
Future<void> chooseModel(String p, String m) async {
if (chat.busy || choosingModel) return;
final composer = widget.composer;
final saved = await ref
.read(settingsOperationProvider(operation).notifier)
.run(() async {
if (provider == null) {
await ref.read(agentSettingsProvider.notifier).selectModel(p, m);
} else {
await ref.read(provider.notifier).selectModel(p, m);
}
});
if (!mounted || !context.mounted) return;
if (saved) composer.useDraftModel();
if (!saved && context.mounted) {
ErrorNotificationHost.of(context).show(
ErrorNotification(
content: Text(context.l10n.agentSaveSettingsFailed),
),
);
}
}
final groups = ref.watch(conversationSidebarProvider).value?.groups;
final items = groups?[projectId] ?? const <ConversationMetadata>[];
final title =
conversation?.title ??
items.where((c) => c.id == selection.selectedId).firstOrNull?.title ??
context.l10n.agentNewConversation;
final inputDecoration = AppComposerStyle.inputDecoration(
context,
hintText: context.l10n.assistantHint,
);
Widget modelButton() => AppDropdownMenu(
enabled: !chat.busy && !choosingModel,
minWidth: ComposerLayout.menuWidth,
maxHeight: ComposerLayout.menuListMaxHeight,
items: [
for (final p in available) ...[
AppMenuLabel(p.name),
for (final m in p.models)
AppMenuItem(
label: m.id,
selectOption: true,
selected: p.id == providerId && m.id == modelId,
onPressed: () => unawaited(chooseModel(p.id, m.id)),
),
],
const Divider(height: 1),
AppMenuItem(
label: context.l10n.agentConfigureModel,
onPressed: () => showSettingsPage(context, initialTab: 1),
),
],
builder: (context, toggle, focus) => Tooltip(
message: selectedModel?.id ?? context.l10n.agentConfigureModel,
child: AppToolbarDropdownButton(
buttonKey: const Key('floating-agent-model-picker'),
focusNode: focus,
onPressed: toggle,
style: AppComposerStyle.controlButton(context),
child: const Icon(AppIcons.model, size: ComposerLayout.iconSize),
),
),
);
final conversationView = ExcludeFocus(
excluding: !widget.expanded && !_resizing,
child: IgnorePointer(
ignoring: !widget.expanded && !_resizing,
child: LayoutBuilder(
builder: (context, constraints) {
final height = constraints.maxHeight.clamp(
AppControlSize.panelToolbar + 1,
double.infinity,
);
return ClipRect(
child: OverflowBox(
alignment: Alignment.topCenter,
minHeight: height,
maxHeight: height,
child: Column(
children: [
SizedBox(
height: AppControlSize.panelToolbar,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.small,
),
child: Row(
children: [
IconButton(
key: const Key('floating-agent-collapse'),
style: AppComposerStyle.controlIcon(context),
tooltip: context.l10n.agentCollapseConversation,
onPressed: widget.onToggleExpanded,
icon: const Icon(
AppIcons.remove,
size: AppIconSize.header,
),
),
Expanded(
child: AppDropdownMenu(
minWidth: ComposerLayout.menuWidth,
maxHeight: ComposerLayout.menuListMaxHeight,
items: [
AppMenuItem(
label: context.l10n.agentNewConversation,
onPressed: () => ref
.read(
conversationSidebarProvider.notifier,
)
.newConversation(),
),
for (final item in items)
AppMenuItem(
label: item.title,
selectOption: true,
selected: item.id == selection.selectedId,
onPressed: () {
final controller = ref.read(
conversationSidebarProvider.notifier,
);
controller.activate(item);
unawaited(
controller.rememberSelection(item),
);
},
),
],
builder: (context, toggle, focus) =>
AppToolbarDropdownButton(
focusNode: focus,
onPressed: toggle,
child: Row(
children: [
Flexible(
child: Text(
title,
key: const Key(
'agent-floating-title',
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
const SizedBox(
width: AppSpacing.tiny,
),
const Icon(
AppIcons.expandMore,
size: AppIconSize.header,
),
],
),
),
),
),
IconButton(
key: const Key('floating-agent-dock'),
style: AppComposerStyle.controlIcon(context),
tooltip: context.l10n.agentDock,
onPressed: widget.onDock,
icon: const Icon(
AppIcons.exitFullscreen,
size: AppIconSize.header,
),
),
],
),
),
),
Expanded(
child: ListView(
controller: _scroll,
key: const Key('floating-agent-messages'),
padding: const EdgeInsets.all(AppSpacing.medium),
children: [
for (final message in chat.messages)
Padding(
padding: const EdgeInsets.only(
bottom: AppSpacing.large,
),
child: Align(
alignment: message.isUser
? Alignment.centerRight
: Alignment.centerLeft,
child: Container(
constraints: const BoxConstraints(
maxWidth: ComposerLayout.maxWidth,
),
padding: message.isUser
? const EdgeInsets.symmetric(
horizontal: AppSpacing.medium,
vertical: AppSpacing.itemVertical,
)
: EdgeInsets.zero,
decoration: message.isUser
? AppTheme.userMessageDecoration(context)
: null,
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
if (message.elapsedMs case final elapsed?)
Text(
context.l10n.agentElapsedTime(
context.l10n.durationSeconds(
(elapsed / 1000).ceil(),
),
),
style: AppTheme.chatMetaTextStyle(
context,
),
),
if (message.isUser)
BreakableSelectableText(
text: AgentComposerMessage.decode(
message.text,
).text,
style: AppTheme.chatMessageTextStyle(
context,
),
)
else
SelectableText(
AgentComposerMessage.decode(
message.text,
).text,
style: AppTheme.chatMessageTextStyle(
context,
),
),
for (final attachment
in AgentComposerMessage.decode(
message.text,
).attachments)
Chip(label: Text(attachment.name)),
if (message.interrupted)
Text(context.l10n.replyInterrupted),
],
),
),
),
),
AgentReplyRegion(
projectId: projectId,
conversationId: selection.selectedId,
draftKey: selection.selectedId == null
? selection.draftKey
: null,
),
],
),
),
],
),
),
);
},
),
),
);
final composerView = Padding(
key: const Key('floating-agent-input-area'),
padding: const EdgeInsets.all(AppSpacing.small),
child: LayoutBuilder(
builder: (context, constraints) => ComposerSuggestionSurface(
controller: widget.input,
width: constraints.maxWidth,
projectId: projectId,
assets: assets,
timelines: widget.state.timelines,
onSend: send,
builder: (context, focus) {
final attachment = IconButton(
style: AppComposerStyle.controlIcon(context),
tooltip: context.l10n.addAttachment,
onPressed:
projectId == null || importing || widget.state.projectBusy
? null
: () async {
try {
await widget.composer.pickAttachments();
} catch (_) {
/* Shared composer publishes import feedback. */
}
},
icon: const Icon(AppIcons.add),
);
final input = TextField(
key: const Key('floating-agent-input'),
controller: widget.input,
focusNode: focus,
minLines: 1,
maxLines: 5,
style: AppTheme.composerTextStyle(context),
cursorHeight: AppTheme.composerCursorHeight(context),
decoration: inputDecoration.copyWith(
constraints: const BoxConstraints(
minHeight: ComposerLayout.controlSize,
),
contentPadding: const EdgeInsets.symmetric(
horizontal: AppSpacing.small,
vertical: AppSpacing.tiny,
),
),
onTap: () {
if (!widget.expanded) {
widget.onToggleExpanded();
}
},
);
final submit = ValueListenableBuilder<TextEditingValue>(
valueListenable: widget.input,
builder: (context, value, _) => IconButton.filled(
style: AppTheme.accentIconButtonStyle(context)
.merge(AppComposerStyle.controlIcon(context)),
tooltip: chat.busy
? context.l10n.stopReply
: context.l10n.sendMessage,
onPressed: chat.busy
? (chat.stopping ? null : ref.read(provider!.notifier).stop)
: provider != null &&
timelineId != null &&
configured &&
!importing &&
!choosingModel &&
!widget.input.hasInvalidReferences &&
(value.text.trim().isNotEmpty ||
widget.composer.attachments.isNotEmpty)
? send
: null,
icon: Icon(
chat.busy ? AppIcons.squareFilled : AppIcons.arrowUp,
size: chat.busy ? 12 : ComposerLayout.iconSize,
),
),
);
// Keep the editor at the same tree position and bottom
// anchor while the conversation opens above it.
return Row(
key: const Key('floating-agent-composer'),
crossAxisAlignment: CrossAxisAlignment.end,
children: [
attachment,
Expanded(child: input),
modelButton(),
submit,
],
);
},
),
),
);
final content = LayoutBuilder(
builder: (context, constraints) {
final conversationHeight =
(constraints.maxHeight -
ComposerLayout.controlSize -
AppSpacing.small * 2)
.clamp(0.0, double.infinity);
return AnimatedBuilder(
animation: _reveal,
builder: (context, _) => MediaImportFeedbackListener(
feedback: widget.composer.feedback,
child: Material(
color: Theme.of(context).colorScheme.surface,
child: Stack(
children: [
Column(
mainAxisSize: MainAxisSize.min,
children: [
Flexible(
child: SizedBox(
key: const Key('floating-agent-conversation-region'),
height: conversationHeight * _reveal.value,
child: ClipRect(
child: Stack(
children: [
Offstage(
offstage: _reveal.value == 0,
child: conversationView,
),
Positioned(
left: 0,
right: 0,
bottom: 0,
child: Divider(
key: const Key(
'floating-agent-input-divider',
),
height: 1,
thickness: 1,
color: AppTheme.floatingDialogDividerColor(
context,
),
),
),
],
),
),
),
),
if (chat.error case final error?)
Padding(
padding: const EdgeInsets.all(AppSpacing.small),
child: Text(
agentChatErrorMessage(context, error),
style: Theme.of(context).textTheme.bodySmall,
),
),
if ({
AgentChatError.recoveryRequired,
AgentChatError.interrupted,
AgentChatError.turnLimit,
AgentChatError.exportReplyFailed,
}.contains(chat.error))
TextButton(
onPressed:
provider == null ||
timelineId == null ||
chat.busy
? null
: () => ref
.read(provider.notifier)
.send(
chat.error ==
AgentChatError.exportReplyFailed
? context.l10n.agentRetrySummary
: context.l10n.agentResumeTask,
timelineId: timelineId,
summaryOnly:
chat.error ==
AgentChatError.exportReplyFailed,
resumeOnly:
chat.error !=
AgentChatError.exportReplyFailed,
onUpdated: widget.onConversationUpdated,
),
child: Text(
chat.error == AgentChatError.exportReplyFailed
? context.l10n.agentRetrySummary
: context.l10n.agentResumeTask,
),
),
ValueListenableBuilder<TextEditingValue>(
valueListenable: widget.input,
builder: (context, _, _) =>
widget.input.hasInvalidReferences
? Padding(
padding: const EdgeInsets.all(AppSpacing.small),
child: Text(
context.l10n.composerReferenceInvalid,
style: AppSurfaces.of(context).errorText,
),
)
: const SizedBox.shrink(),
),
if (widget.composer.attachments.isNotEmpty)
Padding(
padding: const EdgeInsets.all(AppSpacing.small),
child: Wrap(
spacing: AppSpacing.gap,
children: [
for (final asset in widget.composer.attachments)
if (assets
.where((item) => item.id == asset.id)
.firstOrNull
case final document?)
AgentAttachmentCard(
asset: document,
onRemove: () =>
widget.composer.remove(asset.id),
)
else
InputChip(
label: Text(asset.name),
onDeleted: () =>
widget.composer.remove(asset.id),
),
],
),
),
composerView,
],
),
Positioned(
top: 0,
left: ComposerLayout.radius,
right: ComposerLayout.radius,
height: AppSpacing.small,
child: Semantics(
button: true,
label: widget.expanded
? context.l10n.agentCollapseConversation
: context.l10n.agentExpandConversation,
onTap: widget.onToggleExpanded,
child: Stack(
fit: StackFit.expand,
children: [
Center(
child: Container(
width: ComposerLayout.controlSize,
height: 2,
decoration: BoxDecoration(
color: Theme.of(context)
.colorScheme
.onSurfaceVariant
.withValues(alpha: .35),
borderRadius: BorderRadius.circular(
AppRadius.pill,
),
),
),
),
WorkspaceResizeHandle(
key: const Key('floating-agent-resize-handle'),
axis: Axis.vertical,
direction: -1,
initialValue: _reveal.value * conversationHeight,
onStart: _startResize,
onResize: (height) {
if (conversationHeight > 0) {
_reveal.value = (height / conversationHeight)
.clamp(0.0, 1.0);
}
},
onEnd: _finishResize,
),
],
),
),
),
],
),
),
),
);
},
);
return AgentAttachmentDropRegion(
projectId: projectId,
composer: widget.composer,
shrinkWrap: true,
child: content,
);
}
}
@@ -9,6 +9,8 @@ import '../../workspace/project_state.dart';
import '../projects/conversation_sidebar.dart';
import 'agent_chat_panel.dart';
import 'agent_panel_presentation.dart';
import 'floating_agent_panel.dart';
import 'agent_composer_store.dart';
import 'composer_project_selector.dart';
@@ -19,11 +21,13 @@ class WorkspaceAgentSurface extends ConsumerWidget {
required this.state,
required this.onSelectProject,
required this.onCreateProject,
this.showProjectSelector = true,
});
final ProjectState state;
final ValueChanged<RecentProject>? onSelectProject;
final VoidCallback? onCreateProject;
final bool showProjectSelector;
@override
Widget build(BuildContext context, WidgetRef ref) {
@@ -34,21 +38,54 @@ class WorkspaceAgentSurface extends ConsumerWidget {
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),
final presentation = AgentPanelPresentation.of(context);
if (presentation?.compact == true) {
return FloatingAgentPanel(
state: state,
selection: selection,
input: composers.input(
projectId,
conversationId,
projectScoped: !showProjectSelector,
),
composer: composers.composer(
projectId,
conversationId ?? selection.draftKey,
),
projectSelector: ComposerProjectSelector(
expanded: presentation!.expanded,
onToggleExpanded: presentation.onToggleExpanded!,
onDock: presentation.onDock!,
onConversationCreated: (item) => unawaited(
conversations.updateListing(
item,
selectIfDraftKey: selection.draftKey,
),
),
onConversationUpdated: (item) =>
unawaited(conversations.updateListing(item)),
);
}
return AgentChatPanel(
key: ValueKey((projectId, conversationId ?? selection.draftKey)),
inputController: composers.input(
projectId,
conversationId,
projectScoped: !showProjectSelector,
),
composer: composers.composer(
projectId,
conversationId ?? selection.draftKey,
),
projectSelector: showProjectSelector
? ComposerProjectSelector(
backgroundColor: AppTheme.composerUtilityBackground(context),
projects: state.recent,
selected: state.activeProject,
busy: state.projectBusy,
onSelect: (project) => onSelectProject?.call(project),
onCreate: onCreateProject,
),
)
: null,
composerColor: AppSurfaces.of(context).composerBackground,
projectId: projectId,
timelineId: state.timeline?.id,
@@ -2,11 +2,12 @@ import 'package:cutdex/l10n/l10n.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:cutdex_ui/icons.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 '../../shared/widgets/listenable_selector.dart';
import '../../integrations/runtime/processing_resource_state.dart';
import 'package:cutdex_ui/widgets.dart';
@@ -14,9 +15,14 @@ import 'package:cutdex_ui/widgets.dart';
import '../media/background_tasks_dialog.dart';
class BackgroundTasksButton extends ConsumerWidget {
const BackgroundTasksButton({super.key, this.iconSize = AppIconSize.header});
const BackgroundTasksButton({
super.key,
this.iconSize = AppIconSize.header,
this.alignment = AlignmentDirectional.bottomStart,
});
final double iconSize;
final AlignmentGeometry alignment;
@override
Widget build(BuildContext context, WidgetRef ref) {
@@ -25,30 +31,39 @@ class BackgroundTasksButton extends ConsumerWidget {
.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(
: ref.watch(
processingResourcesProvider(resources).select(
(downloads) =>
downloads.subtitleDownloading ||
downloads.installs.any(
(install) =>
install.state == ProcessingResourceState.downloading,
),
),
);
Widget button(VoidCallback toggle, bool running) => IconButton(
key: const ValueKey('background-tasks-button'),
tooltip: context.l10n.backgroundTasks,
onPressed: toggle,
icon: Badge(
isLabelVisible: hasRunningTasks(),
child: Icon(Icons.task_alt_outlined, size: iconSize),
isLabelVisible: running || downloads == true,
child: Icon(AppIcons.success, size: iconSize),
),
);
return AppPopover(
return ListenableSelector<bool>(
listenable: registry,
select: () => registry.runningCount > 0,
builder: (context, running) => AppPopover(
width: 384,
builder: (_, toggle) => button(toggle),
child: BackgroundTasksContent(registry: registry, repository: resources),
alignment: alignment,
builder: (_, toggle) => button(toggle, running),
child: BackgroundTasksContent(
registry: registry,
repository: resources,
),
),
);
}
}
+174 -60
View File
@@ -1,3 +1,5 @@
import '../../shared/widgets/listenable_selector.dart';
import 'dart:async';
import 'package:cutdex/l10n/l10n.dart';
@@ -11,9 +13,12 @@ import 'package:cutdex_native/cutdex_native.dart';
import '../../persistence/app_settings_repositories.dart';
import '../../shared/layout/workspace_layout_metrics.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import '../../workspace/timeline_provider.dart';
import '../../workspace/preview_target.dart';
import '../../workspace/projects.dart';
import '../../workspace/view_settings.dart';
import '../media/media_browser_page.dart';
import '../media/media_panel.dart';
@@ -23,6 +28,7 @@ import '../properties/properties_panel.dart';
import '../timeline/timeline_panel.dart';
import 'editor_presentation_controller.dart';
import 'editor_panel_defaults.dart';
import 'timeline_operation_region.dart';
import 'layouts/bounded_editor_layout.dart';
import 'layouts/expanded_editor_layout.dart';
@@ -36,11 +42,15 @@ class EditorWorkspace extends ConsumerStatefulWidget {
required this.integratedTitlebar,
required this.headerLeading,
this.projectLoading = false,
this.timelineLoading = false,
this.showProjectName = true,
this.experience = DeviceExperience.desktop,
});
final bool projectLoading;
/// Navigation is preparing another timeline; the current content stays visible.
final bool timelineLoading;
final String projectId;
final String timelineId;
final String projectName;
@@ -55,6 +65,13 @@ class EditorWorkspace extends ConsumerStatefulWidget {
class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
final _previewKey = GlobalKey();
bool get _timelinePending => widget.projectLoading;
Widget _timelineInteraction(Widget child) => TimelineOperationRegion(
projectId: widget.projectId,
loading: widget.timelineLoading,
child: child,
);
EditorPresentationController get _presentation =>
ref.read(editorPresentationProvider(widget.projectId));
ProjectViewSettingsData get _viewSettings =>
@@ -66,7 +83,8 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
double? get _timelineHeight => _viewSettings.timelineHeight;
void _saveViewSettings() {
if (!ref.read(projectViewSettingsProvider(widget.projectId)).hasValue) {
if (widget.projectId.isEmpty ||
!ref.read(projectViewSettingsProvider(widget.projectId)).hasValue) {
return;
}
unawaited(_viewController.save());
@@ -79,46 +97,95 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
);
final preview = KeyedSubtree(
key: _previewKey,
child: EditorPreviewPanel(
child: _timelineInteraction(
EditorPreviewPanel(
projectId: widget.projectId,
timelineId: widget.timelineId,
pending: widget.projectLoading,
pending: _timelinePending,
),
),
);
final timeline = EditorTimelinePanel(
projectId: widget.projectId,
timelineId: widget.timelineId,
pending: widget.projectLoading,
timelineLoading: widget.timelineLoading,
);
final properties = widget.projectLoading
final properties = _timelineInteraction(
_timelinePending
? const EditorEmptyPanel()
: EditorPropertiesPanel(
projectId: widget.projectId,
timelineId: widget.timelineId,
),
);
final media = widget.projectLoading
? const EditorEmptyPanel()
: MediaPanel(projectId: widget.projectId);
: MediaPanel(projectId: widget.projectId, projectScoped: true);
return ListenableBuilder(
listenable: ref.watch(editorPresentationProvider(widget.projectId)),
builder: (context, _) => LayoutBuilder(
builder: (context, constraints) {
final desktop = widget.experience == DeviceExperience.desktop;
final mediaOpen = desktop
? _presentation.mediaOpen
: _presentation.activeTool == EditorTool.media;
final mediaWidth = mediaOpen
? WorkspaceLayoutMetrics.mediaPanelWidth +
WorkspaceLayoutMetrics.desktopSpacing
: 0.0;
final sideWidth = (_propertiesOpen
? WorkspaceLayoutMetrics.propertiesPanelWidth + 1
? WorkspaceLayoutMetrics.propertiesPanelWidth +
WorkspaceLayoutMetrics.desktopSpacing
: 0);
final dockPanels =
final dockMedia =
desktop &&
mediaOpen &&
constraints.maxWidth >=
WorkspaceLayoutMetrics.previewMinimumWidth + sideWidth;
final desktopTool = _propertiesOpen ? EditorTool.properties : null;
final headerHeight = desktop ? AppControlSize.panelToolbar : 48.0;
final mediaOpen = _presentation.activeTool == EditorTool.media;
WorkspaceLayoutMetrics.previewMinimumWidth + mediaWidth;
final dockProperties =
desktop &&
_propertiesOpen &&
constraints.maxWidth >=
WorkspaceLayoutMetrics.previewMinimumWidth +
sideWidth +
(dockMedia ? mediaWidth : 0);
final desktopTool =
mediaOpen && !dockMedia && _presentation.desktopToolRequested
? _presentation.desktopTool(propertiesOpen: _propertiesOpen)
: _propertiesOpen && !dockProperties
? EditorTool.properties
: null;
final headerHeight = desktop ? AppDesktopMetrics.panelHeader : 48.0;
final propertiesOpen = desktop
? dockPanels
? dockProperties
? _propertiesOpen
: desktopTool == EditorTool.properties
: _presentation.activeTool == EditorTool.properties;
final mediaButton = 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 (!dockMedia &&
desktopTool != EditorTool.media &&
_presentation.mediaOpen) {
_presentation.preferDesktopTool(EditorTool.media);
} else {
_presentation.toggleMedia();
}
} else {
_presentation.toggleTool(EditorTool.media);
}
},
icon: const Icon(AppIcons.mediaLibrary),
),
),
);
final header = Material(
color: Theme.of(context).colorScheme.surface,
child: SizedBox(
@@ -128,15 +195,22 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
padding: desktop
? const EdgeInsets.symmetric(
horizontal: AppSidebarMetrics.outerPadding,
vertical: AppSpacing.gap,
vertical: AppSpacing.tiny,
)
: EdgeInsets.zero,
child: WindowHeaderPadding(
child: Row(
children: [
widget.headerLeading,
if (desktop) mediaButton,
Expanded(
child: widget.showProjectName
child: desktop
? _PreviewHeaderTitle(
projectId: widget.projectId,
timelineId: widget.timelineId,
pending: _timelinePending,
)
: widget.showProjectName
? Row(
children: [
Flexible(
@@ -153,7 +227,7 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
),
Flexible(
fit: FlexFit.loose,
child: widget.projectLoading
child: _timelinePending
? const SizedBox.shrink()
: _TimelineSaveStatus(
projectId: widget.projectId,
@@ -164,35 +238,7 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
)
: const SizedBox.shrink(),
),
if (!desktop)
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),
),
),
),
if (!desktop) mediaButton,
if (!desktop) const SizedBox(width: AppSpacing.tiny),
HeaderControlRegion(
child: SizedBox.square(
@@ -207,7 +253,7 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
? null
: () {
if (desktop) {
if (dockPanels ||
if (dockProperties ||
desktopTool ==
EditorTool.properties ||
!_propertiesOpen) {
@@ -226,7 +272,7 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
}
},
icon: const Icon(
Icons.tune,
AppIcons.tune,
size: AppIconSize.header,
),
),
@@ -245,8 +291,8 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
header: header,
properties: properties,
media: media,
showMedia: false,
showProperties: showTools && _propertiesOpen,
showMedia: dockMedia,
showProperties: showTools && dockProperties,
timelineHeight: _timelineHeight,
onTimelineHeightChanged: (height) {
if (viewSettings.hasValue) {
@@ -263,7 +309,7 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
children: [
if (!desktop) header,
Expanded(
child: dockPanels
child: desktop && desktopTool == null
? dockedEditing(showTools: true)
: BoundedEditorLayout(
experience: widget.experience,
@@ -288,20 +334,24 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
projectId: widget.projectId,
),
},
properties: widget.projectLoading
properties: _timelinePending
? properties
: switch (widget.experience) {
DeviceExperience.desktop => properties,
DeviceExperience.tablet =>
_timelineInteraction(
PropertiesToolPanel(
projectId: widget.projectId,
timelineId: widget.timelineId,
),
),
DeviceExperience.phone =>
_timelineInteraction(
PropertiesEditorPage(
projectId: widget.projectId,
timelineId: widget.timelineId,
),
),
},
onCloseTool: () {
if (!desktop) {
@@ -334,6 +384,73 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
}
}
class _PreviewHeaderTitle extends ConsumerWidget {
const _PreviewHeaderTitle({
required this.projectId,
required this.timelineId,
required this.pending,
});
final String projectId;
final String timelineId;
final bool pending;
@override
Widget build(BuildContext context, WidgetRef ref) {
final navigation = pending
? const PreviewTargetState.timeline()
: ref.watch(previewNavigationProvider(projectId, timelineId));
final name = pending
? context.l10n.preview
: ref.watch(
projectsProvider.select((value) {
final workspace = value.value;
return switch (navigation) {
SourcePreviewTarget(:final asset) =>
workspace?.assets
.where((item) => item.id == asset.id)
.firstOrNull
?.name ??
asset.name,
_ =>
workspace?.timeline?.id == timelineId
? workspace!.timeline!.name
: context.l10n.preview,
};
}),
);
final session = pending
? null
: ref.watch(editorTimelineProvider(projectId, timelineId)).value;
Widget title(String? saveStatus) => Tooltip(
message: saveStatus == null ? name : '$name\n$saveStatus',
child: Text(
name,
key: const Key('editor-preview-title'),
textAlign: TextAlign.center,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.titleSmall,
),
);
if (session == null) return title(null);
return ListenableSelector<(bool, bool, bool)>(
listenable: session,
select: () => (session.error != null, session.saving, session.dirty),
builder: (context, value) => title(_timelineSaveLabel(context, value)),
);
}
}
String _timelineSaveLabel(BuildContext context, (bool, bool, bool) value) =>
value.$1
? context.l10n.unsaved
: value.$2
? context.l10n.saving
: value.$3
? context.l10n.pendingSave
: context.l10n.saved;
class _TimelineSaveStatus extends ConsumerWidget {
const _TimelineSaveStatus({
required this.projectId,
@@ -350,22 +467,19 @@ class _TimelineSaveStatus extends ConsumerWidget {
.asData
?.value;
if (session == null) return const SizedBox.shrink();
return ListenableBuilder(
return ListenableSelector<(bool, bool, bool)>(
listenable: session,
builder: (context, _) => Padding(
select: () => (session.error != null, session.saving, session.dirty),
builder: (context, value) => 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,
_timelineSaveLabel(context, value),
key: const Key('timeline-save-status'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall?.copyWith(fontSize: 10),
style: AppTheme.isDesktop(context)
? Theme.of(context).textTheme.bodySmall
: Theme.of(context).textTheme.bodySmall?.copyWith(fontSize: 10),
),
),
);
+91 -14
View File
@@ -1,4 +1,7 @@
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex/l10n/l10n.dart';
import 'package:cutdex_ui/widgets.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:flutter/material.dart';
/// Empty values while a project's content is being bound to its cards.
@@ -19,37 +22,111 @@ class EditorTimelineDefaults extends StatelessWidget {
Widget build(BuildContext context) => Column(
children: [
if (showTabs) ...[
const SizedBox(
key: Key('timeline-tabs-bar'),
height: 26,
ColoredBox(
key: const Key('timeline-tabs-background'),
color: AppTheme.timelineTabsBackground(context),
child: SizedBox(
key: const Key('timeline-tabs-bar'),
height: AppTheme.isDesktop(context)
? AppDesktopMetrics.timelineTabs
: 26,
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: AppTheme.isDesktop(context) ? AppSpacing.tiny : 0,
),
child: Row(
children: [
IconButton(onPressed: null, icon: Icon(Icons.add, size: 16)),
if (AppTheme.isDesktop(context))
SizedBox.square(
dimension: AppDesktopMetrics.timelineTabControl,
child: IconButton(
key: const Key('timeline-add-button'),
onPressed: null,
style: AppTheme.timelineTabActionStyle,
icon: const Icon(AppIcons.add, size: 16),
),
)
else
const IconButton(
onPressed: null,
icon: Icon(AppIcons.add, size: 16),
),
],
),
),
),
),
const Divider(height: 1),
],
Expanded(
child: WorkspacePanel(
headerHeight: 32,
headerHeight: AppTheme.isDesktop(context)
? AppDesktopMetrics.timelineToolbar
: 32,
headerPadding: EdgeInsets.zero,
controls: SizedBox(
key: const Key('timeline-toolbar'),
height: 32,
child: SingleChildScrollView(
height: AppTheme.isDesktop(context)
? AppDesktopMetrics.timelineToolbar
: 32,
child: !AppTheme.isDesktop(context)
? SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
for (final icon in [
Icons.undo,
Icons.redo,
Icons.content_cut,
Icons.align_horizontal_left,
Icons.align_horizontal_right,
Icons.delete_outline,
AppIcons.undo,
AppIcons.redo,
AppIcons.cut,
AppIcons.alignLeft,
AppIcons.alignRight,
AppIcons.delete,
])
IconButton(onPressed: null, icon: Icon(icon, size: 16)),
IconButton(
onPressed: null,
icon: Icon(icon, size: 16),
),
],
),
)
: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: AppCommandToolbar(
groups: [
[
AppToolbarCommand(
label: context.l10n.undo,
icon: AppIcons.undo,
onPressed: null,
),
AppToolbarCommand(
label: context.l10n.redo,
icon: AppIcons.redo,
onPressed: null,
),
],
[
AppToolbarCommand(
label: context.l10n.splitAtPlayhead,
icon: AppIcons.cut,
onPressed: null,
),
AppToolbarCommand(
label: context.l10n.trimLeftTooltip,
icon: AppIcons.alignLeft,
onPressed: null,
),
AppToolbarCommand(
label: context.l10n.trimRightTooltip,
icon: AppIcons.alignRight,
onPressed: null,
),
AppToolbarCommand(
label: context.l10n.deleteSelectedClips,
icon: AppIcons.delete,
onPressed: null,
),
],
],
),
),
@@ -12,12 +12,14 @@ final editorPresentationProvider =
/// Presentation choices survive shell changes without changing project data.
class EditorPresentationController extends ChangeNotifier {
bool _mediaOpen = false;
bool _mediaOpen = true;
EditorTool? _activeTool;
EditorTool _preferredDesktopTool = EditorTool.properties;
bool _desktopToolRequested = false;
bool get mediaOpen => _mediaOpen;
EditorTool? get activeTool => _activeTool;
bool get desktopToolRequested => _desktopToolRequested;
EditorTool desktopTool({required bool propertiesOpen}) =>
_preferredDesktopTool == EditorTool.media && _mediaOpen
? EditorTool.media
@@ -26,12 +28,14 @@ class EditorPresentationController extends ChangeNotifier {
: EditorTool.media;
void preferDesktopTool(EditorTool tool) {
_desktopToolRequested = true;
_preferredDesktopTool = tool;
notifyListeners();
}
void toggleMedia() {
_mediaOpen = !_mediaOpen;
_desktopToolRequested = _mediaOpen;
if (_mediaOpen) _preferredDesktopTool = EditorTool.media;
notifyListeners();
}
@@ -5,6 +5,7 @@ import 'package:flutter/material.dart';
import '../../../integrations/platform/device_experience.dart';
import '../../../l10n/l10n.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import '../editor_presentation_controller.dart';
@@ -36,7 +37,11 @@ class BoundedEditorLayout extends StatelessWidget {
Widget toolSurface() => Column(
children: [
SizedBox(
height: desktop ? AppControlSize.panelToolbar : 48,
height: desktop ? AppDesktopMetrics.panelHeader : 48,
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: desktop ? AppSpacing.small : 0,
),
child: Row(
children: [
SizedBox.square(
@@ -46,7 +51,7 @@ class BoundedEditorLayout extends StatelessWidget {
tooltip: MaterialLocalizations.of(context)
.closeButtonTooltip,
onPressed: onCloseTool,
icon: Icon(page ? Icons.arrow_back : Icons.close),
icon: Icon(page ? AppIcons.arrowBack : AppIcons.close),
),
),
Expanded(
@@ -61,6 +66,7 @@ class BoundedEditorLayout extends StatelessWidget {
],
),
),
),
const Divider(height: 1),
Expanded(child: tool == EditorTool.media ? media : properties),
],
@@ -92,7 +98,7 @@ class BoundedEditorLayout extends StatelessWidget {
),
if (tool != null)
Positioned(
top: desktop ? AppControlSize.panelToolbar + 1 : 0,
top: desktop ? AppDesktopMetrics.panelHeader + 1 : 0,
bottom: 0,
right: 0,
width: page
@@ -1,7 +1,6 @@
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:cutdex_ui/theme.dart';
import '../../../shared/layout/workspace_layout_metrics.dart';
import '../../../shared/widgets/workspace_card.dart';
@@ -39,6 +38,13 @@ class ExpandedEditorLayout extends StatefulWidget {
class _ExpandedEditorLayoutState extends State<ExpandedEditorLayout> {
static const gap = WorkspaceLayoutMetrics.desktopSpacing;
late bool _mediaVisited = widget.showMedia;
@override
void didUpdateWidget(covariant ExpandedEditorLayout oldWidget) {
super.didUpdateWidget(oldWidget);
_mediaVisited |= widget.showMedia;
}
Widget _card(String name, Widget child) =>
WorkspaceCard(key: Key('editor-$name-card'), child: child);
@@ -50,8 +56,7 @@ class _ExpandedEditorLayoutState extends State<ExpandedEditorLayout> {
0.0,
constraints.maxHeight -
gap -
AppControlSize.panelToolbar -
WorkspaceLayoutMetrics.timelineMinimumHeight,
WorkspaceLayoutMetrics.previewMinimumHeight,
);
final minimum = math.min(
WorkspaceLayoutMetrics.timelineMinimumHeight,
@@ -63,9 +68,7 @@ class _ExpandedEditorLayoutState extends State<ExpandedEditorLayout> {
WorkspaceLayoutMetrics.timelineDefaultHeightFraction)
.clamp(minimum, maximum)
.toDouble();
final mediaWidth = widget.showMedia
? WorkspaceLayoutMetrics.mediaPanelWidth
: 0.0;
const mediaWidth = WorkspaceLayoutMetrics.mediaPanelWidth;
final propertiesWidth = widget.showProperties
? WorkspaceLayoutMetrics.propertiesPanelWidth
: 0.0;
@@ -74,51 +77,52 @@ class _ExpandedEditorLayoutState extends State<ExpandedEditorLayout> {
children: [
Column(
children: [
Expanded(
child: _card(
'preview',
Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
widget.header,
Expanded(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (widget.showMedia) ...[
SizedBox(
if (_mediaVisited)
Offstage(
offstage: !widget.showMedia,
child: ExcludeFocus(
excluding: !widget.showMedia,
child: TickerMode(
enabled: widget.showMedia,
child: SizedBox(
key: const Key('editor-media-region'),
width: mediaWidth,
child: widget.media,
child: _card('media', widget.media),
),
const VerticalDivider(width: 1),
],
),
),
),
if (widget.showMedia) const SizedBox(width: gap),
Expanded(
child: _card(
'preview',
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
widget.header,
Expanded(child: widget.preview),
],
),
),
],
),
),
if (widget.showProperties) ...[
const VerticalDivider(
const SizedBox(
key: Key('editor-properties-divider'),
width: 1,
width: gap,
),
SizedBox(
key: const Key('editor-properties-region'),
width: propertiesWidth,
child: widget.properties,
child: _card('properties', widget.properties),
),
],
],
),
),
),
const SizedBox(height: gap),
SizedBox(
height: timelineHeight,
@@ -0,0 +1,34 @@
import 'package:flutter/widgets.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../workspace/projects.dart';
/// Keeps the surface mounted while a timeline operation temporarily blocks edits.
class TimelineOperationRegion extends ConsumerWidget {
const TimelineOperationRegion({
super.key,
required this.projectId,
required this.child,
this.loading = false,
});
final String projectId;
final bool loading;
final Widget child;
@override
Widget build(BuildContext context, WidgetRef ref) {
final creating = ref.watch(
projectsProvider.select(
(value) =>
value.value?.activeProject?.id == projectId &&
value.value?.creatingTimeline == true,
),
);
final blocked = loading || creating;
return IgnorePointer(
ignoring: blocked,
child: ExcludeFocus(excluding: blocked, child: child),
);
}
}
+2 -1
View File
@@ -8,6 +8,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../integrations/runtime/media_presentations.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
class AudioAssetTile extends StatelessWidget {
@@ -63,7 +64,7 @@ class _AudioWaveformCover extends ConsumerWidget {
if (waveform == null) {
return Center(
child: Icon(
Icons.audio_file_outlined,
AppIcons.audioFile,
size: AppIconSize.emptyState,
color: theme.colorScheme.onSurfaceVariant,
),
@@ -10,6 +10,7 @@ import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import '../../shared/widgets/confirm_resource_download_cancel.dart';
import '../../shared/widgets/error_notification_host.dart';
import '../../shared/widgets/processing_resource_download_dialog.dart';
import '../../workspace/timeline_session.dart';
@@ -76,10 +77,10 @@ class _BackgroundRemovalDialogState
_closing = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
final messenger = ScaffoldMessenger.maybeOf(context);
final notifications = ErrorNotificationHost.maybeOf(context);
final message = context.l10n.backgroundRemovalTaskStarted;
Navigator.of(context).pop();
messenger?.showSnackBar(SnackBar(content: Text(message)));
notifications?.showMessage(content: Text(message));
});
});
return ref
+143 -8
View File
@@ -1,3 +1,5 @@
import '../../shared/widgets/presentation_list.dart';
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
@@ -44,12 +46,50 @@ class BackgroundTasksContent extends ConsumerWidget {
final ProcessingResourceRepository? repository;
@override
Widget build(BuildContext context, WidgetRef ref) {
final snapshot = ref.watch(
backgroundTasksProvider(registry: registry, session: session),
final tasksProvider = backgroundTasksProvider(
registry: registry,
session: session,
);
ref.watch(
tasksProvider.select(
(snapshot) => (
PresentationList(
snapshot.subtitles.map(
(entry) => (entry.owner.session, entry.job.id),
),
),
PresentationList(
snapshot.removals.map(
(entry) => (entry.owner.session, entry.task.id),
),
),
),
),
);
final snapshot = ref.read(tasksProvider);
if (repository != null) {
ref.watch(
processingResourcesProvider(repository!).select(
(snapshot) => (
snapshot.subtitleDownloading,
PresentationList(
snapshot.installs
.where(
(install) =>
install.state == ProcessingResourceState.downloading ||
install.state == ProcessingResourceState.failed,
)
.map(
(install) => (install.package.capability, install.state),
),
),
),
),
);
}
final resources = repository == null
? null
: ref.watch(processingResourcesProvider(repository!));
: ref.read(processingResourcesProvider(repository!));
final subtitleEntries = snapshot.subtitles;
final removalEntries = snapshot.removals;
final subtitleDownloading = resources?.subtitleDownloading == true;
@@ -118,9 +158,11 @@ class BackgroundTasksContent extends ConsumerWidget {
resourceDownloads.isNotEmpty ||
subtitleDownloading)
const SizedBox(height: 2),
_BackgroundRemovalTaskCard(
key: ValueKey(entry.task.id),
_ObservedRemovalTask(
key: ValueKey((entry.owner.session, entry.task.id)),
entry: entry,
registry: registry,
session: session,
),
],
for (final (index, entry)
@@ -130,9 +172,14 @@ class BackgroundTasksContent extends ConsumerWidget {
removalEntries.isNotEmpty ||
subtitleDownloading)
const SizedBox(height: 2),
_SubtitleTaskCard(
key: ValueKey(entry.job.recognition.id),
_ObservedSubtitleTask(
key: ValueKey((
entry.owner.session,
entry.job.recognition.id,
)),
entry: entry,
registry: registry,
session: session,
),
],
],
@@ -144,6 +191,70 @@ class BackgroundTasksContent extends ConsumerWidget {
}
}
class _ObservedSubtitleTask extends ConsumerWidget {
const _ObservedSubtitleTask({
super.key,
required this.entry,
this.registry,
this.session,
});
final SubtitleTaskEntry entry;
final BackgroundTaskRegistry? registry;
final EditorTimelineSession? session;
@override
Widget build(BuildContext context, WidgetRef ref) {
final current = ref.watch(
backgroundTasksProvider(registry: registry, session: session).select(
(snapshot) => snapshot.subtitles
.where(
(item) =>
identical(item.owner.session, entry.owner.session) &&
item.job.id == entry.job.id,
)
.firstOrNull,
),
);
return current == null
? const SizedBox.shrink()
: _SubtitleTaskCard(
key: ValueKey((current.owner.session, current.job.id)),
entry: current,
);
}
}
class _ObservedRemovalTask extends ConsumerWidget {
const _ObservedRemovalTask({
super.key,
required this.entry,
this.registry,
this.session,
});
final RemovalTaskEntry entry;
final BackgroundTaskRegistry? registry;
final EditorTimelineSession? session;
@override
Widget build(BuildContext context, WidgetRef ref) {
final current = ref.watch(
backgroundTasksProvider(registry: registry, session: session).select(
(snapshot) => snapshot.removals
.where(
(item) =>
identical(item.owner.session, entry.owner.session) &&
item.task.id == entry.task.id,
)
.firstOrNull,
),
);
return current == null
? const SizedBox.shrink()
: _BackgroundRemovalTaskCard(
key: ValueKey((current.owner.session, current.task.id)),
entry: current,
);
}
}
String _ownerName(BackgroundTaskSession owner) => owner.projectName.isEmpty
? owner.timelineName
: '${owner.projectName} · ${owner.timelineName}';
@@ -387,7 +498,31 @@ class _ResourceDownloadCard extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final snapshot = ref.watch(processingResourcesProvider(repository));
final snapshot = ref.watch(
processingResourcesProvider(repository).select((snapshot) {
final capability = this.install?.package.capability;
return snapshot.copyWith(
installs: snapshot.installs
.where((install) => install.package.capability == capability)
.toList(),
paused: capability == null
? const {}
: snapshot.paused.where((item) => item == capability).toSet(),
rates: capability == null
? const {}
: {capability: snapshot.rates[capability] ?? 0},
subtitleDownloading: subtitleBundle && snapshot.subtitleDownloading,
subtitlePaused: subtitleBundle && snapshot.subtitlePaused,
subtitleDownloadedBytes: subtitleBundle
? snapshot.subtitleDownloadedBytes
: 0,
subtitleTotalBytes: subtitleBundle ? snapshot.subtitleTotalBytes : 0,
subtitleBytesPerSecond: subtitleBundle
? snapshot.subtitleBytesPerSecond
: 0,
);
}),
);
final install = this.install == null
? null
: snapshot.installs
@@ -0,0 +1,280 @@
import 'package:cutdex_sdk/project.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:flutter/material.dart';
import '../../l10n/l10n.dart';
import '../../workspace/media_availability.dart';
import 'audio_asset_tile.dart';
import 'media_asset_strip.dart';
import 'media_browser_layout.dart';
import 'unavailable_media_placeholder.dart';
import 'visual_asset_tile.dart';
/// Desktop cards and rows use the same cover, name and availability labels.
class DesktopMediaAssetTile extends StatelessWidget {
const DesktopMediaAssetTile({
super.key,
required this.asset,
required this.grid,
required this.availability,
});
final AssetDocument asset;
final bool grid;
final MediaAvailability? availability;
static TextStyle? _nameStyle(BuildContext context) =>
Theme.of(context).textTheme.bodyMedium
?.copyWith(fontSize: 13, height: 20 / 13);
static TextStyle? _metadataStyle(BuildContext context) =>
Theme.of(context).textTheme.bodySmall
?.copyWith(fontSize: 12, height: 16 / 12);
/// Font fallback and fractional scaling can round a line above size × height.
static double gridLabelHeight(BuildContext context) {
double lineHeight(TextStyle? style) {
final painter = TextPainter(
text: TextSpan(text: '国Ag', style: style),
maxLines: 1,
textDirection: Directionality.of(context),
textScaler: MediaQuery.textScalerOf(context),
locale: Localizations.maybeLocaleOf(context),
textHeightBehavior: DefaultTextStyle.of(context).textHeightBehavior,
)..layout();
final height = painter.height.ceilToDouble();
painter.dispose();
return height;
}
return lineHeight(_nameStyle(context)) +
lineHeight(_metadataStyle(context));
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final unavailable =
availability != null && availability != MediaAvailability.available;
final kind = switch (asset.metadata['kind']) {
'video' => context.l10n.video,
'image' => context.l10n.picture,
'audio' => context.l10n.audio,
_ => context.l10n.materials,
};
final width = asset.metadata['width'];
final height = asset.metadata['height'];
final dimensions = width is num && height is num && width > 0 && height > 0
? '${width.toInt()} × ${height.toInt()}'
: null;
final info = unavailable
? availability == MediaAvailability.missing
? context.l10n.mediaMissing
: context.l10n.mediaUnavailable
: dimensions == null
? kind
: '$kind · $dimensions';
final name = Tooltip(
message: asset.name,
child: Text(
asset.name,
key: ValueKey('media-name-${asset.id}'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: _nameStyle(context),
),
);
Widget metadata({bool showDuration = false}) => Row(
children: [
Flexible(
child: Text(
info,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: _metadataStyle(context)?.copyWith(
color: unavailable
? theme.colorScheme.error
: theme.colorScheme.onSurfaceVariant,
),
),
),
if (showDuration && !unavailable) ...[
const SizedBox(width: 8),
Flexible(child: MediaAssetDuration(asset: asset, badge: false)),
],
],
);
final cover = ClipRRect(
key: ValueKey('desktop-media-cover-${asset.id}'),
borderRadius: BorderRadius.circular(4),
child: Stack(
children: [
if (unavailable)
AspectRatio(
aspectRatio: 16 / 9,
child: UnavailableMediaPlaceholder(
availability: availability!,
showLabel: false,
),
)
else
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 Center(child: Icon(AppIcons.file, size: 20)),
),
),
},
if (grid && !unavailable)
Positioned(
bottom: 4,
left: 4,
right: 4,
child: Align(
alignment: AlignmentDirectional.centerEnd,
child: MediaAssetDuration(asset: asset),
),
),
],
),
);
if (!grid) {
return LayoutBuilder(
builder: (context, constraints) {
final columns = DesktopMediaListColumns(constraints.maxWidth);
return Row(
children: [
SizedBox(
width: DesktopMediaMetrics.listCover,
height: DesktopMediaMetrics.listCover * 9 / 16,
child: cover,
),
const SizedBox(width: DesktopMediaMetrics.gap),
Expanded(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
name,
if (!columns.specification)
metadata(showDuration: !columns.duration),
],
),
),
if (columns.duration)
SizedBox(
width: DesktopMediaListColumns.durationWidth,
child: Align(
alignment: AlignmentDirectional.centerEnd,
child: unavailable
? const SizedBox.shrink()
: MediaAssetDuration(asset: asset, badge: false),
),
),
if (columns.specification) ...[
const SizedBox(width: DesktopMediaMetrics.gap),
SizedBox(
width: DesktopMediaListColumns.specificationWidth,
child: Text(
unavailable ? info : dimensions ?? '—',
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: _metadataStyle(context)?.copyWith(
color: unavailable
? theme.colorScheme.error
: theme.colorScheme.onSurfaceVariant,
),
),
),
],
if (columns.kind) ...[
const SizedBox(width: DesktopMediaMetrics.gap),
SizedBox(
width: DesktopMediaListColumns.kindWidth,
child: Text(
kind,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: _metadataStyle(context),
),
),
],
],
);
},
);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [cover, const SizedBox(height: 4), name, metadata()],
);
}
}
/// List labels follow the same column widths and breakpoints as asset rows.
class DesktopMediaListHeader extends StatelessWidget {
const DesktopMediaListHeader({super.key});
@override
Widget build(BuildContext context) => Padding(
padding: const EdgeInsets.symmetric(
horizontal: DesktopMediaMetrics.padding + DesktopMediaMetrics.tilePadding,
),
child: LayoutBuilder(
builder: (context, constraints) {
final columns = DesktopMediaListColumns(constraints.maxWidth);
Widget label(String text, {bool end = false}) => Text(
text,
maxLines: 1,
overflow: TextOverflow.ellipsis,
textAlign: end ? TextAlign.end : TextAlign.start,
style: DesktopMediaAssetTile._metadataStyle(context)
?.copyWith(color: Theme.of(context).colorScheme.onSurfaceVariant),
);
return SizedBox(
height: (MediaQuery.textScalerOf(context).scale(16) + 8).clamp(
DesktopMediaMetrics.listHeader,
double.infinity,
),
child: Row(
children: [
Expanded(
child: Padding(
padding: const EdgeInsetsDirectional.only(
start:
DesktopMediaMetrics.listCover + DesktopMediaMetrics.gap,
),
child: label(context.l10n.name),
),
),
if (columns.duration)
SizedBox(
width: DesktopMediaListColumns.durationWidth,
child: label(context.l10n.duration, end: true),
),
if (columns.specification) ...[
const SizedBox(width: DesktopMediaMetrics.gap),
SizedBox(
width: DesktopMediaListColumns.specificationWidth,
child: label(context.l10n.mediaSpecification),
),
],
if (columns.kind) ...[
const SizedBox(width: DesktopMediaMetrics.gap),
SizedBox(
width: DesktopMediaListColumns.kindWidth,
child: label(context.l10n.mediaCategory),
),
],
],
),
);
},
),
);
}
+21 -3
View File
@@ -6,6 +6,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../integrations/runtime/media_presentations.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import 'audio_asset_tile.dart';
@@ -64,9 +65,9 @@ class _VisualAssetStrip extends ConsumerWidget {
timeMilliseconds: video && duration != null
? (duration * 1000 * index / count).floor()
: 0,
fallback: const Center(child: Icon(Icons.movie_outlined)),
fallback: const Center(child: Icon(AppIcons.video)),
errorFallback: const Center(
child: Icon(Icons.broken_image_outlined),
child: Icon(AppIcons.imageUnavailable),
),
),
),
@@ -77,8 +78,9 @@ class _VisualAssetStrip extends ConsumerWidget {
}
class MediaAssetDuration extends ConsumerWidget {
const MediaAssetDuration({super.key, required this.asset});
const MediaAssetDuration({super.key, required this.asset, this.badge = true});
final AssetDocument asset;
final bool badge;
@override
Widget build(BuildContext context, WidgetRef ref) {
@@ -94,6 +96,20 @@ class MediaAssetDuration extends ConsumerWidget {
'${hours > 0 ? '$hours:' : ''}'
'${minutes.toString().padLeft(2, '0')}:'
'${(seconds % 60).toString().padLeft(2, '0')}';
if (!badge) {
return Text(
text,
key: ValueKey('media-duration-${asset.id}'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
fontSize: 12,
height: 16 / 12,
color: Theme.of(context).colorScheme.onSurfaceVariant,
fontFeatures: const [FontFeature.tabularFigures()],
),
);
}
return DecoratedBox(
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: .55),
@@ -104,6 +120,8 @@ class MediaAssetDuration extends ConsumerWidget {
child: Text(
text,
key: ValueKey('media-duration-${asset.id}'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Colors.white,
fontFeatures: const [FontFeature.tabularFigures()],
+330 -41
View File
@@ -1,3 +1,5 @@
import '../../shared/widgets/listenable_selector.dart';
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:cutdex/errors/app_failure.dart';
@@ -11,19 +13,24 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../integrations/platform/platform_capabilities.dart';
import 'package:cutdex_ui/icons.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/project_state.dart';
import '../../workspace/projects.dart';
import '../../workspace/timeline_provider.dart';
import '../../workspace/timeline_session.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';
import 'desktop_media_asset_tile.dart';
import 'media_browser_layout.dart';
extension MediaFilterLabel on MediaFilter {
String label(BuildContext context) => switch (this) {
@@ -44,26 +51,37 @@ class MediaBrowserBody extends ConsumerStatefulWidget {
required this.grid,
this.draggable = false,
this.compact = false,
this.desktop = false,
});
final String projectId;
final bool grid;
final bool draggable;
final bool compact;
final bool desktop;
@override
ConsumerState<MediaBrowserBody> createState() => _MediaBrowserBodyState();
}
class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
with WidgetsBindingObserver {
final _desktopScroll = _MediaScrollController();
MediaBrowserController? _anchorOwner;
List<AssetDocument> _anchorAssets = const [];
int _anchorColumns = 1;
double _anchorStride = 1;
Object? _viewportConfiguration;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_desktopScroll.addListener(_storeBrowseAnchor);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_desktopScroll.dispose();
super.dispose();
}
@@ -83,6 +101,67 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
bool get _isGrid => widget.grid;
bool get _desktop => ref.read(platformCapabilitiesProvider).nativeFileDrop;
void _storeBrowseAnchor() {
if (_anchorOwner == null ||
_anchorAssets.isEmpty ||
!_desktopScroll.hasClients) {
return;
}
final rowPosition = math.max(
0.0,
(_desktopScroll.position.pixels - DesktopMediaMetrics.padding) /
_anchorStride,
);
final row = rowPosition.floor();
final index = math.min(_anchorAssets.length - 1, row * _anchorColumns);
_anchorOwner!.viewportAnchor = (
assetId: _anchorAssets[index].id,
fraction: rowPosition - row,
);
}
void _prepareDesktopScroll({
required List<AssetDocument> assets,
required Object configuration,
required int columns,
required double extent,
required double height,
}) {
if (_viewportConfiguration == configuration) return;
_viewportConfiguration = configuration;
final owner = _browser;
final anchor = owner.viewportAnchor;
final index = anchor == null
? -1
: assets.indexWhere((asset) => asset.id == anchor.assetId);
final stride = extent + DesktopMediaMetrics.gap;
final row = index < 0 ? 0 : index ~/ columns;
final fraction = index < 0 ? 0.0 : anchor!.fraction;
final rows = (assets.length / columns).ceil();
final maximum = math.max(
0.0,
DesktopMediaMetrics.padding * 2 +
rows * stride -
(_isGrid && rows > 0 ? DesktopMediaMetrics.gap : 0) -
height,
);
final offset =
(row == 0 && fraction == 0
? 0.0
: DesktopMediaMetrics.padding + (row + fraction) * stride)
.clamp(0.0, maximum);
_anchorOwner = owner;
_anchorAssets = assets;
_anchorColumns = columns;
_anchorStride = stride;
_desktopScroll.initialOffset = offset;
// Layout consumes the corrected pixels before painting. No change
// notification or post-frame jump is needed to preserve the browse anchor.
for (final position in _desktopScroll.positions) {
if (position.pixels != offset) position.correctPixels(offset);
}
}
Future<void> _action(Future<bool> Function() action) async {
final ok = await action();
if (!mounted || ok) return;
@@ -116,15 +195,22 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
],
child: AppField(
label: context.l10n.name,
child: TextField(
child: Builder(
builder: (fieldContext) => TextField(
controller: controller,
autofocus: true,
style: AppTheme.inputTextStyle(fieldContext),
cursorHeight: AppTheme.inputCursorHeight(fieldContext),
textAlignVertical: TextAlignVertical.center,
onSubmitted: (value) {
if (value.trim().isNotEmpty) Navigator.pop(context, value.trim());
if (value.trim().isNotEmpty) {
Navigator.pop(context, value.trim());
}
},
),
),
),
),
);
// The route's closing animation can still read its text controller.
await Future<void>.delayed(const Duration(milliseconds: 200));
@@ -159,12 +245,14 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
}
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: ref.watch(mediaBrowserProvider(widget.projectId)),
builder: (context, _) => _buildBrowser(context),
Widget build(BuildContext context) {
final browser = ref.watch(mediaBrowserProvider(widget.projectId));
// Provider subscriptions belong to this Consumer's build lifecycle. Local
// selector rebuilds must not register watches on this outer ref.
ref.watch(
externalMediaImportProvider(widget.projectId)
.select((value) => value.isLoading),
);
Widget _buildBrowser(BuildContext context) {
ref.watch(externalMediaImportProvider(widget.projectId));
ref.watch(
projectsProvider.select(
(value) => (
@@ -177,12 +265,6 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
);
final workspace = ref.read(projectsProvider).value;
final active = workspace?.activeProject?.id == widget.projectId;
final allAssets = active ? workspace!.assets : <AssetDocument>[];
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
@@ -190,12 +272,40 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
.watch(editorTimelineProvider(widget.projectId, timelineId))
.asData
?.value;
return assets.isEmpty
return ListenableSelector(
listenable: browser,
select: () => (
browser.filter,
widget.desktop ? browser.query : '',
widget.desktop ? browser.sort : MediaSort.importOrder,
widget.desktop ? browser.gridSize : MediaGridSize.medium,
),
builder: (context, _) => _buildBrowser(context, workspace, timeline),
);
}
Widget _buildBrowser(
BuildContext context,
ProjectState? workspace,
EditorTimelineSession? timeline,
) {
final active = workspace?.activeProject?.id == widget.projectId;
final timelineId = active ? workspace?.timeline?.id : null;
final allAssets = active ? workspace!.assets : <AssetDocument>[];
final assets = _browser.visibleAssets(allAssets, desktop: widget.desktop);
if (widget.desktop && assets.isEmpty) {
_viewportConfiguration = null;
_anchorOwner = null;
_anchorAssets = const [];
}
final content = assets.isEmpty
? Center(
child: Padding(
padding: const EdgeInsets.all(AppSpacing.medium),
child: Text(
_filter != MediaFilter.all
widget.desktop && _browser.query.trim().isNotEmpty
? context.l10n.noMatchingMedia
: _filter != MediaFilter.all
? context.l10n.noMediaOfType(_filter.label(context))
: _desktop
? context.l10n.dragMediaHint
@@ -206,16 +316,25 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
)
: LayoutBuilder(
builder: (context, constraints) {
final spacing = widget.compact
final spacing = widget.desktop
? DesktopMediaMetrics.gap
: widget.compact
? AppSpacing.gap
: AppSpacing.small;
final padding = widget.compact
final padding = widget.desktop
? DesktopMediaMetrics.padding
: widget.compact
? AppSidebarMetrics.outerPadding
: AppSpacing.compact;
final width = math.max(1.0, constraints.maxWidth - padding * 2);
final columns = math.max(
1,
widget.compact
widget.desktop
? DesktopMediaMetrics.columns(
width,
_browser.gridSize.targetWidth,
)
: widget.compact
? ((width + spacing) /
(maximumCompactMediaGridTileWidth + spacing))
.ceil()
@@ -228,6 +347,41 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
final labelHeight =
MediaQuery.textScalerOf(context).scale(textStyle.fontSize!) *
(textStyle.height ?? 1.2);
final desktopLabelHeight = widget.desktop && _isGrid
? DesktopMediaAssetTile.gridLabelHeight(context)
: 0.0;
final desktopExtent = !widget.desktop
? 0.0
: _isGrid
? DesktopMediaMetrics.gridExtent(
tileWidth,
desktopLabelHeight,
)
: math.max(
DesktopMediaMetrics.listRow,
DesktopMediaAssetTile.gridLabelHeight(context) +
DesktopMediaMetrics.tilePadding * 2,
);
if (widget.desktop) {
_prepareDesktopScroll(
assets: assets,
configuration: (
widget.projectId,
_browser,
_isGrid,
columns,
desktopExtent,
constraints.maxHeight,
_filter,
_browser.query,
_browser.sort,
allAssets,
),
columns: _isGrid ? columns : 1,
extent: desktopExtent,
height: constraints.maxHeight,
);
}
Widget item(BuildContext context, int index) {
final asset = assets[index];
return Consumer(
@@ -241,7 +395,11 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
final unavailable =
availability != null &&
availability != MediaAvailability.available;
return AppContextMenu(
return ListenableSelector<(bool, bool)>(
listenable: _browser,
select: () =>
(_selectedAssetId == asset.id, _checkingDrop),
builder: (context, presentation) => AppContextMenu(
key: ValueKey(('media-menu', asset.id)),
itemsBuilder: (_) {
final available = ref
@@ -249,33 +407,36 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
.asData
?.value;
final canEdit =
available?.activeProject?.id == widget.projectId &&
available?.activeProject?.id ==
widget.projectId &&
available?.projectBusy == false &&
!_checkingDrop;
final sequence = timeline?.activeSequenceId;
return [
AppMenuItem(
label: context.l10n.addToTimeline,
icon: Icons.add,
icon: AppIcons.add,
onPressed:
canEdit &&
!unavailable &&
sequence != null &&
available?.timeline?.id == timelineId
? () =>
_action(() => _browser.insertAsset(asset))
? () => _action(
() => _browser.insertAsset(asset),
)
: null,
),
AppMenuItem(
label: context.l10n.rename,
icon: Icons.drive_file_rename_outline,
icon: AppIcons.rename,
onPressed: canEdit ? () => _rename(asset) : null,
),
AppMenuItem(
label: defaultTargetPlatform == TargetPlatform.macOS
label:
defaultTargetPlatform == TargetPlatform.macOS
? context.l10n.revealFinder
: context.l10n.revealFileManager,
icon: Icons.folder_open,
icon: AppIcons.folderOpen,
onPressed: canEdit && _desktop
? () => _action(() => _browser.reveal(asset))
: null,
@@ -283,7 +444,7 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
const AppMenuSeparator(),
AppMenuItem(
label: context.l10n.removeMedia,
icon: Icons.delete_outline,
icon: AppIcons.delete,
destructive: true,
onPressed: canEdit ? () => _remove(asset) : null,
),
@@ -292,12 +453,13 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
child: Listener(
onPointerDown: (event) {
if (event.buttons == 2) {
setState(() => _selectedAssetId = asset.id);
_selectedAssetId = asset.id;
}
},
child: _SelectableAsset(
key: ValueKey(asset.id),
grid: _isGrid,
desktop: widget.desktop,
drag: MediaAssetDrag(
projectId: widget.projectId,
assetId: asset.id,
@@ -306,28 +468,46 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
draggable:
widget.draggable &&
!workspace!.projectBusy &&
!_checkingDrop &&
!presentation.$2 &&
!unavailable,
selected: _selectedAssetId == asset.id,
selected: presentation.$1,
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)),
Widget scrollView(ScrollController controller) => !_isGrid
? widget.desktop
? ListView.builder(
key: PageStorageKey((
'media-list',
widget.projectId,
)),
controller: controller,
padding: EdgeInsets.all(padding),
itemCount: assets.length,
itemExtent: desktopExtent + spacing,
itemBuilder: (context, index) => Padding(
padding: EdgeInsets.only(bottom: spacing),
child: item(context, index),
),
)
: ListView.separated(
key: PageStorageKey((
'media-list',
widget.projectId,
)),
controller: controller,
padding: EdgeInsets.all(padding),
itemCount: assets.length,
itemBuilder: item,
separatorBuilder: (_, _) => SizedBox(height: spacing),
separatorBuilder: (_, _) =>
SizedBox(height: spacing),
)
: GridView.builder(
key: PageStorageKey(('media-grid', widget.projectId)),
@@ -336,11 +516,12 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: columns,
crossAxisSpacing: spacing,
mainAxisSpacing: widget.compact
mainAxisSpacing: widget.desktop || widget.compact
? spacing
: AppSpacing.compact,
mainAxisExtent:
tileWidth * 9 / 16 +
mainAxisExtent: widget.desktop
? desktopExtent
: tileWidth * 9 / 16 +
(widget.compact
? AppSpacing.gap
: AppSpacing.small) +
@@ -349,13 +530,73 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
),
itemCount: assets.length,
itemBuilder: item,
),
);
if (widget.desktop) {
return ScrollEdgeFade(
controller: _desktopScroll,
child: scrollView(_desktopScroll),
);
}
return ScrollEdgeFadeBuilder(
key: ValueKey(('media-scroll-fade', widget.projectId, _isGrid)),
builder: scrollView,
);
},
);
if (!widget.desktop) return content;
return Column(
children: [
if (!_isGrid)
const DesktopMediaListHeader(key: Key('media-list-header')),
Expanded(child: content),
const Divider(height: 1),
SizedBox(
key: const Key('media-browser-footer'),
height: 28,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: ListenableSelector(
listenable: _browser,
select: () => assets.any((asset) => asset.id == _selectedAssetId),
builder: (context, selected) => Row(
children: [
Expanded(
child: Text(
context.l10n.mediaCount(assets.length),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall,
),
),
if (selected)
Flexible(
child: Align(
alignment: AlignmentDirectional.centerEnd,
child: Text(
context.l10n.mediaSelectedCount(1),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall,
),
),
),
],
),
),
),
),
],
);
}
Widget _assetTile(AssetDocument asset, MediaAvailability? availability) {
if (widget.desktop) {
return DesktopMediaAssetTile(
asset: asset,
grid: _isGrid,
availability: availability,
);
}
final unavailable =
availability != null && availability != MediaAvailability.available;
final cover = unavailable
@@ -388,7 +629,7 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
aspectRatio: 16 / 9,
child: ColoredBox(
color: AppSurfaces.of(context).previewBackground,
child: const Icon(Icons.insert_drive_file_outlined),
child: const Icon(AppIcons.file),
),
),
};
@@ -429,10 +670,28 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
}
}
class _MediaScrollController extends ScrollController {
_MediaScrollController() : super(keepScrollOffset: false);
double initialOffset = 0;
@override
ScrollPosition createScrollPosition(
ScrollPhysics physics,
ScrollContext context,
ScrollPosition? oldPosition,
) => ScrollPositionWithSingleContext(
physics: physics,
context: context,
initialPixels: initialOffset,
keepScrollOffset: false,
);
}
class _SelectableAsset extends StatelessWidget {
const _SelectableAsset({
super.key,
required this.grid,
this.desktop = false,
required this.selected,
required this.drag,
required this.name,
@@ -443,6 +702,7 @@ class _SelectableAsset extends StatelessWidget {
final bool selected;
final bool grid;
final bool desktop;
final MediaAssetDrag drag;
final String name;
final bool draggable;
@@ -457,7 +717,36 @@ class _SelectableAsset extends StatelessWidget {
);
final tile = Semantics(
selected: selected,
child: desktop
? Material(
color: selected
? Theme.of(context).colorScheme.primary.withValues(alpha: .08)
: Colors.transparent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(6),
side: BorderSide(
color: selected
? Theme.of(context).colorScheme.primary
: Colors.transparent,
),
),
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: onTap,
hoverColor: Theme.of(context).colorScheme.onSurface
.withValues(alpha: .05),
child: Padding(
padding: const EdgeInsets.all(5),
child: grid
? child
: ConstrainedBox(
constraints: const BoxConstraints(minHeight: 38),
child: child,
),
),
),
)
: InkWell(
onTap: onTap,
hoverColor: Colors.transparent,
highlightColor: Colors.transparent,
@@ -14,6 +14,8 @@ import '../../workspace/timeline_provider.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'resource_section.dart';
enum MediaFilter {
all(null),
image('image'),
@@ -24,6 +26,18 @@ enum MediaFilter {
final String? kind;
}
enum MediaSort { importOrder, nameAscending, nameDescending }
/// Desktop thumbnail density, independent of touch-page presentation.
enum MediaGridSize {
small(120),
medium(160),
large(200);
const MediaGridSize(this.targetWidth);
final double targetWidth;
}
final mediaBrowserProvider = Provider.family<MediaBrowserController, String>((
ref,
projectId,
@@ -41,8 +55,9 @@ class MediaBrowserController extends ChangeNotifier {
final feedback = MediaImportFeedbackController();
bool _working = false;
bool _disposed = false;
bool get busy =>
_working || _ref.read(externalMediaImportProvider(projectId)).isLoading;
bool get importing =>
_ref.read(externalMediaImportProvider(projectId)).isLoading;
bool get busy => _working || importing;
bool get active =>
!_disposed &&
_ref.mounted &&
@@ -81,7 +96,11 @@ class MediaBrowserController extends ChangeNotifier {
.importFiles(files);
final asset = result?.selected.firstOrNull;
if (!_disposed && asset != null) {
_resourceSection = ResourceSection.imported;
_selectedAssetId = asset.id;
if (!asset.name.toLowerCase().contains(_query.trim().toLowerCase())) {
_query = '';
}
if (_filter != MediaFilter.all &&
asset.metadata['kind'] != _filter.kind) {
_filter = MediaFilter.all;
@@ -172,23 +191,87 @@ class MediaBrowserController extends ChangeNotifier {
String? _selectedAssetId;
MediaFilter _filter = MediaFilter.all;
bool _grid = true;
String _query = '';
MediaSort _sort = MediaSort.importOrder;
MediaGridSize _gridSize = MediaGridSize.medium;
ResourceSection _resourceSection = ResourceSection.imported;
/// The first visible desktop asset and its fraction through the current row.
/// Scroll updates are silent; browsing does not rebuild controls or metadata.
({String assetId, double fraction})? viewportAnchor;
String? get selectedAssetId => _selectedAssetId;
MediaFilter get filter => _filter;
bool get grid => _grid;
String get query => _query;
MediaSort get sort => _sort;
MediaGridSize get gridSize => _gridSize;
ResourceSection get resourceSection => _resourceSection;
/// Resource libraries are desktop navigation, separate from media filters.
set resourceSection(ResourceSection value) {
if (_resourceSection == value) return;
_resourceSection = value;
notifyListeners();
}
/// Touch pages keep their own presentation while sharing category selection.
List<AssetDocument> visibleAssets(
Iterable<AssetDocument> assets, {
bool desktop = false,
}) {
final query = desktop ? _query.trim().toLowerCase() : '';
final result = assets
.where(
(asset) =>
(_filter == MediaFilter.all ||
asset.metadata['kind'] == _filter.kind) &&
asset.name.toLowerCase().contains(query),
)
.toList();
if (desktop && _sort != MediaSort.importOrder) {
result.sort((a, b) {
var order = a.name.toLowerCase().compareTo(b.name.toLowerCase());
if (order == 0) order = a.id.compareTo(b.id);
return _sort == MediaSort.nameDescending ? -order : order;
});
}
return result;
}
set query(String value) {
if (_query == value) return;
_query = value;
notifyListeners();
}
set sort(MediaSort value) {
if (_sort == value) return;
_sort = value;
notifyListeners();
}
set selectedAssetId(String? value) {
if (_selectedAssetId == value) return;
_selectedAssetId = value;
notifyListeners();
}
set filter(MediaFilter value) {
if (_filter == value) return;
_filter = value;
notifyListeners();
}
set grid(bool value) {
if (_grid == value) return;
_grid = value;
notifyListeners();
}
set gridSize(MediaGridSize value) {
if (_gridSize == value) return;
_gridSize = value;
notifyListeners();
}
}
@@ -0,0 +1,33 @@
import 'dart:math' as math;
/// Shared desktop geometry for cards, rows, headers and browse anchoring.
abstract final class DesktopMediaMetrics {
static const padding = 12.0;
static const gap = 8.0;
static const tilePadding = 5.0;
static const listCover = 56.0;
static const listRow = 48.0;
static const listHeader = 28.0;
static int columns(double width, double targetWidth) =>
math.max(1, ((width + gap) / (targetWidth + gap)).floor());
static double gridExtent(double tileWidth, double labelHeight) =>
(tileWidth - tilePadding * 2) * 9 / 16 +
4 +
labelHeight +
tilePadding * 2;
}
/// Matching list-column visibility for a header and its asset rows.
final class DesktopMediaListColumns {
const DesktopMediaListColumns(double width)
: duration = width >= 240,
specification = width >= 480,
kind = width >= 620;
final bool duration, specification, kind;
static const durationWidth = 64.0;
static const specificationWidth = 136.0;
static const kindWidth = 56.0;
}
+23 -11
View File
@@ -1,4 +1,5 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
@@ -39,8 +40,19 @@ class TouchMediaBrowser extends ConsumerWidget {
@override
Widget build(BuildContext context, WidgetRef ref) {
final browser = ref.watch(mediaBrowserProvider(projectId));
ref.watch(externalMediaImportProvider(projectId));
final workspace = ref.watch(projectsProvider).value;
ref.watch(
externalMediaImportProvider(projectId).select((value) => value.isLoading),
);
final workspace = ref.watch(
projectsProvider.select(
(value) => value.value?.copyWith(
recent: const [],
timelines: const [],
error: null,
creatingTimeline: false,
),
),
);
final timelineId = workspace?.activeProject?.id == projectId
? workspace?.timeline?.id
: null;
@@ -72,20 +84,20 @@ class TouchMediaBrowser extends ConsumerWidget {
height: 56,
child: Row(
children: [
SizedBox.square(
dimension: 48,
child: IconButton(
SizedBox(
height: 48,
child: TextButton(
key: const Key('media-import-button'),
tooltip: context.l10n.importMedia,
onPressed: browser.canImport
? () => pickMediaFiles(browser)
: null,
icon: const Icon(Icons.add),
child: Text(context.l10n.importMedia),
),
),
Expanded(
child: DropdownButton<MediaFilter>(
key: const Key('media-category-picker'),
icon: const Icon(AppIcons.expandMore),
isExpanded: true,
underline: const SizedBox.shrink(),
value: browser.filter,
@@ -110,8 +122,8 @@ class TouchMediaBrowser extends ConsumerWidget {
: context.l10n.gridLayout,
icon: Icon(
browser.grid
? Icons.view_list_outlined
: Icons.grid_view_outlined,
? AppIcons.listView
: AppIcons.gridView,
),
onPressed: () => browser.grid = !browser.grid,
),
@@ -119,7 +131,7 @@ class TouchMediaBrowser extends ConsumerWidget {
],
),
),
if (browser.busy) const LinearProgressIndicator(),
if (browser.importing) const LinearProgressIndicator(),
Expanded(
key: const Key('media-panel-body'),
child: MediaBrowserBody(
@@ -150,7 +162,7 @@ class TouchMediaBrowser extends ConsumerWidget {
);
}
},
icon: const Icon(Icons.add),
icon: const Icon(AppIcons.add),
label: Text(
context.l10n.addToTimeline,
maxLines: 1,
+398 -36
View File
@@ -1,4 +1,5 @@
import 'package:flutter/material.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
@@ -6,6 +7,7 @@ import '../../l10n/l10n.dart';
import '../../workspace/project_state.dart';
import 'media_browser_body.dart';
import 'media_browser_controller.dart';
import 'resource_navigation.dart';
class MediaBrowserToolbar extends StatefulWidget {
const MediaBrowserToolbar({
@@ -19,6 +21,16 @@ class MediaBrowserToolbar extends StatefulWidget {
this.projects = const [],
this.selectedProjectId,
this.onProjectSelected,
this.desktop = false,
this.query = '',
this.onQueryChanged,
this.sort = MediaSort.importOrder,
this.onSortChanged,
this.projectScoped = false,
this.resourceSection = ResourceSection.imported,
this.onResourceSectionChanged,
this.gridSize = MediaGridSize.medium,
this.onGridSizeChanged,
});
final bool canImport;
@@ -30,6 +42,16 @@ class MediaBrowserToolbar extends StatefulWidget {
final List<RecentProject> projects;
final String? selectedProjectId;
final ValueChanged<RecentProject>? onProjectSelected;
final bool desktop;
final bool projectScoped;
final ResourceSection resourceSection;
final ValueChanged<ResourceSection>? onResourceSectionChanged;
final String query;
final ValueChanged<String>? onQueryChanged;
final MediaSort sort;
final ValueChanged<MediaSort>? onSortChanged;
final MediaGridSize gridSize;
final ValueChanged<MediaGridSize>? onGridSizeChanged;
@override
State<MediaBrowserToolbar> createState() => _MediaBrowserToolbarState();
@@ -38,6 +60,25 @@ class MediaBrowserToolbar extends StatefulWidget {
class _MediaBrowserToolbarState extends State<MediaBrowserToolbar> {
Object? _filterConfiguration;
Widget? _filterControls;
final _search = TextEditingController();
@override
void initState() {
super.initState();
_search.text = widget.query;
}
@override
void didUpdateWidget(covariant MediaBrowserToolbar oldWidget) {
super.didUpdateWidget(oldWidget);
if (_search.text != widget.query) _search.text = widget.query;
}
@override
void dispose() {
_search.dispose();
super.dispose();
}
bool get canImport => widget.canImport;
VoidCallback get onImport => widget.onImport;
@@ -57,6 +98,11 @@ class _MediaBrowserToolbarState extends State<MediaBrowserToolbar> {
final configuration = (
filter,
grid,
widget.sort,
widget.gridSize,
widget.desktop,
widget.projectScoped,
canImport,
Theme.of(context),
Localizations.localeOf(context),
MediaQuery.textScalerOf(context),
@@ -69,13 +115,20 @@ class _MediaBrowserToolbarState extends State<MediaBrowserToolbar> {
final selected = projects
.where((project) => project.id == selectedProjectId)
.firstOrNull;
if (widget.desktop || AppTheme.isDesktop(context)) {
return _desktopToolbar(context, selected);
}
Widget row(Key key, Widget child) => SizedBox(
key: key,
height: AppControlSize.panelToolbar,
height: AppTheme.isDesktop(context)
? AppDesktopMetrics.panelHeader
: AppControlSize.panelToolbar,
child: Padding(
padding: const EdgeInsets.symmetric(
padding: EdgeInsets.symmetric(
horizontal: AppSidebarMetrics.outerPadding,
vertical: AppSpacing.gap,
vertical: AppTheme.isDesktop(context)
? AppSpacing.tiny
: AppSpacing.gap,
),
child: child,
),
@@ -87,22 +140,19 @@ class _MediaBrowserToolbarState extends State<MediaBrowserToolbar> {
row(
const Key('media-project-row'),
LayoutBuilder(
builder: (context, constraints) {
final painter = TextPainter(
text: TextSpan(
text: context.l10n.importMedia,
style: AppTheme.toolbarTextStyle(context),
),
textDirection: Directionality.of(context),
textScaler: MediaQuery.textScalerOf(context),
)..layout();
final compact = constraints.maxWidth < painter.width + 140;
painter.dispose();
return Row(
builder: (context, constraints) => Row(
children: [
Expanded(
child: AppDropdownMenu(
enabled: onProjectSelected != null && projects.isNotEmpty,
child: widget.projectScoped
? Text(
context.l10n.materials,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.titleSmall,
)
: AppDropdownMenu(
enabled:
onProjectSelected != null && projects.isNotEmpty,
maxHeight: 320,
items: [
for (final project in projects)
@@ -133,7 +183,7 @@ class _MediaBrowserToolbarState extends State<MediaBrowserToolbar> {
),
const SizedBox(width: AppSpacing.tiny),
const Icon(
Icons.keyboard_arrow_down,
AppIcons.expandMore,
size: AppIconSize.header,
),
],
@@ -142,30 +192,32 @@ class _MediaBrowserToolbarState extends State<MediaBrowserToolbar> {
),
),
const SizedBox(width: AppSpacing.tiny),
if (compact)
SizedBox.square(
dimension: AppControlSize.headerButton,
child: IconButton(
key: const Key('media-import-button'),
tooltip: context.l10n.importMedia,
onPressed: canImport ? onImport : null,
icon: const Icon(Icons.add, size: AppIconSize.header),
ConstrainedBox(
constraints: BoxConstraints(
maxWidth: (constraints.maxWidth * .45).clamp(
28,
double.infinity,
),
)
else
SizedBox(
),
child: SizedBox(
height: AppControlSize.headerButton,
child: TextButton.icon(
child: Tooltip(
message: context.l10n.importMedia,
child: TextButton(
key: const Key('media-import-button'),
style: AppTheme.toolbarButtonStyle(context),
onPressed: canImport ? onImport : null,
icon: const Icon(Icons.add, size: AppIconSize.header),
label: Text(context.l10n.importMedia),
child: Text(
context.l10n.importMedia,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
),
),
),
],
);
},
),
),
),
_filterControls ??= row(
@@ -206,7 +258,7 @@ class _MediaBrowserToolbarState extends State<MediaBrowserToolbar> {
),
const SizedBox(width: AppSpacing.tiny),
const Icon(
Icons.keyboard_arrow_down,
AppIcons.expandMore,
size: AppIconSize.header,
),
],
@@ -224,7 +276,7 @@ class _MediaBrowserToolbarState extends State<MediaBrowserToolbar> {
key: const Key('media-layout-toggle'),
onPressed: onToggleGrid,
icon: Icon(
grid ? Icons.view_list_outlined : Icons.grid_view_outlined,
grid ? AppIcons.listView : AppIcons.gridView,
size: AppIconSize.header,
),
tooltip: grid
@@ -238,4 +290,314 @@ class _MediaBrowserToolbarState extends State<MediaBrowserToolbar> {
],
);
}
Widget _desktopToolbar(BuildContext context, RecentProject? selected) {
Widget category() => Semantics(
label: context.l10n.mediaCategory,
child: AppDropdownMenu(
items: [
for (final option in MediaFilter.values)
AppMenuItem(
key: ValueKey('media-filter-${option.name}'),
label: option.label(context),
selected: option == filter,
selectOption: true,
onPressed: () => onFilterChanged(option),
),
],
builder: (context, toggle, focus) => AppToolbarDropdownButton(
buttonKey: const Key('media-category-button'),
focusNode: focus,
onPressed: toggle,
child: Row(
children: [
Expanded(
child: Text(
filter.label(context),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
const Icon(AppIcons.expandMore, size: 16),
],
),
),
),
);
String sortLabel(MediaSort value) => switch (value) {
MediaSort.importOrder => context.l10n.mediaSortImportOrder,
MediaSort.nameAscending => context.l10n.mediaSortNameAscending,
MediaSort.nameDescending => context.l10n.mediaSortNameDescending,
};
return Column(
key: const Key('media-panel-header'),
mainAxisSize: MainAxisSize.min,
children: [
if (widget.projectScoped)
ResourceSectionTabs(
selected: widget.resourceSection,
onSelected: widget.onResourceSectionChanged,
)
else
SizedBox(
key: const Key('media-project-row'),
height: 36,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
child: LayoutBuilder(
builder: (context, constraints) => Row(
children: [
Expanded(
child: AppDropdownMenu(
enabled:
onProjectSelected != null && projects.isNotEmpty,
maxHeight: 320,
items: [
for (final project in projects)
AppMenuItem(
key: ValueKey('media-project-${project.id}'),
label: project.name,
selected: project.id == selectedProjectId,
selectOption: true,
onPressed: onProjectSelected == null
? null
: () => onProjectSelected!(project),
),
],
builder: (context, toggle, focusNode) =>
AppToolbarDropdownButton(
buttonKey: const Key('media-project-button'),
focusNode: focusNode,
onPressed: toggle,
child: Row(
children: [
Expanded(
child: Text(
selected?.name ??
context.l10n.selectProject,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
const Icon(AppIcons.expandMore, size: 16),
],
),
),
),
),
const SizedBox(width: 4),
ConstrainedBox(
constraints: BoxConstraints(
maxWidth: (constraints.maxWidth * .45).clamp(
28,
double.infinity,
),
),
child: SizedBox(
height: 28,
child: Tooltip(
message: context.l10n.importMedia,
child: TextButton(
key: const Key('media-import-button'),
style: AppTheme.toolbarButtonStyle(context),
onPressed: canImport ? onImport : null,
child: Text(
context.l10n.importMedia,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
),
),
),
],
),
),
),
),
if (!widget.projectScoped ||
widget.resourceSection == ResourceSection.imported)
_filterControls ??= _desktopControls(context, category, sortLabel),
],
);
}
Widget _desktopControls(
BuildContext context,
Widget Function() category,
String Function(MediaSort) sortLabel,
) {
List<Widget> sortItems() => [
for (final value in MediaSort.values)
AppMenuItem(
key: ValueKey('media-sort-${value.name}'),
label: sortLabel(value),
selected: widget.sort == value,
selectOption: true,
onPressed: widget.onSortChanged == null
? null
: () => widget.onSortChanged!(value),
),
];
String sizeLabel(MediaGridSize value) => switch (value) {
MediaGridSize.small => context.l10n.mediaThumbnailSmall,
MediaGridSize.medium => context.l10n.mediaThumbnailMedium,
MediaGridSize.large => context.l10n.mediaThumbnailLarge,
};
List<Widget> sizeItems() => [
for (final value in MediaGridSize.values)
AppMenuItem(
key: ValueKey('media-size-${value.name}'),
label: sizeLabel(value),
selected: widget.gridSize == value,
selectOption: true,
onPressed: !grid || widget.onGridSizeChanged == null
? null
: () => widget.onGridSizeChanged!(value),
),
];
Widget menuButton({
required Key key,
required String tooltip,
required IconData icon,
required List<Widget> items,
}) => SizedBox.square(
dimension: 28,
child: AppDropdownMenu(
items: items,
builder: (context, toggle, focus) => IconButton(
key: key,
focusNode: focus,
tooltip: tooltip,
onPressed: toggle,
padding: EdgeInsets.zero,
icon: Icon(icon, size: 16),
),
),
);
return SizedBox(
key: const Key('media-filter-row'),
height: 40,
child: Padding(
padding: const EdgeInsets.fromLTRB(12, 4, 12, 4),
child: LayoutBuilder(
builder: (context, constraints) {
final wide = constraints.maxWidth >= 400;
return Row(
children: [
Expanded(
child: TextField(
key: const Key('media-search'),
controller: _search,
enabled: widget.onQueryChanged != null,
style: AppTheme.inputTextStyle(
context,
style: AppTheme.toolbarTextStyle(context),
),
cursorHeight: AppTheme.inputCursorHeight(
context,
style: AppTheme.toolbarTextStyle(context),
),
textAlignVertical: TextAlignVertical.center,
decoration: InputDecoration(
hintText: context.l10n.searchOptions(
context.l10n.materials,
),
hintStyle: AppTheme.inputHintStyle(
context,
style: AppTheme.toolbarTextStyle(context),
),
isDense: true,
constraints: const BoxConstraints(minHeight: 32),
contentPadding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 4,
),
prefixIcon: constraints.maxWidth < 160
? null
: const Icon(AppIcons.search, size: 16),
prefixIconConstraints: const BoxConstraints(
minWidth: 28,
minHeight: 28,
),
),
onChanged: (value) => widget.onQueryChanged?.call(value),
),
),
const SizedBox(width: 4),
if (wide) ...[
SizedBox(width: 88, height: 28, child: category()),
const SizedBox(width: 4),
menuButton(
key: const Key('media-sort-button'),
tooltip: context.l10n.sortMedia,
icon: AppIcons.sort,
items: sortItems(),
),
const SizedBox(width: 4),
menuButton(
key: const Key('media-size-button'),
tooltip: context.l10n.mediaThumbnailSize,
icon: AppIcons.gridView,
items: sizeItems(),
),
] else
menuButton(
key: const Key('media-category-button'),
tooltip: MaterialLocalizations.of(context).showMenuTooltip,
icon: AppIcons.more,
items: [
AppMenuLabel(context.l10n.mediaCategory),
for (final option in MediaFilter.values)
AppMenuItem(
key: ValueKey('media-filter-${option.name}'),
label: option.label(context),
selected: option == filter,
selectOption: true,
onPressed: () => onFilterChanged(option),
),
const AppMenuSeparator(),
AppMenuLabel(context.l10n.sortMedia),
...sortItems(),
const AppMenuSeparator(),
AppMenuLabel(context.l10n.mediaThumbnailSize),
...sizeItems(),
],
),
const SizedBox(width: 4),
SizedBox.square(
dimension: 28,
child: IconButton(
key: const Key('media-layout-toggle'),
onPressed: onToggleGrid,
padding: EdgeInsets.zero,
icon: Icon(
grid ? AppIcons.listView : AppIcons.gridView,
size: 16,
),
tooltip: grid
? context.l10n.listLayout
: context.l10n.gridLayout,
),
),
if (widget.projectScoped) ...[
const SizedBox(width: 4),
SizedBox.square(
dimension: 28,
child: IconButton(
key: const Key('media-import-button'),
onPressed: canImport ? () => onImport() : null,
tooltip: context.l10n.importMedia,
padding: EdgeInsets.zero,
icon: const Icon(AppIcons.add, size: 16),
),
),
],
],
);
},
),
),
);
}
}
@@ -0,0 +1,76 @@
import 'package:cutdex_ui/theme.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widget_previews.dart';
import '../../l10n/app_localizations.dart';
import '../../workspace/project_state.dart';
import 'media_browser_controller.dart';
import 'media_browser_toolbar.dart';
@Preview(
name: 'Media toolbar — light',
group: 'Desktop media',
size: Size(320, 76),
)
Widget desktopMediaToolbarLightPreview() => _preview(Brightness.light);
@Preview(
name: 'Media toolbar — dark',
group: 'Desktop media',
size: Size(240, 76),
)
@Preview(
name: 'Media toolbar — narrow',
group: 'Desktop media',
size: Size(180, 76),
)
Widget desktopMediaToolbarDarkPreview() => _preview(Brightness.dark);
@Preview(
name: 'Media toolbar — wide',
group: 'Desktop media',
size: Size(640, 76),
)
Widget desktopMediaToolbarWidePreview() => _preview(Brightness.light);
Widget _preview(Brightness brightness) {
var query = '';
var filter = MediaFilter.all;
var sort = MediaSort.importOrder;
var grid = true;
var gridSize = MediaGridSize.medium;
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: AppTheme.desktopWorkspaceTheme(
AppTheme.forPalette(AppPalette.graphite, brightness),
),
locale: const Locale('zh'),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Scaffold(
body: StatefulBuilder(
builder: (context, setState) => MediaBrowserToolbar(
desktop: true,
projects: const [
RecentProject(id: 'demo', name: '城市漫游', path: '/demo'),
RecentProject(id: 'other', name: '旅行记录', path: '/other'),
],
selectedProjectId: 'demo',
onProjectSelected: (_) {},
canImport: true,
onImport: () {},
filter: filter,
onFilterChanged: (value) => setState(() => filter = value),
grid: grid,
onToggleGrid: () => setState(() => grid = !grid),
query: query,
onQueryChanged: (value) => setState(() => query = value),
sort: sort,
onSortChanged: (value) => setState(() => sort = value),
gridSize: gridSize,
onGridSizeChanged: (value) => setState(() => gridSize = value),
),
),
),
);
}
+59 -6
View File
@@ -16,6 +16,7 @@ import 'media_browser_body.dart';
import 'media_browser_toolbar.dart';
import 'media_browser_controller.dart';
import 'media_browser_feedback.dart';
import 'resource_navigation.dart';
/// Desktop presentation owns compact controls and native file dragging.
class MediaPanel extends ConsumerStatefulWidget {
@@ -26,8 +27,10 @@ class MediaPanel extends ConsumerStatefulWidget {
this.grid,
this.onGridChanged,
this.onSelectProject,
this.projectScoped = false,
}) : assert((grid == null) == (onGridChanged == null));
final String? projectId;
final bool projectScoped;
final ValueChanged<RecentProject>? onSelectProject;
final Color? backgroundColor;
final bool? grid;
@@ -50,6 +53,7 @@ class _MediaPanelState extends ConsumerState<MediaPanel> {
grid: grid,
draggable: true,
compact: true,
desktop: true,
);
}
return _body!;
@@ -81,6 +85,8 @@ class _MediaPanelState extends ConsumerState<MediaPanel> {
child: Column(
children: [
MediaBrowserToolbar(
desktop: true,
projectScoped: widget.projectScoped,
projects: workspace.$1,
onProjectSelected: onSelectProject,
canImport: false,
@@ -96,18 +102,32 @@ class _MediaPanelState extends ConsumerState<MediaPanel> {
);
}
final browser = ref.watch(mediaBrowserProvider(projectId));
ref.watch(externalMediaImportProvider(projectId));
ref.watch(
externalMediaImportProvider(projectId).select((value) => value.isLoading),
);
final nativeDrop = ref.watch(platformCapabilitiesProvider).nativeFileDrop;
return ListenableSelector(
listenable: browser,
select: () =>
(browser.filter, browser.grid, browser.busy, browser.canImport),
select: () => (
browser.filter,
browser.grid,
browser.busy,
browser.importing,
browser.canImport,
browser.query,
browser.sort,
browser.gridSize,
browser.resourceSection,
),
builder: (context, _) {
final grid = widget.grid ?? browser.grid;
final visible =
TickerMode.valuesOf(context).enabled &&
(ModalRoute.of(context)?.isCurrent ?? true);
final enabled = browser.canImport && visible;
final browsingImports =
!widget.projectScoped ||
browser.resourceSection == ResourceSection.imported;
void toggleGrid() {
final next = !grid;
if (widget.onGridChanged case final onChanged?) {
@@ -128,6 +148,11 @@ class _MediaPanelState extends ConsumerState<MediaPanel> {
Column(
children: [
MediaBrowserToolbar(
desktop: true,
projectScoped: widget.projectScoped,
resourceSection: browser.resourceSection,
onResourceSectionChanged: (value) =>
browser.resourceSection = value,
projects: workspace.$1,
selectedProjectId: projectId,
onProjectSelected: onSelectProject,
@@ -137,21 +162,45 @@ class _MediaPanelState extends ConsumerState<MediaPanel> {
onFilterChanged: (value) => browser.filter = value,
grid: grid,
onToggleGrid: toggleGrid,
query: browser.query,
onQueryChanged: (value) => browser.query = value,
sort: browser.sort,
onSortChanged: (value) => browser.sort = value,
gridSize: browser.gridSize,
onGridSizeChanged: (value) => browser.gridSize = value,
),
Expanded(
key: const Key('media-panel-body'),
child: widget.projectScoped
? IndexedStack(
index: browsingImports ? 0 : 1,
children: [
TickerMode(
enabled: browsingImports,
child: _browserBody(projectId, grid),
),
ResourceLibraryEmpty(
key: ValueKey((
'resource-library-empty',
projectId,
browser.resourceSection,
)),
section: browser.resourceSection,
),
],
)
: _browserBody(projectId, grid),
),
],
),
if (browser.busy)
if (browser.importing)
const DelayedLoadingIndicator(
child: Align(
alignment: Alignment.topCenter,
child: LinearProgressIndicator(),
),
),
if (_hovering && enabled)
if (_hovering && enabled && browsingImports)
const DropToAddOverlay(key: Key('media-drop-highlight')),
],
),
@@ -159,7 +208,11 @@ class _MediaPanelState extends ConsumerState<MediaPanel> {
);
if (!nativeDrop) return content;
return NativeProjectDropRegion(
enabled: visible && browser.active && (enabled || browser.busy),
enabled:
browsingImports &&
visible &&
browser.active &&
(enabled || browser.busy),
onEnter: (_) {
if (enabled) setState(() => _hovering = true);
},
+208
View File
@@ -0,0 +1,208 @@
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import '../../l10n/app_localizations.dart';
import 'resource_section.dart';
export 'resource_section.dart';
extension ResourceSectionPresentation on ResourceSection {
String label(AppLocalizations l10n) => switch (this) {
ResourceSection.imported => l10n.resourceMyMedia,
ResourceSection.audio => l10n.audio,
ResourceSection.text => l10n.text,
ResourceSection.stickers => l10n.resourceStickers,
ResourceSection.effects => l10n.resourceEffects,
ResourceSection.transitions => l10n.resourceTransitions,
};
IconData get icon => switch (this) {
ResourceSection.imported => AppIcons.mediaLibrary,
ResourceSection.audio => AppIcons.audio,
ResourceSection.text => AppIcons.rename,
ResourceSection.stickers => AppIcons.image,
ResourceSection.effects => AppIcons.assistant,
ResourceSection.transitions => AppIcons.splitVertical,
};
}
/// Desktop resource tabs share the timeline's scrolling and edge fades.
class ResourceSectionTabs extends StatefulWidget {
const ResourceSectionTabs({
super.key,
required this.selected,
required this.onSelected,
});
final ResourceSection selected;
final ValueChanged<ResourceSection>? onSelected;
@override
State<ResourceSectionTabs> createState() => _ResourceSectionTabsState();
}
class _ResourceSectionTabsState extends State<ResourceSectionTabs> {
final _scrollController = ScrollController();
final _selectedTabKey = GlobalKey();
@override
void initState() {
super.initState();
_showSelectedTab();
}
@override
void didUpdateWidget(covariant ResourceSectionTabs oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.selected != widget.selected) _showSelectedTab();
}
void _showSelectedTab() {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
final selected = _selectedTabKey.currentContext;
if (selected == null) return;
if (_scrollController.hasClients) {
final position = _scrollController.position;
if (widget.selected == ResourceSection.values.first) {
_scrollController.jumpTo(position.minScrollExtent);
return;
}
if (widget.selected == ResourceSection.values.last) {
_scrollController.jumpTo(position.maxScrollExtent);
return;
}
}
Scrollable.ensureVisible(
selected,
alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtEnd,
);
Scrollable.ensureVisible(
selected,
alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart,
);
});
}
void _onPointerSignal(PointerSignalEvent 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;
final target = (position.pixels + delta).clamp(
position.minScrollExtent,
position.maxScrollExtent,
);
if (target == position.pixels) return;
GestureBinding.instance.pointerSignalResolver.register(event, (_) {
if (_scrollController.hasClients) _scrollController.jumpTo(target);
});
}
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
return SizedBox(
key: const Key('resource-section-tabs'),
height: 36,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 5),
child: ScrollEdgeFade(
controller: _scrollController,
axis: Axis.horizontal,
child: Listener(
onPointerSignal: _onPointerSignal,
child: SingleChildScrollView(
key: const Key('resource-tabs-list'),
controller: _scrollController,
scrollDirection: Axis.horizontal,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 4),
child: Row(
children: [
for (final section in ResourceSection.values) ...[
if (section != ResourceSection.values.first)
const SizedBox(width: 4),
KeyedSubtree(
key: widget.selected == section
? _selectedTabKey
: null,
child: Semantics(
selected: widget.selected == section,
child: TextButton(
key: ValueKey('resource-tab-${section.name}'),
style: AppTheme.timelineTabStyle(
context,
selected: widget.selected == section,
),
onPressed: widget.onSelected == null
? null
: () => widget.onSelected!(section),
child: Text(section.label(l10n), maxLines: 1),
),
),
),
],
],
),
),
),
),
),
),
);
}
}
class ResourceLibraryEmpty extends StatelessWidget {
const ResourceLibraryEmpty({super.key, required this.section});
final ResourceSection section;
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final theme = Theme.of(context);
return Center(
child: SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
section.icon,
size: 28,
color: theme.colorScheme.onSurfaceVariant,
),
const SizedBox(height: 12),
Text(
l10n.resourceLibraryEmpty(section.label(l10n)),
textAlign: TextAlign.center,
style: theme.textTheme.bodyMedium,
),
if (section == ResourceSection.audio) ...[
const SizedBox(height: 6),
Text(
l10n.resourceImportedAudioHint,
textAlign: TextAlign.center,
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
],
],
),
),
);
}
}
@@ -0,0 +1,56 @@
import 'package:cutdex_ui/theme.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widget_previews.dart';
import '../../l10n/app_localizations.dart';
import 'resource_navigation.dart';
@Preview(
name: 'Resource categories — wide',
group: 'Desktop media',
size: Size(560, 260),
)
Widget wideResourceNavigationPreview() => _preview(Brightness.light);
@Preview(
name: 'Resource categories — narrow',
group: 'Desktop media',
size: Size(240, 260),
)
Widget narrowResourceNavigationPreview() => _preview(Brightness.dark);
Widget _preview(Brightness brightness) {
var section = ResourceSection.imported;
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: AppTheme.desktopWorkspaceTheme(
AppTheme.forPalette(AppPalette.graphite, brightness),
),
locale: const Locale('zh'),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Scaffold(
body: StatefulBuilder(
builder: (context, setState) => Column(
children: [
ResourceSectionTabs(
selected: section,
onSelected: (value) => setState(() => section = value),
),
const Divider(height: 1),
Expanded(
child: section == ResourceSection.imported
? Center(
child: Text(
AppLocalizations.of(context)!.dragMediaHint,
textAlign: TextAlign.center,
),
)
: ResourceLibraryEmpty(section: section),
),
],
),
),
),
);
}
+2
View File
@@ -0,0 +1,2 @@
/// Resource navigation is separate from filters on project-imported files.
enum ResourceSection { imported, audio, text, stickers, effects, transitions }
+16 -3
View File
@@ -1,3 +1,5 @@
import '../../shared/widgets/listenable_selector.dart';
import 'package:cutdex/l10n/l10n.dart';
import 'package:cutdex_sdk/project.dart';
@@ -11,6 +13,7 @@ import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import '../../shared/widgets/confirm_resource_download_cancel.dart';
import '../../shared/widgets/error_notification_host.dart';
import '../../shared/widgets/processing_resource_download_dialog.dart';
import '../../workspace/timeline_session.dart';
@@ -268,11 +271,11 @@ class _TranscriptionDialogState extends ConsumerState<TranscriptionDialog> {
_closing = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
final messenger = ScaffoldMessenger.maybeOf(context);
final notifications = ErrorNotificationHost.maybeOf(context);
final message = context.l10n.subtitleTaskStarted;
_dismissDialog();
if (next is SubtitleStarted) {
messenger?.showSnackBar(SnackBar(content: Text(message)));
notifications?.showMessage(content: Text(message));
}
});
}
@@ -280,8 +283,18 @@ class _TranscriptionDialogState extends ConsumerState<TranscriptionDialog> {
ref.listen(subtitleDownloadProvider, (_, next) => handleResult(next));
ref.listen(_startProvider, (_, next) => handleResult(next));
return ListenableBuilder(
return ListenableSelector<Object>(
listenable: widget.session,
select: () {
final service = widget.session.transcriptions;
return (
service?.recognitionAvailable,
service?.translationAvailable,
service?.tasks.any((task) => !task.terminal),
service?.translationTasks.any((task) => !task.terminal),
widget.session.acceptsEdits,
);
},
builder: (context, _) {
final service = widget.session.transcriptions;
if (service?.recognitionAvailable != true ||
@@ -1,6 +1,7 @@
import 'package:cutdex/l10n/l10n.dart';
import 'package:flutter/material.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import '../../workspace/media_availability.dart';
@@ -34,7 +35,7 @@ class UnavailableMediaPlaceholder extends StatelessWidget {
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.broken_image_outlined,
AppIcons.imageUnavailable,
size: isPreview ? 32 : 24,
color: theme.colorScheme.error,
),
+3 -2
View File
@@ -3,6 +3,7 @@ import 'package:flutter/material.dart';
import 'media_asset_cover.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
class VisualAssetTile extends StatelessWidget {
@@ -25,8 +26,8 @@ class VisualAssetTile extends StatelessWidget {
fallback: Center(
child: Icon(
asset.metadata['kind'] == 'image'
? Icons.image_outlined
: Icons.movie_outlined,
? AppIcons.image
: AppIcons.video,
size: AppIconSize.emptyState,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
@@ -5,6 +5,7 @@ import 'package:flutter/material.dart';
import '../../l10n/l10n.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
class FullscreenPlaybackBar extends StatefulWidget {
@@ -84,7 +85,7 @@ class _FullscreenPlaybackBarState extends State<FullscreenPlaybackBar> {
alignment: Alignment.centerLeft,
child: _button(
context,
Icons.first_page,
AppIcons.seekStart,
context.l10n.previewGoToStart,
enabled ? () => widget.onSeek!(0) : null,
),
@@ -94,20 +95,20 @@ class _FullscreenPlaybackBarState extends State<FullscreenPlaybackBar> {
children: [
_button(
context,
Icons.skip_previous,
AppIcons.previousFrame,
context.l10n.previewPreviousFrame,
enabled && _position > 0 ? () => _step(-1) : null,
),
_button(
context,
widget.playing ? Icons.pause : Icons.play_arrow,
widget.playing ? AppIcons.pause : AppIcons.play,
widget.playing ? context.l10n.pause : context.l10n.play,
widget.onPlayPause,
size: 32,
),
_button(
context,
Icons.skip_next,
AppIcons.nextFrame,
context.l10n.previewNextFrame,
enabled && _position < widget.durationTick
? () => _step(1)
@@ -119,7 +120,7 @@ class _FullscreenPlaybackBarState extends State<FullscreenPlaybackBar> {
alignment: Alignment.centerRight,
child: _button(
context,
Icons.fullscreen_exit,
AppIcons.exitFullscreen,
context.l10n.exitPreviewFullscreen,
widget.onExit,
key: const Key('preview-fullscreen'),
+7 -2
View File
@@ -6,6 +6,7 @@ import 'package:flutter/services.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_native/cutdex_native.dart';
import 'package:cutdex_sdk/runtime.dart';
/// Moves the existing preview into the root overlay, retaining its native view.
class PreviewFullscreenHost extends StatefulWidget {
@@ -135,7 +136,11 @@ class PreviewFullscreenLayout extends StatelessWidget {
fit: StackFit.expand,
children: [
Positioned.fill(
bottom: fullscreen ? 0 : AppControlSize.panelHeader,
bottom: fullscreen
? 0
: AppTheme.isDesktop(context)
? AppDesktopMetrics.playbackBar
: AppControlSize.panelHeader,
child: canvas,
),
Align(
@@ -158,7 +163,7 @@ class PreviewFullscreenLayout extends StatelessWidget {
borderRadius: BorderRadius.circular(AppRadius.large),
)
: null,
child: toolbar,
child: NativePreviewOcclusion(child: toolbar),
),
),
],
+132 -50
View File
@@ -16,6 +16,7 @@ import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
@@ -118,9 +119,10 @@ FutureOr<PreviewController?> _preparePreview(
}
try {
if (!ref.mounted) throw StateError('Editor closed');
final result = ref
.read(previewControllerRegistryProvider)
.prepare(ids, timeline);
final registry = ref.read(previewControllerRegistryProvider);
final release = registry.retain(ids);
ref.onDispose(release);
final result = registry.prepare(ids, timeline);
if (result case Future<PreviewController?> future) {
return future.catchError((Object error, StackTrace stack) {
AppDiagnostics.failure(
@@ -183,12 +185,12 @@ class _EditorPreviewContent extends ConsumerWidget {
final watched = pending
? const AsyncData<PreviewController?>(null)
: ref.watch(provider);
final cached = watched.isLoading && !watched.hasError
? ref.read(previewControllerRegistryProvider).cached((
projectId,
timelineId,
))
: null;
final prepared = ref.watch(
previewControllerRegistryProvider.select(
(registry) => registry.cached((projectId, timelineId)),
),
);
final cached = watched.isLoading && !watched.hasError ? prepared : null;
final state = cached == null
? watched
: AsyncData<PreviewController?>(cached);
@@ -221,10 +223,22 @@ class _EditorPreviewContent extends ConsumerWidget {
PreviewFullscreenScope.of(context)?.fullscreen != true &&
activeController.session != null &&
activeController.error == null
? (Rect rect) => ListenableBuilder(
? (Rect rect) => ListenableSelector<Object>(
listenable: activeController.positionChanges,
select: () => (
activeController.positionTick,
activeController.selectedVisualIds.isNotEmpty,
activeController.maskEditingElement,
activeController.obscureEditingElement,
),
builder: (context, _) => Theme(
data: AppTheme.previewCanvasTheme,
child: NativePreviewOverlay(
session: activeController.session!,
enabled:
activeController.selectedVisualIds.isNotEmpty ||
activeController.maskEditingElement != null ||
activeController.obscureEditingElement != null,
child:
activeController.maskEditingElement != null ||
activeController.obscureEditingElement != null
@@ -237,7 +251,9 @@ class _EditorPreviewContent extends ConsumerWidget {
)
: PreviewInteractionOverlay(
onError: (error) =>
ErrorNotificationHost.maybeOf(context)?.show(
ErrorNotificationHost.maybeOf(
context,
)?.show(
ErrorNotification(
content: Text(
context.l10n.canvasTransformFailed,
@@ -249,6 +265,7 @@ class _EditorPreviewContent extends ConsumerWidget {
canvasRect: rect,
),
),
),
)
: null;
return showCanvas
@@ -256,6 +273,8 @@ class _EditorPreviewContent extends ConsumerWidget {
padding:
PreviewFullscreenScope.of(context)?.fullscreen == true
? EdgeInsets.zero
: AppTheme.isDesktop(context)
? const EdgeInsets.all(AppDesktopMetrics.panelPadding)
: AppSpacing.panelSection,
child: PreviewCanvas(
alignment: Alignment.center,
@@ -339,7 +358,9 @@ class _EditorPreviewContent extends ConsumerWidget {
return Stack(
fit: StackFit.expand,
children: [
if (preview.session case final session?)
if (preview.session case final session?
when preview.error == null &&
preview.durationTick > 0)
RuntimePreview(session: session),
ListenableSelector(
listenable: Listenable.merge([
@@ -367,6 +388,7 @@ class _EditorPreviewContent extends ConsumerWidget {
padding: const EdgeInsets.all(
AppSpacing.medium,
),
child: NativePreviewOcclusion(
child: Text(
context.l10n.mediaOffline(
unavailable.join(', '),
@@ -374,7 +396,9 @@ class _EditorPreviewContent extends ConsumerWidget {
maxLines: 2,
overflow:
TextOverflow.ellipsis,
textAlign: TextAlign.center,
textAlign:
TextAlign.center,
),
),
),
),
@@ -478,9 +502,11 @@ class _SourcePreviewPanel extends ConsumerWidget {
child: Focus(
autofocus: true,
child: WorkspacePanel(
title: asset.name,
title: AppTheme.isDesktop(context) ? null : asset.name,
showHeaderDivider: false,
headerHeight: PreviewFullscreenScope.of(context)?.fullscreen == true
headerHeight:
AppTheme.isDesktop(context) ||
PreviewFullscreenScope.of(context)?.fullscreen == true
? 0
: AppControlSize.panelHeader,
child: PreviewFullscreenLayout(
@@ -508,6 +534,8 @@ class _SourcePreviewPanel extends ConsumerWidget {
padding:
PreviewFullscreenScope.of(context)?.fullscreen == true
? EdgeInsets.zero
: AppTheme.isDesktop(context)
? const EdgeInsets.all(AppDesktopMetrics.panelPadding)
: AppSpacing.panelSection,
child: PreviewCanvas(
alignment: Alignment.center,
@@ -559,6 +587,7 @@ class _SourcePreviewPanel extends ConsumerWidget {
return Stack(
fit: StackFit.expand,
children: [
if (!source.audioOnly)
RuntimePreview(session: session),
if (source.audioOnly)
IgnorePointer(
@@ -621,6 +650,64 @@ class _PreviewToolbar extends StatelessWidget {
controller?.frameDuration ??
TimelineFormat.fps30.frameDuration;
Future<void> _seek(BuildContext context, int requested) async {
final preview = controller;
final duration = source?.durationTick ?? preview?.durationTick ?? 0;
final frameTick = TimelineClock.standard.toTicks(_frameDuration);
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) {
ErrorNotificationHost.maybeOf(context)?.show(
ErrorNotification(
content: Text(previewErrorMessage(error, context.l10n)),
),
);
}
}
}
Widget _frameButton(
BuildContext context,
int direction,
) => ListenableSelector(
listenable: _clock,
select: () => (
source?.canPlay ?? controller?.canPlay ?? false,
source?.durationTick ?? controller?.durationTick ?? 0,
),
builder: (context, state) => IconButton(
key: Key(direction < 0 ? 'preview-previous-frame' : 'preview-next-frame'),
tooltip: direction < 0
? context.l10n.previewPreviousFrame
: context.l10n.previewNextFrame,
onPressed: !state.$1 || state.$2 <= 0
? null
: () {
final position =
source?.positionTick ?? controller?.positionTick ?? 0;
unawaited(
_seek(
context,
position +
direction *
TimelineClock.standard.toTicks(_frameDuration),
),
);
},
icon: Icon(direction < 0 ? AppIcons.previousFrame : AppIcons.nextFrame),
),
);
Widget _build(BuildContext context) {
final preview = controller;
final playing = source?.playing ?? preview?.playing ?? false;
@@ -633,32 +720,7 @@ class _PreviewToolbar extends StatelessWidget {
final duration = source?.durationTick ?? preview?.durationTick ?? 0;
final frameTick = TimelineClock.standard.toTicks(frameDuration);
final canPlay = source?.canPlay ?? preview?.canPlay ?? false;
Future<void> 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) {
ErrorNotificationHost.maybeOf(context)?.show(
ErrorNotification(
content: Text(previewErrorMessage(error, context.l10n)),
),
);
}
}
}
Future<void> seek(int requested) => _seek(context, requested);
final sequence = preview?.activeSequence();
final view = sequence == null ? null : preview!.viewForSequence(sequence);
@@ -696,10 +758,14 @@ class _PreviewToolbar extends StatelessWidget {
}
return SizedBox(
key: const Key('preview-toolbar'),
height: AppControlSize.panelHeader,
height: AppTheme.isDesktop(context)
? AppDesktopMetrics.playbackBar
: AppControlSize.panelHeader,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.compact),
child: Row(
child: LayoutBuilder(
builder: (context, constraints) {
final controls = Row(
children: [
Expanded(
child: ListenableSelector(
@@ -715,7 +781,9 @@ class _PreviewToolbar extends StatelessWidget {
children: [
TextSpan(
text: _time(
source?.positionTick ?? preview?.positionTick ?? 0,
source?.positionTick ??
preview?.positionTick ??
0,
_frameDuration,
),
style: TextStyle(
@@ -726,7 +794,9 @@ class _PreviewToolbar extends StatelessWidget {
text:
' / ${_time(source?.durationTick ?? preview?.durationTick ?? 0, _frameDuration)}',
style: TextStyle(
color: Theme.of(context).colorScheme.onSurfaceVariant,
color: Theme.of(context)
.colorScheme
.onSurfaceVariant,
),
),
],
@@ -739,6 +809,7 @@ class _PreviewToolbar extends StatelessWidget {
),
),
),
if (AppTheme.isDesktop(context)) _frameButton(context, -1),
ListenableSelector(
listenable: source ?? preview,
select: () => (
@@ -754,10 +825,11 @@ class _PreviewToolbar extends StatelessWidget {
: preview != null && preview.canPlay
? preview.togglePlayback
: null,
icon: Icon(playing ? Icons.pause : Icons.play_arrow),
icon: Icon(playing ? AppIcons.pause : AppIcons.play),
);
},
),
if (AppTheme.isDesktop(context)) _frameButton(context, 1),
Expanded(
child: ListenableSelector(
listenable: source ?? preview,
@@ -781,7 +853,7 @@ class _PreviewToolbar extends StatelessWidget {
IconButton(
tooltip: context.l10n.retryPreview,
onPressed: preview.busy ? null : preview.retry,
icon: const Icon(Icons.refresh),
icon: const Icon(AppIcons.refresh),
),
const SizedBox(width: AppSpacing.gap),
],
@@ -793,7 +865,8 @@ class _PreviewToolbar extends StatelessWidget {
emptyLabel: context.l10n.noMatchingOptions,
label: context.l10n.canvasRatio,
outlined: false,
value: preview?.canvas ?? ProjectCanvas.widescreen,
value:
preview?.canvas ?? ProjectCanvas.widescreen,
onChanged: preview?.setCanvas,
options: [
for (final entry
@@ -818,8 +891,8 @@ class _PreviewToolbar extends StatelessWidget {
: null,
icon: Icon(
fullscreen.fullscreen
? Icons.fullscreen_exit
: Icons.fullscreen,
? AppIcons.exitFullscreen
: AppIcons.fullscreen,
),
),
],
@@ -828,6 +901,15 @@ class _PreviewToolbar extends StatelessWidget {
),
),
],
);
if (AppTheme.isDesktop(context) && constraints.maxWidth < 240) {
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: SizedBox(width: 240, child: controls),
);
}
return controls;
},
),
),
);
+272
View File
@@ -0,0 +1,272 @@
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import 'package:flutter/material.dart';
import '../../l10n/app_localizations.dart';
/// Desktop conversation navigation, independent of project and agent state.
class ChatHeader extends StatelessWidget {
const ChatHeader({
super.key,
required this.title,
required this.historyBuilder,
required this.onNew,
required this.actions,
this.busy = false,
this.panelActions = const [],
});
final String title;
final Widget Function(BuildContext context, VoidCallback close)
historyBuilder;
final VoidCallback? onNew;
final List<Widget> actions;
final bool busy;
final List<Widget> panelActions;
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final iconStyle = IconButton.styleFrom(
fixedSize: const Size.square(26),
minimumSize: const Size.square(26),
maximumSize: const Size.square(26),
padding: EdgeInsets.zero,
iconSize: 16,
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
);
return SizedBox(
key: const Key('project-chat-header'),
height: AppDesktopMetrics.panelHeader,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: Row(
children: [
Expanded(
child: AppPopover(
enabled: !busy,
width: 300,
surfaceKey: const Key('project-chat-history-menu'),
child: Builder(
builder: (menuContext) {
final menu = MenuController.maybeOf(menuContext);
return historyBuilder(menuContext, () {
if (menu?.isOpen == true) menu!.close();
});
},
),
builder: (context, toggle) => Tooltip(
message: '$title\n${l10n.agentConversations}',
child: TextButton(
key: const Key('project-chat-history'),
onPressed: busy ? null : toggle,
style: AppTheme.toolbarButtonStyle(context).copyWith(
minimumSize: const WidgetStatePropertyAll(Size(0, 26)),
maximumSize: const WidgetStatePropertyAll(
Size(double.infinity, 26),
),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
padding: const WidgetStatePropertyAll(
EdgeInsets.symmetric(horizontal: 6),
),
),
child: Row(
children: [
Expanded(
child: Text(
title,
key: const Key('project-chat-title'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: AppTheme.toolbarTextStyle(context)
.copyWith(fontWeight: FontWeight.w500),
),
),
const SizedBox(width: 4),
const Icon(AppIcons.expandMore, size: 14),
],
),
),
),
),
),
const SizedBox(width: 4),
IconButton(
key: const Key('project-chat-new'),
tooltip: l10n.agentNewConversation,
style: iconStyle,
onPressed: busy ? null : onNew,
icon: const Icon(AppIcons.edit),
),
const SizedBox(width: 4),
AppDropdownMenu(
enabled: (!busy && actions.isNotEmpty) || panelActions.isNotEmpty,
items: [
if (!busy) ...actions,
if (!busy && actions.isNotEmpty && panelActions.isNotEmpty)
const AppMenuSeparator(),
...panelActions,
],
builder: (context, toggle, focus) => IconButton(
key: const Key('project-chat-more'),
tooltip: l10n.agentConversationActions,
style: iconStyle,
focusNode: focus,
onPressed: toggle,
icon: const Icon(AppIcons.more),
),
),
],
),
),
);
}
}
typedef ChatHistoryEntry = ({String id, String title});
/// Search remains local to the currently open project's conversation list.
class ChatHistoryMenu extends StatefulWidget {
const ChatHistoryMenu({
super.key,
required this.entries,
required this.onSelect,
this.selectedId,
this.itemBuilder,
this.footer,
this.error,
});
static const contentInset = 8.0;
static const sectionPadding = EdgeInsets.symmetric(
horizontal: contentInset,
vertical: 8,
);
final List<ChatHistoryEntry> entries;
final String? selectedId;
final ValueChanged<String> onSelect;
final Widget Function(BuildContext, String id, VoidCallback onSelect)?
itemBuilder;
final Widget? footer;
final String? error;
@override
State<ChatHistoryMenu> createState() => _ChatHistoryMenuState();
}
class _ChatHistoryMenuState extends State<ChatHistoryMenu> {
String _query = '';
@override
void didUpdateWidget(ChatHistoryMenu oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.entries.isEmpty) _query = '';
}
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context)!;
final searchStyle = AppTheme.inputTextStyle(
context,
style: AppTheme.toolbarTextStyle(context),
);
final entries = widget.entries.where(
(entry) =>
entry.title.toLowerCase().contains(_query.trim().toLowerCase()),
);
return SizedBox(
height:
widget.entries.isEmpty &&
widget.footer == null &&
widget.error == null
? 88
: 360,
child: Padding(
padding: const EdgeInsets.all(8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (widget.entries.isNotEmpty)
TextField(
key: const Key('project-chat-search'),
autofocus: true,
style: searchStyle,
cursorHeight: AppTheme.inputCursorHeight(
context,
style: searchStyle,
),
textAlignVertical: TextAlignVertical.center,
decoration: InputDecoration(
isDense: true,
constraints: const BoxConstraints(minHeight: 28),
contentPadding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 5,
),
hintText: l10n.searchOptions(l10n.agentConversations),
hintStyle: AppTheme.inputHintStyle(
context,
style: searchStyle,
),
prefixIcon: const Icon(AppIcons.search, size: 14),
prefixIconConstraints: const BoxConstraints(
minWidth: 30,
minHeight: 28,
),
),
onChanged: (value) => setState(() => _query = value),
),
Padding(
padding: ChatHistoryMenu.sectionPadding,
child: Text(
key: const Key('project-chat-group'),
l10n.agentConversations,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall,
),
),
Expanded(
child: ListView(
primary: false,
padding: EdgeInsets.zero,
children: [
if (entries.isEmpty)
Padding(
padding: ChatHistoryMenu.sectionPadding,
child: Text(
_query.trim().isEmpty
? l10n.agentNoConversations
: l10n.noMatchingOptions,
),
),
for (final entry in entries)
widget.itemBuilder?.call(
context,
entry.id,
() => widget.onSelect(entry.id),
) ??
AppMenuItem(
key: ValueKey('chat-history-${entry.id}'),
label: entry.title,
selectOption: true,
selected: entry.id == widget.selectedId,
onPressed: () => widget.onSelect(entry.id),
),
if (widget.error != null)
Padding(
padding: ChatHistoryMenu.sectionPadding,
child: Text(widget.error!),
),
if (widget.footer != null) widget.footer!,
],
),
),
],
),
),
);
}
}
@@ -0,0 +1,76 @@
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widget_previews.dart';
import '../../l10n/app_localizations.dart';
import 'chat_header.dart';
@Preview(
name: 'Chat header — dark',
group: 'Desktop conversations',
size: Size(320, 440),
)
Widget chatHeaderDarkPreview() => _preview(Brightness.dark);
@Preview(
name: 'Chat header — light, narrow',
group: 'Desktop conversations',
size: Size(240, 440),
)
Widget chatHeaderLightPreview() => _preview(Brightness.light);
Widget _preview(Brightness brightness) {
const entries = [
(id: 'rough', title: '旅行短片粗剪'),
(id: 'opening', title: '调整片头节奏与镜头衔接,让画面更自然'),
(id: 'captions', title: '字幕与配乐'),
];
String? selected = 'opening';
return MaterialApp(
theme: AppTheme.desktopWorkspaceTheme(
AppTheme.forPalette(AppPalette.graphite, brightness),
),
locale: const Locale('zh'),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Scaffold(
body: StatefulBuilder(
builder: (context, setState) {
final l10n = AppLocalizations.of(context)!;
return Column(
children: [
ChatHeader(
title:
entries
.where((entry) => entry.id == selected)
.firstOrNull
?.title ??
l10n.agentUntitledConversation,
onNew: () => setState(() => selected = null),
actions: selected == null
? const []
: [
AppMenuItem(label: l10n.rename, onPressed: () {}),
AppMenuItem(
label: l10n.agentMoveToTrash,
onPressed: () => setState(() => selected = null),
),
],
historyBuilder: (_, close) => ChatHistoryMenu(
entries: entries,
selectedId: selected,
onSelect: (id) {
close();
setState(() => selected = id);
},
),
),
const Divider(height: 1),
],
);
},
),
),
);
}
@@ -60,8 +60,13 @@ class ConversationSelection extends _$ConversationSelection {
ref.onDispose(() {
if (_draftKey case final key?) composers.removeDraft(projectId, key);
});
ref.watch(
ref.listen(
projectsProvider.select((value) => value.value?.activeProject?.id),
(_, next) {
if (next == projectId && state.selectedId != null) {
state = state.copyWith(initialized: false);
}
},
);
final saved = savedConversationSelectionProvider(projectId);
ref.listen(saved, (_, next) {
@@ -135,7 +135,7 @@ final class ConversationSelectionProvider
}
String _$conversationSelectionHash() =>
r'eef3c6c95f86b017e73d3244adccc257f717699b';
r'5b5036b69fd203ed7827d9f81d446786b7de373c';
/// Keeps a draft or explicit selection stable while the list refreshes.
@@ -3,7 +3,10 @@ import 'package:flutter/material.dart';
import '../../l10n/l10n.dart';
import '../../workspace/project_state.dart';
import '../../integrations/platform/device_experience.dart';
import '../editor/editor_page.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
class EmptyEditor extends StatelessWidget {
@@ -13,15 +16,28 @@ class EmptyEditor extends StatelessWidget {
required this.headerLeading,
required this.showProjectName,
this.desktop = false,
this.experience = DeviceExperience.desktop,
});
final ProjectState state;
final Widget headerLeading;
final bool showProjectName;
final bool desktop;
final DeviceExperience experience;
@override
Widget build(BuildContext context) => Column(
Widget build(BuildContext context) => state.activeProject == null
? EditorWorkspace(
projectId: '',
timelineId: '',
projectName: '',
integratedTitlebar: false,
headerLeading: headerLeading,
showProjectName: showProjectName,
experience: experience,
projectLoading: true,
)
: Column(
children: [
SizedBox(
height: desktop
@@ -38,6 +54,7 @@ class EmptyEditor extends StatelessWidget {
child: Row(
children: [
headerLeading,
if (!showProjectName) const Spacer(),
if (showProjectName)
Expanded(
child: Text(
@@ -61,7 +78,7 @@ class EmptyEditor extends StatelessWidget {
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.movie_outlined,
AppIcons.video,
size: AppIconSize.project,
color: Theme.of(context).colorScheme.primary,
),
+484 -102
View File
@@ -4,6 +4,7 @@ import '../../integrations/platform/device_experience.dart';
import 'touch_project_navigation.dart';
import '../media/media_panel.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import 'dart:async';
@@ -36,6 +37,9 @@ import '../../integrations/agent/agent_models.dart';
import 'widgets/name_dialog.dart';
import 'conversation_sidebar.dart';
import 'chat_header.dart';
import 'sidebar_category_tabs.dart';
import 'sidebar_navigation_controller.dart';
typedef ProjectRenamer = Future<bool> Function(RecentProject project);
@@ -44,7 +48,11 @@ class ProjectSidebar extends ConsumerStatefulWidget {
super.key,
required this.agent,
this.navigationOnly = false,
this.chatOnly = false,
this.chatPanelActions = const [],
this.resourcesSelected = false,
this.onResourcesSelected,
this.librarySelected = false,
this.externalWindowFrame = false,
this.experience = DeviceExperience.desktop,
this.onNavigationComplete,
@@ -66,7 +74,11 @@ class ProjectSidebar extends ConsumerStatefulWidget {
final Widget agent;
final bool navigationOnly;
final bool chatOnly;
final List<Widget> chatPanelActions;
final bool resourcesSelected;
final ValueChanged<bool>? onResourcesSelected;
final bool librarySelected;
final bool externalWindowFrame;
final DeviceExperience experience;
final VoidCallback? onNavigationComplete;
@@ -90,6 +102,13 @@ class ProjectSidebar extends ConsumerStatefulWidget {
}
class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
ProjectState get _projectState =>
ref.read(projectsProvider).value ?? widget.state;
SidebarNavigationContext _navigationContext(ProjectState state) =>
(projectId: state.activeProject?.id, timelineId: state.visibleTimelineId);
late final _navigation = SidebarNavigationController(
_navigationContext(_projectState),
);
bool _resourcesVisited = false;
bool get _touch => widget.experience != DeviceExperience.desktop;
bool _projectHeaderHovered = false;
@@ -115,10 +134,17 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
_projectSelection.value = widget.selectedProjectId;
final ids = widget.state.recent.map((project) => project.id).toSet();
_groupWidgets.removeWhere((id, _) => !ids.contains(id));
_navigation.update(_navigationContext(_projectState));
if (oldWidget.mode != widget.mode ||
oldWidget.resourcesSelected != widget.resourcesSelected ||
oldWidget.librarySelected != widget.librarySelected) {
_navigation.cancel();
}
}
@override
void dispose() {
_navigation.dispose();
_projectSelection.dispose();
super.dispose();
}
@@ -150,11 +176,15 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
}
void _selectProjectFromNavigation(RecentProject project) {
_navigation.cancel();
widget.onSelectProject?.call(project);
if (widget.navigationOnly) _finishNavigation();
}
void _newConversation() => _conversations.newConversation();
void _newConversation() {
_navigation.cancel();
_conversations.newConversation();
}
Future<void> _newConversationForProject(RecentProject project) async {
_cutProjectsMenu.close();
@@ -162,24 +192,38 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
!project.availability.canOpen) {
return;
}
if (widget.state.activeProject?.id != project.id) {
final navigation = _navigation.begin(project.id);
bool isCurrent() => mounted && navigation();
try {
if (_projectState.activeProject?.id != project.id) {
final opened = await ref
.read(projectsProvider.notifier)
.open(project.path, expectedId: project.id);
if (!opened || !mounted) return;
.open(project.path, expectedId: project.id, isCurrent: isCurrent);
if (!opened || !isCurrent()) return;
}
if (!isCurrent() || _projectState.activeProject?.id != project.id) return;
_newConversation();
widget.onModeChanged(WorkspaceMode.agent);
_finishNavigation();
} finally {
_navigation.finish(navigation);
}
}
Future<void> _selectConversation(ConversationMetadata item) async {
_cutProjectsMenu.close();
if (ref.read(projectsProvider).value?.projectBusy == true) return;
final navigation = _navigation.begin(
item.projectId,
timelineId: item.timelineId,
);
bool isCurrent() => mounted && navigation();
try {
await _conversations.rememberSelection(item);
final currentProject = widget.state.activeProject?.id;
if (!isCurrent()) return;
final currentProject = _projectState.activeProject?.id;
if (currentProject != item.projectId) {
final project = widget.state.recent
final project = _projectState.recent
.where((entry) => entry.id == item.projectId)
.firstOrNull;
if (project == null || !project.availability.canOpen) return;
@@ -189,25 +233,34 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
project.path,
expectedId: project.id,
timelineId: item.timelineId,
isCurrent: isCurrent,
);
if (!isCurrent()) return;
if (!opened) {
_navigation.useProjectDefault(navigation);
opened = await ref
.read(projectsProvider.notifier)
.open(project.path, expectedId: project.id);
.open(project.path, expectedId: project.id, isCurrent: isCurrent);
}
if (!opened) return;
} else if (widget.state.timeline?.id != item.timelineId &&
widget.state.timelines.any(
} else if (_projectState.timeline?.id != item.timelineId &&
_projectState.timelines.any(
(timeline) => timeline.id == item.timelineId,
)) {
await ref
final opened = await ref
.read(projectsProvider.notifier)
.openTimeline(item.projectId, item.timelineId);
if (!opened) return;
}
if (!isCurrent() || _projectState.activeProject?.id != item.projectId) {
return;
}
if (!mounted || widget.state.activeProject?.id != item.projectId) return;
_conversations.activate(item);
widget.onModeChanged(WorkspaceMode.agent);
_finishNavigation();
} finally {
_navigation.finish(navigation);
}
}
Future<void> _renameConversation(ConversationMetadata item) async {
@@ -254,7 +307,7 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
),
),
);
if (selected == null) return;
if (selected == null || !mounted) return;
await _conversations.updateMetadata(item.copyWith(providerId: selected));
}
@@ -266,16 +319,12 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
.read(projectsProvider.notifier)
.removeRecentProject(project.id);
if (!removed || !mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
ErrorNotificationHost.of(context).showMessage(
content: Text(context.l10n.projectRemoved),
action: SnackBarAction(
label: context.l10n.undo,
onPressed: () => ref
actionLabel: context.l10n.undo,
onAction: () => ref
.read(projectsProvider.notifier)
.restoreRecentProject(project, index),
),
),
);
}
@@ -325,20 +374,7 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
) ==
true;
Widget _conversationRow(ConversationMetadata item) => Consumer(
builder: (context, ref, _) {
final active = ref.watch(
projectsProvider.select(
(value) => value.value?.activeProject?.id == item.projectId,
),
);
final selected =
ref.watch(
conversationSelectionProvider(item.projectId)
.select((value) => value.selectedId == item.id),
) &&
active;
List<Widget> actions(BuildContext context) => [
List<Widget> _conversationActions(ConversationMetadata item) => [
AppMenuItem(
label: context.l10n.rename,
onPressed: () => _renameConversation(item),
@@ -358,24 +394,58 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
onPressed: () => _deleteForever(item),
),
];
Widget _conversationRow(
ConversationMetadata item, {
VoidCallback? onSelected,
bool inMenu = false,
}) => Consumer(
builder: (context, ref, _) {
final active = ref.watch(
projectsProvider.select(
(value) => value.value?.activeProject?.id == item.projectId,
),
);
final selected =
ref.watch(
conversationSelectionProvider(item.projectId)
.select((value) => value.selectedId == item.id),
) &&
active;
if (inMenu) {
return AppContextMenu(
itemsBuilder: (_) => _conversationActions(item),
child: AppMenuItem(
key: ValueKey('sidebar-conversation-${item.id}'),
label: item.title,
selectOption: true,
selected: selected,
onPressed: onSelected ?? () => _selectConversation(item),
),
);
}
if (_touch) {
return TouchConversationTile(
id: item.id,
title: item.title,
selected: selected,
onSelect: () => _selectConversation(item),
actions: actions,
onSelect: onSelected ?? () => _selectConversation(item),
actions: (_) => _conversationActions(item),
);
}
return Padding(
padding: AppSidebarMetrics.rowPadding,
child: AppContextMenu(
itemsBuilder: actions,
itemsBuilder: (_) => _conversationActions(item),
child: Material(
color: selected
? AppSidebarColors.of(context).hover
: Colors.transparent,
borderRadius: BorderRadius.circular(AppSidebarMetrics.radius),
borderRadius: BorderRadius.circular(
AppTheme.isDesktop(context)
? AppRadius.large
: AppSidebarMetrics.radius,
),
child: InkWell(
key: ValueKey('sidebar-conversation-${item.id}'),
hoverColor: selected
@@ -383,11 +453,38 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
: AppSidebarColors.of(context).hover,
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
borderRadius: BorderRadius.circular(AppSidebarMetrics.radius),
onTap: () => _selectConversation(item),
borderRadius: BorderRadius.circular(
AppTheme.isDesktop(context)
? AppRadius.large
: AppSidebarMetrics.radius,
),
onTap: onSelected ?? () => _selectConversation(item),
child: SizedBox(
height: AppSidebarMetrics.rowHeight,
child: Align(
height: AppTheme.isDesktop(context)
? AppDesktopMetrics.sidebarRow
: AppSidebarMetrics.rowHeight,
child: Stack(
fit: StackFit.expand,
children: [
if (selected && AppTheme.isDesktop(context))
PositionedDirectional(
start: AppSidebarMetrics.cellPadding,
top: 8,
bottom: 8,
width: 2,
child: IgnorePointer(
child: DecoratedBox(
key: ValueKey(
'sidebar-conversation-selection-${item.id}',
),
decoration: BoxDecoration(
color: Theme.of(context).colorScheme.primary,
borderRadius: BorderRadius.circular(1),
),
),
),
),
Align(
alignment: AlignmentDirectional.centerStart,
child: Padding(
padding: const EdgeInsetsDirectional.only(
@@ -400,12 +497,18 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
overflow: TextOverflow.ellipsis,
style: AppSidebarTypography.style(
context,
fontSize: AppSidebarMetrics.conversationFontSize,
height: AppSidebarMetrics.conversationLineHeight,
fontSize: AppTheme.isDesktop(context)
? 13
: AppSidebarMetrics.conversationFontSize,
height: AppTheme.isDesktop(context)
? 20 / 13
: AppSidebarMetrics.conversationLineHeight,
),
),
),
),
],
),
),
),
),
@@ -592,6 +695,130 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
@override
Widget build(BuildContext context) {
_navigation.update(_navigationContext(_projectState));
ref.listen(
projectsProvider.select(
(value) =>
value.value == null ? null : _navigationContext(value.requireValue),
),
(_, next) {
if (next != null) _navigation.update(next);
},
);
if (widget.chatOnly) {
final snapshot = ref.watch(conversationSidebarProvider).value;
final projectId = widget.state.activeProject?.id;
final conversations =
snapshot?.groups[projectId] ?? const <ConversationMetadata>[];
final selectedId = ref.watch(
conversationSelectionProvider(projectId)
.select((value) => value.selectedId),
);
final selected = conversations
.where((item) => item.id == selectedId)
.firstOrNull;
return Material(
key: const Key('project-chat-sidebar'),
color: Theme.of(context).colorScheme.surface,
child: Column(
children: [
ChatHeader(
key: ValueKey(('chat-header', projectId)),
title: selected?.title ?? context.l10n.agentUntitledConversation,
busy: widget.state.projectBusy,
onNew: _newConversation,
panelActions: widget.chatPanelActions,
actions: selected == null
? const []
: _conversationActions(selected),
historyBuilder: (menuContext, close) => ChatHistoryMenu(
entries: [
for (final item in conversations)
(id: item.id, title: item.title),
],
selectedId: selectedId,
error: _conversationError,
onSelect: (id) {
close();
_selectConversation(
conversations.firstWhere((item) => item.id == id),
);
},
itemBuilder: (_, id, onSelect) => _conversationRow(
conversations.firstWhere((item) => item.id == id),
onSelected: onSelect,
inMenu: true,
),
footer: _trashed.isEmpty
? null
: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Divider(),
Padding(
padding: ChatHistoryMenu.sectionPadding,
child: Text(
context.l10n.agentTrash,
key: const Key('project-chat-trash-title'),
style: Theme.of(context).textTheme.bodySmall,
),
),
for (final item in _trashed)
Padding(
padding: const EdgeInsets.symmetric(
horizontal: ChatHistoryMenu.contentInset,
),
child: SizedBox(
height: 28,
child: Row(
children: [
Expanded(
child: Text(
item.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: AppTheme.toolbarTextStyle(
context,
),
),
),
for (final restore in [true, false])
IconButton(
tooltip: restore
? context.l10n.agentRestore
: context.l10n.agentDeleteForever,
style: IconButton.styleFrom(
fixedSize: const Size.square(24),
minimumSize: const Size.square(24),
maximumSize: const Size.square(24),
padding: EdgeInsets.zero,
iconSize: 14,
tapTargetSize:
MaterialTapTargetSize.shrinkWrap,
),
onPressed: () => restore
? _restoreConversation(item)
: _deleteForever(item),
icon: Icon(
restore
? AppIcons.undo
: AppIcons.delete,
),
),
],
),
),
),
],
),
),
),
const Divider(height: 1),
Expanded(child: widget.agent),
],
),
);
}
final compact = MediaQuery.sizeOf(context).height < 520;
final headerHeight = widget.externalWindowFrame
? 0.0
@@ -601,8 +828,12 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
? AppControlSize.panelHeader
: AppControlSize.headerButton;
final modeTop = headerHeight;
final modeHeader = SizedBox(
key: const Key('project-content-header'),
final legacyModeHeader = SizedBox(
key: Key(
!_touch && widget.navigationOnly
? 'sidebar-window-header'
: 'project-content-header',
),
height:
modeTop +
(_touch ? AppSidebarMetrics.modeHeight : 0) +
@@ -713,7 +944,7 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
),
const SizedBox(width: AppSpacing.small),
const Icon(
Icons.keyboard_arrow_down,
AppIcons.expandMore,
size: AppSidebarMetrics.iconSize,
),
],
@@ -725,13 +956,89 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
],
),
);
final sectionHeader = !_touch && widget.externalWindowFrame
? SizedBox(
key: Key(
widget.navigationOnly
? 'sidebar-projects-header'
: 'project-content-header',
),
height: AppDesktopMetrics.panelHeader,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: Row(
children: [
Icon(
widget.resourcesSelected
? AppIcons.mediaLibrary
: AppIcons.folder,
size: 16,
),
const SizedBox(width: 8),
Expanded(
child: Text(
key: !widget.resourcesSelected && !widget.librarySelected
? const Key('projects-heading')
: null,
widget.resourcesSelected
? context.l10n.materials
: widget.librarySelected
? context.l10n.navigationLibrary
: context.l10n.projects,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.titleSmall,
),
),
if (!widget.resourcesSelected && !widget.librarySelected)
IconButton(
key: const Key('create-project'),
tooltip: context.l10n.newProject,
onPressed: widget.onCreateProject,
icon: const Icon(AppIcons.add, size: 16),
),
],
),
),
)
: legacyModeHeader;
final modeHeader = !_touch && widget.navigationOnly
? Column(
key: const Key('project-content-header'),
mainAxisSize: MainAxisSize.min,
children: [
if (!widget.externalWindowFrame) legacyModeHeader,
if (widget.librarySelected)
SizedBox(
height: AppDesktopMetrics.panelHeader,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12),
child: Align(
alignment: AlignmentDirectional.centerStart,
child: Text(context.l10n.navigationLibrary),
),
),
)
else
SidebarCategoryTabs(
mediaSelected: widget.resourcesSelected,
onSelected: widget.onResourcesSelected,
),
if (widget.externalWindowFrame &&
!widget.resourcesSelected &&
!widget.librarySelected)
sectionHeader,
],
)
: sectionHeader;
final projectList = SingleChildScrollView(
key: const Key('sidebar-projects-conversations'),
primary: false,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (widget.mode == WorkspaceMode.agent || widget.navigationOnly)
if ((widget.mode == WorkspaceMode.agent || widget.navigationOnly) &&
(_touch || !widget.externalWindowFrame))
MouseRegion(
onEnter: (_) => setState(() => _projectHeaderHovered = true),
onExit: (_) => setState(() => _projectHeaderHovered = false),
@@ -813,7 +1120,11 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
onExpansionChanged: (value) =>
setState(() => _showTrash = value),
trailing: _trashed.isEmpty
? null
? Icon(
_showTrash
? AppIcons.expandLess
: AppIcons.expandMore,
)
: TextButton(
onPressed: _emptyTrash,
child: Text(context.l10n.agentEmptyTrash),
@@ -838,28 +1149,25 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
color: AppSidebarColors.of(context).secondary,
),
),
trailing: PopupMenuButton<String>(
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,
trailing: AppDropdownMenu(
items: [
AppMenuItem(
label: context.l10n.agentRestore,
onPressed: () => _restoreConversation(item),
),
AppMenuItem(
label: context.l10n.agentDeleteForever,
destructive: true,
onPressed: () => _deleteForever(item),
),
],
builder: (context, toggle, focus) => IconButton(
focusNode: focus,
onPressed: toggle,
icon: const Icon(AppIcons.more),
tooltip:
context.l10n.agentConversationActions,
),
),
);
},
@@ -883,20 +1191,38 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
child: _touch
? projectList
: IndexedStack(
index: widget.resourcesSelected ? 1 : 0,
index: widget.librarySelected
? 2
: widget.resourcesSelected
? 1
: 0,
children: [
TickerMode(
enabled: !widget.resourcesSelected,
enabled:
!widget.resourcesSelected &&
!widget.librarySelected,
child: projectList,
),
TickerMode(
enabled: widget.resourcesSelected,
enabled:
widget.resourcesSelected &&
!widget.librarySelected,
child: ExcludeFocus(
excluding:
!widget.resourcesSelected ||
widget.librarySelected,
child: _resourcesVisited
? MediaPanel(
projectId: widget.state.activeProject?.id,
onSelectProject: widget.onSelectProject,
)
: Center(child: Text(context.l10n.projectsNone)),
: Center(
child: Text(context.l10n.projectsNone),
),
),
),
const SizedBox.expand(
key: Key('resource-library-empty'),
),
],
),
@@ -924,7 +1250,6 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
VerticalDivider(
key: const Key('sidebar-chat-divider'),
width: 1,
thickness: 1,
color: AppTheme.sidebarDividerColor(context),
),
Expanded(
@@ -981,7 +1306,7 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
onPressed: widget.onExpandEditor,
padding: EdgeInsets.zero,
icon: const Icon(
Icons.vertical_split_outlined,
AppIcons.splitVertical,
size: AppIconSize.header,
),
),
@@ -1122,7 +1447,9 @@ class _ProjectsHeader extends StatelessWidget {
overflow: TextOverflow.ellipsis,
style: AppSidebarTypography.style(
context,
fontSize: AppSidebarMetrics.sectionFontSize,
fontSize: AppTheme.isDesktop(context)
? 13
: AppSidebarMetrics.sectionFontSize,
weight: FontWeight.w500,
color: AppSidebarColors.of(context).section,
),
@@ -1131,7 +1458,7 @@ class _ProjectsHeader extends StatelessWidget {
if (onPressed != null) ...[
const SizedBox(width: AppSpacing.tiny),
Icon(
Icons.keyboard_arrow_down,
AppIcons.expandMore,
size: AppSidebarMetrics.iconSize,
color: AppSidebarColors.of(context).secondary,
),
@@ -1152,7 +1479,7 @@ class _ProjectsHeader extends StatelessWidget {
dimension: AppSidebarMetrics.actionSize,
child: Center(
child: Icon(
Icons.more_horiz,
AppIcons.more,
size: AppSidebarMetrics.iconSize,
color: AppSidebarColors.of(context).tertiary,
),
@@ -1172,7 +1499,7 @@ class _ProjectsHeader extends StatelessWidget {
tooltip: context.l10n.newProject,
onPressed: onCreateProject,
padding: EdgeInsets.zero,
icon: const Icon(Icons.add, size: AppSidebarMetrics.iconSize),
icon: const Icon(AppIcons.add, size: AppSidebarMetrics.iconSize),
),
),
),
@@ -1187,6 +1514,38 @@ Color _sidebarItemHighlightColor(BuildContext context) =>
ButtonStyle sidebarActionButtonStyle(BuildContext context) =>
AppTheme.iconButtonStyle(context);
ButtonStyle _projectActionButtonStyle(BuildContext context) {
if (!AppTheme.isDesktop(context)) return sidebarActionButtonStyle(context);
final colors = AppSidebarColors.of(context);
final accent = Theme.of(context).colorScheme.primary;
return sidebarActionButtonStyle(context).copyWith(
foregroundColor: WidgetStateProperty.resolveWith((states) {
if (states.contains(WidgetState.disabled)) return colors.disabled;
if (states.contains(WidgetState.hovered) ||
states.contains(WidgetState.focused) ||
states.contains(WidgetState.pressed)) {
return accent;
}
return colors.secondary;
}),
backgroundColor: const WidgetStatePropertyAll(Colors.transparent),
overlayColor: WidgetStateProperty.resolveWith((states) {
if (states.contains(WidgetState.disabled)) return Colors.transparent;
if (states.contains(WidgetState.pressed)) {
return accent.withValues(alpha: .16);
}
if (states.contains(WidgetState.hovered) ||
states.contains(WidgetState.focused)) {
return accent.withValues(alpha: .10);
}
return Colors.transparent;
}),
shape: WidgetStatePropertyAll(
RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),
),
);
}
String _availabilityLabel(
BuildContext context,
ProjectAvailability availability,
@@ -1228,7 +1587,7 @@ class _ProjectTile extends StatelessWidget {
List<Widget> _menuItems(BuildContext context) => [
AppMenuItem(
label: context.l10n.rename,
icon: Icons.drive_file_rename_outline,
icon: AppIcons.rename,
onPressed: project.availability.canOpen ? onRename : null,
),
if (sidebarStyle) ...[
@@ -1248,14 +1607,20 @@ class _ProjectTile extends StatelessWidget {
'${sidebarStyle ? 'sidebar-project' : 'open-project'}-${project.id}',
),
minTileHeight: sidebarStyle
? AppSidebarMetrics.rowHeight
? (AppTheme.isDesktop(context)
? AppDesktopMetrics.sidebarRow
: AppSidebarMetrics.rowHeight)
: project.availability.canOpen
? 36
: 48,
minVerticalPadding: 0,
contentPadding: EdgeInsets.symmetric(
horizontal: sidebarStyle ? 0 : AppSpacing.small,
),
contentPadding: sidebarStyle
? EdgeInsetsDirectional.only(
end: AppTheme.isDesktop(context)
? AppSidebarMetrics.cellPadding
: 0,
)
: const EdgeInsets.symmetric(horizontal: AppSpacing.small),
horizontalTitleGap: sidebarStyle
? AppSidebarMetrics.iconGap
: AppSpacing.small,
@@ -1264,7 +1629,9 @@ class _ProjectTile extends StatelessWidget {
titleAlignment: ListTileTitleAlignment.center,
selected: active,
selectedTileColor: sidebarStyle
? Colors.transparent
? AppTheme.isDesktop(context)
? AppSidebarColors.of(context).hover
: Colors.transparent
: _sidebarItemHighlightColor(context),
textColor: project.availability.canOpen
? null
@@ -1273,7 +1640,11 @@ class _ProjectTile extends StatelessWidget {
? null
: Theme.of(context).disabledColor,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(AppRadius.extraLarge),
borderRadius: BorderRadius.circular(
sidebarStyle && AppTheme.isDesktop(context)
? AppRadius.large
: AppRadius.extraLarge,
),
),
hoverColor: sidebarStyle
? AppSidebarColors.of(context).hover
@@ -1283,7 +1654,9 @@ class _ProjectTile extends StatelessWidget {
leading: sidebarStyle
? SizedBox(
width: AppSidebarMetrics.iconSlotWidth,
height: AppSidebarMetrics.rowHeight,
height: AppTheme.isDesktop(context)
? AppDesktopMetrics.sidebarRow
: AppSidebarMetrics.rowHeight,
child: IconButton(
key: ValueKey('sidebar-project-toggle-${project.id}'),
tooltip: expanded
@@ -1294,22 +1667,18 @@ class _ProjectTile extends StatelessWidget {
onPressed: onToggleExpanded,
icon: Icon(
!project.availability.canOpen
? Icons.folder_off_outlined
? AppIcons.folderUnavailable
: hovered
? (expanded
? Icons.keyboard_arrow_down
: Icons.chevron_right)
: (expanded
? Icons.folder_open_outlined
: Icons.folder_outlined),
? (expanded ? AppIcons.expandMore : AppIcons.chevronRight)
: (expanded ? AppIcons.folderOpen : AppIcons.folder),
size: AppSidebarMetrics.iconSize,
),
),
)
: Icon(
project.availability.canOpen
? Icons.folder_outlined
: Icons.folder_off_outlined,
? AppIcons.folder
: AppIcons.folderUnavailable,
size: 18,
),
title: Text(
@@ -1319,6 +1688,15 @@ class _ProjectTile extends StatelessWidget {
style: sidebarStyle
? AppSidebarTypography.style(
context,
fontSize: AppTheme.isDesktop(context)
? 13
: AppSidebarMetrics.fontSize,
height: AppTheme.isDesktop(context)
? 20 / 13
: AppSidebarMetrics.lineHeight,
weight: AppTheme.isDesktop(context)
? FontWeight.w500
: FontWeight.w400,
color: project.availability.canOpen
? AppSidebarColors.of(context).primary
: AppSidebarColors.of(context).disabled,
@@ -1364,11 +1742,13 @@ class _ProjectTile extends StatelessWidget {
builder: (context, toggle) => IconButton(
key: ValueKey('sidebar-project-more-${project.id}'),
onPressed: toggle,
style: sidebarActionButtonStyle(context),
style: _projectActionButtonStyle(context),
padding: EdgeInsets.zero,
icon: const Icon(
Icons.more_horiz,
size: AppSidebarMetrics.iconSize,
icon: Icon(
AppIcons.more,
size: AppTheme.isDesktop(context)
? 14
: AppSidebarMetrics.iconSize,
),
),
),
@@ -1380,11 +1760,13 @@ class _ProjectTile extends StatelessWidget {
key: ValueKey('new-agent-conversation-${project.id}'),
tooltip: context.l10n.agentNewConversation,
onPressed: onNewConversation,
style: sidebarActionButtonStyle(context),
style: _projectActionButtonStyle(context),
padding: EdgeInsets.zero,
icon: const Icon(
Icons.edit_square,
size: AppSidebarMetrics.iconSize,
icon: Icon(
AppIcons.edit,
size: AppTheme.isDesktop(context)
? 14
: AppSidebarMetrics.iconSize,
),
),
),
@@ -1,60 +1,19 @@
import 'dart:async';
import 'package:flutter/widgets.dart';
/// Keeps the current content during short switches without delaying completion.
class ProjectSwitchRegion extends StatefulWidget {
/// Keeps prepared content mounted until the next project is published.
class ProjectSwitchRegion extends StatelessWidget {
const ProjectSwitchRegion({
super.key,
required this.pendingProjectId,
required this.builder,
required this.child,
});
final String? pendingProjectId;
final Widget Function(BuildContext context, bool showDefaults) builder;
@override
State<ProjectSwitchRegion> createState() => _ProjectSwitchRegionState();
}
class _ProjectSwitchRegionState extends State<ProjectSwitchRegion> {
Timer? _timer;
bool _showDefaults = false;
@override
void initState() {
super.initState();
_reset();
}
@override
void didUpdateWidget(covariant ProjectSwitchRegion oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.pendingProjectId != widget.pendingProjectId) _reset();
}
void _reset() {
_timer?.cancel();
_showDefaults = false;
if (widget.pendingProjectId != null) {
_timer = Timer(const Duration(milliseconds: 150), () {
if (mounted) setState(() => _showDefaults = true);
});
}
}
final Widget child;
@override
Widget build(BuildContext context) => ExcludeFocus(
excluding: widget.pendingProjectId != null,
child: IgnorePointer(
ignoring: widget.pendingProjectId != null,
child: widget.builder(context, _showDefaults),
),
excluding: pendingProjectId != null,
child: IgnorePointer(ignoring: pendingProjectId != null, child: child),
);
@override
void dispose() {
_timer?.cancel();
super.dispose();
}
}
+434
View File
@@ -0,0 +1,434 @@
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import 'package:flutter/material.dart';
import 'package:cutdex_native/cutdex_native.dart';
import '../../l10n/l10n.dart';
import '../../workspace/project_state.dart';
class ProjectTabsBar extends StatefulWidget {
const ProjectTabsBar({
super.key,
required this.projects,
required this.recent,
required this.selectedId,
required this.onSelect,
required this.onClose,
required this.onCreate,
required this.onOpen,
required this.onRename,
this.onRemoveRecent,
this.projectMenuActions = const [],
this.leadingActions = const [],
this.trailingActions = const [],
});
final List<RecentProject> projects;
final List<RecentProject> recent;
final String? selectedId;
final ValueChanged<RecentProject> onSelect;
final ValueChanged<RecentProject> onClose;
final VoidCallback onCreate;
final VoidCallback onOpen;
final ValueChanged<RecentProject> onRename;
final ValueChanged<RecentProject>? onRemoveRecent;
final List<Widget> projectMenuActions;
final List<Widget> leadingActions;
final List<Widget> trailingActions;
@override
State<ProjectTabsBar> createState() => _ProjectTabsBarState();
}
class _ProjectTabsBarState extends State<ProjectTabsBar> {
final _tabKeys = <String, GlobalKey>{};
final _addKey = GlobalKey();
double? _availableWidth;
bool _active = true;
List<RecentProject> get projects => widget.projects;
List<RecentProject> get recent => widget.recent;
String? get selectedId => widget.selectedId;
ValueChanged<RecentProject> get onSelect => widget.onSelect;
ValueChanged<RecentProject> get onClose => widget.onClose;
VoidCallback get onCreate => widget.onCreate;
VoidCallback get onOpen => widget.onOpen;
ValueChanged<RecentProject> get onRename => widget.onRename;
void _revealSelection() {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted || !_active) return;
final context = projects.lastOrNull?.id == selectedId
? _addKey.currentContext
: _tabKeys[selectedId]?.currentContext;
if (context != null) {
Scrollable.ensureVisible(
context,
duration: const Duration(milliseconds: 150),
alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtEnd,
);
}
});
}
@override
void initState() {
super.initState();
_revealSelection();
}
@override
void didUpdateWidget(covariant ProjectTabsBar oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.selectedId != selectedId ||
oldWidget.projects.length != projects.length ||
oldWidget.projects.any(
(project) =>
projects.where((item) => item.id == project.id).firstOrNull !=
project,
)) {
_revealSelection();
}
final ids = projects.map((project) => project.id).toSet();
_tabKeys.removeWhere((id, _) => !ids.contains(id));
}
@override
void deactivate() {
_active = false;
super.deactivate();
}
@override
void activate() {
super.activate();
_active = true;
_revealSelection();
}
@override
Widget build(BuildContext context) => LayoutBuilder(
builder: (context, constraints) {
if (_availableWidth != constraints.maxWidth) {
_availableWidth = constraints.maxWidth;
_revealSelection();
}
return Padding(
padding: const EdgeInsets.symmetric(
horizontal: AppProjectTabMetrics.gap,
),
child: Row(
key: const Key('window-project-tabs'),
children: [
for (final action in widget.leadingActions) ...[
HeaderControlRegion(
child: SizedBox.square(
dimension: AppProjectTabMetrics.height,
child: action,
),
),
const SizedBox(width: AppProjectTabMetrics.gap),
],
AppDropdownMenu(
maxHeight: 400,
items: [
AppMenuItem(
label: context.l10n.newProject,
icon: AppIcons.add,
onPressed: onCreate,
),
AppMenuItem(
label: context.l10n.openProjectMore,
icon: AppIcons.folder,
onPressed: onOpen,
),
if (recent.isNotEmpty) const AppMenuSeparator(),
for (final project in recent)
AppContextMenu(
itemsBuilder: (_) => [
AppMenuItem(
label: context.l10n.rename,
icon: AppIcons.rename,
onPressed: !project.availability.canOpen
? null
: () => onRename(project),
),
if (widget.onRemoveRecent != null)
AppMenuItem(
label: context.l10n.removeProjectFromRecent,
onPressed: () => widget.onRemoveRecent!(project),
),
],
child: AppMenuItem(
key: ValueKey('project-menu-${project.id}'),
label: project.availability.canOpen
? project.name
: '${project.name} · ${context.l10n.projectAccessFailed}',
icon: project.availability.canOpen
? AppIcons.folder
: AppIcons.folderUnavailable,
selected: project.id == selectedId,
onPressed: () => onSelect(project),
),
),
if (widget.projectMenuActions.isNotEmpty) ...[
const AppMenuSeparator(),
...widget.projectMenuActions,
],
],
builder: (context, toggle, focusNode) => HeaderControlRegion(
child: IconButton(
key: const Key('project-tabs-projects'),
focusNode: focusNode,
tooltip: context.l10n.projects,
onPressed: toggle,
constraints: const BoxConstraints.tightFor(
width: AppProjectTabMetrics.height,
height: AppProjectTabMetrics.height,
),
padding: EdgeInsets.zero,
iconSize: AppIconSize.small,
style: AppTheme.projectTabActionStyle(context),
icon: const Icon(AppIcons.home),
),
),
),
const SizedBox(width: AppProjectTabMetrics.gap),
Expanded(
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
for (var index = 0; index < projects.length; index++) ...[
if (index > 0)
const SizedBox(width: AppProjectTabMetrics.gap),
_ProjectTab(
key: ValueKey(projects[index].id),
anchorKey: _tabKeys.putIfAbsent(
projects[index].id,
GlobalKey.new,
),
project: projects[index],
selected: projects[index].id == selectedId,
maxWidth:
(constraints.maxWidth -
5 * AppProjectTabMetrics.gap -
3 * AppProjectTabMetrics.height -
(widget.leadingActions.length +
widget.trailingActions.length) *
(AppProjectTabMetrics.height +
AppProjectTabMetrics.gap))
.clamp(
AppProjectTabMetrics.minWidth,
AppProjectTabMetrics.maxWidth,
),
onSelect: () => onSelect(projects[index]),
onClose: () => onClose(projects[index]),
onRename: () => onRename(projects[index]),
),
],
if (projects.isNotEmpty)
const SizedBox(width: AppProjectTabMetrics.gap),
HeaderControlRegion(
key: _addKey,
child: IconButton(
key: const Key('project-tabs-add'),
tooltip: context.l10n.newProject,
onPressed: onCreate,
iconSize: 16,
style: AppTheme.projectTabActionStyle(context),
icon: const Icon(AppIcons.add),
),
),
],
),
),
),
const SizedBox(width: AppProjectTabMetrics.gap),
AppDropdownMenu(
enabled: projects.isNotEmpty,
maxHeight: 400,
items: [
for (final project in projects)
AppMenuItem(
key: ValueKey('project-tabs-menu-${project.id}'),
label: project.name,
icon: AppIcons.folder,
selected: project.id == selectedId,
onPressed: () => onSelect(project),
),
],
builder: (context, toggle, focusNode) => HeaderControlRegion(
child: IconButton(
key: const Key('project-tabs-list'),
focusNode: focusNode,
tooltip: context.l10n.selectProject,
onPressed: toggle,
padding: EdgeInsets.zero,
iconSize: 14,
style: AppTheme.projectTabActionStyle(context),
icon: const Icon(AppIcons.expandMore),
),
),
),
for (final action in widget.trailingActions) ...[
const SizedBox(width: AppProjectTabMetrics.gap),
HeaderControlRegion(
child: SizedBox.square(
dimension: AppProjectTabMetrics.height,
child: action,
),
),
],
],
),
);
},
);
}
class _ProjectTab extends StatefulWidget {
const _ProjectTab({
super.key,
required this.anchorKey,
required this.project,
required this.selected,
required this.maxWidth,
required this.onSelect,
required this.onClose,
required this.onRename,
});
final GlobalKey anchorKey;
final RecentProject project;
final bool selected;
final double maxWidth;
final VoidCallback onSelect, onClose, onRename;
@override
State<_ProjectTab> createState() => _ProjectTabState();
}
class _ProjectTabState extends State<_ProjectTab> {
bool _hovered = false;
bool _focused = false;
@override
Widget build(BuildContext context) {
final project = widget.project;
final style = AppTheme.projectTabStyle(context, selected: widget.selected);
final states = <WidgetState>{
if (_hovered) WidgetState.hovered,
if (_focused) WidgetState.focused,
};
final showClose = widget.selected || _hovered || _focused;
return HeaderControlRegion(
child: MouseRegion(
onEnter: (_) => setState(() => _hovered = true),
onExit: (_) => setState(() => _hovered = false),
child: Focus(
canRequestFocus: false,
onFocusChange: (value) => setState(() => _focused = value),
child: AppContextMenu(
itemsBuilder: (_) => [
AppMenuItem(
label: context.l10n.rename,
onPressed: widget.onRename,
),
AppMenuItem(
label: MaterialLocalizations.of(context).closeButtonTooltip,
onPressed: widget.onClose,
),
],
child: Semantics(
selected: widget.selected,
child: Material(
key: widget.anchorKey,
color: style.backgroundColor!.resolve(states),
borderRadius: BorderRadius.circular(
AppProjectTabMetrics.radius,
),
child: ConstrainedBox(
key: ValueKey('project-tab-surface-${project.id}'),
constraints: BoxConstraints(
minWidth: AppProjectTabMetrics.minWidth,
maxWidth: widget.maxWidth,
),
child: IntrinsicWidth(
child: SizedBox(
height: AppProjectTabMetrics.height,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Expanded(
child: Tooltip(
message: '${project.name}\n${project.path}',
child: TextButton(
key: ValueKey('project-tab-${project.id}'),
onPressed: widget.onSelect,
style: style.copyWith(
alignment: Alignment.centerLeft,
backgroundColor: const WidgetStatePropertyAll(
Colors.transparent,
),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Icon(AppIcons.folder, size: 14),
const SizedBox(width: 6),
Flexible(
child: Text(
project.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
),
),
),
),
ExcludeFocus(
excluding: !showClose,
child: IgnorePointer(
ignoring: !showClose,
child: ExcludeSemantics(
excluding: !showClose,
child: Opacity(
opacity: showClose ? 1 : 0,
child: IconButton(
key: ValueKey(
'project-tab-close-${project.id}',
),
tooltip: MaterialLocalizations.of(context)
.closeButtonTooltip,
onPressed: widget.onClose,
constraints: const BoxConstraints.tightFor(
width: AppProjectTabMetrics.close,
height: AppProjectTabMetrics.close,
),
padding: EdgeInsets.zero,
iconSize: 12,
style: AppTheme.projectTabActionStyle(
context,
size: AppProjectTabMetrics.close,
),
icon: const Icon(AppIcons.close),
),
),
),
),
),
const SizedBox(width: 4),
],
),
),
),
),
),
),
),
),
),
);
}
}
@@ -0,0 +1,77 @@
import 'package:cutdex_ui/theme.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widget_previews.dart';
import '../../l10n/app_localizations.dart';
import '../../workspace/project_state.dart';
import 'project_tabs_bar.dart';
@Preview(
name: 'Rounded project tabs — dark',
group: 'Desktop navigation',
size: Size(720, 44),
)
Widget projectTabsDarkPreview() => _preview(Brightness.dark);
@Preview(
name: 'Rounded project tabs — light, narrow',
group: 'Desktop navigation',
size: Size(320, 44),
)
Widget projectTabsLightPreview() => _preview(Brightness.light);
@Preview(
name: 'Rounded project tabs — dark, compact',
group: 'Desktop navigation',
size: Size(240, 44),
)
Widget projectTabsCompactPreview() => _preview(Brightness.dark);
Widget _preview(Brightness brightness) {
const projects = [
RecentProject(id: 'travel', name: '旅行短片', path: '/Projects/Travel.cutdex'),
RecentProject(
id: 'product',
name: '产品介绍',
path: '/Projects/Product.cutdex',
),
RecentProject(id: 'city', name: '城市漫步', path: '/Projects/City.cutdex'),
];
var opened = projects.take(2).toList();
var selected = 'travel';
return MaterialApp(
theme: AppTheme.desktopWorkspaceTheme(
AppTheme.forPalette(AppPalette.graphite, brightness),
),
locale: const Locale('zh'),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Scaffold(
body: StatefulBuilder(
builder: (context, setState) => ColoredBox(
color: Theme.of(context).colorScheme.surfaceContainer,
child: ProjectTabsBar(
projects: opened,
recent: projects,
selectedId: selected,
onSelect: (project) => setState(() {
selected = project.id;
if (!opened.contains(project)) {
opened = [...opened, project];
}
}),
onClose: (project) => setState(() {
opened = opened.where((item) => item.id != project.id).toList();
if (selected == project.id) {
selected = opened.firstOrNull?.id ?? '';
}
}),
onCreate: () {},
onOpen: () {},
onRename: (_) {},
),
),
),
),
);
}
@@ -0,0 +1,52 @@
import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../shared/widgets/presentation_list.dart';
import '../../workspace/project_state.dart';
import '../../workspace/projects.dart';
final projectTabsProvider =
NotifierProvider<ProjectTabsController, List<RecentProject>>(
ProjectTabsController.new,
);
/// Open tabs are separate from the recent-project history.
class ProjectTabsController extends Notifier<List<RecentProject>> {
@override
List<RecentProject> build() {
ref.listen(
projectsProvider.select(
(value) => (
value.value?.activeProject,
PresentationList(value.value?.recent ?? const <RecentProject>[]),
),
),
(_, next) {
final (active, recent) = next;
final metadata = {for (final project in recent) project.id: project};
if (active != null) metadata[active.id] = active;
final updated = [
for (final project in state) metadata[project.id] ?? project,
if (active != null && !state.any((tab) => tab.id == active.id))
active,
];
if (!listEquals(state, updated)) state = List.unmodifiable(updated);
},
);
final active = ref.read(projectsProvider).value?.activeProject;
return List.unmodifiable([?active]);
}
void remove(String id) => state = List.unmodifiable([
for (final tab in state)
if (tab.id != id) tab,
]);
void updateProject(RecentProject project) {
final updated = [
for (final tab in state)
if (tab.id == project.id) project else tab,
];
if (!listEquals(state, updated)) state = List.unmodifiable(updated);
}
}
+343 -90
View File
@@ -1,3 +1,6 @@
import '../../shared/widgets/presentation_list.dart';
import '../assistant/agent_panel_presentation.dart';
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:cutdex/errors/app_failure.dart';
@@ -23,6 +26,8 @@ import 'package:cutdex_native/cutdex_native.dart';
import '../../persistence/app_settings_repositories.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/widgets.dart';
import 'package:cutdex_ui/theme.dart';
import '../../workspace/project_state.dart';
@@ -38,6 +43,8 @@ import '../settings/settings_page.dart';
import 'editor_loading_region.dart';
import 'project_switch_region.dart';
import 'project_sidebar.dart';
import 'project_tabs_bar.dart';
import 'project_tabs_controller.dart';
import 'widgets/name_dialog.dart';
/// The single application surface: project navigation beside the editor.
@@ -90,13 +97,26 @@ class _EditingPageState extends ConsumerState<EditingPage> {
WidgetRef ref, {
required bool create,
}) async {
if (ref.read(projectsProvider).value?.projectBusy == true) return;
if (_switchingProject ||
ref.read(projectsProvider).value?.projectBusy == true) {
return;
}
FocusManager.instance.primaryFocus?.unfocus();
try {
if (create) {
final name = await askName(
context,
title: context.l10n.newProject,
label: context.l10n.projectName,
validateName: (name) async {
final failure = await ref
.read(projectsProvider.notifier)
.validateNewProjectName(name);
if (!context.mounted) return null;
return failure == null
? null
: context.l10n.failureMessage(failure);
},
);
if (name == null || !context.mounted) return;
final created = await ref
@@ -130,15 +150,50 @@ class _EditingPageState extends ConsumerState<EditingPage> {
}
}
Future<void> _openProject(WidgetRef ref, RecentProject project) =>
ref.read(workspaceNavigationProvider.notifier).openProject(project);
Future<void> _openProject(WidgetRef ref, RecentProject project) {
FocusManager.instance.primaryFocus?.unfocus();
return ref.read(workspaceNavigationProvider.notifier).openProject(project);
}
Future<void> _closeProjectTab(RecentProject project) async {
if (_switchingProject ||
ref.read(projectsProvider).value?.projectBusy == true) {
return;
}
FocusManager.instance.primaryFocus?.unfocus();
final tabs = ref.read(projectTabsProvider);
if (ref.read(projectsProvider).value?.activeProject?.id == project.id) {
final index = tabs.indexWhere((tab) => tab.id == project.id);
final neighbors = [
...tabs.skip(index + 1),
...tabs.take(index).toList().reversed,
];
final next = neighbors.firstOrNull;
if (next != null) {
await _openProject(ref, next);
if (!mounted ||
ref.read(projectsProvider).value?.activeProject?.id != next.id) {
return;
}
} else {
final closed = await ref
.read(projectsProvider.notifier)
.closeActiveProject();
if (!closed || !mounted) return;
}
}
if (mounted) ref.read(projectTabsProvider.notifier).remove(project.id);
}
Future<bool> _renameProject(
BuildContext context,
WidgetRef ref,
RecentProject project,
) async {
if (ref.read(projectsProvider).value?.projectBusy == true) return false;
if (_switchingProject ||
ref.read(projectsProvider).value?.projectBusy == true) {
return false;
}
final name = await askName(
context,
title: context.l10n.rename,
@@ -147,7 +202,35 @@ class _EditingPageState extends ConsumerState<EditingPage> {
submitLabel: context.l10n.rename,
);
if (name == null || !context.mounted || name == project.name) return false;
return ref.read(projectsProvider.notifier).renameProject(project, name);
final renamed = await ref
.read(projectsProvider.notifier)
.renameProject(project, name);
if (renamed && mounted) {
ref
.read(projectTabsProvider.notifier)
.updateProject(project.copyWith(name: name.trim()));
}
return renamed;
}
Future<void> _removeRecentProject(RecentProject project) async {
if (_switchingProject ||
ref.read(projectsProvider).value?.projectBusy == true) {
return;
}
final recent = ref.read(projectsProvider).value?.recent ?? const [];
final index = recent.indexWhere((item) => item.id == project.id);
final removed = await ref
.read(projectsProvider.notifier)
.removeRecentProject(project.id);
if (!removed || !mounted) return;
ErrorNotificationHost.of(context).showMessage(
content: Text(context.l10n.projectRemoved),
actionLabel: context.l10n.undo,
onAction: () => ref
.read(projectsProvider.notifier)
.restoreRecentProject(project, index),
);
}
Future<void> _relocateProject(
@@ -155,7 +238,10 @@ class _EditingPageState extends ConsumerState<EditingPage> {
WidgetRef ref,
RecentProject project,
) async {
if (ref.read(projectsProvider).value?.projectBusy == true) return;
if (_switchingProject ||
ref.read(projectsProvider).value?.projectBusy == true) {
return;
}
final directory = await ref
.read(filePickerProvider)
.pickDirectory(confirmButtonText: context.l10n.openProject);
@@ -183,7 +269,30 @@ class _EditingPageState extends ConsumerState<EditingPage> {
final experience = ref.watch(deviceExperienceProvider);
final desktop = experience == DeviceExperience.desktop;
final contentSelection = ref.watch(desktopContentProvider);
final projects = ref.watch(projectsProvider);
final openProjects = ref.watch(projectTabsProvider);
// Window/navigation subscribe to chrome only. Content owns live values.
ref.watch(
projectsProvider.select((value) {
final state = value.value;
return (
value.isLoading,
value.error,
state?.activeProject,
PresentationList(state?.recent ?? const <RecentProject>[]),
state?.timeline?.id,
state?.projectBusy,
state?.openingTimelineId,
state?.error,
PresentationList(
state?.timelines.map(
(timeline) => (timeline.id, timeline.name, timeline.pinned),
) ??
const <(String, String, bool)>[],
),
);
}),
);
final projects = ref.read(projectsProvider);
final state = projects.value ?? const ProjectState();
return EditorWindowChrome(
headerHeight: desktop ? DesktopWindowFrame.headerHeight : 48,
@@ -210,6 +319,42 @@ class _EditingPageState extends ConsumerState<EditingPage> {
);
final navigationCollapsed =
_sidebarCollapsed || navigationHiddenBySpace;
void toggleSidebar() {
if (desktop && _desktopSplits.agentFloating) {
_desktopSplits.setAgentFloating(false);
_sidebarCollapsed = false;
_saveViewState();
if (navigationHiddenBySpace) {
_desktopScaffoldKey.currentState
?.openDrawer();
}
} else if (navigationHiddenBySpace) {
final scaffold =
_desktopScaffoldKey.currentState;
if (scaffold?.isDrawerOpen == true) {
scaffold?.closeDrawer();
} else {
scaffold?.openDrawer();
}
} else {
_sidebarCollapsed = !_sidebarCollapsed;
_saveViewState();
}
}
void toggleAgentFloating() {
final floating = !_desktopSplits.agentFloating;
if (floating) {
_desktopScaffoldKey.currentState?.closeDrawer();
_sidebarCollapsed = false;
_saveViewState();
}
_desktopSplits.setAgentFloating(floating);
if (!floating && navigationHiddenBySpace) {
_desktopScaffoldKey.currentState?.openDrawer();
}
}
Widget controlSlot(Widget child) {
if (!desktop) {
return SizedBox.square(
@@ -263,9 +408,7 @@ class _EditingPageState extends ConsumerState<EditingPage> {
child: Padding(
padding: EdgeInsets.only(
left: desktop
? (DesktopWindowFrame.railWidth -
AppControlSize.headerButton) /
2
? DesktopWindowFrame.headerInset
: 0,
),
child: Row(
@@ -281,21 +424,12 @@ class _EditingPageState extends ConsumerState<EditingPage> {
tooltip: navigationCollapsed
? context.l10n.expandSidebar
: context.l10n.collapseSidebar,
onPressed: () {
if (navigationHiddenBySpace) {
_desktopScaffoldKey.currentState
?.openDrawer();
} else {
_sidebarCollapsed =
!_sidebarCollapsed;
_saveViewState();
}
},
onPressed: toggleSidebar,
style: sidebarActionButtonStyle(
context,
),
icon: const Icon(
Icons.view_sidebar_outlined,
AppIcons.sidebar,
size: AppIconSize.header,
),
),
@@ -316,7 +450,7 @@ class _EditingPageState extends ConsumerState<EditingPage> {
context,
),
icon: const Icon(
Icons.settings_outlined,
AppIcons.settings,
size: AppIconSize.header,
),
),
@@ -349,6 +483,7 @@ class _EditingPageState extends ConsumerState<EditingPage> {
final agent = WorkspaceAgentSurface(
key: _agentKey,
showProjectSelector: !desktop,
state: state,
onSelectProject: (project) =>
project.availability.canOpen
@@ -357,14 +492,10 @@ class _EditingPageState extends ConsumerState<EditingPage> {
onCreateProject: () =>
_selectProject(context, ref, create: true),
);
void selectSidebar(bool resources) {
void selectSidebar(DesktopContent surface) {
ref
.read(desktopContentProvider.notifier)
.select(
resources
? DesktopContent.library
: DesktopContent.workspace,
);
.select(surface);
setState(() => _sidebarCollapsed = false);
_saveViewState();
if (navigationHiddenBySpace) {
@@ -384,15 +515,23 @@ class _EditingPageState extends ConsumerState<EditingPage> {
VoidCallback? expandEditor,
bool drawer = false,
}) => ProjectSidebar(
chatOnly: desktop,
experience: experience,
librarySelected:
desktop && contentSelection.librarySelected,
resourcesSelected:
desktop && contentSelection.resourcesSelected,
onResourcesSelected: desktop
? (media) => selectSidebar(
media
? DesktopContent.library
: DesktopContent.workspace,
)
: null,
key: drawer
? _drawerNavigationKey
: _navigationKey,
agent: desktop && !drawer
? agent
: const SizedBox.shrink(),
agent: desktop ? agent : const SizedBox.shrink(),
navigationOnly: true,
onNavigationComplete: desktop && !drawer
? null
@@ -431,48 +570,47 @@ class _EditingPageState extends ConsumerState<EditingPage> {
onPressed: () =>
Scaffold.of(context)
.closeDrawer(),
icon: const Icon(Icons.close),
icon: const Icon(AppIcons.close),
),
),
],
),
),
);
final pendingProject = _switchingProject
? state.recent
final selectedProjectId =
_selectedProjectId ?? state.activeProject?.id;
final pendingProject = _selectedProjectId == null
? null
: state.recent
.where(
(item) => item.id == _selectedProjectId,
(item) => item.id == selectedProjectId,
)
.firstOrNull
: null;
final projectLoading =
pendingProject != null &&
pendingProject.id != state.activeProject?.id;
.firstOrNull;
final visibleProjects = [
...openProjects,
if (pendingProject != null &&
!openProjects.any(
(item) => item.id == pendingProject.id,
))
pendingProject,
];
final editor = ProjectSwitchRegion(
pendingProjectId: projectLoading
? pendingProject.id
pendingProjectId:
selectedProjectId != state.activeProject?.id
? _selectedProjectId
: null,
builder: (context, showDefaults) {
final displayDefaults =
projectLoading && showDefaults;
final visibleProject = displayDefaults
? pendingProject
: state.activeProject;
return visibleProject != null &&
(displayDefaults ||
state.timeline != null)
child:
state.activeProject != null &&
state.timeline != null
? EditorWorkspace(
key: _editorKey,
experience: experience,
projectId: visibleProject.id,
timelineId: displayDefaults
? ''
: state.timeline!.id,
projectName: visibleProject.name,
projectLoading: displayDefaults,
showProjectName:
desktop &&
_mode == WorkspaceMode.cut,
projectId: state.activeProject!.id,
timelineId: state.timeline!.id,
projectName: state.activeProject!.name,
timelineLoading:
state.openingTimelineId != null,
showProjectName: false,
integratedTitlebar: false,
headerLeading: desktop
? const SizedBox.shrink()
@@ -481,18 +619,17 @@ class _EditingPageState extends ConsumerState<EditingPage> {
),
)
: EmptyEditor(
experience: experience,
desktop: desktop,
state: state,
showProjectName:
desktop &&
_mode == WorkspaceMode.cut,
desktop && _mode == WorkspaceMode.cut,
headerLeading: desktop
? const SizedBox.shrink()
: const SizedBox(
width: AppSpacing.compact,
),
);
},
),
);
Widget contentSurface(
DesktopContent surface,
@@ -532,6 +669,12 @@ class _EditingPageState extends ConsumerState<EditingPage> {
),
child: SettingsContent(
cardLayout: true,
onBack: () => ref
.read(
desktopContentProvider
.notifier,
)
.closeSettings(),
initialTab:
contentSelection.settingsTab,
navigationRequest: contentSelection
@@ -547,22 +690,105 @@ class _EditingPageState extends ConsumerState<EditingPage> {
return switch (experience) {
DeviceExperience.desktop => DesktopWindowFrame(
integratedTitlebar: integrated,
headerControls: controls(),
librarySelected:
headerControls: const SizedBox.shrink(),
projectTabs: ListenableBuilder(
listenable: _desktopSplits,
builder: (context, _) => ProjectTabsBar(
projects: visibleProjects,
recent: state.recent,
selectedId: selectedProjectId,
onSelect: (project) {
ref
.read(desktopContentProvider.notifier)
.select(DesktopContent.workspace);
selectProject(project);
},
onClose: _closeProjectTab,
onCreate: () => _selectProject(
context,
ref,
create: true,
),
onOpen: () => _selectProject(
context,
ref,
create: false,
),
onRename: (project) =>
_renameProject(context, ref, project),
onRemoveRecent: _removeRecentProject,
leadingActions: [
IconButton(
key: const Key(
'project-sidebar-toggle',
),
tooltip:
navigationCollapsed ||
_desktopSplits.agentFloating
? context.l10n.expandSidebar
: context.l10n.collapseSidebar,
onPressed: toggleSidebar,
style: AppTheme.projectTabActionStyle(
context,
),
icon: const Icon(
AppIcons.sidebar,
size: 16,
),
),
],
trailingActions: [
IconButton(
key: const Key('agent-minimize-button'),
tooltip: _desktopSplits.agentFloating
? context.l10n.agentDock
: context.l10n.agentMinimize,
onPressed: toggleAgentFloating,
isSelected:
_desktopSplits.agentFloating,
style: AppTheme.projectTabActionStyle(
context,
),
icon: const Icon(
AppIcons.fullscreen,
size: 16,
),
),
const BackgroundTasksButton(
iconSize: 16,
alignment:
AlignmentDirectional.bottomEnd,
),
],
projectMenuActions: [
AppMenuItem(
key: const Key(
'project-settings-button',
),
label: context.l10n.settings,
icon: AppIcons.settings,
onPressed: () =>
showSettingsPage(context),
),
],
),
),
resourceLibrarySelected:
contentSelection.surface ==
DesktopContent.library,
DesktopContent.resourceLibrary,
onResourceLibraryPressed: () => selectSidebar(
DesktopContent.resourceLibrary,
),
settingsSelected:
contentSelection.surface ==
DesktopContent.settings,
onModeChanged: (mode) {
selectSidebar(false);
_setMode(mode);
},
onLibraryPressed: () => selectSidebar(true),
onHomePressed: () =>
selectSidebar(DesktopContent.workspace),
onSettingsPressed: () =>
showSettingsPage(context),
child: desktopContents(
DesktopWorkspaceShell(
projectTabsLayout: true,
controller: _desktopSplits,
scaffoldKey: _desktopScaffoldKey,
navigationDrawer: navigation(drawer: true),
@@ -582,53 +808,80 @@ class _EditingPageState extends ConsumerState<EditingPage> {
geometry: geometry,
expandEditor: expand,
),
agentBuilder: (geometry, expand) => Column(
agentBuilder: (geometry, expand) =>
_desktopSplits.agentFloating
? AgentPanelPresentation(
compact: true,
expanded: _desktopSplits
.agentFloatingExpanded,
onToggleExpanded: _desktopSplits
.toggleFloatingConversation,
onDock: () => _desktopSplits
.setAgentFloating(false),
child: agent,
)
: Column(
children: [
SizedBox(
key: const Key(
'agent-content-header',
),
height: AppControlSize.panelToolbar,
height: AppDesktopMetrics
.panelHeader,
child: Padding(
padding: const EdgeInsets.all(
AppSpacing.gap,
padding:
const EdgeInsets.symmetric(
horizontal: 12,
),
child: Row(
children: [
const Spacer(),
const Icon(
AppIcons.chat,
size: 16,
),
const SizedBox(width: 8),
Expanded(
child: Text(
context
.l10n
.workspaceAgent,
maxLines: 1,
overflow: TextOverflow
.ellipsis,
),
),
HeaderControlRegion(
child: SizedBox.square(
dimension: AppControlSize
.headerButton,
child: IconButton(
key: const Key(
'agent-fullscreen-button',
),
isSelected:
geometry.editorHidden,
_desktopSplits
.agentFullscreen,
tooltip:
geometry.editorHidden
geometry
.editorHidden
? context
.l10n
.exitPreviewFullscreen
.expandEditor
: context
.l10n
.agentFullscreen,
onPressed:
geometry.editorHidden
geometry
.editorHidden
? expand
: () => _desktopSplits
.setAgentFullscreen(
true,
),
icon: Icon(
size:
AppIconSize.header,
geometry.editorHidden
? Icons
.fullscreen_exit
: Icons.fullscreen,
),
? AppIcons
.splitVertical
: AppIcons
.fullscreen,
size: 16,
),
),
),
@@ -0,0 +1,66 @@
import 'package:cutdex_ui/theme.dart';
import 'package:flutter/material.dart';
import '../../l10n/l10n.dart';
/// Desktop sidebar categories change navigation content, not workspace layout.
class SidebarCategoryTabs extends StatelessWidget {
const SidebarCategoryTabs({
super.key,
required this.mediaSelected,
required this.onSelected,
});
final bool mediaSelected;
final ValueChanged<bool>? onSelected;
@override
Widget build(BuildContext context) => SizedBox(
key: const Key('sidebar-category-header'),
height: AppDesktopMetrics.panelHeader,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
child: Row(
children: [
for (final media in [false, true]) ...[
if (media) const SizedBox(width: 4),
Expanded(
child: Semantics(
selected: mediaSelected == media,
child: Tooltip(
message: media
? context.l10n.materials
: context.l10n.navigationChat,
child: TextButton(
key: Key(
media ? 'sidebar-tab-resources' : 'sidebar-tab-chat',
),
onPressed: onSelected == null
? null
: () => onSelected!(media),
style:
AppTheme.panelTabStyle(
context,
selected: mediaSelected == media,
).copyWith(
padding: const WidgetStatePropertyAll(
EdgeInsets.symmetric(horizontal: 6),
),
),
child: Text(
media
? context.l10n.materials
: context.l10n.navigationChat,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
),
),
),
],
],
),
),
);
}
@@ -0,0 +1,40 @@
import 'package:cutdex_ui/theme.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widget_previews.dart';
import '../../l10n/app_localizations.dart';
import 'sidebar_category_tabs.dart';
@Preview(
name: 'Sidebar categories — light',
group: 'Desktop navigation',
size: Size(280, 36),
)
Widget sidebarCategoriesLightPreview() => _preview(Brightness.light);
@Preview(
name: 'Sidebar categories — dark',
group: 'Desktop navigation',
size: Size(180, 36),
)
Widget sidebarCategoriesDarkPreview() => _preview(Brightness.dark);
Widget _preview(Brightness brightness) {
var media = false;
return MaterialApp(
theme: AppTheme.desktopWorkspaceTheme(
AppTheme.forPalette(AppPalette.graphite, brightness),
),
locale: const Locale('zh'),
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Scaffold(
body: StatefulBuilder(
builder: (context, setState) => SidebarCategoryTabs(
mediaSelected: media,
onSelected: (value) => setState(() => media = value),
),
),
),
);
}
Loaded 100 of 346 files, more files were not shown because too many files have changed in this diff. Show more