28 Commits
379 changed files with 56848 additions and 4625 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"
}
+82
View File
@@ -0,0 +1,82 @@
# Gitea Windows and Android builds
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.
Set CUTDEX_GITEA_TOKEN in repository Actions Secrets with repository read and
package read access. It authenticates private Gitea native package downloads.
The Android APK includes ARM64 and x86_64, uses the production flavor and currently
uses the project's debug signing configuration. Configure formal signing before
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.
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)`. 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. 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
similarly reuse their upstream artifacts. Use the failed-job rerun option: a
whole-workflow rerun executes compilation again. A job always restarts from its
first step. Saving the Windows app adds one artifact transfer between the jobs.
CI artifact uploads attempt at most three times, waiting 5 and 15 seconds between
attempts and replacing incomplete artifacts of the same job-owned name. Release
attachment uploads use the same bounded delays for temporary HTTP/network errors,
and check for already saved filenames before repeating a POST. Permanent errors
fail immediately and final attachment byte verification remains required. If the
Windows app cannot be saved after all attempts, its build job still needs to be
rerun. Draft creation and final publication are not automatically retried.
After main CI succeeds, create v<pubspec version> at that exact commit, or manually
dispatch the Release workflow with the existing tag. Release preparation selects
a successful main ci.yml run for the exact tagged commit and requires unexpired
cutdex-android-build, cutdex-windows-build and cutdex-release-metadata artifacts. It creates a draft bound to both that commit and
that CI run. Release jobs never rebuild the app or reinstall Flutter dependencies.
Android and Windows independently download their platform artifacts from the
selected CI run and immediately upload them to the draft. These jobs run in
parallel. The final job accepts only the compact metadata artifact from that same
CI run. Complete binary archives cannot substitute for platform packages or
metadata. Missing, expired or duplicate required artifacts block preparation
before any draft is created. Platform uploads check attachment presence without
reading back their bytes. Before publication, every attachment is read back once
and verified against trusted SHA256 checksums; the full update package also
matches its index SHA1 and size. Upload and verification batches use at most two
requests per job. Verification reads in 1 MiB chunks. Tag, CI, draft and attachment
ID/name bindings are rechecked before the Release is made public.
A failed upload leaves the draft unpublished with successful uploads retained.
Manual dispatch with the same tag resumes the original CI run, even if another CI
for that commit has since succeeded. Matching attachments are reused; changed or
unrelated attachments block publication rather than being replaced. If the
original platform or metadata artifacts have expired, release preparation fails and requires
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.
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
promotion entry point or format fallback.
+156
View File
@@ -0,0 +1,156 @@
# CI build performance
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
builds the APK. The final job downloads only platform packages and
validates the complete release manifest, update feed and checksums. The public
artifact remains `cutdex-release-packages`.
Build jobs explicitly use persistent runner-user Pub and Gradle caches, respecting
existing `PUB_CACHE` and `GRADLE_USER_HOME` overrides. Gradle task output caching is
enabled for CI. Do not clear these caches between runs. Each job must have its own
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.
The runner needs at least two execution slots. The local runner configuration at
`D:/workspace/gitea-stack/runner/config.yaml` currently has `capacity: 2`. The host
has 12 logical processors and approximately 16 GB RAM; the Android job retains its
3 GB heap and four-worker limit to leave room for concurrent Windows compilation.
`prepare-package-tools.ps1` installs pinned `pefile` and `vpk` on first use under
the runner user's `%LOCALAPPDATA%/Cutdex/ci-tools/`. Later builds reuse them after
version checks. Python interpreter identity and tool versions isolate the cache,
and a mutex protects installation across concurrent workflows. .NET setup remains
in the Windows packaging job to provide SDK 10 and the runtime required by `vpk`.
The .NET installation uses the runner user's `Cutdex/ci-tools/dotnet` directory
through `DOTNET_INSTALL_DIR` and `DOTNET_ROOT`, so setup needs no administrator
access and later jobs reuse the installed SDK and runtime.
The Windows build verifies that the resolved deskup native SDK matches the pinned
Velopack version before saving the app. Packaging imports no Flutter package
configuration and independently verifies the installed vpk version.
APK and Windows package uploads use `compression-level: 0` to avoid recompressing
already compressed artifacts. The saved Windows app uses compression level 1,
preserves nested and hidden runtime assets, and excludes the same debug files and
optional workers omitted by packaging. The saved app, platform packages, compact
metadata and validated release artifact all retain 30 days.
This host runs both Gitea and the runner. The workflows set
`CUTDEX_GITEA_INTERNAL_URL=http://127.0.0.1:3000` and override `ACTIONS_RESULTS_URL`
on artifact upload/download steps, so those transfers stay on the host instead of
looping through the public FRP tunnel. Release API uploads and byte verification
also use this loopback endpoint; tooling rewrites only the validated public Gitea
origin. The server's public URL remains `https://git.orangraph.com`, and the runner
registration is unchanged. These workflow labels require this shared-host layout;
configure a reachable private endpoint before using runners on other hosts.
Checkout uses the same endpoint through its `github-server-url` input, retaining
the requested commit/tag and disabling persisted credentials. Release requests
retain the public Host header so Gitea response links pass the public-origin checks.
CI artifact ZIP download requests retain the loopback Host instead: Gitea returns
a signed redirect to the raw archive, and its Host must remain local for that
second request to avoid the public tunnel. Release attachment links stay public.
Compare warm CI runs after the first cache fill. Measure checks, Android compile,
Windows compile, packaging and artifact transfer separately. Total duration follows
the slower platform branch, plus checks and final assembly; no fixed speedup is
assumed. Release audits and artifact validation remain mandatory.
## Failure recovery
Use Gitea's failed-job rerun rather than rerunning the entire workflow. A job
reruns from its first step, including downstream dependent jobs. Once the Windows
app artifact has been saved, a Windows packaging failure can be retried without
recompilation. Assembly failures reuse the saved Android and Windows packages;
Release failures reuse the successful main CI. Splitting Windows adds one app
upload/download on successful runs in exchange for this recovery point.
Every CI artifact upload uses the local `upload-artifact` composite, with at most
three action attempts and 5/15-second delays. Attempts replace incomplete
artifacts with the same name; each name belongs to one producing job. Exhausted
retries fail the job. If the first Windows app checkpoint cannot be uploaded,
the build job must still be rerun; it has no saved app to restore.
Release attachment uploads retry temporary network errors, HTTP 408/429 and
500/502/503/504 up to three POST attempts per file, also with 5/15-second delays.
The specific FRP HTML "Not Found" page observed during tunnel reconnection is
also treated as temporary; ordinary Gitea API or HTML 404 responses still fail.
Before retrying a POST, the uploader checks whether Gitea already saved the named
attachment, including after the final response is lost. This avoids duplicate
uploads after a timeout. Authorization, invalid-input and other permanent errors
fail immediately. No draft creation or publication PATCH is automatically retried.
Attachment-list reads have their own bounded retries. Final byte verification
remains mandatory even when an existing filename is reused.
The tag/manual Release workflow reuses a successful main CI for the exact tagged
commit; it performs no Flutter builds, dependency resolution or Windows packaging.
A prepare job binds the draft and both platform upload jobs to one CI run. Android
and Windows independently fetch and upload their existing packages in parallel.
Publication requires the small cutdex-release-metadata artifact; it never
downloads the combined binary artifact. Missing or expired metadata/platform
artifacts fail preparation, with no old-format fallback. Every remote file is read and verified once, immediately
before publication, with two verification workers and 1 MiB chunks. Platform
upload steps check presence without repeating binary readbacks. Each upload
batch also uses at most two workers; while both platform jobs run, Android can
have one upload in flight alongside two Windows uploads.
Retries retain the original CI-run binding. Ordinary CI never creates
drafts. Wait for main CI success before tagging or retry Release after it finishes;
platform Release uploads overlap each other, not the original main builds.
-26
View File
@@ -1,26 +0,0 @@
# Gitea Windows and Android builds
The Windows x64 host runner needs Flutter 3.47.5, 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.
Set CUTDEX_GITEA_TOKEN in repository Actions Secrets with repository read and
package read access. It authenticates private Gitea native package downloads.
The Android APK includes ARM64 and x86_64, uses the production flavor and currently
uses the project's debug signing configuration. Configure formal signing before
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. Protect main
with `Gitea CI / Gitea CI passed (pull_request)`.
After main CI succeeds, create v<pubspec version> at that exact commit. The Release
workflow downloads the existing CI artifact, requires both APK and Windows ZIP,
checks their digests, uploads to a draft Release, verifies remote bytes, then
publishes it. It refuses to overwrite a published Release. A manual dispatch with
the existing tag can retry an interrupted draft publication. 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.
+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
+69
View File
@@ -0,0 +1,69 @@
name: Upload CI artifact with bounded retries
description: Save an artifact with at most three attempts, replacing incomplete uploads of the same name.
inputs:
name:
description: Artifact name, unique to this job in the workflow run
required: true
path:
description: Files and directories to upload
required: true
compression-level:
description: ZIP compression level
default: '0'
retention-days:
description: Artifact retention in days
default: '30'
runs:
using: composite
steps:
- name: Upload artifact (attempt 1 of 3)
id: first
continue-on-error: true
uses: https://github.com/actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
env:
ACTIONS_RESULTS_URL: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
with:
name: ${{ inputs.name }}
path: ${{ inputs.path }}
compression-level: ${{ inputs.compression-level }}
retention-days: ${{ inputs.retention-days }}
if-no-files-found: error
include-hidden-files: true
overwrite: true
- name: Wait before second upload attempt
if: ${{ !cancelled() && steps.first.outcome == 'failure' }}
shell: pwsh
run: Start-Sleep -Seconds 5
- name: Upload artifact (attempt 2 of 3)
id: second
if: ${{ !cancelled() && steps.first.outcome == 'failure' }}
continue-on-error: true
uses: https://github.com/actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
env:
ACTIONS_RESULTS_URL: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
with:
name: ${{ inputs.name }}
path: ${{ inputs.path }}
compression-level: ${{ inputs.compression-level }}
retention-days: ${{ inputs.retention-days }}
if-no-files-found: error
include-hidden-files: true
overwrite: true
- name: Wait before final upload attempt
if: ${{ !cancelled() && steps.first.outcome == 'failure' && steps.second.outcome == 'failure' }}
shell: pwsh
run: Start-Sleep -Seconds 15
- name: Upload artifact (attempt 3 of 3)
id: third
if: ${{ !cancelled() && steps.first.outcome == 'failure' && steps.second.outcome == 'failure' }}
uses: https://github.com/actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
env:
ACTIONS_RESULTS_URL: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
with:
name: ${{ inputs.name }}
path: ${{ inputs.path }}
compression-level: ${{ inputs.compression-level }}
retention-days: ${{ inputs.retention-days }}
if-no-files-found: error
include-hidden-files: true
overwrite: true
+202 -31
View File
@@ -12,66 +12,237 @@ concurrency:
group: app-${{ gitea.ref }} group: app-${{ gitea.ref }}
cancel-in-progress: true cancel-in-progress: true
env: env:
CI: 'true'
PYTHONUTF8: '1' PYTHONUTF8: '1'
CUTDEX_GITEA_INTERNAL_URL: http://127.0.0.1:3000
GIT_CONFIG_COUNT: '2' GIT_CONFIG_COUNT: '2'
GIT_CONFIG_KEY_0: core.autocrlf GIT_CONFIG_KEY_0: core.autocrlf
GIT_CONFIG_VALUE_0: 'false' GIT_CONFIG_VALUE_0: 'false'
GIT_CONFIG_KEY_1: core.eol GIT_CONFIG_KEY_1: core.eol
GIT_CONFIG_VALUE_1: lf GIT_CONFIG_VALUE_1: lf
jobs: jobs:
build: quality:
name: Windows x64 and Android name: Check code and tests
runs-on: cutdex-windows-x64 runs-on: cutdex-windows-x64
outputs:
build-app: ${{ steps.scope.outputs.build-app }}
package-app: ${{ steps.scope.outputs.package-app }}
env: env:
GITEA_ACTOR: lingjhf
CUTDEX_GITEA_TOKEN: ${{ secrets.CUTDEX_GITEA_TOKEN }} CUTDEX_GITEA_TOKEN: ${{ secrets.CUTDEX_GITEA_TOKEN }}
steps: steps:
- uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 - name: Check out source
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with: with:
persist-credentials: false persist-credentials: false
- name: Verify toolchains github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
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: | run: |
$version = flutter --version --machine | ConvertFrom-Json python tool/gitea/ci_scope.py
if ($version.frameworkVersion -ne '3.47.5') { throw 'Flutter 3.47.5 required.' } if ($LASTEXITCODE -ne 0) { throw 'CI scope selection failed.' }
flutter config --jdk-dir=$env:JAVA_HOME - name: Prepare Flutter environment
if ($LASTEXITCODE -ne 0) { throw 'Flutter JDK setup failed.' } uses: ./.gitea/actions/prepare-flutter
- run: flutter pub get --enforce-lockfile with:
- run: dart analyze --fatal-infos configure-java: 'true'
- run: flutter test --reporter expanded test packages/cutdex_ui/test packages/cutdex_native/test - name: Analyze Dart code
- name: Bound Android build memory on the shared runner run: python tool/check.py --suite analyze
- name: Run Flutter tests
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:
CUTDEX_GITEA_TOKEN: ${{ secrets.CUTDEX_GITEA_TOKEN }}
steps:
- name: Check out source
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with:
persist-credentials: false
github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
- name: Prepare Flutter environment
uses: ./.gitea/actions/prepare-flutter
with:
configure-java: 'true'
- name: Configure Gradle memory and build cache
run: | run: |
$file = 'android/gradle.properties' $file = 'android/gradle.properties'
$properties = [IO.File]::ReadAllText($file).Replace('-Xmx8G', '-Xmx3G').Replace('MaxMetaspaceSize=4G', 'MaxMetaspaceSize=768m') $properties = [IO.File]::ReadAllText($file).Replace('-Xmx8G', '-Xmx3G').Replace('MaxMetaspaceSize=4G', 'MaxMetaspaceSize=768m')
[IO.File]::WriteAllText($file, $properties + "`norg.gradle.workers.max=4`n") [IO.File]::WriteAllText($file, $properties + "`norg.gradle.workers.max=4`norg.gradle.caching=true`n")
- run: flutter build apk --release --flavor production --target-platform android-arm64,android-x64 - name: Build production Android APK
- name: Build Windows from the pinned Gitea native release 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
path: build/app/outputs/flutter-apk/app-production-release.apk
compression-level: 0
retention-days: 30
windows-build:
name: Build Windows x64 app
needs: quality
if: ${{ needs.quality.outputs.build-app == 'true' }}
runs-on: cutdex-windows-x64
env:
CUTDEX_GITEA_TOKEN: ${{ secrets.CUTDEX_GITEA_TOKEN }}
steps:
- name: Check out source
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with:
persist-credentials: false
github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
- name: Prepare Flutter environment
uses: ./.gitea/actions/prepare-flutter
- name: Reuse verified Velopack native archive
run: |
python tool/windows/native_cache.py
if ($LASTEXITCODE -ne 0) { throw 'Windows native archive cache preparation failed.' }
- name: Build production Windows app
run: | run: |
Remove-Item Env:CUTDEX_WINDOWS_PATH, Env:CUTDEX_WINDOWS_PACKAGE_PATH -ErrorAction SilentlyContinue 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.' } if ($LASTEXITCODE -ne 0) { throw 'Windows build failed.' }
- name: Prepare isolated packaging tools - name: Verify native SDK matches pinned packaging tools
run: | run: |
python -m venv .build/package-tools python tool/windows/windows_updates.py verify-sdk
if ($LASTEXITCODE -ne 0) { throw 'Packaging environment setup failed.' } if ($LASTEXITCODE -ne 0) { throw 'Windows native SDK version validation failed.' }
& ./.build/package-tools/Scripts/python.exe -m pip install pefile==2024.8.26 - name: Save Windows app for independent packaging retries
if ($LASTEXITCODE -ne 0) { throw 'Packaging dependency installation failed.' } if: ${{ needs.quality.outputs.package-app == 'true' }}
- name: Package application uses: ./.gitea/actions/upload-artifact
with:
name: cutdex-windows-app
path: |
build/windows/x64/production/runner/Release/
!build/windows/x64/production/runner/Release/**/processing/**
!build/windows/x64/production/runner/Release/**/*.pdb
!build/windows/x64/production/runner/Release/**/*.lib
!build/windows/x64/production/runner/Release/**/*.exp
!build/windows/x64/production/runner/Release/**/dartjni.dll
compression-level: 1
retention-days: 30
windows:
name: Audit and package Windows x64
needs: [quality, windows-build]
if: ${{ needs.quality.outputs.package-app == 'true' }}
runs-on: cutdex-windows-x64
steps:
- name: Check out source
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with:
persist-credentials: false
github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
- name: Download saved Windows app
uses: https://github.com/actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093
env:
ACTIONS_RESULTS_URL: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
with:
name: cutdex-windows-app
path: build/windows/x64/production/runner/Release/
- name: Prepare Windows packaging environment
uses: ./.gitea/actions/prepare-windows-packaging
- name: Audit and package Windows release
run: | run: |
& ./.build/package-tools/Scripts/python.exe tool/gitea/package-app.py & $env:PACKAGE_PYTHON tool/gitea/package-app.py --platform windows --vpk $env:VPK_PATH
- name: Upload Android and Windows packages if ($LASTEXITCODE -ne 0) { throw 'Windows packaging failed.' }
uses: https://github.com/actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 - name: Upload Windows CI artifact
uses: ./.gitea/actions/upload-artifact
with:
name: cutdex-windows-build
path: dist/*
compression-level: 0
retention-days: 30
build:
name: Assemble and validate CI artifacts
needs: [quality, android, windows]
if: ${{ needs.quality.outputs.package-app == 'true' }}
runs-on: cutdex-windows-x64
steps:
- name: Check out source
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with:
persist-credentials: false
github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
- name: Download Android CI artifact
uses: https://github.com/actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093
env:
ACTIONS_RESULTS_URL: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
with:
name: cutdex-android-build
path: build/app/outputs/flutter-apk/
- name: Download Windows CI artifact
uses: https://github.com/actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093
env:
ACTIONS_RESULTS_URL: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
with:
name: cutdex-windows-build
path: .build/windows-packages/
- name: Validate packages and generate metadata
run: |
python tool/gitea/package-app.py --platform assemble --windows-packages .build/windows-packages
if ($LASTEXITCODE -ne 0) { throw 'Application artifact validation failed.' }
- name: Upload combined CI artifact
uses: ./.gitea/actions/upload-artifact
with: with:
name: cutdex-release-packages name: cutdex-release-packages
path: dist/* path: dist/*
if-no-files-found: error compression-level: 0
retention-days: 30
- name: Upload release verification metadata
uses: ./.gitea/actions/upload-artifact
with:
name: cutdex-release-metadata
path: .build/release-metadata/*
compression-level: 0
retention-days: 30 retention-days: 30
checks: checks:
name: Gitea CI passed name: Gitea CI passed
if: always() if: always()
needs: build needs: [quality, android, windows-build, windows, build]
runs-on: cutdex-windows-x64 runs-on: cutdex-windows-x64
steps: steps:
- env: - name: Verify CI result
RESULT: ${{ needs.build.result }} env:
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: | 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)." }
}
+110 -10
View File
@@ -13,21 +13,121 @@ permissions:
concurrency: concurrency:
group: cutdex-release group: cutdex-release
cancel-in-progress: false cancel-in-progress: false
defaults:
run:
shell: pwsh
env:
PYTHONUTF8: '1'
CUTDEX_GITEA_INTERNAL_URL: http://127.0.0.1:3000
GIT_CONFIG_COUNT: '2'
GIT_CONFIG_KEY_0: core.autocrlf
GIT_CONFIG_VALUE_0: 'false'
GIT_CONFIG_KEY_1: core.eol
GIT_CONFIG_VALUE_1: lf
RELEASE_TAG: ${{ gitea.event.inputs.tag || gitea.ref_name }}
GITEA_REPOSITORY: ${{ gitea.repository }}
jobs: jobs:
release: prepare:
name: Prepare draft Release
runs-on: cutdex-windows-x64 runs-on: cutdex-windows-x64
outputs:
sha: ${{ steps.draft.outputs.sha }}
release-id: ${{ steps.draft.outputs.release-id }}
ci-run-id: ${{ steps.draft.outputs.ci-run-id }}
artifact-id: ${{ steps.draft.outputs.artifact-id }}
android-artifact-id: ${{ steps.draft.outputs.android-artifact-id }}
windows-artifact-id: ${{ steps.draft.outputs.windows-artifact-id }}
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
steps: steps:
- uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 - name: Check out release tag
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with: with:
ref: ${{ gitea.event.inputs.tag || gitea.ref_name }} ref: ${{ gitea.event.inputs.tag || gitea.ref_name }}
persist-credentials: false persist-credentials: false
- name: Publish validated Android and Windows packages github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
shell: pwsh - name: Select successful CI and prepare draft
env: id: draft
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
GITEA_REPOSITORY: ${{ gitea.repository }}
RELEASE_TAG: ${{ gitea.event.inputs.tag || gitea.ref_name }}
run: | run: |
$env:GITEA_SHA = git rev-parse HEAD $env:GITEA_SHA = git rev-parse HEAD
python tool/gitea/promote-release.py if ($LASTEXITCODE -ne 0) { throw 'Release source resolution failed.' }
if ($LASTEXITCODE -ne 0) { throw 'Release promotion failed.' } python tool/gitea/stage-release.py prepare-ci
if ($LASTEXITCODE -ne 0) { throw 'CI selection or draft preparation failed.' }
android:
name: Upload Android to draft Release
needs: prepare
runs-on: cutdex-windows-x64
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
GITEA_SHA: ${{ needs.prepare.outputs.sha }}
RELEASE_ID: ${{ needs.prepare.outputs.release-id }}
CI_RUN_ID: ${{ needs.prepare.outputs.ci-run-id }}
CI_ARTIFACT_ID: ${{ needs.prepare.outputs.android-artifact-id }}
steps:
- name: Check out release commit
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with:
ref: ${{ needs.prepare.outputs.sha }}
persist-credentials: false
github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
- name: Download Android CI artifact
run: |
python tool/gitea/stage-release.py fetch-android --path .build/android
if ($LASTEXITCODE -ne 0) { throw 'android CI artifact download failed.' }
- name: Upload Android packages to draft
run: |
python tool/gitea/stage-release.py android --path .build/android
if ($LASTEXITCODE -ne 0) { throw 'android draft upload failed.' }
windows:
name: Upload Windows to draft Release
needs: prepare
runs-on: cutdex-windows-x64
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
GITEA_SHA: ${{ needs.prepare.outputs.sha }}
RELEASE_ID: ${{ needs.prepare.outputs.release-id }}
CI_RUN_ID: ${{ needs.prepare.outputs.ci-run-id }}
CI_ARTIFACT_ID: ${{ needs.prepare.outputs.windows-artifact-id }}
steps:
- name: Check out release commit
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with:
ref: ${{ needs.prepare.outputs.sha }}
persist-credentials: false
github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
- name: Download Windows CI artifact
run: |
python tool/gitea/stage-release.py fetch-windows --path .build/windows
if ($LASTEXITCODE -ne 0) { throw 'windows CI artifact download failed.' }
- name: Upload Windows packages to draft
run: |
python tool/gitea/stage-release.py windows --path .build/windows
if ($LASTEXITCODE -ne 0) { throw 'windows draft upload failed.' }
publish:
name: Verify and publish Release
needs: [prepare, android, windows]
runs-on: cutdex-windows-x64
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
GITEA_SHA: ${{ needs.prepare.outputs.sha }}
RELEASE_ID: ${{ needs.prepare.outputs.release-id }}
CI_RUN_ID: ${{ needs.prepare.outputs.ci-run-id }}
CI_ARTIFACT_ID: ${{ needs.prepare.outputs.artifact-id }}
steps:
- name: Check out release commit
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with:
ref: ${{ needs.prepare.outputs.sha }}
persist-credentials: false
github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
- name: Download release verification metadata
run: |
python tool/gitea/stage-release.py fetch-release --path dist
if ($LASTEXITCODE -ne 0) { throw 'CI verification metadata validation failed.' }
- name: Verify attachments and publish Release
run: |
python tool/gitea/stage-release.py publish --path dist
if ($LASTEXITCODE -ne 0) { throw 'Release publication failed.' }
+4
View File
@@ -101,3 +101,7 @@ pubspec_overrides.yaml
*.aab *.aab
.vscode/* .vscode/*
!.vscode/launch.json !.vscode/launch.json
!.vscode/settings.json
# FVM Version Cache
.fvm/
+27 -1
View File
@@ -5,7 +5,33 @@
"name": "Cutdex", "name": "Cutdex",
"request": "launch", "request": "launch",
"type": "dart", "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)。 需要连接外部 AI 工具时,可查看 [MCP 连接指南](docs/mcp-connection.md)。
+2
View File
@@ -7,3 +7,5 @@ Flutter/Dart 依赖及解析版本记录在 `pubspec.yaml`、内部包的 `pubsp
应用发行包捆绑的媒体处理库、推理工具和模型遵循各自的许可与再分发要求。打包时保留随附的许可证和通知文件;不能用本仓库的 MIT 许可替代。 应用发行包捆绑的媒体处理库、推理工具和模型遵循各自的许可与再分发要求。打包时保留随附的许可证和通知文件;不能用本仓库的 MIT 许可替代。
仓库中的测试不附带个人媒体或模型。新增第三方素材、字体或代码时,应一同记录来源和许可证,并保留要求的版权声明。 仓库中的测试不附带个人媒体或模型。新增第三方素材、字体或代码时,应一同记录来源和许可证,并保留要求的版权声明。
桌面属性栏使用 [Inter 4.1](https://github.com/rsms/inter/releases/tag/v4.1) 的可变字体,遵循 SIL Open Font License 1.1。原始字体与版权声明保存在 `packages/cutdex_ui/assets/fonts/InterVariable.ttf` 和 `INTER_LICENSE.txt` 中。
+13 -1
View File
@@ -33,6 +33,8 @@ android {
defaultConfig { defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId = "com.example.cutdex" applicationId = "com.example.cutdex"
manifestPlaceholders["cutdexPreviewReverseCacheMiB"] = "0"
manifestPlaceholders["cutdexNativeSurfacePreview"] = "false"
// You can update the following values to match your application needs. // You can update the following values to match your application needs.
// For more information, see: https://flutter.dev/to/review-gradle-config. // For more information, see: https://flutter.dev/to/review-gradle-config.
minSdk = 31 minSdk = 31
@@ -50,7 +52,17 @@ android {
create("development") { create("development") {
dimension = "environment" dimension = "environment"
applicationIdSuffix = ".dev" 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") { create("production") {
dimension = "environment" dimension = "environment"
+4
View File
@@ -3,6 +3,10 @@
android:label="@string/app_name" android:label="@string/app_name"
android:name="${applicationName}" android:name="${applicationName}"
android:icon="@mipmap/cutdex_launcher"> 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 <activity
android:name=".MainActivity" android:name=".MainActivity"
android:exported="true" android:exported="true"
+4 -1
View File
@@ -26,7 +26,10 @@ plugins {
include(":app") include(":app")
// Native source development is opt-in; default resolution uses Gitea Maven packages. // 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) { includeBuild(nativePath) {
dependencySubstitution { dependencySubstitution {
substitute(module("dev.cutdex:cutdex-android")).using(project(":cutdex-android")) 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` 创建覆盖配置。覆盖文件只用于本机开发,不提交。 本地联调其他包时,可参考 `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 根目录运行: 在 Cutdex 根目录运行:
```sh ```sh
flutter pub get fvm dart tool/flutter_local.dart pub get
dart run build_runner build fvm dart run build_runner build
flutter run -d macos --flavor development fvm dart tool/flutter_local.dart run -d macos --flavor development
``` ```
Android、macOS、Windows 配置了 development 与 production flavor,默认是 development。按目标平台替换设备参数。iOS 使用 `Runner` scheme。构建或集成测试前,退出占用同一构建目录的应用。 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 时显式指定目标: Android 支持 ARM64 和 x86_64。按架构拆分 APK 时显式指定目标:
```sh ```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) 中适用的检查。界面改动还需检查桌面、平板和手机布局,以及明暗主题和不同语言下的表现。 执行 [测试指南](testing.md) 中适用的检查。界面改动还需检查桌面、平板和手机布局,以及明暗主题和不同语言下的表现。
@@ -64,6 +99,15 @@ flutter build apk --flavor development --split-per-abi --target-platform android
构建、打包和更新验证入口见 [仓库工具](../tool/README.md)。完成集成测试后,使用 `lib/main.dart` 重建正式应用,避免分发测试入口。 构建、打包和更新验证入口见 [仓库工具](../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 本身不提供发布证书。 Android release 当前使用调试签名,正式分发前需配置发布签名;production flavor 本身不提供发布证书。
macOS 默认 ad-hoc 签名。开发证书配置放在 `macos/Runner/Configs/Signing.local.xcconfig`;iOS 真机的 Team 设置放在 `ios/Flutter/Signing.local.xcconfig`。这些文件已忽略,凭据与私钥保留在本地或 CI 私密配置中。 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`,以本仓库为工作目录运行: MCP 默认关闭,在设置中启用并获取端口和访问令牌。外部客户端设置 `CUTDEX_MCP_PORT`、`CUTDEX_MCP_TOKEN`,以本仓库为工作目录运行:
```sh ```sh
dart run tool/mcp_stdio.dart fvm dart run tool/mcp_stdio.dart
``` ```
连接通过本机端口访问正在运行的 Cutdex。工具范围由当前工作区和可用功能决定,参数以客户端发现结果为准。 连接通过本机端口访问正在运行的 Cutdex。工具范围由当前工作区和可用功能决定,参数以客户端发现结果为准。
+8 -6
View File
@@ -13,9 +13,7 @@ python3 tool/check_public_repository.py
该检查覆盖 Git 跟踪及未被忽略的待提交文件,可识别常见凭据格式、误纳入的本地产物和失效的本地文档链接;不代替 Git 历史审计,也不能识别任意自定义密码。 该检查覆盖 Git 跟踪及未被忽略的待提交文件,可识别常见凭据格式、误纳入的本地产物和失效的本地文档链接;不代替 Git 历史审计,也不能识别任意自定义密码。
```sh ```sh
flutter pub get fvm dart tool/flutter_local.dart pub get
dart analyze --fatal-infos
flutter test test packages/cutdex_ui/test packages/cutdex_native/test
# Python 3.11+ # Python 3.11+
python3 tool/check.py python3 tool/check.py
``` ```
@@ -27,15 +25,19 @@ python3 tool/check.py
| [integration_test](../integration_test/README.md) | 对应平台上的真实预览、媒体编辑与处理任务 | | [integration_test](../integration_test/README.md) | 对应平台上的真实预览、媒体编辑与处理任务 |
| [tool](../tool/README.md) | 脚本检查、发布包验证和平台诊断 | | [tool](../tool/README.md) | 脚本检查、发布包验证和平台诊断 |
本地完整检查与 CI 共用相同的套件,可用 `python3 tool/check.py --suite analyze`、
`--suite flutter` 或 `--suite tools` 单独执行或重试。静态分析启用 `--fatal-infos`;
Flutter 套件同时运行应用与内部包测试。所有入口使用项目 SDK 和相同环境加载规则。
App 测试验证宿主行为,底层算法、协议及插件生命周期在所属包测试。普通测试通过不代表真实播放或模型质量已经验证。 App 测试验证宿主行为,底层算法、协议及插件生命周期在所属包测试。普通测试通过不代表真实播放或模型质量已经验证。
## 生成文件 ## 生成文件
```sh ```sh
dart run build_runner build fvm dart run build_runner build
# UI 模型修改后,在 packages/cutdex_ui 中运行相同生成命令 # UI 模型修改后,在 packages/cutdex_ui 中运行相同生成命令
flutter gen-l10n fvm dart tool/flutter_local.dart gen-l10n
flutter test test/generated_code_test.dart test/localization_resources_test.dart fvm dart tool/flutter_local.dart test test/generated_code_test.dart test/localization_resources_test.dart
``` ```
生成文件应与源码一同提交。生成校验会重新生成应用与 UI 包并比较前后内容,同时检查应用生成文件的跟踪状态;不要暂存无关文件来掩盖失败。 生成文件应与源码一同提交。生成校验会重新生成应用与 UI 包并比较前后内容,同时检查应用生成文件的跟踪状态;不要暂存无关文件来掩盖失败。
+85
View File
@@ -0,0 +1,85 @@
# Windows 更新与 Gitea 发布
Cutdex 使用 deskup 0.3.0 的 Gitea 更新源,下载、校验、安装和重启由
Velopack 1.2.161 完成。正式版构建固定使用公开仓库
`https://git.orangraph.com/lingjhf/cutdex`,包身份为 `Cutdex`,更新频道为
`win-x64`。正式版不读取开发更新源环境变量,也不包含 Gitea 访问令牌。
## 发布附件
每个正式 Gitea Release 同时包含:
| 附件 | 用途 |
| --- | --- |
| `Cutdex-win-x64-Setup.exe` | 新用户安装 |
| `Cutdex-win-x64-Portable.zip` | Velopack 便携发行包,可自动更新 |
| `Cutdex-<更新版本>-win-x64-full.nupkg` | 完整更新包 |
| `releases.win-x64.json` | Windows x64 更新索引 |
| `cutdex-<显示版本>-android.apk` | Android ARM64/x86_64 应用 |
| `windows-dependency-audit.json` | Windows 原生依赖审计 |
| `SHA256SUMS` / `release-manifest.json` | 附件哈希与版本、频道、包身份声明 |
CI 构建正常应用后,在临时目录组装 Windows 发行内容,排除构建符号、
不用的 JNI DLL 和独立分发的 processing worker。审计及暂存文件校验后,
使用固定版本的 `vpk` 生成安装、便携和更新产物。每次使用新的打包输出目录,
索引只引用本次 Release 的一个完整包;不生成增量包。
`tool/gitea/package-app.py --vpk <vpk.exe 或 vpk.dll>` 要求 `dist` 为空。
打包机需要 .NET(仅运行 vpk)与 `pefile`;用户电脑不需要 .NET 或 Python。
CI 安装 .NET 10 和 vpk 1.2.161。
发布工作流只提升**同一提交**成功的 main CI 产物。上传前校验完整附件集合、
版本、包身份、频道及索引指向的包哈希;上传至草稿 Release,重新读取所有
附件逐字节核对,并拒绝多余或过期附件,之后才发布。发布失败保留草稿,
同内容可重试;已发布版本不可覆盖。
## 版本与迁移
例如 `pubspec.yaml` 的 `0.1.1+2` 对应显示版本/标签 `0.1.1`/`v0.1.1`,
Velopack 更新版本为 `0.1.1-build.2`。数字构建号参与更新版本排序,
避免 SemVer `+2` 不参与排序的问题。Windows 可执行文件版本必须与 pubspec
一致;每次正式发布提升应用版本与构建号,勿复用已发布标签。
旧的普通 `cutdex-<版本>-windows-x64.zip` 不含 Velopack 安装元数据,不能
直接获得自动更新。旧用户需要先使用新的 Setup.exe 安装,或解压新的
Velopack Portable ZIP;之后由应用内更新完成升级。
Gitea SDK 查询最近 10 个 Release,跳过标为预发布的 Release,并读取对应
频道索引。需要保持最新正式 Windows Release 在这个查询窗口中。
索引遗漏或损坏可能被 SDK 跳过并表现为没有更新,因此发布流程必须保证
附件完整。仓库及附件必须可匿名下载,Gitea 服务的 API 应位于 `/api/v1`。
## 开发与验证
development 包身份为 `Cutdex.Dev`,默认不配置更新源。
更新策略通过 Dart 的 `WindowsUpdateConfiguration` 传入,不再使用 CMake
更新源变量。正式版固定选用正式 Gitea 仓库,保留 `Cutdex` 注册表偏好命名空间;
安装时显式传入静默和自动重启选项。
开发更新源通过编译期 Dart defines 配置,修改后需重新构建。例如本地测试:
```powershell
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
```
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'
python -m unittest discover -s tool/windows -p '*_unit.py'
python tool/windows/test_windows_updates.py --vpk <vpk.exe 或 vpk.dll> --offline
```
本地更新测试会构建两版独立测试应用,验证损坏包拒绝、重新下载、安装和
重启;不修改运行中的开发应用,也不上传真实 Release。正式发布前还应在
独立 Windows 环境验证应用持久化与安装/便携两种分发方式。Android 签名与
processing worker 独立分发策略沿用现有流水线。
+131 -19
View File
@@ -2,10 +2,84 @@
`integration_test/` contains opt-in tests for the real application and native `integration_test/` contains opt-in tests for the real application and native
backends. `test_driver/integration_test.dart` is the host driver used by 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 media, models, reports and credentials are supplied locally and stay outside
version control. Normal release builds use `lib/main.dart`. 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 ## Desktop plugin registration
`native_desktop_plugins_test.dart` checks the real application's registration of `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. channel. It requires no media or models and does not simulate Finder/Explorer drops.
```sh ```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. 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`: `CUTDEX_PROCESSING_ROOT` and `CUTDEX_ASR_FIXTURE`:
```sh ```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 --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. native backend itself produced these failures.
```sh ```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 \ --driver=test_driver/integration_test.dart \
--target=integration_test/edit_diagnostics_test.dart \ --target=integration_test/edit_diagnostics_test.dart \
--dart-define=CUTDEX_TEST_SOURCE=/absolute/path/to/generated-720p30.mp4 \ --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. must not be presented as Profile measurements.
```sh ```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 \ --driver=test_driver/integration_test.dart \
--target=integration_test/edit_diagnostics_test.dart \ --target=integration_test/edit_diagnostics_test.dart \
--dart-define=CUTDEX_DIAGNOSTIC_CADENCE=true \ --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. when the native backend can probe an unprotected video stream.
```powershell ```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_SOURCE='D:\validation\media-originals' `
--dart-define=CUTDEX_VALIDATION_ROOT='D:\validation\windows-editing' --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. measure native preview delivery, not physical monitor refresh or speaker sound.
`CUTDEX_VALIDATION_SOURCE_ROOTS` accepts semicolon-separated source directories `CUTDEX_VALIDATION_SOURCE_ROOTS` accepts semicolon-separated source directories
when validating multiple collections. For Flutter performance measurements use 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 --driver=test_driver/integration_test.dart
--target=integration_test/windows_real_media_test.dart` with the same 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 record process/time boundaries and Flutter build/raster timings for correlation
with actual Windows audio-session peaks. Native textures can redraw without Dart 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 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 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 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 `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 ```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 ` --driver=test_driver/integration_test.dart `
--target=integration_test/windows_seek_latency_test.dart ` --target=integration_test/windows_seek_latency_test.dart `
--dart-define=CUTDEX_SEEK_SOURCE='D:/validation/media-originals/video.mp4' ` --dart-define=CUTDEX_SEEK_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. longer than ten seconds, with audible content in the 2–6 second edit interval.
```powershell ```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_SOURCE=D:/validation/audio-originals `
--dart-define=CUTDEX_VALIDATION_ROOT=D:/validation/audio-results --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: originals on the host. On a POSIX shell:
```sh ```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 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 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 \ 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 < /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 \ --flavor development --no-uninstall \
--dart-define=CUTDEX_VALIDATION_SOURCE=/data/user/0/com.example.cutdex.dev/files/real-media \ --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 --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 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 An optional
`CUTDEX_VALIDATION_FILTER` selects filenames containing any comma-separated `CUTDEX_VALIDATION_FILTER` selects filenames containing any comma-separated
substring. `CUTDEX_VALIDATION_SAMPLE_START` selects the edit sample start in 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. to the normal application database. Without the required Dart defines, it skips.
```sh ```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 \ --flavor development \
--dart-define=CUTDEX_VALIDATION_SOURCE=/absolute/path/to/media \ --dart-define=CUTDEX_VALIDATION_SOURCE=/absolute/path/to/media \
--dart-define=CUTDEX_VALIDATION_ROOT=/absolute/path/to/output --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: other platforms. First install the test host using the shared empty-timeline test:
```sh ```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 \ --flavor Runner --no-uninstall \
--plain-name 'opening a timeline initializes native preview through App providers' --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 \ --source /absolute/path/to/source.mp4 \
--destination Documents/cutdex-validation-source.mp4 \ --destination Documents/cutdex-validation-source.mp4 \
--domain-type appDataContainer --domain-identifier com.example.cutdex --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 \ --flavor Runner --no-uninstall --reporter expanded \
--dart-define=CUTDEX_TEST_SOURCE_DOCUMENT=cutdex-validation-source.mp4 \ --dart-define=CUTDEX_TEST_SOURCE_DOCUMENT=cutdex-validation-source.mp4 \
--dart-define=CUTDEX_TEST_OUTPUT=ios-keyframes --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. `CUTDEX_TEST_SOURCE`; `CUTDEX_TEST_OUTPUT` optionally preserves the export.
```sh ```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 \ --flavor production \
--dart-define=CUTDEX_TEST_SOURCE=/absolute/path/to/source.mp4 \ --dart-define=CUTDEX_TEST_SOURCE=/absolute/path/to/source.mp4 \
--dart-define=CUTDEX_TEST_OUTPUT=/absolute/path/to/export.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. native probing, thumbnails, playback, seeking and a video/audio export.
```sh ```sh
flutter drive --debug --keep-app-running \ fvm dart tool/flutter_local.dart drive --debug --keep-app-running \
--driver=test_driver/integration_test.dart \ --driver=test_driver/integration_test.dart \
--target=integration_test/android_document_import_test.dart \ --target=integration_test/android_document_import_test.dart \
-d DEVICE_SERIAL --flavor development \ -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 Some devices disconnect the host driver while DocumentsUI is foreground. In
that case, inspect the original application's log and private JSON reports; a that case, inspect the original application's log and private JSON reports; a
driver disconnection alone does not establish whether the import succeeded. 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/model.dart';
import 'package:cutdex_sdk/timeline_ui.dart'; import 'package:cutdex_sdk/timeline_ui.dart';
import 'package:drift/native.dart'; import 'package:drift/native.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
@@ -161,9 +162,7 @@ void main() {
final panel = find.byType(EditorPreviewPanel); final panel = find.byType(EditorPreviewPanel);
await tester.tap( await tester.tap(
find find.descendant(of: panel, matching: find.byIcon(AppIcons.play)).first,
.descendant(of: panel, matching: find.byIcon(Icons.play_arrow))
.first,
); );
await until(() => preview.playing, label: 'UI play'); await until(() => preview.playing, label: 'UI play');
await Future<void>.delayed(const Duration(milliseconds: 700)); await Future<void>.delayed(const Duration(milliseconds: 700));
@@ -173,7 +172,7 @@ void main() {
greaterThan(0), greaterThan(0),
); );
await tester.tap( 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'); await until(() => !preview.playing, label: 'UI pause');
mark('real play and pause buttons advanced native media clock'); mark('real play and pause buttons advanced native media clock');
@@ -0,0 +1,68 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
enum DesktopContent { workspace, library, resourceLibrary, settings }
typedef DesktopContentSelection = ({
DesktopContent surface,
int settingsTab,
int settingsRequest,
(String, String)? workspace,
bool settingsVisited,
bool resourcesSelected,
bool librarySelected,
});
final desktopContentProvider =
NotifierProvider<DesktopContentController, DesktopContentSelection>(
DesktopContentController.new,
);
/// Navigation changes visibility without disposing any visited content.
class DesktopContentController extends Notifier<DesktopContentSelection> {
DesktopContent _settingsReturnSurface = DesktopContent.workspace;
@override
DesktopContentSelection build() => (
surface: DesktopContent.workspace,
settingsTab: 0,
settingsRequest: 0,
workspace: null,
settingsVisited: false,
resourcesSelected: false,
librarySelected: false,
);
void select(DesktopContent surface) {
state = (
surface: surface,
settingsTab: state.settingsTab,
settingsRequest: state.settingsRequest,
workspace: state.workspace,
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,
settingsRequest: state.settingsRequest + (tab == null ? 0 : 1),
workspace: workspace ?? state.workspace,
settingsVisited: true,
resourcesSelected: state.resourcesSelected,
librarySelected: state.librarySelected,
);
}
void closeSettings() {
if (state.surface == DesktopContent.settings) {
select(_settingsReturnSurface);
}
}
}
@@ -3,14 +3,51 @@ import 'package:flutter/foundation.dart';
/// Desktop split preferences outlive the desktop shell when a window narrows. /// Desktop split preferences outlive the desktop shell when a window narrows.
class DesktopWorkspaceController extends ChangeNotifier { class DesktopWorkspaceController extends ChangeNotifier {
double? _agentWidth; double? _agentWidth;
bool _editorCollapsedByAgent = false; bool _agentFullscreen = false;
bool _agentFloating = false;
bool _agentFloatingExpanded = false;
bool _agentVisible = false;
double? get agentWidth => _agentWidth; double? get agentWidth => _agentWidth;
bool get editorCollapsedByAgent => _editorCollapsedByAgent; bool get agentFullscreen => _agentFullscreen;
bool get agentFloating => _agentFloating;
bool get agentFloatingExpanded => _agentFloatingExpanded;
bool get agentVisible => _agentVisible;
void setSplit(double? width, {required bool editorCollapsed}) { 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; _agentWidth = width;
_editorCollapsedByAgent = editorCollapsed; 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 && !(value && _agentFloating)) return;
if (value) _agentFloating = false;
_agentFullscreen = value;
notifyListeners(); notifyListeners();
} }
} }
@@ -9,7 +9,7 @@ abstract final class WorkspaceLayoutPolicy {
width >= width >=
WorkspaceLayoutMetrics.sidebarMinimumWidth + WorkspaceLayoutMetrics.sidebarMinimumWidth +
WorkspaceLayoutMetrics.contentMinimumWidth + WorkspaceLayoutMetrics.contentMinimumWidth +
1; WorkspaceLayoutMetrics.desktopSpacing;
static bool showAgentBesideEditor(double width) => static bool showAgentBesideEditor(double width) =>
width >= WorkspaceLayoutMetrics.dualPaneMinimumWidth; width >= WorkspaceLayoutMetrics.dualPaneMinimumWidth;
@@ -23,8 +23,7 @@ final class DesktopWorkspaceGeometry {
required this.editorHidden, required this.editorHidden,
}); });
static const editorCollapseWidth = 480.0; static const editorMinimumWidth = 480.0;
static const editorCollapseDragBuffer = editorCollapseWidth / 3;
static const editorRestoreWidth = 560.0; static const editorRestoreWidth = 560.0;
final double sidebarWidth; final double sidebarWidth;
@@ -42,7 +41,7 @@ final class DesktopWorkspaceGeometry {
required bool sidebarCollapsed, required bool sidebarCollapsed,
double? sidebarWidth, double? sidebarWidth,
double? agentWidth, double? agentWidth,
bool editorCollapsedByAgent = false, bool agentFullscreen = false,
}) { }) {
final navigationWidth = final navigationWidth =
(sidebarWidth ?? WorkspaceLayoutMetrics.sidebarDefaultWidth) (sidebarWidth ?? WorkspaceLayoutMetrics.sidebarDefaultWidth)
@@ -57,19 +56,17 @@ final class DesktopWorkspaceGeometry {
.clamp(220.0, math.max(220.0, width - navigationSpace - 1)) .clamp(220.0, math.max(220.0, width - navigationSpace - 1))
.toDouble() .toDouble()
: 0.0; : 0.0;
final remaining = width - navigationSpace - requestedAgentWidth - 1;
final hidden = final hidden =
mode == WorkspaceMode.agent && mode == WorkspaceMode.agent &&
(width - navigationSpace - 1 < 220 + editorCollapseWidth || (width - navigationSpace - 1 < 220 + editorMinimumWidth ||
(editorCollapsedByAgent && remaining < editorRestoreWidth) || agentFullscreen);
remaining <= editorCollapseWidth - editorCollapseDragBuffer);
return DesktopWorkspaceGeometry( return DesktopWorkspaceGeometry(
sidebarWidth: navigationWidth, sidebarWidth: navigationWidth,
agentWidth: hidden agentWidth: hidden
? width - navigationSpace ? width - navigationSpace
: mode == WorkspaceMode.agent : mode == WorkspaceMode.agent
? requestedAgentWidth ? requestedAgentWidth
.clamp(220.0, width - navigationSpace - editorCollapseWidth - 1) .clamp(220.0, width - navigationSpace - editorMinimumWidth - 1)
.toDouble() .toDouble()
: 0, : 0,
editorHidden: hidden, editorHidden: hidden,
+17 -4
View File
@@ -10,26 +10,39 @@ import 'router/app_router.dart';
import '../integrations/app_updates.dart'; import '../integrations/app_updates.dart';
import '../integrations/editor_tools.dart'; import '../integrations/editor_tools.dart';
import '../features/settings/appearance_settings.dart'; import '../features/settings/appearance_settings.dart';
import '../shared/widgets/error_notification_host.dart';
import '../integrations/platform/device_experience.dart';
class CutdexApp extends ConsumerWidget { class CutdexApp extends ConsumerWidget {
const CutdexApp({super.key}); const CutdexApp({super.key});
@override @override
Widget build(BuildContext context, WidgetRef ref) { Widget build(BuildContext context, WidgetRef ref) {
ref.watch(applicationMcpConnectionProvider); ref.watch(applicationMcpConnectionProvider.select((_) => null));
ref.watch(appUpdateLifecycleProvider); ref.watch(appUpdateLifecycleProvider.select((_) => null));
final appearance = final appearance =
ref.watch(appearanceSettingsProvider).asData?.value ?? ref.watch(appearanceSettingsProvider).asData?.value ??
AppAppearance.system; 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( return MaterialApp.router(
builder: (context, child) =>
ErrorNotificationHost(child: child ?? const SizedBox.shrink()),
title: 'Cutdex', title: 'Cutdex',
locale: ref.watch(languageSettingsProvider).asData?.value.locale, locale: ref.watch(languageSettingsProvider).asData?.value.locale,
localizationsDelegates: AppLocalizations.localizationsDelegates, localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales, supportedLocales: AppLocalizations.supportedLocales,
localeListResolutionCallback: resolveAppLocale, localeListResolutionCallback: resolveAppLocale,
debugShowCheckedModeBanner: false, debugShowCheckedModeBanner: false,
theme: EditorTheme.penLight, theme: theme(Brightness.light),
darkTheme: EditorTheme.penDark, darkTheme: theme(Brightness.dark),
themeMode: appearance.themeMode, themeMode: appearance.themeMode,
routerConfig: ref.watch(appRouterProvider), 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 penLight => adapt(AppTheme.penLight);
static ThemeData get penDark => adapt(AppTheme.penDark); 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) { static ThemeData adapt(ThemeData theme) {
final palette = theme.brightness == Brightness.dark final palette = AppColors.of(theme);
? AppColors.penDark
: AppColors.penLight;
final dark = theme.brightness == Brightness.dark; final dark = theme.brightness == Brightness.dark;
final text = theme.textTheme; final text = theme.textTheme;
final timelineBorder = palette.divider; final timelineBorder = palette.divider;
@@ -27,8 +56,8 @@ abstract final class EditorTheme {
backgroundColor: palette.background, backgroundColor: palette.background,
primaryLaneBackgroundColor: palette.sidebar, primaryLaneBackgroundColor: palette.sidebar,
visualClipColor: palette.visualClip, visualClipColor: palette.visualClip,
audioClipColor: palette.popover, audioClipColor: palette.audioClip,
audioAccentColor: timelineSecondary, audioAccentColor: palette.audioWaveform,
gapColor: timelineBorder, gapColor: timelineBorder,
gapBorderColor: timelineBorder, gapBorderColor: timelineBorder,
containerAccentColor: timelineSecondary, containerAccentColor: timelineSecondary,
@@ -37,7 +66,7 @@ abstract final class EditorTheme {
connectionLineWidth: 3, connectionLineWidth: 3,
clipBorderColor: timelineBorder, clipBorderColor: timelineBorder,
clipBorderWidth: 1, clipBorderWidth: 1,
selectionOutlineColor: palette.foreground, selectionOutlineColor: palette.selection,
selectionOutlineWidth: 2, selectionOutlineWidth: 2,
keyframeColor: timelineSecondary, keyframeColor: timelineSecondary,
keyframeBorderColor: palette.background, keyframeBorderColor: palette.background,
+18 -1
View File
@@ -4,6 +4,7 @@ import 'package:go_router/go_router.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../../features/projects/projects_page.dart'; import '../../features/projects/projects_page.dart';
import '../../features/settings/settings_page.dart';
part 'app_router.g.dart'; part 'app_router.g.dart';
@@ -12,7 +13,23 @@ part 'app_router.g.dart';
GoRouter appRouter(Ref ref) { GoRouter appRouter(Ref ref) {
final router = GoRouter( final router = GoRouter(
routes: [ routes: [
GoRoute(path: '/', builder: (context, state) => const EditingPage()), GoRoute(
path: '/',
builder: (context, state) => const EditingPage(),
routes: [
GoRoute(
path: 'settings',
builder: (context, state) => SettingsPage(
initialTab:
(int.tryParse(state.uri.queryParameters['tab'] ?? '') ?? 0)
.clamp(0, 3),
workspace: state.extra is (String, String)
? state.extra as (String, String)
: null,
),
),
],
),
], ],
errorBuilder: (context, state) => Scaffold( errorBuilder: (context, state) => Scaffold(
body: Center( body: Center(
+1 -1
View File
@@ -48,4 +48,4 @@ final class AppRouterProvider
} }
} }
String _$appRouterHash() => r'ebb3f9239a43568767def98552081806bd614bb4'; String _$appRouterHash() => r'ea1ed83ca5ca1f7079b268b1a94940d575b6ddf9';
+229
View File
@@ -0,0 +1,229 @@
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 '../editor_theme.dart';
/// Keeps window chrome outside the shared workspace surface.
class DesktopWindowFrame extends StatelessWidget {
const DesktopWindowFrame({
super.key,
required this.integratedTitlebar,
required this.headerControls,
this.projectTabs,
this.headerTrailing = const SizedBox.shrink(),
this.settingsSelected = false,
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 = 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 Widget? projectTabs;
final Widget headerTrailing;
final bool settingsSelected;
final bool resourceLibrarySelected;
final VoidCallback? onResourceLibraryPressed;
final VoidCallback onHomePressed;
final VoidCallback onSettingsPressed;
final Widget child;
@override
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,
children: [
SizedBox(
key: const Key('desktop-window-header'),
height: headerHeight,
child: WindowHeaderPadding(
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',
),
width: EditorWindowChrome.leadingWidth,
height: headerHeight,
),
headerControls,
],
),
),
),
headerTrailing,
],
),
),
),
Expanded(
child: Row(
children: [
if (projectTabs == null)
SizedBox(
key: const Key('desktop-navigation-rail'),
width: railWidth,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 10),
child: Column(
children: [
for (final section in [0, 2])
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: IconButton.filledTonal(
key: ValueKey(switch (section) {
0 => 'desktop-rail-home',
_ => 'desktop-rail-resources',
}),
tooltip: switch (section) {
0 => context.l10n.navigationHome,
_ => context.l10n.navigationLibrary,
},
isSelected:
!settingsSelected &&
(section == 2
? resourceLibrarySelected
: !resourceLibrarySelected),
style: IconButton.styleFrom(
fixedSize: const Size.square(railButtonSize),
minimumSize: const Size.square(railButtonSize),
maximumSize: const Size.square(railButtonSize),
padding: EdgeInsets.zero,
iconSize: railIconSize,
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
backgroundColor:
!settingsSelected &&
(section == 2
? resourceLibrarySelected
: !resourceLibrarySelected)
? null
: Colors.transparent,
),
onPressed: switch (section) {
0 => onHomePressed,
_ => onResourceLibraryPressed,
},
icon: Icon(switch (section) {
0 => AppIcons.home,
_ => AppIcons.folder,
}),
),
),
const Spacer(),
IconButton(
key: const Key('project-settings-button'),
tooltip: context.l10n.settings,
isSelected: settingsSelected,
onPressed: onSettingsPressed,
style: IconButton.styleFrom(
fixedSize: const Size.square(railButtonSize),
minimumSize: const Size.square(railButtonSize),
maximumSize: const Size.square(railButtonSize),
padding: EdgeInsets.zero,
iconSize: railIconSize,
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
icon: const Icon(AppIcons.settings),
),
],
),
),
),
Expanded(
child: Padding(
padding: EdgeInsets.only(
left: projectTabs == null ? 0 : contentInset,
right: contentInset,
bottom: contentInset,
),
child: SizedBox(
key: const Key('desktop-content-container'),
child: WindowHeaderPane(
offset: Offset(
projectTabs == null ? railWidth : contentInset,
headerHeight,
),
child: LayoutBuilder(
builder: (context, constraints) =>
constraints.maxWidth < 200
? SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: SizedBox(
width: 200,
height: constraints.maxHeight,
child: child,
),
)
: child,
),
),
),
),
),
],
),
),
],
),
);
}
+273 -146
View File
@@ -1,22 +1,22 @@
import '../adaptive/desktop_workspace_controller.dart'; import 'dart:math' as math;
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../../workspace/workspace_mode.dart';
import '../../shared/layout/workspace_layout_metrics.dart';
import 'package:cutdex_ui/theme.dart'; import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_native/cutdex_native.dart'; import 'package:cutdex_ui/widgets.dart';
import '../adaptive/desktop_workspace_controller.dart';
import '../adaptive/workspace_layout_policy.dart'; import '../adaptive/workspace_layout_policy.dart';
import '../../shared/layout/workspace_layout_metrics.dart';
import '../../shared/widgets/workspace_card.dart';
import '../../shared/widgets/workspace_resize_handle.dart';
import '../../workspace/workspace_mode.dart';
typedef WorkspaceSidebarBuilder = Widget Function( typedef WorkspaceSidebarBuilder = Widget Function(
DesktopWorkspaceGeometry geometry, DesktopWorkspaceGeometry geometry,
VoidCallback expandEditor, VoidCallback expandEditor,
); );
/// Arranges slots and handles splitters; it does not own editing sessions. /// Three independent desktop surfaces with resize gutters between them.
class DesktopWorkspaceShell extends StatefulWidget { class DesktopWorkspaceShell extends StatefulWidget {
const DesktopWorkspaceShell({ const DesktopWorkspaceShell({
super.key, super.key,
@@ -27,11 +27,14 @@ class DesktopWorkspaceShell extends StatefulWidget {
required this.onSidebarCollapsedChanged, required this.onSidebarCollapsedChanged,
required this.onSidebarWidthChanged, required this.onSidebarWidthChanged,
required this.sidebarBuilder, required this.sidebarBuilder,
required this.agentBuilder,
required this.editor, required this.editor,
required this.scaffoldKey, required this.scaffoldKey,
required this.navigationDrawer, required this.navigationDrawer,
this.projectTabsLayout = false,
}); });
static const gutterWidth = WorkspaceLayoutMetrics.desktopSpacing;
final WorkspaceMode mode; final WorkspaceMode mode;
final DesktopWorkspaceController controller; final DesktopWorkspaceController controller;
final bool sidebarCollapsed; final bool sidebarCollapsed;
@@ -39,18 +42,17 @@ class DesktopWorkspaceShell extends StatefulWidget {
final ValueChanged<bool> onSidebarCollapsedChanged; final ValueChanged<bool> onSidebarCollapsedChanged;
final ValueChanged<double> onSidebarWidthChanged; final ValueChanged<double> onSidebarWidthChanged;
final WorkspaceSidebarBuilder sidebarBuilder; final WorkspaceSidebarBuilder sidebarBuilder;
final WorkspaceSidebarBuilder agentBuilder;
final Widget editor; final Widget editor;
final GlobalKey<ScaffoldState> scaffoldKey; final GlobalKey<ScaffoldState> scaffoldKey;
final Widget navigationDrawer; final Widget navigationDrawer;
final bool projectTabsLayout;
@override @override
State<DesktopWorkspaceShell> createState() => _DesktopWorkspaceShellState(); State<DesktopWorkspaceShell> createState() => _DesktopWorkspaceShellState();
} }
class _DesktopWorkspaceShellState extends State<DesktopWorkspaceShell> { class _DesktopWorkspaceShellState extends State<DesktopWorkspaceShell> {
double? get _agentWidth => widget.controller.agentWidth;
bool get _editorCollapsedByAgent => widget.controller.editorCollapsedByAgent;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
@@ -74,65 +76,118 @@ class _DesktopWorkspaceShellState extends State<DesktopWorkspaceShell> {
super.dispose(); super.dispose();
} }
double? _sidebarDragStart; Widget _card(String name, Widget child) =>
double _sidebarDragWidth = 0; WorkspaceCard(key: Key('desktop-$name-card'), child: child);
double? _agentDragStart;
double _agentDragWidth = 0; Widget _gutter({
required String name,
required double initialWidth,
required ValueChanged<double> onResize,
double direction = 1,
VoidCallback? onEnd,
}) => SizedBox(
width: WorkspaceLayoutMetrics.desktopResizeHitExtent,
height: double.infinity,
child: WorkspaceResizeHandle(
key: Key('$name-resize'),
axis: Axis.horizontal,
initialValue: initialWidth,
direction: direction,
onResize: onResize,
onEnd: onEnd,
),
);
@override @override
Widget build(BuildContext context) => LayoutBuilder( Widget build(BuildContext context) => widget.projectTabsLayout
? _projectWorkspace(context)
: LayoutBuilder(
builder: (context, constraints) { builder: (context, constraints) {
const gap = DesktopWorkspaceShell.gutterWidth;
final width = constraints.maxWidth; final width = constraints.maxWidth;
final geometry = DesktopWorkspaceGeometry.resolve( final requestedFloating = widget.controller.agentFloating;
width: width, final showAgent =
mode: widget.mode, 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: requestedFloating || !showAgent
? WorkspaceMode.cut
: WorkspaceMode.agent,
sidebarCollapsed: widget.sidebarCollapsed, sidebarCollapsed: widget.sidebarCollapsed,
sidebarWidth: widget.sidebarWidth, sidebarWidth: widget.sidebarWidth,
agentWidth: _agentWidth, agentWidth: widget.controller.agentWidth,
editorCollapsedByAgent: _editorCollapsedByAgent, agentFullscreen: widget.controller.agentFullscreen,
); );
final navigationSpace = widget.sidebarCollapsed final navigationSpace = widget.sidebarCollapsed
? 0.0 ? 0.0
: geometry.sidebarWidth; : resolved.sidebarWidth;
void expandEditor() { final floating =
final collapseNavigation = width - navigationSpace - 1 < 780; requestedFloating ||
if (collapseNavigation) widget.onSidebarCollapsedChanged(true); (showAgent &&
widget.controller.setSplit( widget.mode == WorkspaceMode.cut &&
width - resolved.editorHidden &&
(collapseNavigation ? 0 : navigationSpace) - !widget.controller.agentFullscreen);
DesktopWorkspaceGeometry.editorRestoreWidth - final agentHidden =
1, floating ||
editorCollapsed: false, !showAgent ||
resolved.editorHidden &&
widget.mode == WorkspaceMode.cut &&
!widget.controller.agentFullscreen;
final geometry = DesktopWorkspaceGeometry(
sidebarWidth: resolved.sidebarWidth,
agentWidth: agentHidden
? 0
: resolved.editorHidden
? width - navigationSpace - navigationGap
: resolved.agentWidth,
editorHidden: resolved.editorHidden && !agentHidden,
); );
final available = width - navigationSpace - navigationGap;
void expandEditor() {
final collapseNavigation =
available <
220 + gap + DesktopWorkspaceGeometry.editorMinimumWidth;
if (collapseNavigation) widget.onSidebarCollapsedChanged(true);
widget.controller.setAgentFullscreen(false);
}
void resizeAgent(double requested) {
final maximum =
available - gap - DesktopWorkspaceGeometry.editorMinimumWidth;
if (maximum < 220) return;
final agentWidth = requested.clamp(220.0, maximum);
widget.controller.setAgentWidth(agentWidth);
} }
return Scaffold( return Scaffold(
key: widget.scaffoldKey, key: widget.scaffoldKey,
backgroundColor: Colors.transparent,
drawer: Drawer( drawer: Drawer(
width: 320, width: 320,
child: SafeArea(child: widget.navigationDrawer), child: SafeArea(child: widget.navigationDrawer),
), ),
body: Stack( body: Stack(
key: const Key('desktop-workspace-shell'), key: const Key('desktop-workspace-shell'),
fit: StackFit.expand,
children: [ children: [
Row( Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
if (!widget.sidebarCollapsed || if (!widget.sidebarCollapsed) ...[
widget.mode == WorkspaceMode.agent)
SizedBox( SizedBox(
width: navigationSpace + geometry.agentWidth, width: navigationSpace,
child: widget.sidebarBuilder(geometry, expandEditor), child: _card(
), 'project',
if (!widget.sidebarCollapsed && !geometry.editorHidden) widget.sidebarBuilder(geometry, expandEditor),
SizedBox(
width: 1,
height: double.infinity,
child: ColoredBox(
key: const Key('project-sidebar-separator'),
color: AppTheme.sidebarDividerColor(context),
), ),
), ),
const SizedBox(
key: Key('project-sidebar-divider'),
width: gap,
),
],
Expanded( Expanded(
child: Offstage( child: Offstage(
key: const Key('editor-auto-collapse'), key: const Key('editor-auto-collapse'),
@@ -147,124 +202,196 @@ class _DesktopWorkspaceShellState extends State<DesktopWorkspaceShell> {
maxWidth: geometry.editorHidden maxWidth: geometry.editorHidden
? DesktopWorkspaceGeometry.editorRestoreWidth ? DesktopWorkspaceGeometry.editorRestoreWidth
: null, : null,
child: WindowHeaderPane( child: SizedBox(
offset: Offset( key: const Key('desktop-editor-card'),
navigationSpace +
geometry.agentWidth +
(!widget.sidebarCollapsed &&
!geometry.editorHidden
? 1
: 0),
0,
),
child: widget.editor, child: widget.editor,
), ),
), ),
), ),
), ),
), ),
if (!agentHidden && !geometry.editorHidden)
const SizedBox(width: gap),
if (!floating)
Offstage(
offstage: agentHidden,
child: ExcludeFocus(
excluding: agentHidden,
child: TickerMode(
enabled: !agentHidden,
child: SizedBox(
key: const Key('desktop-agent-slot'),
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) if (!widget.sidebarCollapsed)
Positioned( Positioned(
key: const Key('project-sidebar-divider'), left:
top: AppControlSize.panelHeader, navigationSpace -
bottom: 0, WorkspaceLayoutMetrics.desktopResizeSlop,
left: geometry.sidebarWidth - 4,
width: 8,
child: MouseRegion(
cursor: SystemMouseCursors.resizeColumn,
child: GestureDetector(
key: const Key('project-sidebar-resize'),
behavior: HitTestBehavior.opaque,
dragStartBehavior: DragStartBehavior.down,
onHorizontalDragStart: (details) {
_sidebarDragStart = details.globalPosition.dx;
_sidebarDragWidth = geometry.sidebarWidth;
},
onHorizontalDragUpdate: (details) {
final start = _sidebarDragStart;
if (start == null) return;
widget.onSidebarWidthChanged(
(_sidebarDragWidth + details.globalPosition.dx - start)
.clamp(
WorkspaceLayoutMetrics.sidebarMinimumWidth,
DesktopWorkspaceGeometry.sidebarMaximum(
width,
widget.mode,
),
)
.toDouble(),
);
},
onHorizontalDragEnd: (_) => _sidebarDragStart = null,
onHorizontalDragCancel: () => _sidebarDragStart = null,
child: const SizedBox.expand(),
),
),
),
if (widget.mode == WorkspaceMode.agent &&
width - navigationSpace - 1 >= 220)
Positioned(
top: 0, top: 0,
bottom: 0, bottom: 0,
left: child: _gutter(
navigationSpace + name: 'project-sidebar',
initialWidth: navigationSpace,
onResize: (value) => widget.onSidebarWidthChanged(
value.clamp(
WorkspaceLayoutMetrics.sidebarMinimumWidth,
DesktopWorkspaceGeometry.sidebarMaximum(
width - 2 * gap + 1,
WorkspaceMode.agent,
),
),
),
),
),
if (!agentHidden && !geometry.editorHidden)
Positioned(
left: geometry.editorHidden
? navigationSpace +
navigationGap +
(widget.sidebarCollapsed
? 0
: WorkspaceLayoutMetrics.desktopResizeSlop)
: width -
geometry.agentWidth - geometry.agentWidth -
(geometry.editorHidden ? 8 : 4), gap -
width: 8, WorkspaceLayoutMetrics.desktopResizeSlop,
child: MouseRegion( top: 0,
cursor: SystemMouseCursors.resizeColumn, bottom: 0,
child: GestureDetector( child: _gutter(
key: const Key('agent-panel-resize'), name: 'agent-panel',
behavior: HitTestBehavior.opaque, initialWidth: geometry.agentWidth,
dragStartBehavior: DragStartBehavior.down, direction: -1,
onHorizontalDragStart: (details) { onResize: resizeAgent,
_agentDragStart = details.globalPosition.dx; ),
_agentDragWidth = geometry.agentWidth; ),
}, ],
onHorizontalDragUpdate: (details) {
final start = _agentDragStart;
if (start == null) return;
final agentWidth =
(_agentDragWidth + details.globalPosition.dx - start)
.clamp(220.0, width - navigationSpace - 1);
final remaining =
width - navigationSpace - agentWidth - 1;
widget.controller.setSplit(
agentWidth,
editorCollapsed: geometry.editorHidden
? remaining <
DesktopWorkspaceGeometry.editorRestoreWidth
: remaining <=
DesktopWorkspaceGeometry.editorCollapseWidth -
DesktopWorkspaceGeometry
.editorCollapseDragBuffer,
);
},
onHorizontalDragEnd: (_) {
_agentDragStart = null;
if (!_editorCollapsedByAgent &&
_agentWidth != null &&
width -
navigationSpace -
DesktopWorkspaceGeometry.editorCollapseWidth -
1 >=
220) {
widget.controller.setSplit(
_agentWidth!.clamp(
220.0,
width -
navigationSpace -
DesktopWorkspaceGeometry.editorCollapseWidth -
1,
), ),
editorCollapsed: false,
); );
}
}, },
onHorizontalDragCancel: () => _agentDragStart = null, );
child: const SizedBox.expand(),
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 'package:flutter/material.dart';
import '../../l10n/l10n.dart'; import '../../l10n/l10n.dart';
@@ -43,12 +44,12 @@ class PhoneWorkspaceShell extends StatelessWidget {
destinations: [ destinations: [
NavigationDestination( NavigationDestination(
key: const Key('workspace-agent-destination'), key: const Key('workspace-agent-destination'),
icon: const Icon(Icons.chat_bubble_outline), icon: const Icon(AppIcons.chat),
label: context.l10n.workspaceAgent, label: context.l10n.workspaceAgent,
), ),
NavigationDestination( NavigationDestination(
key: const Key('workspace-cut-destination'), key: const Key('workspace-cut-destination'),
icon: const Icon(Icons.movie_outlined), icon: const Icon(AppIcons.video),
label: context.l10n.workspaceCut, label: context.l10n.workspaceCut,
), ),
], ],
+3 -2
View File
@@ -1,5 +1,6 @@
import 'dart:math' as math; import 'dart:math' as math;
import 'package:cutdex_ui/icons.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../../l10n/l10n.dart'; import '../../l10n/l10n.dart';
@@ -55,14 +56,14 @@ class TabletWorkspaceShell extends StatelessWidget {
destinations: [ destinations: [
NavigationRailDestination( NavigationRailDestination(
icon: const Icon( icon: const Icon(
Icons.chat_bubble_outline, AppIcons.chat,
key: Key('workspace-agent-destination'), key: Key('workspace-agent-destination'),
), ),
label: Text(context.l10n.workspaceAgent), label: Text(context.l10n.workspaceAgent),
), ),
NavigationRailDestination( NavigationRailDestination(
icon: const Icon( icon: const Icon(
Icons.movie_outlined, AppIcons.video,
key: Key('workspace-cut-destination'), key: Key('workspace-cut-destination'),
), ),
label: Text(context.l10n.workspaceCut), 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 'package:flutter/material.dart';
import '../../integrations/platform/editor_window_chrome.dart'; import '../../integrations/platform/editor_window_chrome.dart';
@@ -45,7 +46,7 @@ class WorkspaceFrame extends StatelessWidget {
key: const Key('workspace-navigation-button'), key: const Key('workspace-navigation-button'),
tooltip: context.l10n.expandSidebar, tooltip: context.l10n.expandSidebar,
onPressed: () => Scaffold.of(context).openDrawer(), 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, openMatchingProject,
openTimelineFailed, openTimelineFailed,
projectMismatch, projectMismatch,
projectAlreadyExists,
openProjectFirst, openProjectFirst,
localFilesOnly, localFilesOnly,
foldersUnsupported, foldersUnsupported,
@@ -3,6 +3,7 @@ import 'package:flutter/material.dart';
import '../media/media_asset_cover.dart'; import '../media/media_asset_cover.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart'; import 'package:cutdex_ui/theme.dart';
import '../media/audio_asset_tile.dart'; import '../media/audio_asset_tile.dart';
@@ -25,13 +26,13 @@ class AgentAttachmentCard extends StatelessWidget {
fit: BoxFit.cover, fit: BoxFit.cover,
fallback: Center( fallback: Center(
child: Icon( child: Icon(
kind == 'image' ? Icons.image_outlined : Icons.movie_outlined, kind == 'image' ? AppIcons.image : AppIcons.video,
color: colors.onSurfaceVariant, color: colors.onSurfaceVariant,
), ),
), ),
errorFallback: Center( errorFallback: Center(
child: Icon( child: Icon(
Icons.broken_image_outlined, AppIcons.imageUnavailable,
color: colors.onSurfaceVariant, color: colors.onSurfaceVariant,
), ),
), ),
@@ -42,12 +43,7 @@ class AgentAttachmentCard extends StatelessWidget {
showName: false, showName: false,
aspectRatio: 132 / 96, aspectRatio: 132 / 96,
), ),
_ => Center( _ => Center(child: Icon(AppIcons.file, color: colors.onSurfaceVariant)),
child: Icon(
Icons.insert_drive_file_outlined,
color: colors.onSurfaceVariant,
),
),
}; };
return SizedBox( return SizedBox(
width: 132, width: 132,
@@ -93,7 +89,7 @@ class AgentAttachmentCard extends StatelessWidget {
backgroundColor: colors.surface, backgroundColor: colors.surface,
foregroundColor: colors.onSurface, 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,
};
+78 -195
View File
@@ -1,3 +1,7 @@
import 'agent_reply_region.dart';
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import '../../shared/layout/composer_layout.dart'; import '../../shared/layout/composer_layout.dart';
import '../../shared/theme/composer_style.dart'; import '../../shared/theme/composer_style.dart';
@@ -7,6 +11,8 @@ import 'package:cutdex_sdk/project.dart';
import '../../integrations/platform/platform_capabilities.dart'; import '../../integrations/platform/platform_capabilities.dart';
import 'agent_composer_controller.dart'; import 'agent_composer_controller.dart';
import 'agent_attachment_drop_region.dart';
import 'agent_chat_actions.dart';
import 'agent_composer_store.dart'; import 'agent_composer_store.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@@ -14,21 +20,17 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../integrations/agent/agent_provider.dart'; import '../../integrations/agent/agent_provider.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart'; import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart'; import 'package:cutdex_ui/widgets.dart';
import '../../shared/widgets/drop_to_add_overlay.dart'; import '../settings/settings_page.dart';
import '../settings/settings_dialog.dart';
import 'chat_controller.dart'; import 'chat_controller.dart';
import 'chat_state.dart'; import 'chat_state.dart';
import '../../integrations/agent/conversation_repository.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 '../../workspace/external_media_import.dart';
import '../../settings/settings_operation.dart'; import '../../settings/settings_operation.dart';
import '../../workspace/projects.dart'; import '../../workspace/projects.dart';
import '../media/media_asset_drag.dart';
import '../media/media_browser_feedback.dart'; import '../media/media_browser_feedback.dart';
import 'agent_attachment_card.dart'; import 'agent_attachment_card.dart';
import 'agent_media_attachments.dart'; import 'agent_media_attachments.dart';
@@ -95,8 +97,7 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
'agent-model-${widget.projectId}-${widget.conversationId ?? widget.draftKey ?? 'new'}'; 'agent-model-${widget.projectId}-${widget.conversationId ?? widget.draftKey ?? 'new'}';
bool get _choosingModel => bool get _choosingModel =>
ref.read(settingsOperationProvider(_modelOperation)).isLoading; ref.read(settingsOperationProvider(_modelOperation)).isLoading;
bool _usingDraftModel = false; bool get _usingDraftModel => _composer.usingDraftModel;
bool _dropHovering = false;
bool get _importingAttachments => bool get _importingAttachments =>
_composer.busy || _composer.busy ||
widget.projectId != null && widget.projectId != null &&
@@ -141,33 +142,12 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
if (oldWidget.conversationId != widget.conversationId || if (oldWidget.conversationId != widget.conversationId ||
oldWidget.projectId != widget.projectId || oldWidget.projectId != widget.projectId ||
oldWidget.draftKey != widget.draftKey) { oldWidget.draftKey != widget.draftKey) {
_usingDraftModel = false;
_composer.removeListener(_composerChanged); _composer.removeListener(_composerChanged);
_composer = _resolveComposer(); _composer = _resolveComposer();
_composer.addListener(_composerChanged); _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 @override
void initState() { void initState() {
super.initState(); super.initState();
@@ -187,41 +167,6 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
super.dispose(); super.dispose();
} }
bool _canAttach(MediaAssetDrag drag) {
final workspace = ref.read(projectsProvider).asData?.value;
return widget.projectId == drag.projectId &&
workspace?.activeProject?.id == drag.projectId &&
!_attachments.any((item) => item.id == drag.assetId) &&
workspace!.assets.any((asset) => asset.id == drag.assetId);
}
bool _canAttachExternalFiles(List<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 { Future<void> _pickAttachments() async {
try { try {
await _composer.pickAttachments(); await _composer.pickAttachments();
@@ -230,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 @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
ref.watch(settingsOperationProvider(_modelOperation)); ref.watch(
settingsOperationProvider(_modelOperation)
.select((value) => value.isLoading),
);
if (widget.projectId != null) { 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( final referenceValidator = ComposerReferenceValidator(
workspace: workspace, workspace: workspace,
projectId: widget.projectId, projectId: widget.projectId,
@@ -303,7 +211,9 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
draftKey: widget.draftKey, draftKey: widget.draftKey,
) )
: null; : 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 settings = ref.watch(agentSettingsProvider).asData?.value;
final available = final available =
settings?.providers settings?.providers
@@ -358,10 +268,12 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
}); });
if (!mounted || !context.mounted) return; if (!mounted || !context.mounted) return;
if (saved) { if (saved) {
setState(() => _usingDraftModel = true); _composer.useDraftModel();
} else { } else {
ScaffoldMessenger.of(context).showSnackBar( ErrorNotificationHost.of(context).show(
SnackBar(content: Text(context.l10n.agentSaveSettingsFailed)), ErrorNotification(
content: Text(context.l10n.agentSaveSettingsFailed),
),
); );
} }
} }
@@ -374,8 +286,8 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
return TextButton.icon( return TextButton.icon(
key: const Key('agent-configure-model'), key: const Key('agent-configure-model'),
style: compactButtonStyle, style: compactButtonStyle,
onPressed: () => showSettingsDialog(context, initialTab: 1), onPressed: () => showSettingsPage(context, initialTab: 1),
icon: const Icon(Icons.tune, size: 16), icon: const Icon(AppIcons.tune, size: 16),
label: Text(context.l10n.agentConfigureModel), label: Text(context.l10n.agentConfigureModel),
); );
} }
@@ -398,11 +310,11 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
AppMenuItem( AppMenuItem(
label: context.l10n.agentConfigureModel, label: context.l10n.agentConfigureModel,
selectOption: true, selectOption: true,
onPressed: () => showSettingsDialog(context, initialTab: 1), onPressed: () => showSettingsPage(context, initialTab: 1),
), ),
], ],
builder: (context, toggle, focus) => TextButton( builder: (context, toggle, focus) => AppToolbarDropdownButton(
key: const Key('agent-model-picker'), buttonKey: const Key('agent-model-picker'),
focusNode: focus, focusNode: focus,
onPressed: () { onPressed: () {
if (!state.busy && !_choosingModel) toggle?.call(); if (!state.busy && !_choosingModel) toggle?.call();
@@ -419,14 +331,14 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
), ),
), ),
const SizedBox(width: 4), 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) { ref.listen(provider, (previous, next) {
if (_follow) { if (_follow) {
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
@@ -449,12 +361,7 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
(_input.text.trim().isEmpty && _attachments.isEmpty)) { (_input.text.trim().isEmpty && _attachments.isEmpty)) {
return; return;
} }
final text = AgentComposerMessage.encodeDocument( final text = takeAgentDraft(_input, _composer);
_input.segments,
_attachments,
);
_input.clearDocument();
_composer.clear();
_follow = true; _follow = true;
ref ref
.read(provider.notifier) .read(provider.notifier)
@@ -467,8 +374,10 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
} }
final theme = Theme.of(context); final theme = Theme.of(context);
final content = _agentDropRegion( final content = AgentAttachmentDropRegion(
LayoutBuilder( projectId: widget.projectId,
composer: _composer,
child: LayoutBuilder(
builder: (context, constraints) { builder: (context, constraints) {
final panelWidth = final panelWidth =
(constraints.maxWidth - ComposerLayout.horizontalInset * 2) (constraints.maxWidth - ComposerLayout.horizontalInset * 2)
@@ -558,8 +467,8 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
), ),
), ),
Icon( Icon(
Icons AppIcons
.chevron_right, .chevronRight,
size: 14, size: 14,
color: color:
AppTheme.chatMetaTextStyle( AppTheme.chatMetaTextStyle(
@@ -571,7 +480,6 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
), ),
Divider( Divider(
height: 1, height: 1,
thickness: 1,
color: color:
theme.dividerColor, theme.dividerColor,
), ),
@@ -636,10 +544,13 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
in AgentComposerMessage.decode( in AgentComposerMessage.decode(
message.text, message.text,
).attachments) ).attachments)
if (ref Consumer(
.watch( builder: (context, ref, _) {
projectsProvider, final asset = ref.watch(
) projectsProvider.select(
(
value,
) => value
.asData .asData
?.value ?.value
.assets .assets
@@ -650,17 +561,21 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
asset.id == asset.id ==
attachment.id, attachment.id,
) )
.firstOrNull .firstOrNull,
case final asset?)
AgentAttachmentCard(
asset: asset,
)
else
Chip(
label: Text(
attachment
.name,
), ),
);
return asset ==
null
? Chip(
label: Text(
attachment.name,
),
)
: AgentAttachmentCard(
asset:
asset,
);
},
), ),
], ],
), ),
@@ -677,44 +592,12 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
], ],
), ),
), ),
if (state.busy) ...[ AgentReplyRegion(
if (state projectId: widget.projectId,
.partialResponse conversationId:
.isNotEmpty) widget.conversationId,
SelectableText( draftKey: widget.draftKey,
state.partialResponse,
style:
AppTheme.chatMessageTextStyle(
context,
), ),
),
Text(
state.stopping
? context.l10n.stopping
: switch (state.activity) {
AgentChatActivity
.compacting =>
context
.l10n
.agentCompacting,
AgentChatActivity
.editing =>
context
.l10n
.agentEditing,
AgentChatActivity
.verifying =>
context
.l10n
.agentVerifying,
AgentChatActivity
.replying =>
context.l10n.replying,
},
style:
theme.textTheme.bodySmall,
),
],
], ],
), ),
), ),
@@ -747,7 +630,7 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
horizontal: AppSpacing.compact, horizontal: AppSpacing.compact,
), ),
child: Text( child: Text(
_errorMessage(context, error), agentChatErrorMessage(context, error),
style: theme.textTheme.bodySmall, style: theme.textTheme.bodySmall,
), ),
), ),
@@ -1041,7 +924,7 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
? _pickAttachments ? _pickAttachments
: null, : null,
icon: const Icon( icon: const Icon(
Icons.add, AppIcons.add,
), ),
), ),
const SizedBox( const SizedBox(
@@ -1081,7 +964,7 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
) )
.stop, .stop,
icon: const Icon( icon: const Icon(
Icons.stop, AppIcons.stop,
), ),
) )
else else
@@ -1116,7 +999,7 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
? send ? send
: null, : null,
icon: const Icon( icon: const Icon(
Icons.arrow_upward, AppIcons.arrowUp,
), ),
), ),
), ),
@@ -22,6 +22,14 @@ class AgentComposerController extends ChangeNotifier {
final List<AgentMediaAttachment> attachments; final List<AgentMediaAttachment> attachments;
final feedback = MediaImportFeedbackController(); final feedback = MediaImportFeedbackController();
bool _busy = false; bool _busy = false;
bool _usingDraftModel = false;
bool get usingDraftModel => _usingDraftModel;
void useDraftModel() {
if (_disposed) return;
_usingDraftModel = true;
notifyListeners();
}
bool _disposed = false; bool _disposed = false;
bool get busy => _busy; bool get busy => _busy;
@@ -37,12 +37,24 @@ final class AgentComposerStore {
final AgentComposerController Function(String?) createComposer; final AgentComposerController Function(String?) createComposer;
ComposerDocumentController _draft = ComposerDocumentController(); ComposerDocumentController _draft = ComposerDocumentController();
ComposerDocumentController get draft => _draft; ComposerDocumentController get draft => _draft;
final _projectDrafts = <String?, ComposerDocumentController>{};
final _inputs = <(String?, String), ComposerDocumentController>{}; final _inputs = <(String?, String), ComposerDocumentController>{};
final _composers = <(String?, String), AgentComposerController>{}; final _composers = <(String?, String), AgentComposerController>{};
ComposerDocumentController input(String? projectId, String? conversationId) => ComposerDocumentController input(
conversationId == null String? projectId,
? draft String? conversationId, {
bool projectScoped = false,
}) => conversationId == null
? projectScoped
? _projectDrafts.putIfAbsent(
projectId,
() => projectId == null
? ComposerDocumentController()
: _projectDrafts.remove(null) ??
ComposerDocumentController(),
)
: draft
: _inputs.putIfAbsent(( : _inputs.putIfAbsent((
projectId, projectId,
conversationId, conversationId,
@@ -57,8 +69,9 @@ final class AgentComposerStore {
void promoteDraft(String projectId, String draftKey, String conversationId) { void promoteDraft(String projectId, String draftKey, String conversationId) {
final destination = (projectId, conversationId); final destination = (projectId, conversationId);
_inputs.remove(destination)?.dispose(); _inputs.remove(destination)?.dispose();
_inputs[destination] = _draft; final scoped = _projectDrafts.remove(projectId);
_draft = ComposerDocumentController(); _inputs[destination] = scoped ?? _draft;
if (scoped == null) _draft = ComposerDocumentController();
final composer = _composers.remove((projectId, draftKey)); final composer = _composers.remove((projectId, draftKey));
if (composer != null) { if (composer != null) {
_composers.remove(destination)?.dispose(); _composers.remove(destination)?.dispose();
@@ -77,6 +90,10 @@ final class AgentComposerStore {
void dispose() { void dispose() {
draft.dispose(); draft.dispose();
for (final input in _projectDrafts.values) {
input.dispose();
}
_projectDrafts.clear();
for (final input in _inputs.values) { for (final input in _inputs.values) {
input.dispose(); 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:flutter/material.dart';
import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart'; import 'package:cutdex_ui/theme.dart';
part 'composer_document.freezed.dart'; part 'composer_document.freezed.dart';
@@ -322,8 +323,8 @@ class ComposerDocumentController extends TextEditingController {
padding: const EdgeInsets.only(right: 4), padding: const EdgeInsets.only(right: 4),
child: Icon( child: Icon(
mark.reference.kind == ComposerReferenceKind.timeline mark.reference.kind == ComposerReferenceKind.timeline
? Icons.view_timeline_outlined ? AppIcons.timeline
: Icons.attach_file, : AppIcons.attachment,
size: 14, size: 14,
color: color, color: color,
), ),
@@ -4,6 +4,7 @@ import '../../l10n/l10n.dart';
import '../../shared/layout/composer_layout.dart'; import '../../shared/layout/composer_layout.dart';
import '../../shared/theme/composer_style.dart'; import '../../shared/theme/composer_style.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart'; import 'package:cutdex_ui/theme.dart';
import '../../workspace/project_state.dart'; import '../../workspace/project_state.dart';
@@ -72,7 +73,7 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
if (selected == true) ...[ if (selected == true) ...[
const SizedBox(width: ComposerLayout.menuIconGap), const SizedBox(width: ComposerLayout.menuIconGap),
Icon( Icon(
Icons.check, AppIcons.check,
size: ComposerLayout.menuIconSize, size: ComposerLayout.menuIconSize,
color: colors.onSurfaceVariant, color: colors.onSurfaceVariant,
), ),
@@ -85,10 +86,7 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
Widget _separator() => const Padding( Widget _separator() => const Padding(
padding: AppComposerStyle.menuSeparatorPadding, padding: AppComposerStyle.menuSeparatorPadding,
child: Divider( child: Divider(height: 1),
height: 1,
thickness: AppComposerStyle.menuSeparatorThickness,
),
); );
@override @override
@@ -97,6 +95,18 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
final projects = widget.projects final projects = widget.projects
.where((project) => project.name.toLowerCase().contains(query)) .where((project) => project.name.toLowerCase().contains(query))
.toList(); .toList();
final listHeight = projects.isEmpty
? ComposerLayout.menuRowHeight +
AppComposerStyle.menuEmptyPadding.vertical
: (projects.length * ComposerLayout.menuRowHeight).clamp(
0.0,
ComposerLayout.menuListMaxHeight,
);
final contentHeight =
ComposerLayout.menuRowHeight * 2 +
(AppComposerStyle.menuSeparatorPadding.vertical + 1) * 2 +
listHeight;
final menuHeight = contentHeight + ComposerLayout.menuGutter * 2;
return Material( return Material(
key: const Key('composer-project-bar'), key: const Key('composer-project-bar'),
color: widget.backgroundColor, color: widget.backgroundColor,
@@ -109,12 +119,15 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
alignment: AlignmentDirectional.centerStart, alignment: AlignmentDirectional.centerStart,
child: MenuAnchor( child: MenuAnchor(
controller: _menu, controller: _menu,
alignmentOffset: Offset(0, -menuHeight - 4),
consumeOutsideTap: false, consumeOutsideTap: false,
onClose: () => setState(_search.clear), onClose: () => setState(_search.clear),
style: AppComposerStyle.projectMenu(context), style: AppComposerStyle.projectMenu(context)
.copyWith(alignment: AlignmentDirectional.topStart),
menuChildren: [ menuChildren: [
SizedBox( SizedBox(
width: ComposerLayout.menuContentWidth, width: ComposerLayout.menuContentWidth,
height: contentHeight,
child: Column( child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
@@ -126,6 +139,8 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
controller: _search, controller: _search,
autofocus: true, autofocus: true,
style: AppTheme.composerTextStyle(context), style: AppTheme.composerTextStyle(context),
cursorHeight: AppTheme.composerCursorHeight(context),
textAlignVertical: TextAlignVertical.center,
onChanged: (_) => setState(() {}), onChanged: (_) => setState(() {}),
decoration: AppComposerStyle.projectSearchDecoration( decoration: AppComposerStyle.projectSearchDecoration(
context, context,
@@ -134,10 +149,7 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
), ),
), ),
_separator(), _separator(),
ConstrainedBox( Expanded(
constraints: const BoxConstraints(
maxHeight: ComposerLayout.menuListMaxHeight,
),
child: SingleChildScrollView( child: SingleChildScrollView(
primary: false, primary: false,
child: Column( child: Column(
@@ -157,7 +169,7 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
_item( _item(
key: ValueKey('composer-project-${project.id}'), key: ValueKey('composer-project-${project.id}'),
label: project.name, label: project.name,
icon: Icons.folder_outlined, icon: AppIcons.folder,
selected: project.id == widget.selected?.id, selected: project.id == widget.selected?.id,
onPressed: onPressed:
widget.busy || !project.availability.canOpen widget.busy || !project.availability.canOpen
@@ -176,7 +188,7 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
key: const Key('composer-new-project'), key: const Key('composer-new-project'),
secondary: true, secondary: true,
label: context.l10n.newProject, label: context.l10n.newProject,
icon: Icons.add, icon: AppIcons.add,
onPressed: widget.busy || widget.onCreate == null onPressed: widget.busy || widget.onCreate == null
? null ? null
: () { : () {
@@ -197,7 +209,7 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
: controller.open(), : controller.open(),
style: AppComposerStyle.projectTrigger(context), style: AppComposerStyle.projectTrigger(context),
icon: const Icon( icon: const Icon(
Icons.folder_outlined, AppIcons.folder,
size: ComposerLayout.menuIconSize, size: ComposerLayout.menuIconSize,
), ),
label: Text( label: Text(
@@ -1,5 +1,6 @@
import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:cutdex_sdk/project.dart'; import 'package:cutdex_sdk/project.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../../l10n/app_localizations.dart'; import '../../l10n/app_localizations.dart';
@@ -62,10 +63,10 @@ abstract final class ComposerOptionCatalog {
title: asset.name, title: asset.name,
subtitle: l10n.materials, subtitle: l10n.materials,
icon: switch (asset.metadata['kind']) { icon: switch (asset.metadata['kind']) {
'video' => Icons.movie_outlined, 'video' => AppIcons.video,
'audio' => Icons.audiotrack_outlined, 'audio' => AppIcons.audio,
'image' => Icons.image_outlined, 'image' => AppIcons.image,
_ => Icons.insert_drive_file_outlined, _ => AppIcons.file,
}, },
group: ComposerOptionGroup.media, group: ComposerOptionGroup.media,
reference: ComposerReference( reference: ComposerReference(
@@ -80,7 +81,7 @@ abstract final class ComposerOptionCatalog {
trigger: '@', trigger: '@',
title: timeline.name, title: timeline.name,
subtitle: l10n.timelines, subtitle: l10n.timelines,
icon: Icons.view_timeline_outlined, icon: AppIcons.timeline,
group: ComposerOptionGroup.timeline, group: ComposerOptionGroup.timeline,
reference: ComposerReference( reference: ComposerReference(
kind: ComposerReferenceKind.timeline, 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 '../projects/conversation_sidebar.dart';
import 'agent_chat_panel.dart'; import 'agent_chat_panel.dart';
import 'agent_panel_presentation.dart';
import 'floating_agent_panel.dart';
import 'agent_composer_store.dart'; import 'agent_composer_store.dart';
import 'composer_project_selector.dart'; import 'composer_project_selector.dart';
@@ -19,11 +21,13 @@ class WorkspaceAgentSurface extends ConsumerWidget {
required this.state, required this.state,
required this.onSelectProject, required this.onSelectProject,
required this.onCreateProject, required this.onCreateProject,
this.showProjectSelector = true,
}); });
final ProjectState state; final ProjectState state;
final ValueChanged<RecentProject>? onSelectProject; final ValueChanged<RecentProject>? onSelectProject;
final VoidCallback? onCreateProject; final VoidCallback? onCreateProject;
final bool showProjectSelector;
@override @override
Widget build(BuildContext context, WidgetRef ref) { Widget build(BuildContext context, WidgetRef ref) {
@@ -34,21 +38,54 @@ class WorkspaceAgentSurface extends ConsumerWidget {
final composers = ref.watch(agentComposerStoreProvider); final composers = ref.watch(agentComposerStoreProvider);
final projectId = state.activeProject?.id; final projectId = state.activeProject?.id;
final conversationId = selection.selectedId; final conversationId = selection.selectedId;
return AgentChatPanel( final presentation = AgentPanelPresentation.of(context);
key: ValueKey((projectId, conversationId ?? selection.draftKey)), if (presentation?.compact == true) {
inputController: composers.input(projectId, conversationId), return FloatingAgentPanel(
state: state,
selection: selection,
input: composers.input(
projectId,
conversationId,
projectScoped: !showProjectSelector,
),
composer: composers.composer( composer: composers.composer(
projectId, projectId,
conversationId ?? selection.draftKey, 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), backgroundColor: AppTheme.composerUtilityBackground(context),
projects: state.recent, projects: state.recent,
selected: state.activeProject, selected: state.activeProject,
busy: state.projectBusy, busy: state.projectBusy,
onSelect: (project) => onSelectProject?.call(project), onSelect: (project) => onSelectProject?.call(project),
onCreate: onCreateProject, onCreate: onCreateProject,
), )
: null,
composerColor: AppSurfaces.of(context).composerBackground, composerColor: AppSurfaces.of(context).composerBackground,
projectId: projectId, projectId: projectId,
timelineId: state.timeline?.id, timelineId: state.timeline?.id,
@@ -2,11 +2,12 @@ import 'package:cutdex/l10n/l10n.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart'; import 'package:cutdex_ui/theme.dart';
import '../../integrations/runtime/processing_resource_repository.dart'; import '../../integrations/runtime/processing_resource_repository.dart';
import '../../workspace/background_task_registry.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 '../../integrations/runtime/processing_resource_state.dart';
import 'package:cutdex_ui/widgets.dart'; import 'package:cutdex_ui/widgets.dart';
@@ -14,7 +15,14 @@ import 'package:cutdex_ui/widgets.dart';
import '../media/background_tasks_dialog.dart'; import '../media/background_tasks_dialog.dart';
class BackgroundTasksButton extends ConsumerWidget { class BackgroundTasksButton extends ConsumerWidget {
const BackgroundTasksButton({super.key}); const BackgroundTasksButton({
super.key,
this.iconSize = AppIconSize.header,
this.alignment = AlignmentDirectional.bottomStart,
});
final double iconSize;
final AlignmentGeometry alignment;
@override @override
Widget build(BuildContext context, WidgetRef ref) { Widget build(BuildContext context, WidgetRef ref) {
@@ -23,30 +31,39 @@ class BackgroundTasksButton extends ConsumerWidget {
.watch(processingResourceRepositoryProvider) .watch(processingResourceRepositoryProvider)
.asData .asData
?.value; ?.value;
final tasks = ref.watch(backgroundTasksProvider(registry: registry));
final downloads = resources == null final downloads = resources == null
? null ? null
: ref.watch(processingResourcesProvider(resources)); : ref.watch(
bool hasRunningTasks() => processingResourcesProvider(resources).select(
tasks.runningCount > 0 || (downloads) =>
downloads?.subtitleDownloading == true || downloads.subtitleDownloading ||
(downloads?.installs.any( downloads.installs.any(
(install) => install.state == ProcessingResourceState.downloading, (install) =>
) ?? install.state == ProcessingResourceState.downloading,
false); ),
Widget button(VoidCallback toggle) => IconButton( ),
);
Widget button(VoidCallback toggle, bool running) => IconButton(
key: const ValueKey('background-tasks-button'), key: const ValueKey('background-tasks-button'),
tooltip: context.l10n.backgroundTasks, tooltip: context.l10n.backgroundTasks,
onPressed: toggle, onPressed: toggle,
icon: Badge( icon: Badge(
isLabelVisible: hasRunningTasks(), isLabelVisible: running || downloads == true,
child: const Icon(Icons.task_alt_outlined, size: AppIconSize.header), child: Icon(AppIcons.success, size: iconSize),
), ),
); );
return AppPopover( return ListenableSelector<bool>(
listenable: registry,
select: () => registry.runningCount > 0,
builder: (context, running) => AppPopover(
width: 384, width: 384,
builder: (_, toggle) => button(toggle), alignment: alignment,
child: BackgroundTasksContent(registry: registry, repository: resources), builder: (_, toggle) => button(toggle, running),
child: BackgroundTasksContent(
registry: registry,
repository: resources,
),
),
); );
} }
} }
+227 -99
View File
@@ -1,3 +1,5 @@
import '../../shared/widgets/listenable_selector.dart';
import 'dart:async'; import 'dart:async';
import 'package:cutdex/l10n/l10n.dart'; import 'package:cutdex/l10n/l10n.dart';
@@ -11,9 +13,12 @@ import 'package:cutdex_native/cutdex_native.dart';
import '../../persistence/app_settings_repositories.dart'; import '../../persistence/app_settings_repositories.dart';
import '../../shared/layout/workspace_layout_metrics.dart'; import '../../shared/layout/workspace_layout_metrics.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart'; import 'package:cutdex_ui/theme.dart';
import '../../workspace/timeline_provider.dart'; import '../../workspace/timeline_provider.dart';
import '../../workspace/preview_target.dart';
import '../../workspace/projects.dart';
import '../../workspace/view_settings.dart'; import '../../workspace/view_settings.dart';
import '../media/media_browser_page.dart'; import '../media/media_browser_page.dart';
import '../media/media_panel.dart'; import '../media/media_panel.dart';
@@ -22,6 +27,8 @@ import '../properties/properties_editor_page.dart';
import '../properties/properties_panel.dart'; import '../properties/properties_panel.dart';
import '../timeline/timeline_panel.dart'; import '../timeline/timeline_panel.dart';
import 'editor_presentation_controller.dart'; import 'editor_presentation_controller.dart';
import 'editor_panel_defaults.dart';
import 'timeline_operation_region.dart';
import 'layouts/bounded_editor_layout.dart'; import 'layouts/bounded_editor_layout.dart';
import 'layouts/expanded_editor_layout.dart'; import 'layouts/expanded_editor_layout.dart';
@@ -34,10 +41,16 @@ class EditorWorkspace extends ConsumerStatefulWidget {
required this.projectName, required this.projectName,
required this.integratedTitlebar, required this.integratedTitlebar,
required this.headerLeading, required this.headerLeading,
this.projectLoading = false,
this.timelineLoading = false,
this.showProjectName = true, this.showProjectName = true,
this.experience = DeviceExperience.desktop, 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 projectId;
final String timelineId; final String timelineId;
final String projectName; final String projectName;
@@ -52,6 +65,13 @@ class EditorWorkspace extends ConsumerStatefulWidget {
class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> { class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
final _previewKey = GlobalKey(); final _previewKey = GlobalKey();
bool get _timelinePending => widget.projectLoading;
Widget _timelineInteraction(Widget child) => TimelineOperationRegion(
projectId: widget.projectId,
loading: widget.timelineLoading,
child: child,
);
EditorPresentationController get _presentation => EditorPresentationController get _presentation =>
ref.read(editorPresentationProvider(widget.projectId)); ref.read(editorPresentationProvider(widget.projectId));
ProjectViewSettingsData get _viewSettings => ProjectViewSettingsData get _viewSettings =>
@@ -63,7 +83,8 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
double? get _timelineHeight => _viewSettings.timelineHeight; double? get _timelineHeight => _viewSettings.timelineHeight;
void _saveViewSettings() { void _saveViewSettings() {
if (!ref.read(projectViewSettingsProvider(widget.projectId)).hasValue) { if (widget.projectId.isEmpty ||
!ref.read(projectViewSettingsProvider(widget.projectId)).hasValue) {
return; return;
} }
unawaited(_viewController.save()); unawaited(_viewController.save());
@@ -76,91 +97,127 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
); );
final preview = KeyedSubtree( final preview = KeyedSubtree(
key: _previewKey, key: _previewKey,
child: EditorPreviewPanel( child: _timelineInteraction(
EditorPreviewPanel(
projectId: widget.projectId, projectId: widget.projectId,
timelineId: widget.timelineId, timelineId: widget.timelineId,
pending: _timelinePending,
),
), ),
); );
final timeline = EditorTimelinePanel( final timeline = EditorTimelinePanel(
projectId: widget.projectId, projectId: widget.projectId,
timelineId: widget.timelineId, timelineId: widget.timelineId,
pending: widget.projectLoading,
timelineLoading: widget.timelineLoading,
); );
final properties = EditorPropertiesPanel( final properties = _timelineInteraction(
_timelinePending
? const EditorEmptyPanel()
: EditorPropertiesPanel(
projectId: widget.projectId, projectId: widget.projectId,
timelineId: widget.timelineId, timelineId: widget.timelineId,
),
); );
final media = MediaPanel(projectId: widget.projectId); final media = widget.projectLoading
? const EditorEmptyPanel()
: MediaPanel(projectId: widget.projectId, projectScoped: true);
return ListenableBuilder( return ListenableBuilder(
listenable: ref.watch(editorPresentationProvider(widget.projectId)), listenable: ref.watch(editorPresentationProvider(widget.projectId)),
builder: (context, _) => LayoutBuilder( builder: (context, _) => LayoutBuilder(
builder: (context, constraints) { builder: (context, constraints) {
final desktop = widget.experience == DeviceExperience.desktop; final desktop = widget.experience == DeviceExperience.desktop;
final sideWidth =
(_presentation.mediaOpen
? WorkspaceLayoutMetrics.mediaPanelWidth + 1
: 0) +
(_propertiesOpen
? WorkspaceLayoutMetrics.propertiesPanelWidth + 1
: 0);
final dockPanels =
desktop &&
constraints.maxWidth >=
WorkspaceLayoutMetrics.previewMinimumWidth + sideWidth;
final desktopTool = sideWidth == 0
? null
: _presentation.desktopTool(propertiesOpen: _propertiesOpen);
final headerHeight = desktop ? AppControlSize.panelHeader : 48.0;
final mediaOpen = desktop final mediaOpen = desktop
? dockPanels
? _presentation.mediaOpen ? _presentation.mediaOpen
: desktopTool == EditorTool.media
: _presentation.activeTool == EditorTool.media; : _presentation.activeTool == EditorTool.media;
final mediaWidth = mediaOpen
? WorkspaceLayoutMetrics.mediaPanelWidth +
WorkspaceLayoutMetrics.desktopSpacing
: 0.0;
final sideWidth = (_propertiesOpen
? WorkspaceLayoutMetrics.propertiesPanelWidth +
WorkspaceLayoutMetrics.desktopSpacing
: 0);
final dockMedia =
desktop &&
mediaOpen &&
constraints.maxWidth >=
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 final propertiesOpen = desktop
? dockPanels ? dockProperties
? _propertiesOpen ? _propertiesOpen
: desktopTool == EditorTool.properties : desktopTool == EditorTool.properties
: _presentation.activeTool == EditorTool.properties; : _presentation.activeTool == EditorTool.properties;
Widget dockedEditing({required bool showTools}) => final mediaButton = HeaderControlRegion(
ExpandedEditorLayout( child: SizedBox.square(
preview: preview, dimension: desktop ? AppControlSize.headerButton : 48,
properties: properties, child: IconButton(
media: media, key: const Key('editor-media-button'),
showMedia: showTools && _presentation.mediaOpen, tooltip: context.l10n.materials,
showProperties: showTools && _propertiesOpen, isSelected: mediaOpen,
timelineHeight: _timelineHeight, onPressed: () {
onTimelineHeightChanged: (height) { if (desktop) {
if (viewSettings.hasValue) { if (!dockMedia &&
_viewController.setTimelineHeight(height); desktopTool != EditorTool.media &&
_presentation.mediaOpen) {
_presentation.preferDesktopTool(EditorTool.media);
} else {
_presentation.toggleMedia();
}
} else {
_presentation.toggleTool(EditorTool.media);
} }
}, },
onTimelineHeightChangeEnd: _saveViewSettings, icon: const Icon(AppIcons.mediaLibrary),
timeline: timeline, ),
),
); );
return Stack( final header = Material(
fit: StackFit.expand,
children: [
Column(
children: [
Material(
color: Theme.of(context).colorScheme.surface, color: Theme.of(context).colorScheme.surface,
child: SizedBox( child: SizedBox(
key: const Key('editor-content-header'), key: const Key('editor-content-header'),
height: headerHeight, height: headerHeight,
child: Padding(
padding: desktop
? const EdgeInsets.symmetric(
horizontal: AppSidebarMetrics.outerPadding,
vertical: AppSpacing.tiny,
)
: EdgeInsets.zero,
child: WindowHeaderPadding( child: WindowHeaderPadding(
child: Row( child: Row(
children: [ children: [
widget.headerLeading, widget.headerLeading,
if (desktop) mediaButton,
Expanded( Expanded(
child: widget.showProjectName child: desktop
? _PreviewHeaderTitle(
projectId: widget.projectId,
timelineId: widget.timelineId,
pending: _timelinePending,
)
: widget.showProjectName
? Row( ? Row(
children: [ children: [
Flexible( Flexible(
fit: FlexFit.loose, fit: FlexFit.loose,
child: Text( child: Text(
widget.projectName, widget.projectName,
key: const Key( key: const Key('workspace-project-title'),
'workspace-project-title',
),
maxLines: 1, maxLines: 1,
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
style: Theme.of(context) style: Theme.of(context)
@@ -170,7 +227,9 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
), ),
Flexible( Flexible(
fit: FlexFit.loose, fit: FlexFit.loose,
child: _TimelineSaveStatus( child: _timelinePending
? const SizedBox.shrink()
: _TimelineSaveStatus(
projectId: widget.projectId, projectId: widget.projectId,
timelineId: widget.timelineId, timelineId: widget.timelineId,
), ),
@@ -179,42 +238,11 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
) )
: const SizedBox.shrink(), : const SizedBox.shrink(),
), ),
if (!desktop) mediaButton,
if (!desktop) const SizedBox(width: AppSpacing.tiny),
HeaderControlRegion( HeaderControlRegion(
child: SizedBox.square( child: SizedBox.square(
dimension: desktop dimension: desktop ? AppControlSize.headerButton : 48,
? AppControlSize.headerButton
: 48,
child: IconButton(
key: const Key('editor-media-button'),
tooltip: context.l10n.materials,
isSelected: mediaOpen,
onPressed: () {
if (desktop) {
if (!dockPanels &&
desktopTool != EditorTool.media &&
_presentation.mediaOpen) {
_presentation.preferDesktopTool(
EditorTool.media,
);
} else {
_presentation.toggleMedia();
}
} else {
_presentation.toggleTool(
EditorTool.media,
);
}
},
icon: const Icon(Icons.perm_media_outlined),
),
),
),
const SizedBox(width: AppSpacing.tiny),
HeaderControlRegion(
child: SizedBox.square(
dimension: desktop
? AppControlSize.headerButton
: 48,
child: IconButton( child: IconButton(
key: const Key('editor-properties-button'), key: const Key('editor-properties-button'),
tooltip: propertiesOpen tooltip: propertiesOpen
@@ -225,7 +253,7 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
? null ? null
: () { : () {
if (desktop) { if (desktop) {
if (dockPanels || if (dockProperties ||
desktopTool == desktopTool ==
EditorTool.properties || EditorTool.properties ||
!_propertiesOpen) { !_propertiesOpen) {
@@ -244,20 +272,44 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
} }
}, },
icon: const Icon( icon: const Icon(
Icons.tune, AppIcons.tune,
size: AppIconSize.header, size: AppIconSize.header,
), ),
), ),
), ),
), ),
const SizedBox(width: AppSpacing.compact), if (!desktop) const SizedBox(width: AppSpacing.compact),
], ],
), ),
), ),
), ),
), ),
);
Widget dockedEditing({required bool showTools}) =>
ExpandedEditorLayout(
preview: preview,
header: header,
properties: properties,
media: media,
showMedia: dockMedia,
showProperties: showTools && dockProperties,
timelineHeight: _timelineHeight,
onTimelineHeightChanged: (height) {
if (viewSettings.hasValue) {
_viewController.setTimelineHeight(height);
}
},
onTimelineHeightChangeEnd: _saveViewSettings,
timeline: timeline,
);
return Stack(
fit: StackFit.expand,
children: [
Column(
children: [
if (!desktop) header,
Expanded( Expanded(
child: dockPanels child: desktop && desktopTool == null
? dockedEditing(showTools: true) ? dockedEditing(showTools: true)
: BoundedEditorLayout( : BoundedEditorLayout(
experience: widget.experience, experience: widget.experience,
@@ -270,25 +322,36 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
tool: desktop tool: desktop
? desktopTool ? desktopTool
: _presentation.activeTool, : _presentation.activeTool,
media: switch (widget.experience) { media: widget.projectLoading
? media
: switch (widget.experience) {
DeviceExperience.desktop => media, DeviceExperience.desktop => media,
DeviceExperience.tablet => MediaBrowserDrawer( DeviceExperience.tablet =>
MediaBrowserDrawer(
projectId: widget.projectId, projectId: widget.projectId,
), ),
DeviceExperience.phone => MediaBrowserPage( DeviceExperience.phone => MediaBrowserPage(
projectId: widget.projectId, projectId: widget.projectId,
), ),
}, },
properties: switch (widget.experience) { properties: _timelinePending
? properties
: switch (widget.experience) {
DeviceExperience.desktop => properties, DeviceExperience.desktop => properties,
DeviceExperience.tablet => PropertiesToolPanel( DeviceExperience.tablet =>
_timelineInteraction(
PropertiesToolPanel(
projectId: widget.projectId, projectId: widget.projectId,
timelineId: widget.timelineId, timelineId: widget.timelineId,
), ),
DeviceExperience.phone => PropertiesEditorPage( ),
DeviceExperience.phone =>
_timelineInteraction(
PropertiesEditorPage(
projectId: widget.projectId, projectId: widget.projectId,
timelineId: widget.timelineId, timelineId: widget.timelineId,
), ),
),
}, },
onCloseTool: () { onCloseTool: () {
if (!desktop) { if (!desktop) {
@@ -304,6 +367,7 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
), ),
], ],
), ),
if (!desktop)
Positioned( Positioned(
key: const Key('editing-top-divider'), key: const Key('editing-top-divider'),
top: headerHeight, top: headerHeight,
@@ -320,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 { class _TimelineSaveStatus extends ConsumerWidget {
const _TimelineSaveStatus({ const _TimelineSaveStatus({
required this.projectId, required this.projectId,
@@ -336,22 +467,19 @@ class _TimelineSaveStatus extends ConsumerWidget {
.asData .asData
?.value; ?.value;
if (session == null) return const SizedBox.shrink(); if (session == null) return const SizedBox.shrink();
return ListenableBuilder( return ListenableSelector<(bool, bool, bool)>(
listenable: session, listenable: session,
builder: (context, _) => Padding( select: () => (session.error != null, session.saving, session.dirty),
builder: (context, value) => Padding(
padding: const EdgeInsets.only(left: AppSpacing.small), padding: const EdgeInsets.only(left: AppSpacing.small),
child: Text( child: Text(
session.error != null _timelineSaveLabel(context, value),
? context.l10n.unsaved
: session.saving
? context.l10n.saving
: session.dirty
? context.l10n.pendingSave
: context.l10n.saved,
key: const Key('timeline-save-status'), key: const Key('timeline-save-status'),
maxLines: 1, maxLines: 1,
overflow: TextOverflow.ellipsis, 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),
), ),
), ),
); );
@@ -0,0 +1,139 @@
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.
class EditorEmptyPanel extends StatelessWidget {
const EditorEmptyPanel({super.key});
@override
Widget build(BuildContext context) =>
const WorkspacePanel(child: SizedBox.expand());
}
class EditorTimelineDefaults extends StatelessWidget {
const EditorTimelineDefaults({super.key, this.showTabs = true});
final bool showTabs;
@override
Widget build(BuildContext context) => Column(
children: [
if (showTabs) ...[
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: [
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: AppTheme.isDesktop(context)
? AppDesktopMetrics.timelineToolbar
: 32,
headerPadding: EdgeInsets.zero,
controls: SizedBox(
key: const Key('timeline-toolbar'),
height: AppTheme.isDesktop(context)
? AppDesktopMetrics.timelineToolbar
: 32,
child: !AppTheme.isDesktop(context)
? SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
for (final icon in [
AppIcons.undo,
AppIcons.redo,
AppIcons.cut,
AppIcons.alignLeft,
AppIcons.alignRight,
AppIcons.delete,
])
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,
),
],
],
),
),
),
child: const SizedBox.expand(key: Key('timeline-default-tracks')),
),
),
],
);
}
@@ -12,12 +12,14 @@ final editorPresentationProvider =
/// Presentation choices survive shell changes without changing project data. /// Presentation choices survive shell changes without changing project data.
class EditorPresentationController extends ChangeNotifier { class EditorPresentationController extends ChangeNotifier {
bool _mediaOpen = false; bool _mediaOpen = true;
EditorTool? _activeTool; EditorTool? _activeTool;
EditorTool _preferredDesktopTool = EditorTool.properties; EditorTool _preferredDesktopTool = EditorTool.properties;
bool _desktopToolRequested = false;
bool get mediaOpen => _mediaOpen; bool get mediaOpen => _mediaOpen;
EditorTool? get activeTool => _activeTool; EditorTool? get activeTool => _activeTool;
bool get desktopToolRequested => _desktopToolRequested;
EditorTool desktopTool({required bool propertiesOpen}) => EditorTool desktopTool({required bool propertiesOpen}) =>
_preferredDesktopTool == EditorTool.media && _mediaOpen _preferredDesktopTool == EditorTool.media && _mediaOpen
? EditorTool.media ? EditorTool.media
@@ -26,12 +28,14 @@ class EditorPresentationController extends ChangeNotifier {
: EditorTool.media; : EditorTool.media;
void preferDesktopTool(EditorTool tool) { void preferDesktopTool(EditorTool tool) {
_desktopToolRequested = true;
_preferredDesktopTool = tool; _preferredDesktopTool = tool;
notifyListeners(); notifyListeners();
} }
void toggleMedia() { void toggleMedia() {
_mediaOpen = !_mediaOpen; _mediaOpen = !_mediaOpen;
_desktopToolRequested = _mediaOpen;
if (_mediaOpen) _preferredDesktopTool = EditorTool.media; if (_mediaOpen) _preferredDesktopTool = EditorTool.media;
notifyListeners(); notifyListeners();
} }
@@ -5,6 +5,7 @@ import 'package:flutter/material.dart';
import '../../../integrations/platform/device_experience.dart'; import '../../../integrations/platform/device_experience.dart';
import '../../../l10n/l10n.dart'; import '../../../l10n/l10n.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart'; import 'package:cutdex_ui/theme.dart';
import '../editor_presentation_controller.dart'; import '../editor_presentation_controller.dart';
@@ -36,7 +37,11 @@ class BoundedEditorLayout extends StatelessWidget {
Widget toolSurface() => Column( Widget toolSurface() => Column(
children: [ children: [
SizedBox( SizedBox(
height: desktop ? AppControlSize.panelHeader : 48, height: desktop ? AppDesktopMetrics.panelHeader : 48,
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: desktop ? AppSpacing.small : 0,
),
child: Row( child: Row(
children: [ children: [
SizedBox.square( SizedBox.square(
@@ -46,7 +51,7 @@ class BoundedEditorLayout extends StatelessWidget {
tooltip: MaterialLocalizations.of(context) tooltip: MaterialLocalizations.of(context)
.closeButtonTooltip, .closeButtonTooltip,
onPressed: onCloseTool, onPressed: onCloseTool,
icon: Icon(page ? Icons.arrow_back : Icons.close), icon: Icon(page ? AppIcons.arrowBack : AppIcons.close),
), ),
), ),
Expanded( Expanded(
@@ -61,6 +66,7 @@ class BoundedEditorLayout extends StatelessWidget {
], ],
), ),
), ),
),
const Divider(height: 1), const Divider(height: 1),
Expanded(child: tool == EditorTool.media ? media : properties), Expanded(child: tool == EditorTool.media ? media : properties),
], ],
@@ -92,7 +98,7 @@ class BoundedEditorLayout extends StatelessWidget {
), ),
if (tool != null) if (tool != null)
Positioned( Positioned(
top: 0, top: desktop ? AppDesktopMetrics.panelHeader + 1 : 0,
bottom: 0, bottom: 0,
right: 0, right: 0,
width: page width: page
@@ -1,14 +1,16 @@
import 'dart:math' as math; import 'dart:math' as math;
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../../../shared/layout/workspace_layout_metrics.dart'; import '../../../shared/layout/workspace_layout_metrics.dart';
import '../../../shared/widgets/workspace_card.dart';
import '../../../shared/widgets/workspace_resize_handle.dart';
class ExpandedEditorLayout extends StatefulWidget { class ExpandedEditorLayout extends StatefulWidget {
const ExpandedEditorLayout({ const ExpandedEditorLayout({
super.key, super.key,
required this.preview, required this.preview,
required this.header,
required this.properties, required this.properties,
required this.media, required this.media,
required this.showMedia, required this.showMedia,
@@ -20,6 +22,7 @@ class ExpandedEditorLayout extends StatefulWidget {
}); });
final Widget preview; final Widget preview;
final Widget header;
final Widget properties; final Widget properties;
final Widget media; final Widget media;
final bool showMedia; final bool showMedia;
@@ -34,15 +37,26 @@ class ExpandedEditorLayout extends StatefulWidget {
} }
class _ExpandedEditorLayoutState extends State<ExpandedEditorLayout> { class _ExpandedEditorLayoutState extends State<ExpandedEditorLayout> {
double? _timelineDragStartY; static const gap = WorkspaceLayoutMetrics.desktopSpacing;
double _timelineDragStartHeight = 0; 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);
@override @override
Widget build(BuildContext context) => LayoutBuilder( Widget build(BuildContext context) => LayoutBuilder(
builder: (context, constraints) { builder: (context, constraints) {
final maximum = math.max( final maximum = math.max(
0.0, 0.0,
constraints.maxHeight - WorkspaceLayoutMetrics.timelineMinimumHeight, constraints.maxHeight -
gap -
WorkspaceLayoutMetrics.previewMinimumHeight,
); );
final minimum = math.min( final minimum = math.min(
WorkspaceLayoutMetrics.timelineMinimumHeight, WorkspaceLayoutMetrics.timelineMinimumHeight,
@@ -54,9 +68,7 @@ class _ExpandedEditorLayoutState extends State<ExpandedEditorLayout> {
WorkspaceLayoutMetrics.timelineDefaultHeightFraction) WorkspaceLayoutMetrics.timelineDefaultHeightFraction)
.clamp(minimum, maximum) .clamp(minimum, maximum)
.toDouble(); .toDouble();
final mediaWidth = widget.showMedia const mediaWidth = WorkspaceLayoutMetrics.mediaPanelWidth;
? WorkspaceLayoutMetrics.mediaPanelWidth
: 0.0;
final propertiesWidth = widget.showProperties final propertiesWidth = widget.showProperties
? WorkspaceLayoutMetrics.propertiesPanelWidth ? WorkspaceLayoutMetrics.propertiesPanelWidth
: 0.0; : 0.0;
@@ -69,73 +81,70 @@ class _ExpandedEditorLayoutState extends State<ExpandedEditorLayout> {
child: Row( child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
if (widget.showMedia) ...[ if (_mediaVisited)
SizedBox( Offstage(
offstage: !widget.showMedia,
child: ExcludeFocus(
excluding: !widget.showMedia,
child: TickerMode(
enabled: widget.showMedia,
child: SizedBox(
key: const Key('editor-media-region'), key: const Key('editor-media-region'),
width: mediaWidth, 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), Expanded(child: widget.preview),
],
),
),
),
if (widget.showProperties) ...[ if (widget.showProperties) ...[
const VerticalDivider(width: 1), const SizedBox(
key: Key('editor-properties-divider'),
width: gap,
),
SizedBox( SizedBox(
key: const Key('editor-properties-region'), key: const Key('editor-properties-region'),
width: propertiesWidth, width: propertiesWidth,
child: widget.properties, child: _card('properties', widget.properties),
), ),
], ],
], ],
), ),
), ),
const SizedBox(height: 1), const SizedBox(height: gap),
SizedBox(height: timelineHeight, child: widget.timeline), SizedBox(
height: timelineHeight,
child: _card('timeline', widget.timeline),
),
], ],
), ),
Positioned( Positioned(
key: const Key('editor-timeline-divider'), key: const Key('editor-timeline-divider'),
left: 0, left: 0,
right: 0, right: 0,
bottom: timelineHeight - 4, bottom: timelineHeight - WorkspaceLayoutMetrics.desktopResizeSlop,
height: 8, height: WorkspaceLayoutMetrics.desktopResizeHitExtent,
child: MouseRegion( child: WorkspaceResizeHandle(
cursor: SystemMouseCursors.resizeRow,
child: GestureDetector(
key: const Key('editor-timeline-resize'), key: const Key('editor-timeline-resize'),
behavior: HitTestBehavior.opaque, axis: Axis.vertical,
dragStartBehavior: DragStartBehavior.down, initialValue: timelineHeight,
onVerticalDragStart: (details) { direction: -1,
_timelineDragStartY = details.globalPosition.dy; onResize: (height) => widget.onTimelineHeightChanged(
_timelineDragStartHeight = timelineHeight; height.clamp(minimum, maximum).toDouble(),
},
onVerticalDragUpdate: (details) {
final start = _timelineDragStartY;
if (start == null) return;
widget.onTimelineHeightChanged(
(_timelineDragStartHeight +
start -
details.globalPosition.dy)
.clamp(minimum, maximum)
.toDouble(),
);
},
onVerticalDragEnd: (_) {
_timelineDragStartY = null;
widget.onTimelineHeightChangeEnd();
},
onVerticalDragCancel: () {
_timelineDragStartY = null;
widget.onTimelineHeightChangeEnd();
},
child: const Center(
child: SizedBox(
height: 1,
width: double.infinity,
child: Divider(height: 1),
),
),
), ),
onEnd: widget.onTimelineHeightChangeEnd,
), ),
), ),
], ],
@@ -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 '../../integrations/runtime/media_presentations.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart'; import 'package:cutdex_ui/theme.dart';
class AudioAssetTile extends StatelessWidget { class AudioAssetTile extends StatelessWidget {
@@ -63,7 +64,7 @@ class _AudioWaveformCover extends ConsumerWidget {
if (waveform == null) { if (waveform == null) {
return Center( return Center(
child: Icon( child: Icon(
Icons.audio_file_outlined, AppIcons.audioFile,
size: AppIconSize.emptyState, size: AppIconSize.emptyState,
color: theme.colorScheme.onSurfaceVariant, color: theme.colorScheme.onSurfaceVariant,
), ),
@@ -10,6 +10,7 @@ import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart'; import 'package:cutdex_ui/widgets.dart';
import '../../shared/widgets/confirm_resource_download_cancel.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 '../../shared/widgets/processing_resource_download_dialog.dart';
import '../../workspace/timeline_session.dart'; import '../../workspace/timeline_session.dart';
@@ -76,10 +77,10 @@ class _BackgroundRemovalDialogState
_closing = true; _closing = true;
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return; if (!mounted) return;
final messenger = ScaffoldMessenger.maybeOf(context); final notifications = ErrorNotificationHost.maybeOf(context);
final message = context.l10n.backgroundRemovalTaskStarted; final message = context.l10n.backgroundRemovalTaskStarted;
Navigator.of(context).pop(); Navigator.of(context).pop();
messenger?.showSnackBar(SnackBar(content: Text(message))); notifications?.showMessage(content: Text(message));
}); });
}); });
return ref return ref
+146 -10
View File
@@ -1,3 +1,6 @@
import '../../shared/widgets/presentation_list.dart';
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'subtitle_download.dart'; import 'subtitle_download.dart';
@@ -43,12 +46,50 @@ class BackgroundTasksContent extends ConsumerWidget {
final ProcessingResourceRepository? repository; final ProcessingResourceRepository? repository;
@override @override
Widget build(BuildContext context, WidgetRef ref) { Widget build(BuildContext context, WidgetRef ref) {
final snapshot = ref.watch( final tasksProvider = backgroundTasksProvider(
backgroundTasksProvider(registry: registry, session: session), 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 final resources = repository == null
? null ? null
: ref.watch(processingResourcesProvider(repository!)); : ref.read(processingResourcesProvider(repository!));
final subtitleEntries = snapshot.subtitles; final subtitleEntries = snapshot.subtitles;
final removalEntries = snapshot.removals; final removalEntries = snapshot.removals;
final subtitleDownloading = resources?.subtitleDownloading == true; final subtitleDownloading = resources?.subtitleDownloading == true;
@@ -117,9 +158,11 @@ class BackgroundTasksContent extends ConsumerWidget {
resourceDownloads.isNotEmpty || resourceDownloads.isNotEmpty ||
subtitleDownloading) subtitleDownloading)
const SizedBox(height: 2), const SizedBox(height: 2),
_BackgroundRemovalTaskCard( _ObservedRemovalTask(
key: ValueKey(entry.task.id), key: ValueKey((entry.owner.session, entry.task.id)),
entry: entry, entry: entry,
registry: registry,
session: session,
), ),
], ],
for (final (index, entry) for (final (index, entry)
@@ -129,9 +172,14 @@ class BackgroundTasksContent extends ConsumerWidget {
removalEntries.isNotEmpty || removalEntries.isNotEmpty ||
subtitleDownloading) subtitleDownloading)
const SizedBox(height: 2), const SizedBox(height: 2),
_SubtitleTaskCard( _ObservedSubtitleTask(
key: ValueKey(entry.job.recognition.id), key: ValueKey((
entry.owner.session,
entry.job.recognition.id,
)),
entry: entry, entry: entry,
registry: registry,
session: session,
), ),
], ],
], ],
@@ -143,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 String _ownerName(BackgroundTaskSession owner) => owner.projectName.isEmpty
? owner.timelineName ? owner.timelineName
: '${owner.projectName} · ${owner.timelineName}'; : '${owner.projectName} · ${owner.timelineName}';
@@ -386,7 +498,31 @@ class _ResourceDownloadCard extends ConsumerWidget {
@override @override
Widget build(BuildContext context, WidgetRef ref) { 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 final install = this.install == null
? null ? null
: snapshot.installs : snapshot.installs
@@ -691,8 +827,8 @@ class _SubtitleTaskCardState extends ConsumerState<_SubtitleTaskCard> {
setState(() => _validationError = null); setState(() => _validationError = null);
await action(); await action();
if (mounted && !widget.details && _error != null) { if (mounted && !widget.details && _error != null) {
ScaffoldMessenger.maybeOf(context) ErrorNotificationHost.maybeOf(context)
?.showSnackBar(SnackBar(content: Text(_error!))); ?.show(ErrorNotification(content: Text(_error!)));
} }
} }
@@ -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 '../../integrations/runtime/media_presentations.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart'; import 'package:cutdex_ui/theme.dart';
import 'audio_asset_tile.dart'; import 'audio_asset_tile.dart';
@@ -64,9 +65,9 @@ class _VisualAssetStrip extends ConsumerWidget {
timeMilliseconds: video && duration != null timeMilliseconds: video && duration != null
? (duration * 1000 * index / count).floor() ? (duration * 1000 * index / count).floor()
: 0, : 0,
fallback: const Center(child: Icon(Icons.movie_outlined)), fallback: const Center(child: Icon(AppIcons.video)),
errorFallback: const Center( 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 { 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 AssetDocument asset;
final bool badge;
@override @override
Widget build(BuildContext context, WidgetRef ref) { Widget build(BuildContext context, WidgetRef ref) {
@@ -94,6 +96,20 @@ class MediaAssetDuration extends ConsumerWidget {
'${hours > 0 ? '$hours:' : ''}' '${hours > 0 ? '$hours:' : ''}'
'${minutes.toString().padLeft(2, '0')}:' '${minutes.toString().padLeft(2, '0')}:'
'${(seconds % 60).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( return DecoratedBox(
decoration: BoxDecoration( decoration: BoxDecoration(
color: Colors.black.withValues(alpha: .55), color: Colors.black.withValues(alpha: .55),
@@ -104,6 +120,8 @@ class MediaAssetDuration extends ConsumerWidget {
child: Text( child: Text(
text, text,
key: ValueKey('media-duration-${asset.id}'), key: ValueKey('media-duration-${asset.id}'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall?.copyWith( style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Colors.white, color: Colors.white,
fontFeatures: const [FontFeature.tabularFigures()], fontFeatures: const [FontFeature.tabularFigures()],
+366 -58
View File
@@ -1,3 +1,6 @@
import '../../shared/widgets/listenable_selector.dart';
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:cutdex/errors/app_failure.dart'; import 'package:cutdex/errors/app_failure.dart';
import 'dart:math' as math; import 'dart:math' as math;
@@ -10,19 +13,24 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../integrations/platform/platform_capabilities.dart'; import '../../integrations/platform/platform_capabilities.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart'; import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart'; import 'package:cutdex_ui/widgets.dart';
import '../../workspace/external_media_import.dart'; import '../../workspace/external_media_import.dart';
import '../../workspace/media_availability.dart'; import '../../workspace/media_availability.dart';
import '../../workspace/project_state.dart';
import '../../workspace/projects.dart'; import '../../workspace/projects.dart';
import '../../workspace/timeline_provider.dart'; import '../../workspace/timeline_provider.dart';
import '../../workspace/timeline_session.dart';
import 'audio_asset_tile.dart'; import 'audio_asset_tile.dart';
import 'media_asset_drag.dart'; import 'media_asset_drag.dart';
import 'media_asset_strip.dart'; import 'media_asset_strip.dart';
import 'media_browser_controller.dart'; import 'media_browser_controller.dart';
import 'unavailable_media_placeholder.dart'; import 'unavailable_media_placeholder.dart';
import 'visual_asset_tile.dart'; import 'visual_asset_tile.dart';
import 'desktop_media_asset_tile.dart';
import 'media_browser_layout.dart';
extension MediaFilterLabel on MediaFilter { extension MediaFilterLabel on MediaFilter {
String label(BuildContext context) => switch (this) { String label(BuildContext context) => switch (this) {
@@ -34,6 +42,7 @@ extension MediaFilterLabel on MediaFilter {
} }
const maximumMediaGridTileWidth = 160.0; const maximumMediaGridTileWidth = 160.0;
const maximumCompactMediaGridTileWidth = 120.0;
class MediaBrowserBody extends ConsumerStatefulWidget { class MediaBrowserBody extends ConsumerStatefulWidget {
const MediaBrowserBody({ const MediaBrowserBody({
@@ -41,25 +50,38 @@ class MediaBrowserBody extends ConsumerStatefulWidget {
required this.projectId, required this.projectId,
required this.grid, required this.grid,
this.draggable = false, this.draggable = false,
this.compact = false,
this.desktop = false,
}); });
final String projectId; final String projectId;
final bool grid; final bool grid;
final bool draggable; final bool draggable;
final bool compact;
final bool desktop;
@override @override
ConsumerState<MediaBrowserBody> createState() => _MediaBrowserBodyState(); ConsumerState<MediaBrowserBody> createState() => _MediaBrowserBodyState();
} }
class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody> class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
with WidgetsBindingObserver { with WidgetsBindingObserver {
final _desktopScroll = _MediaScrollController();
MediaBrowserController? _anchorOwner;
List<AssetDocument> _anchorAssets = const [];
int _anchorColumns = 1;
double _anchorStride = 1;
Object? _viewportConfiguration;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
WidgetsBinding.instance.addObserver(this); WidgetsBinding.instance.addObserver(this);
_desktopScroll.addListener(_storeBrowseAnchor);
} }
@override @override
void dispose() { void dispose() {
WidgetsBinding.instance.removeObserver(this); WidgetsBinding.instance.removeObserver(this);
_desktopScroll.dispose();
super.dispose(); super.dispose();
} }
@@ -79,19 +101,75 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
bool get _isGrid => widget.grid; bool get _isGrid => widget.grid;
bool get _desktop => ref.read(platformCapabilitiesProvider).nativeFileDrop; 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 { Future<void> _action(Future<bool> Function() action) async {
final ok = await action(); final ok = await action();
if (!mounted || ok) return; if (!mounted || ok) return;
ScaffoldMessenger.of(context).showSnackBar( final failure =
SnackBar(
content: Text(
context.l10n.failureMessage(
ref.read(projectsProvider).asData?.value.error ?? ref.read(projectsProvider).asData?.value.error ??
const AppFailure(AppErrorCode.operationFailed), const AppFailure(AppErrorCode.operationFailed);
), ErrorNotificationHost.of(context)
), .showFailure(failure, context.l10n.failureMessage(failure));
),
);
} }
Future<void> _rename(AssetDocument asset) async { Future<void> _rename(AssetDocument asset) async {
@@ -117,15 +195,22 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
], ],
child: AppField( child: AppField(
label: context.l10n.name, label: context.l10n.name,
child: TextField( child: Builder(
builder: (fieldContext) => TextField(
controller: controller, controller: controller,
autofocus: true, autofocus: true,
style: AppTheme.inputTextStyle(fieldContext),
cursorHeight: AppTheme.inputCursorHeight(fieldContext),
textAlignVertical: TextAlignVertical.center,
onSubmitted: (value) { 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. // The route's closing animation can still read its text controller.
await Future<void>.delayed(const Duration(milliseconds: 200)); await Future<void>.delayed(const Duration(milliseconds: 200));
@@ -160,20 +245,26 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
} }
@override @override
Widget build(BuildContext context) => ListenableBuilder( Widget build(BuildContext context) {
listenable: ref.watch(mediaBrowserProvider(widget.projectId)), final browser = ref.watch(mediaBrowserProvider(widget.projectId));
builder: (context, _) => _buildBrowser(context), // 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(
ref.watch(externalMediaImportProvider(widget.projectId)); projectsProvider.select(
final workspace = ref.watch(projectsProvider).asData?.value; (value) => (
value.value?.activeProject?.id,
value.value?.assets,
value.value?.timeline?.id,
value.value?.projectBusy,
),
),
);
final workspace = ref.read(projectsProvider).value;
final active = workspace?.activeProject?.id == widget.projectId; 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 timelineId = active ? workspace?.timeline?.id : null;
final timeline = timelineId == null final timeline = timelineId == null
? null ? null
@@ -181,12 +272,40 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
.watch(editorTimelineProvider(widget.projectId, timelineId)) .watch(editorTimelineProvider(widget.projectId, timelineId))
.asData .asData
?.value; ?.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( ? Center(
child: Padding( child: Padding(
padding: const EdgeInsets.all(AppSpacing.medium), padding: const EdgeInsets.all(AppSpacing.medium),
child: Text( child: Text(
_filter != MediaFilter.all widget.desktop && _browser.query.trim().isNotEmpty
? context.l10n.noMatchingMedia
: _filter != MediaFilter.all
? context.l10n.noMediaOfType(_filter.label(context)) ? context.l10n.noMediaOfType(_filter.label(context))
: _desktop : _desktop
? context.l10n.dragMediaHint ? context.l10n.dragMediaHint
@@ -197,14 +316,30 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
) )
: LayoutBuilder( : LayoutBuilder(
builder: (context, constraints) { builder: (context, constraints) {
const spacing = AppSpacing.small; final spacing = widget.desktop
final width = math.max( ? DesktopMediaMetrics.gap
1.0, : widget.compact
constraints.maxWidth - AppSpacing.compact * 2, ? AppSpacing.gap
); : AppSpacing.small;
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( final columns = math.max(
1, 1,
((width + spacing) / (maximumMediaGridTileWidth + spacing)) widget.desktop
? DesktopMediaMetrics.columns(
width,
_browser.gridSize.targetWidth,
)
: widget.compact
? ((width + spacing) /
(maximumCompactMediaGridTileWidth + spacing))
.ceil()
: ((width + spacing) /
(maximumMediaGridTileWidth + spacing))
.ceil(), .ceil(),
); );
final tileWidth = (width - spacing * (columns - 1)) / columns; final tileWidth = (width - spacing * (columns - 1)) / columns;
@@ -212,6 +347,41 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
final labelHeight = final labelHeight =
MediaQuery.textScalerOf(context).scale(textStyle.fontSize!) * MediaQuery.textScalerOf(context).scale(textStyle.fontSize!) *
(textStyle.height ?? 1.2); (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) { Widget item(BuildContext context, int index) {
final asset = assets[index]; final asset = assets[index];
return Consumer( return Consumer(
@@ -225,7 +395,11 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
final unavailable = final unavailable =
availability != null && availability != null &&
availability != MediaAvailability.available; 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)), key: ValueKey(('media-menu', asset.id)),
itemsBuilder: (_) { itemsBuilder: (_) {
final available = ref final available = ref
@@ -233,33 +407,36 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
.asData .asData
?.value; ?.value;
final canEdit = final canEdit =
available?.activeProject?.id == widget.projectId && available?.activeProject?.id ==
widget.projectId &&
available?.projectBusy == false && available?.projectBusy == false &&
!_checkingDrop; !_checkingDrop;
final sequence = timeline?.activeSequenceId; final sequence = timeline?.activeSequenceId;
return [ return [
AppMenuItem( AppMenuItem(
label: context.l10n.addToTimeline, label: context.l10n.addToTimeline,
icon: Icons.add, icon: AppIcons.add,
onPressed: onPressed:
canEdit && canEdit &&
!unavailable && !unavailable &&
sequence != null && sequence != null &&
available?.timeline?.id == timelineId available?.timeline?.id == timelineId
? () => ? () => _action(
_action(() => _browser.insertAsset(asset)) () => _browser.insertAsset(asset),
)
: null, : null,
), ),
AppMenuItem( AppMenuItem(
label: context.l10n.rename, label: context.l10n.rename,
icon: Icons.drive_file_rename_outline, icon: AppIcons.rename,
onPressed: canEdit ? () => _rename(asset) : null, onPressed: canEdit ? () => _rename(asset) : null,
), ),
AppMenuItem( AppMenuItem(
label: defaultTargetPlatform == TargetPlatform.macOS label:
defaultTargetPlatform == TargetPlatform.macOS
? context.l10n.revealFinder ? context.l10n.revealFinder
: context.l10n.revealFileManager, : context.l10n.revealFileManager,
icon: Icons.folder_open, icon: AppIcons.folderOpen,
onPressed: canEdit && _desktop onPressed: canEdit && _desktop
? () => _action(() => _browser.reveal(asset)) ? () => _action(() => _browser.reveal(asset))
: null, : null,
@@ -267,7 +444,7 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
const AppMenuSeparator(), const AppMenuSeparator(),
AppMenuItem( AppMenuItem(
label: context.l10n.removeMedia, label: context.l10n.removeMedia,
icon: Icons.delete_outline, icon: AppIcons.delete,
destructive: true, destructive: true,
onPressed: canEdit ? () => _remove(asset) : null, onPressed: canEdit ? () => _remove(asset) : null,
), ),
@@ -276,12 +453,13 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
child: Listener( child: Listener(
onPointerDown: (event) { onPointerDown: (event) {
if (event.buttons == 2) { if (event.buttons == 2) {
setState(() => _selectedAssetId = asset.id); _selectedAssetId = asset.id;
} }
}, },
child: _SelectableAsset( child: _SelectableAsset(
key: ValueKey(asset.id), key: ValueKey(asset.id),
grid: _isGrid, grid: _isGrid,
desktop: widget.desktop,
drag: MediaAssetDrag( drag: MediaAssetDrag(
projectId: widget.projectId, projectId: widget.projectId,
assetId: asset.id, assetId: asset.id,
@@ -290,53 +468,135 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
draggable: draggable:
widget.draggable && widget.draggable &&
!workspace!.projectBusy && !workspace!.projectBusy &&
!_checkingDrop && !presentation.$2 &&
!unavailable, !unavailable,
selected: _selectedAssetId == asset.id, selected: presentation.$1,
onTap: () => _browser.selectAsset(asset), onTap: () => _browser.selectAsset(asset),
child: _assetTile(asset, availability), child: _assetTile(asset, availability),
), ),
), ),
),
); );
}, },
); );
} }
return ScrollEdgeFadeBuilder( Widget scrollView(ScrollController controller) => !_isGrid
key: ValueKey(('media-scroll-fade', widget.projectId, _isGrid)), ? widget.desktop
builder: (controller) => !_isGrid ? ListView.builder(
? ListView.separated( key: PageStorageKey((
key: PageStorageKey(('media-list', widget.projectId)), 'media-list',
widget.projectId,
)),
controller: controller, controller: controller,
padding: const EdgeInsets.all(AppSpacing.compact), 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, itemCount: assets.length,
itemBuilder: item, itemBuilder: item,
separatorBuilder: (_, _) => separatorBuilder: (_, _) =>
const SizedBox(height: AppSpacing.small), SizedBox(height: spacing),
) )
: GridView.builder( : GridView.builder(
key: PageStorageKey(('media-grid', widget.projectId)), key: PageStorageKey(('media-grid', widget.projectId)),
controller: controller, controller: controller,
padding: const EdgeInsets.all(AppSpacing.compact), padding: EdgeInsets.all(padding),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: columns, crossAxisCount: columns,
crossAxisSpacing: spacing, crossAxisSpacing: spacing,
mainAxisSpacing: AppSpacing.compact, mainAxisSpacing: widget.desktop || widget.compact
mainAxisExtent: ? spacing
tileWidth * 9 / 16 + : AppSpacing.compact,
AppSpacing.small + mainAxisExtent: widget.desktop
? desktopExtent
: tileWidth * 9 / 16 +
(widget.compact
? AppSpacing.gap
: AppSpacing.small) +
labelHeight + labelHeight +
2, 2,
), ),
itemCount: assets.length, itemCount: assets.length,
itemBuilder: item, 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) { Widget _assetTile(AssetDocument asset, MediaAvailability? availability) {
if (widget.desktop) {
return DesktopMediaAssetTile(
asset: asset,
grid: _isGrid,
availability: availability,
);
}
final unavailable = final unavailable =
availability != null && availability != MediaAvailability.available; availability != null && availability != MediaAvailability.available;
final cover = unavailable final cover = unavailable
@@ -369,7 +629,7 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
aspectRatio: 16 / 9, aspectRatio: 16 / 9,
child: ColoredBox( child: ColoredBox(
color: AppSurfaces.of(context).previewBackground, color: AppSurfaces.of(context).previewBackground,
child: const Icon(Icons.insert_drive_file_outlined), child: const Icon(AppIcons.file),
), ),
), ),
}; };
@@ -403,17 +663,35 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
], ],
), ),
), ),
const SizedBox(height: AppSpacing.small), SizedBox(height: widget.compact ? AppSpacing.gap : AppSpacing.small),
name, name,
], ],
); );
} }
} }
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 { class _SelectableAsset extends StatelessWidget {
const _SelectableAsset({ const _SelectableAsset({
super.key, super.key,
required this.grid, required this.grid,
this.desktop = false,
required this.selected, required this.selected,
required this.drag, required this.drag,
required this.name, required this.name,
@@ -424,6 +702,7 @@ class _SelectableAsset extends StatelessWidget {
final bool selected; final bool selected;
final bool grid; final bool grid;
final bool desktop;
final MediaAssetDrag drag; final MediaAssetDrag drag;
final String name; final String name;
final bool draggable; final bool draggable;
@@ -438,7 +717,36 @@ class _SelectableAsset extends StatelessWidget {
); );
final tile = Semantics( final tile = Semantics(
selected: selected, 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( 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, onTap: onTap,
hoverColor: Colors.transparent, hoverColor: Colors.transparent,
highlightColor: Colors.transparent, highlightColor: Colors.transparent,
@@ -14,6 +14,8 @@ import '../../workspace/timeline_provider.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'resource_section.dart';
enum MediaFilter { enum MediaFilter {
all(null), all(null),
image('image'), image('image'),
@@ -24,6 +26,18 @@ enum MediaFilter {
final String? kind; 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>(( final mediaBrowserProvider = Provider.family<MediaBrowserController, String>((
ref, ref,
projectId, projectId,
@@ -41,8 +55,9 @@ class MediaBrowserController extends ChangeNotifier {
final feedback = MediaImportFeedbackController(); final feedback = MediaImportFeedbackController();
bool _working = false; bool _working = false;
bool _disposed = false; bool _disposed = false;
bool get busy => bool get importing =>
_working || _ref.read(externalMediaImportProvider(projectId)).isLoading; _ref.read(externalMediaImportProvider(projectId)).isLoading;
bool get busy => _working || importing;
bool get active => bool get active =>
!_disposed && !_disposed &&
_ref.mounted && _ref.mounted &&
@@ -81,7 +96,11 @@ class MediaBrowserController extends ChangeNotifier {
.importFiles(files); .importFiles(files);
final asset = result?.selected.firstOrNull; final asset = result?.selected.firstOrNull;
if (!_disposed && asset != null) { if (!_disposed && asset != null) {
_resourceSection = ResourceSection.imported;
_selectedAssetId = asset.id; _selectedAssetId = asset.id;
if (!asset.name.toLowerCase().contains(_query.trim().toLowerCase())) {
_query = '';
}
if (_filter != MediaFilter.all && if (_filter != MediaFilter.all &&
asset.metadata['kind'] != _filter.kind) { asset.metadata['kind'] != _filter.kind) {
_filter = MediaFilter.all; _filter = MediaFilter.all;
@@ -172,23 +191,87 @@ class MediaBrowserController extends ChangeNotifier {
String? _selectedAssetId; String? _selectedAssetId;
MediaFilter _filter = MediaFilter.all; MediaFilter _filter = MediaFilter.all;
bool _grid = true; 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; String? get selectedAssetId => _selectedAssetId;
MediaFilter get filter => _filter; MediaFilter get filter => _filter;
bool get grid => _grid; 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) { set selectedAssetId(String? value) {
if (_selectedAssetId == value) return;
_selectedAssetId = value; _selectedAssetId = value;
notifyListeners(); notifyListeners();
} }
set filter(MediaFilter value) { set filter(MediaFilter value) {
if (_filter == value) return;
_filter = value; _filter = value;
notifyListeners(); notifyListeners();
} }
set grid(bool value) { set grid(bool value) {
if (_grid == value) return;
_grid = value; _grid = value;
notifyListeners(); notifyListeners();
} }
set gridSize(MediaGridSize value) {
if (_gridSize == value) return;
_gridSize = value;
notifyListeners();
}
} }
@@ -1,3 +1,4 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../../l10n/l10n.dart'; import '../../l10n/l10n.dart';
@@ -74,7 +75,7 @@ class _MediaImportFeedbackListenerState
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
_scheduled = false; _scheduled = false;
if (!mounted || !_visible || !widget.feedback.hasPending) return; if (!mounted || !_visible || !widget.feedback.hasPending) return;
final messenger = ScaffoldMessenger.maybeOf(context); final messenger = ErrorNotificationHost.maybeOf(context);
if (messenger == null) return; if (messenger == null) return;
for (final result in widget.feedback.takePending()) { for (final result in widget.feedback.takePending()) {
final messages = [ final messages = [
@@ -84,8 +85,13 @@ class _MediaImportFeedbackListenerState
'${failure.name}: ${context.l10n.failureMessage(failure.failure)}', '${failure.name}: ${context.l10n.failureMessage(failure.failure)}',
if (result?.failed == true) context.l10n.noImportableFiles, if (result?.failed == true) context.l10n.noImportableFiles,
]; ];
messenger.showSnackBar( messenger.show(
SnackBar( ErrorNotification(
details: [
for (final failure
in result?.result?.failures ?? <MediaImportFailure>[])
'${failure.name}: code=${failure.failure.code.name}\n${failure.failure.diagnostic ?? ''}',
].join('\n'),
content: ConstrainedBox( content: ConstrainedBox(
constraints: const BoxConstraints(maxHeight: 180), constraints: const BoxConstraints(maxHeight: 180),
child: SingleChildScrollView(child: Text(messages.join('\n'))), child: SingleChildScrollView(child: Text(messages.join('\n'))),
@@ -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;
}
+26 -13
View File
@@ -1,3 +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/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
@@ -38,8 +40,19 @@ class TouchMediaBrowser extends ConsumerWidget {
@override @override
Widget build(BuildContext context, WidgetRef ref) { Widget build(BuildContext context, WidgetRef ref) {
final browser = ref.watch(mediaBrowserProvider(projectId)); final browser = ref.watch(mediaBrowserProvider(projectId));
ref.watch(externalMediaImportProvider(projectId)); ref.watch(
final workspace = ref.watch(projectsProvider).value; 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 final timelineId = workspace?.activeProject?.id == projectId
? workspace?.timeline?.id ? workspace?.timeline?.id
: null; : null;
@@ -71,20 +84,20 @@ class TouchMediaBrowser extends ConsumerWidget {
height: 56, height: 56,
child: Row( child: Row(
children: [ children: [
SizedBox.square( SizedBox(
dimension: 48, height: 48,
child: IconButton( child: TextButton(
key: const Key('media-import-button'), key: const Key('media-import-button'),
tooltip: context.l10n.importMedia,
onPressed: browser.canImport onPressed: browser.canImport
? () => pickMediaFiles(browser) ? () => pickMediaFiles(browser)
: null, : null,
icon: const Icon(Icons.add), child: Text(context.l10n.importMedia),
), ),
), ),
Expanded( Expanded(
child: DropdownButton<MediaFilter>( child: DropdownButton<MediaFilter>(
key: const Key('media-category-picker'), key: const Key('media-category-picker'),
icon: const Icon(AppIcons.expandMore),
isExpanded: true, isExpanded: true,
underline: const SizedBox.shrink(), underline: const SizedBox.shrink(),
value: browser.filter, value: browser.filter,
@@ -109,8 +122,8 @@ class TouchMediaBrowser extends ConsumerWidget {
: context.l10n.gridLayout, : context.l10n.gridLayout,
icon: Icon( icon: Icon(
browser.grid browser.grid
? Icons.view_list_outlined ? AppIcons.listView
: Icons.grid_view_outlined, : AppIcons.gridView,
), ),
onPressed: () => browser.grid = !browser.grid, onPressed: () => browser.grid = !browser.grid,
), ),
@@ -118,7 +131,7 @@ class TouchMediaBrowser extends ConsumerWidget {
], ],
), ),
), ),
if (browser.busy) const LinearProgressIndicator(), if (browser.importing) const LinearProgressIndicator(),
Expanded( Expanded(
key: const Key('media-panel-body'), key: const Key('media-panel-body'),
child: MediaBrowserBody( child: MediaBrowserBody(
@@ -142,14 +155,14 @@ class TouchMediaBrowser extends ConsumerWidget {
selected, selected,
); );
if (!inserted && context.mounted) { if (!inserted && context.mounted) {
ScaffoldMessenger.of(context).showSnackBar( ErrorNotificationHost.of(context).show(
SnackBar( ErrorNotification(
content: Text(context.l10n.operationFailed), content: Text(context.l10n.operationFailed),
), ),
); );
} }
}, },
icon: const Icon(Icons.add), icon: const Icon(AppIcons.add),
label: Text( label: Text(
context.l10n.addToTimeline, context.l10n.addToTimeline,
maxLines: 1, maxLines: 1,
@@ -0,0 +1,603 @@
import 'package:flutter/material.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
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({
super.key,
required this.canImport,
required this.onImport,
required this.filter,
required this.onFilterChanged,
required this.grid,
required this.onToggleGrid,
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;
final VoidCallback onImport;
final MediaFilter filter;
final ValueChanged<MediaFilter> onFilterChanged;
final bool grid;
final VoidCallback onToggleGrid;
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();
}
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;
MediaFilter get filter => widget.filter;
ValueChanged<MediaFilter> get onFilterChanged =>
(value) => widget.onFilterChanged(value);
bool get grid => widget.grid;
VoidCallback get onToggleGrid =>
() => widget.onToggleGrid();
List<RecentProject> get projects => widget.projects;
String? get selectedProjectId => widget.selectedProjectId;
ValueChanged<RecentProject>? get onProjectSelected =>
widget.onProjectSelected;
@override
Widget build(BuildContext context) {
final configuration = (
filter,
grid,
widget.sort,
widget.gridSize,
widget.desktop,
widget.projectScoped,
canImport,
Theme.of(context),
Localizations.localeOf(context),
MediaQuery.textScalerOf(context),
Directionality.of(context),
);
if (_filterConfiguration != configuration) {
_filterConfiguration = configuration;
_filterControls = null;
}
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: AppTheme.isDesktop(context)
? AppDesktopMetrics.panelHeader
: AppControlSize.panelToolbar,
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: AppSidebarMetrics.outerPadding,
vertical: AppTheme.isDesktop(context)
? AppSpacing.tiny
: AppSpacing.gap,
),
child: child,
),
);
return Column(
key: const Key('media-panel-header'),
mainAxisSize: MainAxisSize.min,
children: [
row(
const Key('media-project-row'),
LayoutBuilder(
builder: (context, constraints) => Row(
children: [
Expanded(
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)
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 SizedBox(width: AppSpacing.tiny),
const Icon(
AppIcons.expandMore,
size: AppIconSize.header,
),
],
),
),
),
),
const SizedBox(width: AppSpacing.tiny),
ConstrainedBox(
constraints: BoxConstraints(
maxWidth: (constraints.maxWidth * .45).clamp(
28,
double.infinity,
),
),
child: SizedBox(
height: AppControlSize.headerButton,
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,
),
),
),
),
),
],
),
),
),
_filterControls ??= row(
const Key('media-filter-row'),
Row(
children: [
Expanded(
child: Align(
alignment: AlignmentDirectional.centerStart,
child: SizedBox(
width: 88,
height: AppControlSize.headerButton,
child: Semantics(
label: context.l10n.mediaCategory,
child: AppDropdownMenu(
items: [
for (final option in MediaFilter.values)
AppMenuItem(
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 SizedBox(width: AppSpacing.tiny),
const Icon(
AppIcons.expandMore,
size: AppIconSize.header,
),
],
),
),
),
),
),
),
),
const SizedBox(width: AppSpacing.tiny),
SizedBox.square(
dimension: AppControlSize.headerButton,
child: IconButton(
key: const Key('media-layout-toggle'),
onPressed: onToggleGrid,
icon: Icon(
grid ? AppIcons.listView : AppIcons.gridView,
size: AppIconSize.header,
),
tooltip: grid
? context.l10n.listLayout
: context.l10n.gridLayout,
),
),
],
),
),
],
);
}
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),
),
),
),
);
}
+134 -116
View File
@@ -1,19 +1,22 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../l10n/l10n.dart';
import '../../integrations/platform/native_project_drop_region.dart'; import '../../integrations/platform/native_project_drop_region.dart';
import '../../integrations/platform/platform_capabilities.dart'; import '../../integrations/platform/platform_capabilities.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart'; import 'package:cutdex_ui/widgets.dart';
import '../../shared/widgets/drop_to_add_overlay.dart'; import '../../shared/widgets/drop_to_add_overlay.dart';
import '../../shared/widgets/listenable_selector.dart';
import '../../workspace/external_media_import.dart'; import '../../workspace/external_media_import.dart';
import '../../workspace/projects.dart'; import '../../workspace/projects.dart';
import '../../workspace/project_state.dart';
import '../../l10n/l10n.dart';
import 'media_browser_body.dart'; import 'media_browser_body.dart';
import 'media_browser_toolbar.dart';
import 'media_browser_controller.dart'; import 'media_browser_controller.dart';
import 'media_browser_feedback.dart'; import 'media_browser_feedback.dart';
import 'resource_navigation.dart';
/// Desktop presentation owns compact controls and native file dragging. /// Desktop presentation owns compact controls and native file dragging.
class MediaPanel extends ConsumerStatefulWidget { class MediaPanel extends ConsumerStatefulWidget {
@@ -23,8 +26,12 @@ class MediaPanel extends ConsumerStatefulWidget {
this.backgroundColor, this.backgroundColor,
this.grid, this.grid,
this.onGridChanged, this.onGridChanged,
this.onSelectProject,
this.projectScoped = false,
}) : assert((grid == null) == (onGridChanged == null)); }) : assert((grid == null) == (onGridChanged == null));
final String projectId; final String? projectId;
final bool projectScoped;
final ValueChanged<RecentProject>? onSelectProject;
final Color? backgroundColor; final Color? backgroundColor;
final bool? grid; final bool? grid;
final ValueChanged<bool>? onGridChanged; final ValueChanged<bool>? onGridChanged;
@@ -34,20 +41,93 @@ class MediaPanel extends ConsumerStatefulWidget {
class _MediaPanelState extends ConsumerState<MediaPanel> { class _MediaPanelState extends ConsumerState<MediaPanel> {
bool _hovering = false; bool _hovering = false;
(String, bool)? _bodyConfiguration;
Widget? _body;
Widget _browserBody(String projectId, bool grid) {
final configuration = (projectId, grid);
if (_bodyConfiguration != configuration) {
_bodyConfiguration = configuration;
_body = MediaBrowserBody(
projectId: projectId,
grid: grid,
draggable: true,
compact: true,
desktop: true,
);
}
return _body!;
}
@override
void didUpdateWidget(covariant MediaPanel oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.projectId != widget.projectId) _hovering = false;
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
ref.watch(projectsProvider); final workspace = ref.watch(
final browser = ref.watch(mediaBrowserProvider(widget.projectId)); projectsProvider.select(
ref.watch(externalMediaImportProvider(widget.projectId)); (value) => (
value.value?.recent ?? const <RecentProject>[],
value.value?.projectBusy ?? false,
value.value?.activeProject?.id,
),
),
);
final projectId = widget.projectId;
final onSelectProject = workspace.$2 ? null : widget.onSelectProject;
if (projectId == null) {
return Material(
key: const Key('media-panel-surface'),
color: widget.backgroundColor ?? Colors.transparent,
child: Column(
children: [
MediaBrowserToolbar(
desktop: true,
projectScoped: widget.projectScoped,
projects: workspace.$1,
onProjectSelected: onSelectProject,
canImport: false,
onImport: () {},
filter: MediaFilter.all,
onFilterChanged: (_) {},
grid: true,
onToggleGrid: () {},
),
Expanded(child: Center(child: Text(context.l10n.selectProject))),
],
),
);
}
final browser = ref.watch(mediaBrowserProvider(projectId));
ref.watch(
externalMediaImportProvider(projectId).select((value) => value.isLoading),
);
final nativeDrop = ref.watch(platformCapabilitiesProvider).nativeFileDrop; final nativeDrop = ref.watch(platformCapabilitiesProvider).nativeFileDrop;
return ListenableBuilder( return ListenableSelector(
listenable: browser, listenable: browser,
select: () => (
browser.filter,
browser.grid,
browser.busy,
browser.importing,
browser.canImport,
browser.query,
browser.sort,
browser.gridSize,
browser.resourceSection,
),
builder: (context, _) { builder: (context, _) {
final grid = widget.grid ?? browser.grid; final grid = widget.grid ?? browser.grid;
final visible = final visible =
TickerMode.valuesOf(context).enabled && TickerMode.valuesOf(context).enabled &&
(ModalRoute.of(context)?.isCurrent ?? true); (ModalRoute.of(context)?.isCurrent ?? true);
final enabled = browser.canImport && visible; final enabled = browser.canImport && visible;
final browsingImports =
!widget.projectScoped ||
browser.resourceSection == ResourceSection.imported;
void toggleGrid() { void toggleGrid() {
final next = !grid; final next = !grid;
if (widget.onGridChanged case final onChanged?) { if (widget.onGridChanged case final onChanged?) {
@@ -61,132 +141,66 @@ class _MediaPanelState extends ConsumerState<MediaPanel> {
feedback: browser.feedback, feedback: browser.feedback,
child: Material( child: Material(
key: const Key('media-panel-surface'), key: const Key('media-panel-surface'),
color: widget.backgroundColor, color: widget.backgroundColor ?? Colors.transparent,
child: Stack( child: Stack(
fit: StackFit.expand, fit: StackFit.expand,
children: [ children: [
Column( Column(
children: [ children: [
SizedBox( MediaBrowserToolbar(
key: const Key('media-panel-header'), desktop: true,
height: AppControlSize.panelToolbar, projectScoped: widget.projectScoped,
child: Padding( resourceSection: browser.resourceSection,
padding: const EdgeInsets.all(AppSpacing.gap), onResourceSectionChanged: (value) =>
child: LayoutBuilder( browser.resourceSection = value,
builder: (context, constraints) { projects: workspace.$1,
final compact = constraints.maxWidth < 180; selectedProjectId: projectId,
final controls = Row( onProjectSelected: onSelectProject,
mainAxisSize: compact canImport: enabled,
? MainAxisSize.min onImport: () => pickMediaFiles(browser),
: MainAxisSize.max, filter: browser.filter,
children: [ onFilterChanged: (value) => browser.filter = value,
if (compact) grid: grid,
SizedBox.square( onToggleGrid: toggleGrid,
dimension: AppControlSize.headerButton, query: browser.query,
child: IconButton( onQueryChanged: (value) => browser.query = value,
key: const Key('media-import-button'), sort: browser.sort,
tooltip: context.l10n.importMedia, onSortChanged: (value) => browser.sort = value,
onPressed: enabled gridSize: browser.gridSize,
? () => pickMediaFiles(browser) onGridSizeChanged: (value) => browser.gridSize = value,
: null,
icon: const Icon(
Icons.add,
size: AppIconSize.header,
),
),
)
else
SizedBox(
height: AppControlSize.headerButton,
child: TextButton.icon(
key: const Key('media-import-button'),
style: AppTheme.toolbarButtonStyle(
context,
),
onPressed: enabled
? () => pickMediaFiles(browser)
: null,
icon: const Icon(
Icons.add,
size: AppIconSize.header,
),
label: Text(context.l10n.importMedia),
),
),
if (compact)
const SizedBox(width: AppSpacing.tiny)
else
const Spacer(),
SizedBox(
width: 76,
child: AppSelect<MediaFilter>(
emptyLabel: context.l10n.noMatchingOptions,
label: context.l10n.mediaCategory,
outlined: false,
controlHeight: AppControlSize.headerButton,
textStyle: AppTheme.toolbarTextStyle(
context,
),
value: browser.filter,
onChanged: (value) =>
browser.filter = value,
options: [
for (final filter in MediaFilter.values)
AppSelectOption(
filter,
filter.label(context),
),
],
),
),
const SizedBox(width: AppSpacing.tiny),
SizedBox.square(
dimension: AppControlSize.headerButton,
child: IconButton(
key: const Key('media-layout-toggle'),
onPressed: toggleGrid,
icon: Icon(
grid
? Icons.view_list_outlined
: Icons.grid_view_outlined,
size: AppIconSize.header,
),
tooltip: grid
? context.l10n.listLayout
: context.l10n.gridLayout,
),
),
],
);
return compact
? SingleChildScrollView(
key: const Key('media-header-scroll'),
scrollDirection: Axis.horizontal,
child: controls,
)
: controls;
},
),
),
), ),
Expanded( Expanded(
key: const Key('media-panel-body'), key: const Key('media-panel-body'),
child: MediaBrowserBody( child: widget.projectScoped
projectId: widget.projectId, ? IndexedStack(
grid: grid, index: browsingImports ? 0 : 1,
draggable: true, 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( const DelayedLoadingIndicator(
child: Align( child: Align(
alignment: Alignment.topCenter, alignment: Alignment.topCenter,
child: LinearProgressIndicator(), child: LinearProgressIndicator(),
), ),
), ),
if (_hovering && enabled) if (_hovering && enabled && browsingImports)
const DropToAddOverlay(key: Key('media-drop-highlight')), const DropToAddOverlay(key: Key('media-drop-highlight')),
], ],
), ),
@@ -194,7 +208,11 @@ class _MediaPanelState extends ConsumerState<MediaPanel> {
); );
if (!nativeDrop) return content; if (!nativeDrop) return content;
return NativeProjectDropRegion( return NativeProjectDropRegion(
enabled: visible && browser.active && (enabled || browser.busy), enabled:
browsingImports &&
visible &&
browser.active &&
(enabled || browser.busy),
onEnter: (_) { onEnter: (_) {
if (enabled) setState(() => _hovering = true); 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/l10n/l10n.dart';
import 'package:cutdex_sdk/project.dart'; import 'package:cutdex_sdk/project.dart';
@@ -11,6 +13,7 @@ import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart'; import 'package:cutdex_ui/widgets.dart';
import '../../shared/widgets/confirm_resource_download_cancel.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 '../../shared/widgets/processing_resource_download_dialog.dart';
import '../../workspace/timeline_session.dart'; import '../../workspace/timeline_session.dart';
@@ -268,11 +271,11 @@ class _TranscriptionDialogState extends ConsumerState<TranscriptionDialog> {
_closing = true; _closing = true;
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return; if (!mounted) return;
final messenger = ScaffoldMessenger.maybeOf(context); final notifications = ErrorNotificationHost.maybeOf(context);
final message = context.l10n.subtitleTaskStarted; final message = context.l10n.subtitleTaskStarted;
_dismissDialog(); _dismissDialog();
if (next is SubtitleStarted) { 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(subtitleDownloadProvider, (_, next) => handleResult(next));
ref.listen(_startProvider, (_, next) => handleResult(next)); ref.listen(_startProvider, (_, next) => handleResult(next));
return ListenableBuilder( return ListenableSelector<Object>(
listenable: widget.session, 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, _) { builder: (context, _) {
final service = widget.session.transcriptions; final service = widget.session.transcriptions;
if (service?.recognitionAvailable != true || if (service?.recognitionAvailable != true ||
@@ -1,6 +1,7 @@
import 'package:cutdex/l10n/l10n.dart'; import 'package:cutdex/l10n/l10n.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart'; import 'package:cutdex_ui/theme.dart';
import '../../workspace/media_availability.dart'; import '../../workspace/media_availability.dart';
@@ -34,7 +35,7 @@ class UnavailableMediaPlaceholder extends StatelessWidget {
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
Icon( Icon(
Icons.broken_image_outlined, AppIcons.imageUnavailable,
size: isPreview ? 32 : 24, size: isPreview ? 32 : 24,
color: theme.colorScheme.error, color: theme.colorScheme.error,
), ),
+3 -2
View File
@@ -3,6 +3,7 @@ import 'package:flutter/material.dart';
import 'media_asset_cover.dart'; import 'media_asset_cover.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart'; import 'package:cutdex_ui/theme.dart';
class VisualAssetTile extends StatelessWidget { class VisualAssetTile extends StatelessWidget {
@@ -25,8 +26,8 @@ class VisualAssetTile extends StatelessWidget {
fallback: Center( fallback: Center(
child: Icon( child: Icon(
asset.metadata['kind'] == 'image' asset.metadata['kind'] == 'image'
? Icons.image_outlined ? AppIcons.image
: Icons.movie_outlined, : AppIcons.video,
size: AppIconSize.emptyState, size: AppIconSize.emptyState,
color: Theme.of(context).colorScheme.onSurfaceVariant, color: Theme.of(context).colorScheme.onSurfaceVariant,
), ),
@@ -5,6 +5,7 @@ import 'package:flutter/material.dart';
import '../../l10n/l10n.dart'; import '../../l10n/l10n.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart'; import 'package:cutdex_ui/theme.dart';
class FullscreenPlaybackBar extends StatefulWidget { class FullscreenPlaybackBar extends StatefulWidget {
@@ -84,7 +85,7 @@ class _FullscreenPlaybackBarState extends State<FullscreenPlaybackBar> {
alignment: Alignment.centerLeft, alignment: Alignment.centerLeft,
child: _button( child: _button(
context, context,
Icons.first_page, AppIcons.seekStart,
context.l10n.previewGoToStart, context.l10n.previewGoToStart,
enabled ? () => widget.onSeek!(0) : null, enabled ? () => widget.onSeek!(0) : null,
), ),
@@ -94,20 +95,20 @@ class _FullscreenPlaybackBarState extends State<FullscreenPlaybackBar> {
children: [ children: [
_button( _button(
context, context,
Icons.skip_previous, AppIcons.previousFrame,
context.l10n.previewPreviousFrame, context.l10n.previewPreviousFrame,
enabled && _position > 0 ? () => _step(-1) : null, enabled && _position > 0 ? () => _step(-1) : null,
), ),
_button( _button(
context, context,
widget.playing ? Icons.pause : Icons.play_arrow, widget.playing ? AppIcons.pause : AppIcons.play,
widget.playing ? context.l10n.pause : context.l10n.play, widget.playing ? context.l10n.pause : context.l10n.play,
widget.onPlayPause, widget.onPlayPause,
size: 32, size: 32,
), ),
_button( _button(
context, context,
Icons.skip_next, AppIcons.nextFrame,
context.l10n.previewNextFrame, context.l10n.previewNextFrame,
enabled && _position < widget.durationTick enabled && _position < widget.durationTick
? () => _step(1) ? () => _step(1)
@@ -119,7 +120,7 @@ class _FullscreenPlaybackBarState extends State<FullscreenPlaybackBar> {
alignment: Alignment.centerRight, alignment: Alignment.centerRight,
child: _button( child: _button(
context, context,
Icons.fullscreen_exit, AppIcons.exitFullscreen,
context.l10n.exitPreviewFullscreen, context.l10n.exitPreviewFullscreen,
widget.onExit, widget.onExit,
key: const Key('preview-fullscreen'), 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_ui/theme.dart';
import 'package:cutdex_native/cutdex_native.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. /// Moves the existing preview into the root overlay, retaining its native view.
class PreviewFullscreenHost extends StatefulWidget { class PreviewFullscreenHost extends StatefulWidget {
@@ -135,7 +136,11 @@ class PreviewFullscreenLayout extends StatelessWidget {
fit: StackFit.expand, fit: StackFit.expand,
children: [ children: [
Positioned.fill( Positioned.fill(
bottom: fullscreen ? 0 : AppControlSize.panelHeader, bottom: fullscreen
? 0
: AppTheme.isDesktop(context)
? AppDesktopMetrics.playbackBar
: AppControlSize.panelHeader,
child: canvas, child: canvas,
), ),
Align( Align(
@@ -158,7 +163,7 @@ class PreviewFullscreenLayout extends StatelessWidget {
borderRadius: BorderRadius.circular(AppRadius.large), borderRadius: BorderRadius.circular(AppRadius.large),
) )
: null, : null,
child: toolbar, child: NativePreviewOcclusion(child: toolbar),
), ),
), ),
], ],
+300 -102
View File
@@ -1,3 +1,5 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import '../../diagnostics/app_diagnostics.dart'; import '../../diagnostics/app_diagnostics.dart';
import 'dart:async'; import 'dart:async';
@@ -14,9 +16,11 @@ import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:cutdex_ui/icons.dart';
import 'package:cutdex_ui/theme.dart'; import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart'; import 'package:cutdex_ui/widgets.dart';
import '../../shared/widgets/listenable_selector.dart';
import '../../workspace/media_availability.dart'; import '../../workspace/media_availability.dart';
import '../../workspace/preview_controller_registry.dart'; import '../../workspace/preview_controller_registry.dart';
import '../../workspace/preview_target.dart'; import '../../workspace/preview_target.dart';
@@ -115,9 +119,10 @@ FutureOr<PreviewController?> _preparePreview(
} }
try { try {
if (!ref.mounted) throw StateError('Editor closed'); if (!ref.mounted) throw StateError('Editor closed');
final result = ref final registry = ref.read(previewControllerRegistryProvider);
.read(previewControllerRegistryProvider) final release = registry.retain(ids);
.prepare(ids, timeline); ref.onDispose(release);
final result = registry.prepare(ids, timeline);
if (result case Future<PreviewController?> future) { if (result case Future<PreviewController?> future) {
return future.catchError((Object error, StackTrace stack) { return future.catchError((Object error, StackTrace stack) {
AppDiagnostics.failure( AppDiagnostics.failure(
@@ -148,13 +153,19 @@ class EditorPreviewPanel extends StatelessWidget {
super.key, super.key,
required this.projectId, required this.projectId,
required this.timelineId, required this.timelineId,
this.pending = false,
}); });
final String projectId; final String projectId;
final String timelineId; final String timelineId;
final bool pending;
@override @override
Widget build(BuildContext context) => PreviewFullscreenHost( Widget build(BuildContext context) => PreviewFullscreenHost(
child: _EditorPreviewContent(projectId: projectId, timelineId: timelineId), child: _EditorPreviewContent(
projectId: projectId,
timelineId: timelineId,
pending: pending,
),
); );
} }
@@ -162,18 +173,47 @@ class _EditorPreviewContent extends ConsumerWidget {
const _EditorPreviewContent({ const _EditorPreviewContent({
required this.projectId, required this.projectId,
required this.timelineId, required this.timelineId,
this.pending = false,
}); });
final String projectId; final String projectId;
final String timelineId; final String timelineId;
final bool pending;
@override @override
Widget build(BuildContext context, WidgetRef ref) { Widget build(BuildContext context, WidgetRef ref) {
final provider = editorPreviewProvider(projectId, timelineId); final provider = editorPreviewProvider(projectId, timelineId);
final state = ref.watch(provider); final watched = pending
? const AsyncData<PreviewController?>(null)
: ref.watch(provider);
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);
final controller = state.asData?.value; final controller = state.asData?.value;
Widget panel() { Widget panel() => WorkspacePanel(
headerHeight: 0,
showHeaderDivider: false,
child: PreviewFullscreenLayout(
canvas: ListenableSelector(
listenable: controller,
select: () => (
controller?.canvas,
controller?.session,
controller?.error,
(controller?.durationTick ?? 0) > 0,
),
builder: (context, _) {
final activeController = controller; final activeController = controller;
final defaultCanvas =
pending ||
(state.isLoading && !state.hasError && controller == null);
final showCanvas = final showCanvas =
defaultCanvas ||
state.hasError || state.hasError ||
(activeController != null && (activeController != null &&
(activeController.durationTick > 0 || (activeController.durationTick > 0 ||
@@ -183,47 +223,64 @@ class _EditorPreviewContent extends ConsumerWidget {
PreviewFullscreenScope.of(context)?.fullscreen != true && PreviewFullscreenScope.of(context)?.fullscreen != true &&
activeController.session != null && activeController.session != null &&
activeController.error == null activeController.error == null
? (Rect rect) => ListenableBuilder( ? (Rect rect) => ListenableSelector<Object>(
listenable: activeController.positionChanges, listenable: activeController.positionChanges,
select: () => (
activeController.positionTick,
activeController.selectedVisualIds.isNotEmpty,
activeController.maskEditingElement,
activeController.obscureEditingElement,
),
builder: (context, _) => Theme( builder: (context, _) => Theme(
data: AppTheme.previewCanvasTheme, data: AppTheme.previewCanvasTheme,
child: NativePreviewOverlay(
session: activeController.session!,
enabled:
activeController.selectedVisualIds.isNotEmpty ||
activeController.maskEditingElement != null ||
activeController.obscureEditingElement != null,
child: child:
activeController.maskEditingElement != null || activeController.maskEditingElement != null ||
activeController.obscureEditingElement != null activeController.obscureEditingElement != null
? MaskInteractionOverlay( ? MaskInteractionOverlay(
controller: activeController, controller: activeController,
canvasRect: rect, canvasRect: rect,
obscure: activeController.obscureEditingElement != null, obscure:
activeController.obscureEditingElement !=
null,
) )
: PreviewInteractionOverlay( : PreviewInteractionOverlay(
onError: (_) => ScaffoldMessenger.maybeOf(context) onError: (error) =>
?.showSnackBar( ErrorNotificationHost.maybeOf(
SnackBar( context,
)?.show(
ErrorNotification(
content: Text( content: Text(
context.l10n.canvasTransformFailed, context.l10n.canvasTransformFailed,
), ),
details: error.toString(),
), ),
), ),
controller: activeController, controller: activeController,
canvasRect: rect, canvasRect: rect,
), ),
), ),
),
) )
: null; : null;
return WorkspacePanel( return showCanvas
headerHeight: 0,
showHeaderDivider: false,
child: PreviewFullscreenLayout(
canvas: showCanvas
? Padding( ? Padding(
padding: padding:
PreviewFullscreenScope.of(context)?.fullscreen == true PreviewFullscreenScope.of(context)?.fullscreen == true
? EdgeInsets.zero ? EdgeInsets.zero
: AppTheme.isDesktop(context)
? const EdgeInsets.all(AppDesktopMetrics.panelPadding)
: AppSpacing.panelSection, : AppSpacing.panelSection,
child: PreviewCanvas( child: PreviewCanvas(
alignment: Alignment.center, alignment: Alignment.center,
horizontalPadding: 0, horizontalPadding: 0,
backgroundColor: AppSurfaces.of(context).previewBackground, backgroundColor: AppSurfaces.of(context)
.previewBackground,
overlayBuilder: overlayBuilder, overlayBuilder: overlayBuilder,
aspectRatio: aspectRatio:
(activeController?.canvas ?? ProjectCanvas.widescreen) (activeController?.canvas ?? ProjectCanvas.widescreen)
@@ -231,9 +288,16 @@ class _EditorPreviewContent extends ConsumerWidget {
child: Theme( child: Theme(
data: AppTheme.previewCanvasTheme, data: AppTheme.previewCanvasTheme,
child: Builder( child: Builder(
builder: (context) => state.when( builder: (context) => defaultCanvas
loading: () => const DelayedLoadingIndicator( ? const ColoredBox(
child: Center(child: CircularProgressIndicator()), key: Key('preview-default-frame'),
color: Colors.black,
)
: state.when(
skipLoadingOnReload: true,
loading: () => const ColoredBox(
key: Key('preview-default-frame'),
color: Colors.black,
), ),
error: (error, _) => Center( error: (error, _) => Center(
child: SingleChildScrollView( child: SingleChildScrollView(
@@ -243,10 +307,15 @@ class _EditorPreviewContent extends ConsumerWidget {
children: [ children: [
Text( Text(
error is EditorSessionStartupException error is EditorSessionStartupException
? context.l10n.editorSessionStartFailed ? context
.l10n
.editorSessionStartFailed
: error is RuntimeException && : error is RuntimeException &&
error.code == 'unsupported' error.code ==
? context.l10n.nativePreviewUnsupported 'unsupported'
? context
.l10n
.nativePreviewUnsupported
: context.l10n.previewStartFailed, : context.l10n.previewStartFailed,
textAlign: TextAlign.center, textAlign: TextAlign.center,
), ),
@@ -289,10 +358,21 @@ class _EditorPreviewContent extends ConsumerWidget {
return Stack( return Stack(
fit: StackFit.expand, fit: StackFit.expand,
children: [ children: [
if (preview.session case final session?) if (preview.session case final session?
when preview.error == null &&
preview.durationTick > 0)
RuntimePreview(session: session), RuntimePreview(session: session),
ListenableBuilder( ListenableSelector(
listenable: preview.positionChanges, listenable: Listenable.merge([
preview,
preview.positionChanges,
]),
select: () => (
preview.error,
preview.unavailableAtPlayhead.join(
', ',
),
),
builder: (context, _) { builder: (context, _) {
final unavailable = final unavailable =
preview.unavailableAtPlayhead; preview.unavailableAtPlayhead;
@@ -302,18 +382,23 @@ class _EditorPreviewContent extends ConsumerWidget {
} }
return IgnorePointer( return IgnorePointer(
child: Align( child: Align(
alignment: Alignment.bottomCenter, alignment:
Alignment.bottomCenter,
child: Padding( child: Padding(
padding: const EdgeInsets.all( padding: const EdgeInsets.all(
AppSpacing.medium, AppSpacing.medium,
), ),
child: NativePreviewOcclusion(
child: Text( child: Text(
context.l10n.mediaOffline( context.l10n.mediaOffline(
unavailable.join(', '), unavailable.join(', '),
), ),
maxLines: 2, maxLines: 2,
overflow: TextOverflow.ellipsis, overflow:
textAlign: TextAlign.center, TextOverflow.ellipsis,
textAlign:
TextAlign.center,
),
), ),
), ),
), ),
@@ -332,7 +417,9 @@ class _EditorPreviewContent extends ConsumerWidget {
), ),
child: Text( child: Text(
preview.error == null preview.error == null
? context.l10n.noPreviewContent ? context
.l10n
.noPreviewContent
: previewErrorMessage( : previewErrorMessage(
preview.error!, preview.error!,
context.l10n, context.l10n,
@@ -350,11 +437,14 @@ class _EditorPreviewContent extends ConsumerWidget {
), ),
), ),
) )
: const SizedBox.expand(key: Key('empty-preview-area')), : const SizedBox.expand(key: Key('empty-preview-area'));
},
),
toolbar: _PreviewToolbar(controller: controller), toolbar: _PreviewToolbar(controller: controller),
), ),
); );
}
if (pending) return panel();
final target = ref.watch(previewTargetProvider(projectId, timelineId)); final target = ref.watch(previewTargetProvider(projectId, timelineId));
final navigation = ref.watch( final navigation = ref.watch(
@@ -381,12 +471,7 @@ class _EditorPreviewContent extends ConsumerWidget {
target.togglePlayback = controller == null target.togglePlayback = controller == null
? null ? null
: () => unawaited(controller.togglePlayback()); : () => unawaited(controller.togglePlayback());
return controller == null return panel();
? panel()
: ListenableBuilder(
listenable: controller,
builder: (_, _) => panel(),
);
}, },
), ),
}, },
@@ -410,8 +495,31 @@ class _SourcePreviewPanel extends ConsumerWidget {
.watch(mediaAvailabilityProvider(projectId, asset)) .watch(mediaAvailabilityProvider(projectId, asset))
.asData .asData
?.value; ?.value;
return ListenableBuilder( return CallbackShortcuts(
bindings: {
const SingleActivator(LogicalKeyboardKey.space): source.togglePlayback,
},
child: Focus(
autofocus: true,
child: WorkspacePanel(
title: AppTheme.isDesktop(context) ? null : asset.name,
showHeaderDivider: false,
headerHeight:
AppTheme.isDesktop(context) ||
PreviewFullscreenScope.of(context)?.fullscreen == true
? 0
: AppControlSize.panelHeader,
child: PreviewFullscreenLayout(
canvas: ListenableSelector(
listenable: source, listenable: source,
select: () => (
source.session,
source.image,
source.error,
source.busy,
source.aspectRatio,
source.audioOnly,
),
builder: (context, _) { builder: (context, _) {
// The availability probe can finish while a newly dropped file is // The availability probe can finish while a newly dropped file is
// still switching security-scoped leases. Once the runtime has opened // still switching security-scoped leases. Once the runtime has opened
@@ -422,25 +530,12 @@ class _SourcePreviewPanel extends ConsumerWidget {
availability != MediaAvailability.available && availability != MediaAvailability.available &&
source.session == null && source.session == null &&
source.image == null; source.image == null;
return CallbackShortcuts( return Padding(
bindings: {
const SingleActivator(LogicalKeyboardKey.space):
source.togglePlayback,
},
child: Focus(
autofocus: true,
child: WorkspacePanel(
title: asset.name,
showHeaderDivider: false,
headerHeight:
PreviewFullscreenScope.of(context)?.fullscreen == true
? 0
: AppControlSize.panelHeader,
child: PreviewFullscreenLayout(
canvas: Padding(
padding: padding:
PreviewFullscreenScope.of(context)?.fullscreen == true PreviewFullscreenScope.of(context)?.fullscreen == true
? EdgeInsets.zero ? EdgeInsets.zero
: AppTheme.isDesktop(context)
? const EdgeInsets.all(AppDesktopMetrics.panelPadding)
: AppSpacing.panelSection, : AppSpacing.panelSection,
child: PreviewCanvas( child: PreviewCanvas(
alignment: Alignment.center, alignment: Alignment.center,
@@ -492,6 +587,7 @@ class _SourcePreviewPanel extends ConsumerWidget {
return Stack( return Stack(
fit: StackFit.expand, fit: StackFit.expand,
children: [ children: [
if (!source.audioOnly)
RuntimePreview(session: session), RuntimePreview(session: session),
if (source.audioOnly) if (source.audioOnly)
IgnorePointer( IgnorePointer(
@@ -508,14 +604,14 @@ class _SourcePreviewPanel extends ConsumerWidget {
), ),
), ),
), ),
);
},
), ),
toolbar: _PreviewToolbar(controller: null, source: source), toolbar: _PreviewToolbar(controller: null, source: source),
), ),
), ),
), ),
); );
},
);
} }
} }
@@ -527,18 +623,91 @@ class _PreviewToolbar extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final listenable = source == null && controller != null if (PreviewFullscreenScope.of(context)?.fullscreen == true) {
? Listenable.merge([controller!, controller!.positionChanges]) return ListenableSelector(
: source; listenable: _clock,
if (listenable != null) { select: () => (
return ListenableBuilder( source?.positionTick ?? controller?.positionTick ?? 0,
listenable: listenable, source?.durationTick ?? controller?.durationTick ?? 0,
source?.frameDuration ?? controller?.frameDuration,
source?.playing ?? controller?.playing ?? false,
source?.canPlay ?? controller?.canPlay ?? false,
),
builder: (context, _) => _build(context), builder: (context, _) => _build(context),
); );
} }
return _build(context); return _build(context);
} }
Listenable? get _clock =>
source ??
(controller == null
? null
: Listenable.merge([controller!, controller!.positionChanges]));
RationalTime get _frameDuration =>
source?.frameDuration ??
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) { Widget _build(BuildContext context) {
final preview = controller; final preview = controller;
final playing = source?.playing ?? preview?.playing ?? false; final playing = source?.playing ?? preview?.playing ?? false;
@@ -551,30 +720,7 @@ class _PreviewToolbar extends StatelessWidget {
final duration = source?.durationTick ?? preview?.durationTick ?? 0; final duration = source?.durationTick ?? preview?.durationTick ?? 0;
final frameTick = TimelineClock.standard.toTicks(frameDuration); final frameTick = TimelineClock.standard.toTicks(frameDuration);
final canPlay = source?.canPlay ?? preview?.canPlay ?? false; final canPlay = source?.canPlay ?? preview?.canPlay ?? false;
Future<void> seek(int requested) async { Future<void> seek(int requested) => _seek(context, requested);
final lastTick = duration > 0
? ((duration - 1) ~/ frameTick) * frameTick
: 0;
final tick = requested.clamp(0, lastTick);
try {
final time = CommandTime(tick, TimelineClock.ticksPerSecond);
if (source case final source?) {
await source.control(SourcePreviewAction.seek, at: time);
} else if (preview?.activeSequence() case final sequence?) {
await preview!.controlPreview(
sequence,
PreviewAction.seek,
at: time,
);
}
} catch (error) {
if (context.mounted) {
ScaffoldMessenger.maybeOf(context)?.showSnackBar(
SnackBar(content: Text(previewErrorMessage(error, context.l10n))),
);
}
}
}
final sequence = preview?.activeSequence(); final sequence = preview?.activeSequence();
final view = sequence == null ? null : preview!.viewForSequence(sequence); final view = sequence == null ? null : preview!.viewForSequence(sequence);
@@ -612,19 +758,33 @@ class _PreviewToolbar extends StatelessWidget {
} }
return SizedBox( return SizedBox(
key: const Key('preview-toolbar'), key: const Key('preview-toolbar'),
height: AppControlSize.panelHeader, height: AppTheme.isDesktop(context)
? AppDesktopMetrics.playbackBar
: AppControlSize.panelHeader,
child: Padding( child: Padding(
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.compact), padding: const EdgeInsets.symmetric(horizontal: AppSpacing.compact),
child: Row( child: LayoutBuilder(
builder: (context, constraints) {
final controls = Row(
children: [ children: [
Expanded( Expanded(
child: Text.rich( child: ListenableSelector(
key: const Key('preview-time'),
listenable: _clock,
select: () => (
source?.positionTick ?? preview?.positionTick ?? 0,
source?.durationTick ?? preview?.durationTick ?? 0,
_frameDuration,
),
builder: (context, _) => Text.rich(
TextSpan( TextSpan(
children: [ children: [
TextSpan( TextSpan(
text: _time( text: _time(
source?.positionTick ?? preview?.positionTick ?? 0, source?.positionTick ??
frameDuration, preview?.positionTick ??
0,
_frameDuration,
), ),
style: TextStyle( style: TextStyle(
color: Theme.of(context).colorScheme.onSurface, color: Theme.of(context).colorScheme.onSurface,
@@ -632,9 +792,11 @@ class _PreviewToolbar extends StatelessWidget {
), ),
TextSpan( TextSpan(
text: text:
' / ${_time(source?.durationTick ?? preview?.durationTick ?? 0, frameDuration)}', ' / ${_time(source?.durationTick ?? preview?.durationTick ?? 0, _frameDuration)}',
style: TextStyle( style: TextStyle(
color: Theme.of(context).colorScheme.onSurfaceVariant, color: Theme.of(context)
.colorScheme
.onSurfaceVariant,
), ),
), ),
], ],
@@ -646,17 +808,41 @@ class _PreviewToolbar extends StatelessWidget {
), ),
), ),
), ),
IconButton( ),
if (AppTheme.isDesktop(context)) _frameButton(context, -1),
ListenableSelector(
listenable: source ?? preview,
select: () => (
source?.playing ?? preview?.playing ?? false,
source?.canPlay ?? preview?.canPlay ?? false,
),
builder: (context, value) {
final playing = value.$1;
return IconButton(
tooltip: playing ? context.l10n.pause : context.l10n.play, tooltip: playing ? context.l10n.pause : context.l10n.play,
onPressed: source != null onPressed: source != null
? (source!.canPlay ? source!.togglePlayback : null) ? (source!.canPlay ? source!.togglePlayback : null)
: preview != null && preview.canPlay : preview != null && preview.canPlay
? preview.togglePlayback ? preview.togglePlayback
: null, : null,
icon: Icon(playing ? Icons.pause : Icons.play_arrow), icon: Icon(playing ? AppIcons.pause : AppIcons.play),
);
},
), ),
if (AppTheme.isDesktop(context)) _frameButton(context, 1),
Expanded( Expanded(
child: Align( child: ListenableSelector(
listenable: source ?? preview,
select: () => (
preview?.canvas,
preview?.error,
preview?.hasUnavailableMedia,
preview?.busy,
preview?.session,
source?.session,
source?.image,
),
builder: (context, _) => Align(
alignment: Alignment.centerRight, alignment: Alignment.centerRight,
child: Row( child: Row(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
@@ -667,18 +853,20 @@ class _PreviewToolbar extends StatelessWidget {
IconButton( IconButton(
tooltip: context.l10n.retryPreview, tooltip: context.l10n.retryPreview,
onPressed: preview.busy ? null : preview.retry, onPressed: preview.busy ? null : preview.retry,
icon: const Icon(Icons.refresh), icon: const Icon(AppIcons.refresh),
), ),
const SizedBox(width: AppSpacing.gap), const SizedBox(width: AppSpacing.gap),
], ],
if (source == null && if (source == null &&
PreviewFullscreenScope.of(context)?.fullscreen != true) PreviewFullscreenScope.of(context)?.fullscreen !=
true)
Flexible( Flexible(
child: AppSelect<ProjectCanvas>( child: AppSelect<ProjectCanvas>(
emptyLabel: context.l10n.noMatchingOptions, emptyLabel: context.l10n.noMatchingOptions,
label: context.l10n.canvasRatio, label: context.l10n.canvasRatio,
outlined: false, outlined: false,
value: preview?.canvas ?? ProjectCanvas.widescreen, value:
preview?.canvas ?? ProjectCanvas.widescreen,
onChanged: preview?.setCanvas, onChanged: preview?.setCanvas,
options: [ options: [
for (final entry for (final entry
@@ -703,15 +891,25 @@ class _PreviewToolbar extends StatelessWidget {
: null, : null,
icon: Icon( icon: Icon(
fullscreen.fullscreen fullscreen.fullscreen
? Icons.fullscreen_exit ? AppIcons.exitFullscreen
: Icons.fullscreen, : AppIcons.fullscreen,
), ),
), ),
], ],
), ),
), ),
), ),
),
], ],
);
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),
],
);
},
),
),
);
}
@@ -1,3 +1,5 @@
import 'dart:async';
import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart';
@@ -58,8 +60,13 @@ class ConversationSelection extends _$ConversationSelection {
ref.onDispose(() { ref.onDispose(() {
if (_draftKey case final key?) composers.removeDraft(projectId, key); if (_draftKey case final key?) composers.removeDraft(projectId, key);
}); });
ref.watch( ref.listen(
projectsProvider.select((value) => value.value?.activeProject?.id), projectsProvider.select((value) => value.value?.activeProject?.id),
(_, next) {
if (next == projectId && state.selectedId != null) {
state = state.copyWith(initialized: false);
}
},
); );
final saved = savedConversationSelectionProvider(projectId); final saved = savedConversationSelectionProvider(projectId);
ref.listen(saved, (_, next) { ref.listen(saved, (_, next) {
@@ -97,17 +104,72 @@ class ConversationSidebar extends _$ConversationSidebar {
@override @override
Future<ConversationSnapshot> build() async { Future<ConversationSnapshot> build() async {
ref.listen(
projectsProvider.select((value) => value.value?.activeProject?.id),
(before, after) {
if (before != after) unawaited(_refreshContext(after));
},
);
await ref.watch( await ref.watch(
projectsProvider.selectAsync( projectsProvider.selectAsync(
(workspace) => ConversationWorkspaceKey( (workspace) => ConversationWorkspaceKey(
projectId: workspace.activeProject?.id,
projectIds: [for (final project in workspace.recent) project.id], projectIds: [for (final project in workspace.recent) project.id],
), ),
), ),
); );
_revision++; _revision++;
final workspace = ref.read(projectsProvider).requireValue; final workspace = ref.read(projectsProvider).requireValue;
return _load(workspace); final loaded = await _load(workspace);
if (!ref.mounted) return loaded;
final activeId = ref.read(projectsProvider).value?.activeProject?.id;
return activeId == loaded.projectId
? loaded
: _loadContext(loaded, activeId);
}
/// Project selection changes only contextual data, never the global groups.
Future<ConversationSnapshot> _loadContext(
ConversationSnapshot current,
String? projectId,
) async {
final repository = await ref.read(conversationRepositoryProvider.future);
final trashed = projectId == null
? const <ConversationMetadata>[]
: await repository.list(projectId, trash: true);
final selectedId = await ref.read(
savedConversationSelectionProvider(projectId).future,
);
return current.copyWith(
projectId: projectId,
trashed: List.unmodifiable(trashed),
selectedId: selectedId,
reloadFailed: false,
);
}
Future<void> _refreshContext(String? projectId) async {
final current = state.value;
if (current == null) return; // Initial loading resolves the latest context.
final revision = ++_revision;
state = AsyncData(
current.copyWith(
projectId: projectId,
trashed: const [],
selectedId: null,
),
);
try {
final next = await _loadContext(current, projectId);
if (ref.mounted &&
revision == _revision &&
ref.read(projectsProvider).value?.activeProject?.id == projectId) {
state = AsyncData(next);
}
} catch (_) {
if (ref.mounted && revision == _revision) {
state = AsyncData(state.requireValue.copyWith(reloadFailed: true));
}
}
} }
Future<ConversationSnapshot> _load(ProjectState workspace) async { Future<ConversationSnapshot> _load(ProjectState workspace) async {
@@ -135,7 +135,7 @@ final class ConversationSelectionProvider
} }
String _$conversationSelectionHash() => String _$conversationSelectionHash() =>
r'eef3c6c95f86b017e73d3244adccc257f717699b'; r'5b5036b69fd203ed7827d9f81d446786b7de373c';
/// Keeps a draft or explicit selection stable while the list refreshes. /// Keeps a draft or explicit selection stable while the list refreshes.
@@ -220,7 +220,7 @@ final class ConversationSidebarProvider
} }
String _$conversationSidebarHash() => String _$conversationSidebarHash() =>
r'13122a844ce87622c8d4919042e4dbefc69b790f'; r'ccb6d44f3c675b664a0e0925f9257b351061a899';
abstract class _$ConversationSidebar abstract class _$ConversationSidebar
extends $AsyncNotifier<ConversationSnapshot> { extends $AsyncNotifier<ConversationSnapshot> {
@@ -3,9 +3,11 @@ import 'package:flutter/material.dart';
import '../../l10n/l10n.dart'; import '../../l10n/l10n.dart';
import '../../workspace/project_state.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'; import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
class EmptyEditor extends StatelessWidget { class EmptyEditor extends StatelessWidget {
const EmptyEditor({ const EmptyEditor({
@@ -13,21 +15,46 @@ class EmptyEditor extends StatelessWidget {
required this.state, required this.state,
required this.headerLeading, required this.headerLeading,
required this.showProjectName, required this.showProjectName,
this.desktop = false,
this.experience = DeviceExperience.desktop,
}); });
final ProjectState state; final ProjectState state;
final Widget headerLeading; final Widget headerLeading;
final bool showProjectName; final bool showProjectName;
final bool desktop;
final DeviceExperience experience;
@override @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: [ children: [
SizedBox( SizedBox(
height: AppControlSize.panelHeader, height: desktop
? AppControlSize.panelToolbar
: AppControlSize.panelHeader,
child: Padding(
padding: desktop
? const EdgeInsets.symmetric(
horizontal: AppSidebarMetrics.outerPadding,
vertical: AppSpacing.gap,
)
: EdgeInsets.zero,
child: WindowHeaderPadding( child: WindowHeaderPadding(
child: Row( child: Row(
children: [ children: [
headerLeading, headerLeading,
if (!showProjectName) const Spacer(),
if (showProjectName) if (showProjectName)
Expanded( Expanded(
child: Text( child: Text(
@@ -42,6 +69,7 @@ class EmptyEditor extends StatelessWidget {
), ),
), ),
), ),
),
Expanded( Expanded(
child: Center( child: Center(
child: SingleChildScrollView( child: SingleChildScrollView(
@@ -50,7 +78,7 @@ class EmptyEditor extends StatelessWidget {
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
Icon( Icon(
Icons.movie_outlined, AppIcons.video,
size: AppIconSize.project, size: AppIconSize.project,
color: Theme.of(context).colorScheme.primary, color: Theme.of(context).colorScheme.primary,
), ),
@@ -77,40 +105,3 @@ class EmptyEditor extends StatelessWidget {
], ],
); );
} }
class ProjectLoadingRegion extends StatelessWidget {
const ProjectLoadingRegion({
super.key,
required this.loading,
required this.child,
});
final bool loading;
final Widget child;
@override
Widget build(BuildContext context) => Stack(
fit: StackFit.expand,
children: [
ExcludeFocus(
excluding: loading,
child: IgnorePointer(ignoring: loading, child: child),
),
if (loading)
DelayedLoadingIndicator(
child: Positioned.fill(
child: ColoredBox(
key: const Key('editor-project-loading'),
color: Theme.of(context).colorScheme.surface,
child: const Center(
child: SizedBox.square(
dimension: 20,
child: CircularProgressIndicator(strokeWidth: 2),
),
),
),
),
),
],
);
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,19 @@
import 'package:flutter/widgets.dart';
/// Keeps prepared content mounted until the next project is published.
class ProjectSwitchRegion extends StatelessWidget {
const ProjectSwitchRegion({
super.key,
required this.pendingProjectId,
required this.child,
});
final String? pendingProjectId;
final Widget child;
@override
Widget build(BuildContext context) => ExcludeFocus(
excluding: pendingProjectId != null,
child: IgnorePointer(ignoring: pendingProjectId != null, child: child),
);
}
+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),
],
),
),
),
),
),
),
),
),
),
);
}
}
Loaded 100 of 379 files, more files were not shown because too many files have changed in this diff. Show more