Compare commits
30
Commits
No files matched your search
@@ -0,0 +1,39 @@
|
||||
# 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.
|
||||
|
||||
# Default: consume exact platform releases from cutdex_native_flutter/native-dependencies.json.
|
||||
# Explicit pinned releases: CUTDEX_NATIVE_BUILD_MODE=artifacts (clear source overrides).
|
||||
# CUTDEX_NATIVE_BUILD_MODE=source
|
||||
|
||||
# Optional Windows native source override. Rustup/LLVM must be installed;
|
||||
# the plugin prepares the pinned Rust target and FFmpeg SDK automatically.
|
||||
# CUTDEX_WINDOWS_PATH=D:/workspace/cutdex-windows
|
||||
# FFMPEG_DIR=D:/tools/ffmpeg
|
||||
|
||||
# Artifacts mode only: use an extracted Windows native package.
|
||||
# CUTDEX_WINDOWS_PACKAGE_PATH=D:/packages/cutdex-windows
|
||||
# CUTDEX_WINDOWS_PACKAGE_SHA256=<verified Windows release ZIP digest>
|
||||
|
||||
# macOS / iOS native source development.
|
||||
# CUTDEX_APPLE_PATH=/Users/your-name/workspace/CutdexApple
|
||||
|
||||
# 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
|
||||
@@ -0,0 +1,110 @@
|
||||
# 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. `dependencies.json` fixes the Core release version,
|
||||
source commit and source ZIP SHA256, together with its bundled native Flutter
|
||||
version and commit. `.gitea/actions/prepare-flutter` downloads that published Core
|
||||
archive and verifies its SHA256 and `RELEASE.json` before extracting a job-local
|
||||
`.dependencies/cutdex_core`. The app and preview package both use its
|
||||
`native_flutter` directory, so Pub resolves one integration source.
|
||||
Core is hosted at `lingjhf/cutdex_core`; Flutter integration is hosted at
|
||||
`cutdex-native/cutdex_native_flutter`. Local source development uses the ignored
|
||||
`pubspec_overrides.yaml` sibling overrides. Release CI does not follow branches or
|
||||
need platform repository checkout steps.
|
||||
|
||||
Production Android/Windows CI defaults to `CUTDEX_NATIVE_BUILD_MODE=artifacts` and
|
||||
consumes the exact platform versions and Windows archive digest recorded by the
|
||||
Flutter integration. Set the repository variable to `source` only for development CI;
|
||||
that mode lets the Flutter integration fetch the platform's locked SHA during the
|
||||
build. Android uses its single Settings hook; Windows automatically prepares the
|
||||
pinned Rust toolchain/target and verified FFmpeg SDK, then links and bundles DLLs.
|
||||
Applications do not need platform checkout steps or `FFMPEG_DIR`. Source-mode
|
||||
hosts need Git, Python 3.11+, Rustup/LLVM for Windows and NDK/CMake/MSYS2 for Android.
|
||||
`CUTDEX_NATIVE_SOURCE_TOKEN` reads private Gitea platform source repositories;
|
||||
`CUTDEX_NATIVE_SOURCE_SERVER_URL` selects the runner-reachable checkout server.
|
||||
Platform publication and Flutter integration CI are owned by their independent repositories.
|
||||
|
||||
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 distributed separately; these workflows do not bundle them.
|
||||
|
||||
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. Gitea can retain old artifact API rows after a job rerun despite overwrite.
|
||||
Selection requires the exact CI run and source commit, and exactly one artifact
|
||||
created within its current successful producer job's execution interval. Jobs
|
||||
preserved during a partial rerun retain their original intervals and artifacts.
|
||||
Missing, expired or ambiguous artifacts in that interval 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.
|
||||
|
||||
Release tools are checked out at the workflow's exact commit; tagged application
|
||||
source is checked out separately in `.release-source`. A manual dispatch on main
|
||||
can therefore apply a reviewed release-tool fix to an existing tag without moving
|
||||
that tag or substituting another application's version or CI artifacts.
|
||||
|
||||
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.
|
||||
@@ -0,0 +1,162 @@
|
||||
# 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.
|
||||
|
||||
Core source archives are cached by their pinned SHA256 under the runner user's
|
||||
`.cache/cutdex/core`. Every use verifies the bytes and both dependency identities;
|
||||
the archive is freshly extracted into each job's workspace. Native Flutter is
|
||||
bundled with Core and reused from that one source directory. No application build
|
||||
outputs or package configurations are shared between jobs.
|
||||
|
||||
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.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,31 @@
|
||||
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: Prepare verified Core source release
|
||||
shell: pwsh
|
||||
run: python tool/gitea/prepare_dependencies.py
|
||||
- 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
|
||||
@@ -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
|
||||
+218
-32
@@ -12,66 +12,252 @@ concurrency:
|
||||
group: app-${{ gitea.ref }}
|
||||
cancel-in-progress: true
|
||||
env:
|
||||
CI: 'true'
|
||||
PYTHONUTF8: '1'
|
||||
CUTDEX_NATIVE_SOURCE_TOKEN: ${{ secrets.CUTDEX_NATIVE_SOURCE_TOKEN }}
|
||||
CUTDEX_GITEA_INTERNAL_URL: http://127.0.0.1:3000
|
||||
CUTDEX_NATIVE_SOURCE_SERVER_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
|
||||
jobs:
|
||||
build:
|
||||
name: Windows x64 and Android
|
||||
quality:
|
||||
name: Check code and tests
|
||||
runs-on: cutdex-windows-x64
|
||||
outputs:
|
||||
build-app: ${{ steps.scope.outputs.build-app }}
|
||||
package-app: ${{ steps.scope.outputs.package-app }}
|
||||
env:
|
||||
GITEA_ACTOR: lingjhf
|
||||
CUTDEX_GITEA_TOKEN: ${{ secrets.CUTDEX_GITEA_TOKEN }}
|
||||
steps:
|
||||
- uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
|
||||
- name: Check out source
|
||||
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
|
||||
with:
|
||||
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: |
|
||||
$version = flutter --version --machine | ConvertFrom-Json
|
||||
if ($version.frameworkVersion -ne '3.47.5') { throw 'Flutter 3.47.5 required.' }
|
||||
flutter config --jdk-dir=$env:JAVA_HOME
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Flutter JDK setup failed.' }
|
||||
- run: flutter pub get --enforce-lockfile
|
||||
- run: dart analyze --fatal-infos
|
||||
- run: flutter test --reporter expanded test packages/cutdex_ui/test packages/cutdex_native/test
|
||||
- name: Bound Android build memory on the shared runner
|
||||
python tool/gitea/ci_scope.py
|
||||
if ($LASTEXITCODE -ne 0) { throw 'CI scope selection failed.' }
|
||||
- name: Prepare Flutter environment
|
||||
uses: ./.gitea/actions/prepare-flutter
|
||||
with:
|
||||
configure-java: 'true'
|
||||
- name: Analyze Dart code
|
||||
run: 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: |
|
||||
$file = 'android/gradle.properties'
|
||||
$properties = [IO.File]::ReadAllText($file).Replace('-Xmx8G', '-Xmx3G').Replace('MaxMetaspaceSize=4G', 'MaxMetaspaceSize=768m')
|
||||
[IO.File]::WriteAllText($file, $properties + "`norg.gradle.workers.max=4`n")
|
||||
- run: flutter build apk --release --flavor production --target-platform android-arm64,android-x64
|
||||
- name: Build Windows from the pinned Gitea native release
|
||||
[IO.File]::WriteAllText($file, $properties + "`norg.gradle.workers.max=4`norg.gradle.caching=true`n")
|
||||
- uses: ./.dependencies/cutdex_core/native_flutter/.gitea/actions/setup-android
|
||||
if: vars.CUTDEX_NATIVE_BUILD_MODE == 'source'
|
||||
- name: Build production Android APK
|
||||
env:
|
||||
GITEA_ACTOR: lingjhf
|
||||
run: |
|
||||
Remove-Item Env:CUTDEX_WINDOWS_PATH, Env:CUTDEX_WINDOWS_PACKAGE_PATH -ErrorAction SilentlyContinue
|
||||
flutter build windows --release --flavor production
|
||||
$env:CUTDEX_NATIVE_BUILD_MODE = '${{ vars.CUTDEX_NATIVE_BUILD_MODE || 'artifacts' }}'
|
||||
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: Clear inherited native build overrides
|
||||
run: |
|
||||
foreach ($key in @('CUTDEX_WINDOWS_PATH', 'CUTDEX_WINDOWS_PACKAGE_PATH', 'FFMPEG_DIR', 'LIBCLANG_PATH')) {
|
||||
Remove-Item "Env:$key" -ErrorAction SilentlyContinue
|
||||
"$key=" >> $env:GITHUB_ENV
|
||||
}
|
||||
- uses: ./.dependencies/cutdex_core/native_flutter/.gitea/actions/setup-windows
|
||||
if: vars.CUTDEX_NATIVE_BUILD_MODE == 'source'
|
||||
with:
|
||||
libclang-path: ${{ vars.CUTDEX_LIBCLANG_PATH }}
|
||||
- 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: |
|
||||
$env:CUTDEX_NATIVE_BUILD_MODE = '${{ vars.CUTDEX_NATIVE_BUILD_MODE || 'artifacts' }}'
|
||||
python tool/build.py windows
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Windows build failed.' }
|
||||
- name: Prepare isolated packaging tools
|
||||
- name: Verify native SDK matches pinned packaging tools
|
||||
run: |
|
||||
python -m venv .build/package-tools
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Packaging environment setup failed.' }
|
||||
& ./.build/package-tools/Scripts/python.exe -m pip install pefile==2024.8.26
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Packaging dependency installation failed.' }
|
||||
- name: Package application
|
||||
python tool/windows/windows_updates.py verify-sdk
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Windows native SDK version validation failed.' }
|
||||
- name: Save Windows app for independent packaging retries
|
||||
if: ${{ needs.quality.outputs.package-app == 'true' }}
|
||||
uses: ./.gitea/actions/upload-artifact
|
||||
with:
|
||||
name: cutdex-windows-app
|
||||
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: |
|
||||
& ./.build/package-tools/Scripts/python.exe tool/gitea/package-app.py
|
||||
- name: Upload Android and Windows packages
|
||||
uses: https://github.com/actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
|
||||
& $env:PACKAGE_PYTHON tool/gitea/package-app.py --platform windows --vpk $env:VPK_PATH
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Windows packaging failed.' }
|
||||
- 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:
|
||||
name: cutdex-release-packages
|
||||
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
|
||||
checks:
|
||||
name: Gitea CI passed
|
||||
if: always()
|
||||
needs: build
|
||||
needs: [quality, android, windows-build, windows, build]
|
||||
runs-on: cutdex-windows-x64
|
||||
steps:
|
||||
- env:
|
||||
RESULT: ${{ needs.build.result }}
|
||||
- name: Verify CI 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: |
|
||||
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)." }
|
||||
}
|
||||
+140
-11
@@ -13,21 +13,150 @@ permissions:
|
||||
concurrency:
|
||||
group: cutdex-release
|
||||
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_PUBSPEC: .release-source/pubspec.yaml
|
||||
RELEASE_TAG: ${{ gitea.event.inputs.tag || gitea.ref_name }}
|
||||
GITEA_REPOSITORY: ${{ gitea.repository }}
|
||||
jobs:
|
||||
release:
|
||||
prepare:
|
||||
name: Prepare draft Release
|
||||
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:
|
||||
- uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
|
||||
- name: Check out pinned release tools
|
||||
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
|
||||
with:
|
||||
ref: ${{ gitea.sha }}
|
||||
persist-credentials: false
|
||||
github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
|
||||
- name: Check out release source separately
|
||||
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
|
||||
with:
|
||||
ref: ${{ gitea.event.inputs.tag || gitea.ref_name }}
|
||||
path: .release-source
|
||||
persist-credentials: false
|
||||
- name: Publish validated Android and Windows packages
|
||||
shell: pwsh
|
||||
env:
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
GITEA_REPOSITORY: ${{ gitea.repository }}
|
||||
RELEASE_TAG: ${{ gitea.event.inputs.tag || gitea.ref_name }}
|
||||
github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
|
||||
- name: Select successful CI and prepare draft
|
||||
id: draft
|
||||
run: |
|
||||
$env:GITEA_SHA = git rev-parse HEAD
|
||||
python tool/gitea/promote-release.py
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Release promotion failed.' }
|
||||
$env:GITEA_SHA = git -C .release-source rev-parse HEAD
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Release source resolution 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 pinned release tools
|
||||
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
|
||||
with:
|
||||
ref: ${{ gitea.sha }}
|
||||
persist-credentials: false
|
||||
github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
|
||||
- name: Check out release source separately
|
||||
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
|
||||
with:
|
||||
ref: ${{ gitea.event.inputs.tag || gitea.ref_name }}
|
||||
path: .release-source
|
||||
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 pinned release tools
|
||||
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
|
||||
with:
|
||||
ref: ${{ gitea.sha }}
|
||||
persist-credentials: false
|
||||
github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
|
||||
- name: Check out release source separately
|
||||
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
|
||||
with:
|
||||
ref: ${{ gitea.event.inputs.tag || gitea.ref_name }}
|
||||
path: .release-source
|
||||
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 pinned release tools
|
||||
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
|
||||
with:
|
||||
ref: ${{ gitea.sha }}
|
||||
persist-credentials: false
|
||||
github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
|
||||
- name: Check out release source separately
|
||||
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
|
||||
with:
|
||||
ref: ${{ gitea.event.inputs.tag || gitea.ref_name }}
|
||||
path: .release-source
|
||||
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.' }
|
||||
@@ -101,3 +101,11 @@ pubspec_overrides.yaml
|
||||
*.aab
|
||||
.vscode/*
|
||||
!.vscode/launch.json
|
||||
!.vscode/settings.json
|
||||
|
||||
# FVM Version Cache
|
||||
.fvm/
|
||||
|
||||
# Core and native source checkouts prepared by CI or local development.
|
||||
.dependencies/
|
||||
.release-source/
|
||||
Vendored
+27
-1
@@ -5,7 +5,33 @@
|
||||
"name": "Cutdex",
|
||||
"request": "launch",
|
||||
"type": "dart",
|
||||
"program": "lib/main.dart"
|
||||
"program": "lib/main.dart",
|
||||
"customTool": "${workspaceFolder}/tool/flutter-local.sh",
|
||||
"windows": {
|
||||
"customTool": "${workspaceFolder}/tool/flutter-local.bat"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Cutdex (Profile)",
|
||||
"request": "launch",
|
||||
"type": "dart",
|
||||
"program": "lib/main.dart",
|
||||
"flutterMode": "profile",
|
||||
"customTool": "${workspaceFolder}/tool/flutter-local.sh",
|
||||
"windows": {
|
||||
"customTool": "${workspaceFolder}/tool/flutter-local.bat"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "Cutdex (Release)",
|
||||
"request": "launch",
|
||||
"type": "dart",
|
||||
"program": "lib/main.dart",
|
||||
"flutterMode": "release",
|
||||
"customTool": "${workspaceFolder}/tool/flutter-local.sh",
|
||||
"windows": {
|
||||
"customTool": "${workspaceFolder}/tool/flutter-local.bat"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
Vendored
+3
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"dart.flutterSdkPath": ".fvm/versions/3.47.5"
|
||||
}
|
||||
@@ -17,7 +17,7 @@ Cutdex 是一款视频剪辑应用。你可以在时间线上编辑视频、音
|
||||
|
||||
## 下载与安装
|
||||
|
||||
本仓库目前尚未发布可下载的安装包。
|
||||
可从 [Gitea Releases](https://git.orangraph.com/lingjhf/cutdex/releases) 下载 Windows x64 安装包或便携包,以及 Android ARM64/x86_64 APK。当前 Android APK 使用开发签名;macOS 和 iOS 暂未提供安装包。
|
||||
|
||||
## 可以做什么
|
||||
|
||||
@@ -53,6 +53,14 @@ Cutdex 是一款视频剪辑应用。你可以在时间线上编辑视频、音
|
||||
|
||||
“设置 → 通用”可以切换语言、明暗主题和存储位置。桌面版还提供软件更新入口,是否可用取决于安装包的更新配置。
|
||||
|
||||
配色方案提供石墨灰与蓝色、柔灰与紫色、暖灰与青绿三种选择。每种方案都有浅色和深色版本,也可跟随系统外观;配色方案与明暗选择分别保存。
|
||||
|
||||
桌面剪辑工作区采用独立的控件与布局尺寸:素材、预览和属性分别成面板,下方时间线横跨编辑区,播放栏固定在预览底部。时间线标签、编辑命令和标尺分层排列,窄面板中的次要命令收进更多菜单。顶部可展开或收起聊天,草稿会保留;聊天区域宽度和时间线高度支持拖动并保存。手机和平板继续使用各自的页面与工具面板。
|
||||
|
||||
桌面窗口顶部以标签页切换已打开的项目,“+”菜单可新建、打开或选择最近项目。左侧只展示当前项目的聊天,会话历史与新建聊天位于聊天区头部;素材库属于当前项目,放在编辑区内,可独立收起并保留浏览状态。关闭标签不会删除项目,切换项目会保留各自的聊天草稿。
|
||||
|
||||
桌面素材区提供紧凑卡片和列表视图,可按名称搜索,并按导入顺序或名称升降序排列。视频、图片和音频共用选中状态,时长来自实际素材信息;缺失素材保留名称并标明原因。搜索、排序和视图选择按项目保留。
|
||||
|
||||
遇到编辑、保存、预览或后台任务错误时,可在“设置 → 通用 → 诊断”中导出诊断包,协助定位问题。分享前请检查内容,移除不希望公开的信息。
|
||||
|
||||
需要连接外部 AI 工具时,可查看 [MCP 连接指南](docs/mcp-connection.md)。
|
||||
|
||||
@@ -7,3 +7,5 @@ Flutter/Dart 依赖及解析版本记录在 `pubspec.yaml`、内部包的 `pubsp
|
||||
应用发行包捆绑的媒体处理库、推理工具和模型遵循各自的许可与再分发要求。打包时保留随附的许可证和通知文件;不能用本仓库的 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,7 +13,6 @@ analyzer:
|
||||
- windows/**
|
||||
- macos/**
|
||||
- linux/**
|
||||
- packages/*/example/**
|
||||
|
||||
plugins:
|
||||
riverpod_lint: ^3.1.9
|
||||
|
||||
@@ -33,6 +33,8 @@ android {
|
||||
defaultConfig {
|
||||
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
|
||||
applicationId = "com.example.cutdex"
|
||||
manifestPlaceholders["cutdexPreviewReverseCacheMiB"] = "0"
|
||||
manifestPlaceholders["cutdexNativeSurfacePreview"] = "false"
|
||||
// You can update the following values to match your application needs.
|
||||
// For more information, see: https://flutter.dev/to/review-gradle-config.
|
||||
minSdk = 31
|
||||
@@ -50,7 +52,17 @@ android {
|
||||
create("development") {
|
||||
dimension = "environment"
|
||||
applicationIdSuffix = ".dev"
|
||||
resValue("string", "app_name", "Cutdex Dev")
|
||||
// Device validation can coexist with an app signed on another machine.
|
||||
val validationId = providers.gradleProperty("cutdexValidationApplicationId")
|
||||
.orElse(providers.environmentVariable("CUTDEX_VALIDATION_APPLICATION_ID")).orNull
|
||||
if (validationId != null) applicationId = validationId
|
||||
resValue("string", "app_name", if (validationId == null) "Cutdex Dev" else "Cutdex Decoder Test")
|
||||
manifestPlaceholders["cutdexPreviewReverseCacheMiB"] = providers
|
||||
.gradleProperty("cutdexPreviewReverseCacheMiB")
|
||||
.orElse(providers.environmentVariable("CUTDEX_PREVIEW_REVERSE_CACHE_MIB")).getOrElse("0")
|
||||
manifestPlaceholders["cutdexNativeSurfacePreview"] = providers
|
||||
.gradleProperty("cutdexNativeSurfacePreview")
|
||||
.orElse(providers.environmentVariable("CUTDEX_NATIVE_SURFACE_PREVIEW")).getOrElse("false")
|
||||
}
|
||||
create("production") {
|
||||
dimension = "environment"
|
||||
|
||||
@@ -3,6 +3,10 @@
|
||||
android:label="@string/app_name"
|
||||
android:name="${applicationName}"
|
||||
android:icon="@mipmap/cutdex_launcher">
|
||||
<meta-data android:name="dev.cutdex.previewReverseCacheMiB"
|
||||
android:value="${cutdexPreviewReverseCacheMiB}" />
|
||||
<meta-data android:name="dev.cutdex.nativeSurfacePreview"
|
||||
android:value="${cutdexNativeSurfacePreview}" />
|
||||
<activity
|
||||
android:name=".MainActivity"
|
||||
android:exported="true"
|
||||
|
||||
@@ -25,11 +25,5 @@ plugins {
|
||||
|
||||
include(":app")
|
||||
|
||||
// Native source development is opt-in; default resolution uses Gitea Maven packages.
|
||||
providers.gradleProperty("cutdex.android.path").orNull?.let { nativePath ->
|
||||
includeBuild(nativePath) {
|
||||
dependencySubstitution {
|
||||
substitute(module("dev.cutdex:cutdex-android")).using(project(":cutdex-android"))
|
||||
}
|
||||
}
|
||||
}
|
||||
// Register native source dependencies before Gradle creates the projects.
|
||||
apply(from = project(":cutdex_native_flutter").projectDir.resolve("native-settings.gradle"))
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"core": {
|
||||
"repository": "lingjhf/cutdex_core",
|
||||
"version": "0.0.1",
|
||||
"ref": "v0.0.1",
|
||||
"revision": "a9c245ada56536f1642b39b1370c6ec2bb1a2a13",
|
||||
"artifact": {
|
||||
"file": "cutdex-core-0.0.1.zip",
|
||||
"sha256": "9fbff6317b8e4876c423c73dc0da319fad6d96523c50878687dffdb88edde979"
|
||||
}
|
||||
},
|
||||
"nativeFlutter": {
|
||||
"repository": "cutdex-native/cutdex_native_flutter",
|
||||
"version": "0.0.1",
|
||||
"ref": "v0.0.1",
|
||||
"revision": "6349cd61676617eb1f739b37b7758a74b0a780cb"
|
||||
}
|
||||
}
|
||||
+63
-10
@@ -4,20 +4,64 @@
|
||||
|
||||
## 准备环境
|
||||
|
||||
使用满足 `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` 创建覆盖配置。覆盖文件只用于本机开发,不提交。
|
||||
|
||||
## 运行应用
|
||||
应用直接依赖 `cutdex_core` 和 `cutdex_native_flutter`,预览协调与时间线 UI 位于应用内部包。
|
||||
正式构建由 `dependencies.json` 固定 Core 的发布版本、源码提交和 ZIP SHA256,
|
||||
同时记录随 Core 分发的 Flutter 集成版本与提交。运行
|
||||
`python3 tool/gitea/prepare_dependencies.py` 后,验证的 Core 源码放到
|
||||
`.dependencies/cutdex_core`;应用及预览包共用其中的 `native_flutter`,避免重复解析两个原生集成来源。
|
||||
私有下载使用 `CUTDEX_GITEA_TOKEN`。缓存只复用校验过的 ZIP,每个 CI job 独立解压。
|
||||
|
||||
Core 远端为 `lingjhf/cutdex_core`,Flutter 集成远端为 `cutdex-native/cutdex_native_flutter`。
|
||||
本地源码联调使用 `pubspec_overrides.yaml.example` 指向同级 checkout,覆盖文件不提交。
|
||||
发布 ZIP 包含 `RELEASE.json`,应用同时校验 Core 和 Flutter 集成的版本、提交及平台依赖元数据。
|
||||
|
||||
原生实现位于独立的 `CutdexApple`、`cutdex-android`、`cutdex-windows` 仓库。
|
||||
它们的开发提交和确切发布版本由 Flutter 集成的 `native-dependencies.json` 固定。
|
||||
默认 `CUTDEX_NATIVE_BUILD_MODE=artifacts` 消费发布版本;开发设置 `source` 按完整 SHA 编译。
|
||||
本地联调显式设置 `CUTDEX_APPLE_PATH`、`CUTDEX_ANDROID_PATH` 或 `CUTDEX_WINDOWS_PATH`,
|
||||
可以使用未提交修改。正式构建清除这些覆盖。
|
||||
|
||||
源码模式需要目标平台工具链;Android 通过共享 Settings 注册 composite build,
|
||||
Windows 需要 Rust、FFmpeg SDK 与 libclang,Apple 通过 SwiftPM 消费独立源码包。
|
||||
发布模式使用确切 Apple Git 版本、Android Maven 版本和 Windows Release 版本及架构摘要。
|
||||
切换模式后清理宿主生成目录并重新解析依赖。认证和具体构建说明见独立 Flutter 集成 README。
|
||||
|
||||
`CUTDEX_PROCESSING_ROOT` 指定处理 worker 目录;Android 私有 Maven 认证可填写
|
||||
`GITEA_ACTOR` 和 `CUTDEX_GITEA_TOKEN`,账号应属于令牌的认证用户。
|
||||
|
||||
VS Code 的 Debug、Profile、Release 启动项与下述命令共用
|
||||
`tool/flutter_local.dart` 加载规则。VS Code 的项目 SDK 设置由 `fvm use` 自动同步,
|
||||
启动入口通过 `.fvm/flutter_sdk` 使用同一项目版本,不通过 `FLUTTER` 环境变量或
|
||||
全局 PATH 选择 Flutter。
|
||||
未准备项目 SDK 时先运行 `fvm use`。现有进程环境变量优先于文件,包括显式空值。
|
||||
文件支持 `KEY=value`、单双引号和注释;值按字面读取,不执行命令,不展开变量或
|
||||
反斜杠转义。格式错误会在构建前报错,不输出配置值。
|
||||
|
||||
Flutter 启动入口、Python 构建/检查入口和 macOS 打包共用同一个 Dart 加载器,
|
||||
配置注入整个工具流水线的子进程环境,不修改系统环境或 SDK 文件。
|
||||
检测到 `CI`、`GITEA_ACTIONS` 或 `GITHUB_ACTIONS` 为 true/1/yes 时,不读取本地文件。
|
||||
现有 CI 继续使用工作流配置与 Secrets。直接执行 `fvm flutter` 不加载此文件。
|
||||
更换 Windows 原生路径后,若 CMake 仍缓存旧路径,先退出应用并运行 `fvm dart tool/flutter_local.dart clean`。
|
||||
|
||||
Flutter 自带的 `--dart-define-from-file` 也支持 `.env` 格式,但生成的是 Dart 编译期
|
||||
配置,由 `String.fromEnvironment` 读取,不会设置 CMake、Gradle 或 Swift 读取的
|
||||
进程环境。原生依赖路径与认证使用上述启动入口;应用自身的编译期选项可继续使用
|
||||
`--dart-define` 或 `--dart-define-from-file`,不要把原生包认证文件作为 Dart define 输入。
|
||||
|
||||
在 Cutdex 根目录运行:
|
||||
|
||||
```sh
|
||||
flutter pub get
|
||||
dart run build_runner build
|
||||
flutter run -d macos --flavor development
|
||||
fvm dart tool/flutter_local.dart pub get
|
||||
fvm dart run build_runner build
|
||||
fvm dart tool/flutter_local.dart run -d macos --flavor development
|
||||
```
|
||||
|
||||
Android、macOS、Windows 配置了 development 与 production flavor,默认是 development。按目标平台替换设备参数。iOS 使用 `Runner` scheme。构建或集成测试前,退出占用同一构建目录的应用。
|
||||
@@ -25,7 +69,7 @@ Android、macOS、Windows 配置了 development 与 production flavor,默认
|
||||
Android 支持 ARM64 和 x86_64。按架构拆分 APK 时显式指定目标:
|
||||
|
||||
```sh
|
||||
flutter build apk --flavor development --split-per-abi --target-platform android-arm64,android-x64
|
||||
python3 tool/build.py android --flavor development --split-per-abi
|
||||
```
|
||||
|
||||
字幕、翻译和抠像的功能验证需要相应资源。按应用提示准备资源,并使用合成或允许再分发的素材;不要把个人媒体、模型服务凭据或项目文件提交到仓库。
|
||||
@@ -42,15 +86,15 @@ flutter build apk --flavor development --split-per-abi --target-platform android
|
||||
| 设置、诊断与更新界面 | `lib/features/settings/` |
|
||||
| 桌面、平板与手机布局 | `lib/app/shells/` |
|
||||
|
||||
应用根目录是 Pub workspace。[cutdex_ui](../packages/cutdex_ui/README.md) 维护通用组件与基础主题,[cutdex_native](../packages/cutdex_native/README.md) 维护设备信息与桌面交互。应用集成入口在 `lib/integrations/`,共享布局与业务样式在 `lib/shared/`。
|
||||
应用根目录是 Pub workspace。`packages/cutdex_preview` 持有预览协调与画布交互,`packages/cutdex_timeline_ui` 持有时间线 UI 和示例;正式编辑计划由 core 统一编译与同步。[cutdex_ui](../packages/cutdex_ui/README.md) 维护通用组件与基础主题,[cutdex_native](../packages/cutdex_native/README.md) 维护设备信息与桌面交互。应用集成入口在 `lib/integrations/`,共享布局与业务样式在 `lib/shared/`。
|
||||
|
||||
修改剪辑操作时,检查预览、保存、撤销和重做;修改素材导入时,检查文件访问及项目重新打开后的可用性;修改后台任务时,检查完成、失败和取消后的界面状态。
|
||||
|
||||
## 文案与代码生成
|
||||
|
||||
修改需要生成代码的模型后,在所属包目录运行 `dart run build_runner build`,将生成文件与源码一起提交。
|
||||
修改需要生成代码的模型后,在所属包目录运行 `fvm dart run build_runner build`,将生成文件与源码一起提交。
|
||||
|
||||
修改文案时更新 `lib/l10n/` 中的 ARB,再运行 `flutter gen-l10n`。简体中文同时维护 `app_zh.arb` 和 `app_zh_Hans.arb`;增加界面语言时更新语言选择与 Apple bundle 声明。
|
||||
修改文案时更新 `lib/l10n/` 中的 ARB,再运行 `fvm dart tool/flutter_local.dart gen-l10n`。简体中文同时维护 `app_zh.arb` 和 `app_zh_Hans.arb`;增加界面语言时更新语言选择与 Apple bundle 声明。
|
||||
|
||||
执行 [测试指南](testing.md) 中适用的检查。界面改动还需检查桌面、平板和手机布局,以及明暗主题和不同语言下的表现。
|
||||
|
||||
@@ -64,6 +108,15 @@ flutter build apk --flavor development --split-per-abi --target-platform android
|
||||
|
||||
构建、打包和更新验证入口见 [仓库工具](../tool/README.md)。完成集成测试后,使用 `lib/main.dart` 重建正式应用,避免分发测试入口。
|
||||
|
||||
`python3 tool/build.py android|windows|macos` 与 CI 共用 production/release 预设,
|
||||
额外 Flutter 参数放在 `--` 后。仅构建 macOS 应用时使用此入口;完整 ZIP/DMG
|
||||
打包、processing 嵌入、签名和公证使用 `build_macos_release.py`。
|
||||
|
||||
环境文件合并时进程变量优先,包括空值。原生构建仍遵循 `cutdex_native_flutter` 的覆盖规则:
|
||||
Android Gradle 属性先于环境变量;Windows CMake 已缓存的非空路径先于环境变量,
|
||||
修改后需 clean;processing 的非空 Dart define 先于进程环境,再使用随包默认路径。
|
||||
`CUTDEX_GITEA_TOKEN` 用于依赖访问,Release 的 `GITEA_TOKEN` 用于发布和 CI 产物读取。
|
||||
|
||||
Android release 当前使用调试签名,正式分发前需配置发布签名;production flavor 本身不提供发布证书。
|
||||
|
||||
macOS 默认 ad-hoc 签名。开发证书配置放在 `macos/Runner/Configs/Signing.local.xcconfig`;iOS 真机的 Team 设置放在 `ios/Flutter/Signing.local.xcconfig`。这些文件已忽略,凭据与私钥保留在本地或 CI 私密配置中。
|
||||
@@ -7,7 +7,7 @@
|
||||
MCP 默认关闭,在设置中启用并获取端口和访问令牌。外部客户端设置 `CUTDEX_MCP_PORT`、`CUTDEX_MCP_TOKEN`,以本仓库为工作目录运行:
|
||||
|
||||
```sh
|
||||
dart run tool/mcp_stdio.dart
|
||||
fvm dart run tool/mcp_stdio.dart
|
||||
```
|
||||
|
||||
连接通过本机端口访问正在运行的 Cutdex。工具范围由当前工作区和可用功能决定,参数以客户端发现结果为准。
|
||||
|
||||
+22
-6
@@ -13,9 +13,7 @@ python3 tool/check_public_repository.py
|
||||
该检查覆盖 Git 跟踪及未被忽略的待提交文件,可识别常见凭据格式、误纳入的本地产物和失效的本地文档链接;不代替 Git 历史审计,也不能识别任意自定义密码。
|
||||
|
||||
```sh
|
||||
flutter pub get
|
||||
dart analyze --fatal-infos
|
||||
flutter test test packages/cutdex_ui/test packages/cutdex_native/test
|
||||
fvm dart tool/flutter_local.dart pub get
|
||||
# Python 3.11+
|
||||
python3 tool/check.py
|
||||
```
|
||||
@@ -27,15 +25,19 @@ python3 tool/check.py
|
||||
| [integration_test](../integration_test/README.md) | 对应平台上的真实预览、媒体编辑与处理任务 |
|
||||
| [tool](../tool/README.md) | 脚本检查、发布包验证和平台诊断 |
|
||||
|
||||
本地完整检查与 CI 共用相同的套件,可用 `python3 tool/check.py --suite analyze`、
|
||||
`--suite flutter` 或 `--suite tools` 单独执行或重试。静态分析启用 `--fatal-infos`;
|
||||
Flutter 套件同时运行应用与内部包测试。所有入口使用项目 SDK 和相同环境加载规则。
|
||||
|
||||
App 测试验证宿主行为,底层算法、协议及插件生命周期在所属包测试。普通测试通过不代表真实播放或模型质量已经验证。
|
||||
|
||||
## 生成文件
|
||||
|
||||
```sh
|
||||
dart run build_runner build
|
||||
fvm dart run build_runner build
|
||||
# UI 模型修改后,在 packages/cutdex_ui 中运行相同生成命令
|
||||
flutter gen-l10n
|
||||
flutter test test/generated_code_test.dart test/localization_resources_test.dart
|
||||
fvm dart tool/flutter_local.dart gen-l10n
|
||||
fvm dart tool/flutter_local.dart test test/generated_code_test.dart test/localization_resources_test.dart
|
||||
```
|
||||
|
||||
生成文件应与源码一同提交。生成校验会重新生成应用与 UI 包并比较前后内容,同时检查应用生成文件的跟踪状态;不要暂存无关文件来掩盖失败。
|
||||
@@ -47,3 +49,17 @@ flutter test test/generated_code_test.dart test/localization_resources_test.dart
|
||||
普通测试中的可选真实模型回归使用环境变量:`CUTDEX_ACCEPTANCE_LIVE` 和 `CUTDEX_BEAT_LIVE` 指向对应测试的配置 JSON,`CUTDEX_ASR_FIXTURE` 指定语音素材。配置字段以测试读取代码为准,素材、模型及凭据放在仓库外。
|
||||
|
||||
记录实际运行的平台、输入、失败和跳过原因。缺少模型、设备或素材时明确跳过;失败先核对夹具与当前契约,不通过放宽断言或无条件跳过掩盖问题。
|
||||
|
||||
## 应用持有的编辑 UI
|
||||
|
||||
迁入的预览协调和时间线 UI 与应用一起验证:
|
||||
|
||||
```sh
|
||||
flutter test --no-pub packages/cutdex_preview/test packages/cutdex_timeline_ui/test packages/cutdex_timeline_ui/example/test
|
||||
```
|
||||
|
||||
这两个包及时间线示例的测试由 `tool/check.py --suite flutter` 自动纳入常规 CI;示例源码也纳入静态分析。示例从时间 `0` 开始,测试手势通过实际视口和片段布局计算位置,并验证命中目标。裁剪的逐帧预览需先 `pump` 再断言;选择、提交、撤销与重做仍验证明确的编辑结果和版本。
|
||||
|
||||
core 的编译、求值、同步和编辑业务测试在 core 仓库使用 Dart VM 运行;native Flutter 的平台适配测试仍在 native 仓库。
|
||||
|
||||
应用及 UI 包的生产源码不得持有 `cutdex_runtime` 通道;原生媒体通信通过 `cutdex_native_flutter` 的公共接口进入内部 transport。`tool/check_package_boundaries.py` 检查通道名称,测试可以保留 wire mock,应用自己的窗口与生命周期通道仍由应用管理。性能诊断使用已有原生会话的 `previewDiagnostics()`,应用只负责采样、计时校准与报告。
|
||||
@@ -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 独立分发策略沿用现有流水线。
|
||||
+130
-19
@@ -2,10 +2,83 @@
|
||||
|
||||
`integration_test/` contains opt-in tests for the real application and native
|
||||
backends. `test_driver/integration_test.dart` is the host driver used by
|
||||
`flutter drive` for Profile measurements. Both directories contain test source;
|
||||
`fvm dart tool/flutter_local.dart drive` for Profile measurements. Both directories contain test source;
|
||||
media, models, reports and credentials are supplied locally and stay outside
|
||||
version control. Normal release builds use `lib/main.dart`.
|
||||
|
||||
## Android navigation and playhead measurements
|
||||
|
||||
`android_decoder_material_performance_test.dart` extends the production workspace
|
||||
benchmark to other source rates and variable timestamps. Supply
|
||||
`CUTDEX_TEST_SOURCE_PTS` as an independent, sorted list of original frame PTS
|
||||
(one integer source tick per line), with `CUTDEX_TEST_SOURCE_TIMESCALE` set to
|
||||
that clock's denominator, such as 90000. The default timescale is 1000000 for
|
||||
existing integer-microsecond fixtures; preserve original source ticks for frame
|
||||
boundaries that cannot be represented in microseconds. `CUTDEX_TEST_FRAME_STEP_US`
|
||||
is the nominal frame period rounded to microseconds. Its eight `matchedSeeks` use
|
||||
the standalone benchmark's exact request sequence. Full-source ruler drags and
|
||||
20-frame local drags use the production timeline and are reported separately;
|
||||
their inputs differ from the standalone source replay.
|
||||
|
||||
`CUTDEX_TEST_CALIBRATE=true` explicitly runs native/software calibration before
|
||||
opening the workspace and verifies both sets against the external PTS list.
|
||||
It asserts the admitted backend throughout later navigation and gestures.
|
||||
The application opens no calibration workload automatically.
|
||||
|
||||
If the device's installed application has a different signing certificate,
|
||||
build the development flavor with
|
||||
`CUTDEX_VALIDATION_APPLICATION_ID=com.example.cutdex.decoder_validation`.
|
||||
This creates `com.example.cutdex.decoder_validation.dev`, labeled
|
||||
`Cutdex Decoder Test`, while preserving the installed application and its data.
|
||||
For a cache baseline, set `CUTDEX_PREVIEW_REVERSE_CACHE_MIB=24`;
|
||||
set it to `0` for normal device policy. These properties affect development only.
|
||||
Use matching private file paths and retain the app between runs.
|
||||
|
||||
`android_navigation_performance_test.dart` mounts the production `EditorWorkspace`
|
||||
with real `Projects`, preview and native playback providers. Its project and
|
||||
application database are isolated. Supply a complete original video through
|
||||
`CUTDEX_TEST_SOURCE` and an app-writable JSON path through `CUTDEX_TEST_REPORT`.
|
||||
The test keeps production audible-skimming policy and uses touch input on real
|
||||
timeline tabs and the timeline ruler. It measures cold/cached selection, rapid
|
||||
selection replacement, exact seeks, full-source fit-to-viewport and local
|
||||
20-frame drags, and both immediate release and a one-second stationary hold.
|
||||
The source-frame containment checks currently require an untrimmed CFR
|
||||
2997/100 fps source.
|
||||
Use `--dart-define=CUTDEX_TEST_DECODER=ffmpeg` to assert the actual decoder
|
||||
from initial load through seeks, both drag directions and final release.
|
||||
Reports retain per-layer backend and selection-reason diagnostics.
|
||||
|
||||
```powershell
|
||||
fvm dart tool/flutter_local.dart drive --profile --flavor development -d DEVICE_ID --keep-app-running `
|
||||
--driver=test_driver/integration_test.dart `
|
||||
--target=integration_test/android_navigation_performance_test.dart `
|
||||
--dart-define=CUTDEX_TEST_SOURCE=/data/user/0/com.example.cutdex.dev/files/cutdex-validation/source.mp4 `
|
||||
--dart-define=CUTDEX_TEST_REPORT=/data/user/0/com.example.cutdex.dev/files/cutdex-validation/results.json
|
||||
```
|
||||
|
||||
The Flutter adapter uses the Android Maven version pinned in its `native-dependencies.json` by default. For unpublished changes, select `CUTDEX_NATIVE_BUILD_MODE=source` and set `CUTDEX_ANDROID_PATH` to the local native checkout. Calibration
|
||||
requires a `--debug` build; profile/production hosts do not register its channel.
|
||||
UI timing ends at the
|
||||
target workspace's post-frame callback. Native diagnostics record queued output
|
||||
frames/content timestamps and backend seek/reuse counters; those do not measure
|
||||
physical display refresh. The planned drag input rate is 60 Hz; retain actual
|
||||
input timestamps and report achieved input cadence. The test uses `fullyLive`
|
||||
frame scheduling and does not pump a Flutter frame for every pointer input.
|
||||
Native polling has at most
|
||||
one outstanding request, so decoder latency cannot accumulate diagnostic reads.
|
||||
Source PTS is distinct from the requested timeline sample. A stationary release
|
||||
must preserve source PTS, output-frame count and seek count; the final source
|
||||
frame must cover the target tick. These counters measure queued native output,
|
||||
not physical scanout. A cached timeline's nonzero frame counter alone does not
|
||||
prove that its new Surface has displayed the retained frame.
|
||||
Rebuild/install the normal `lib/main.dart` entry point after testing. Do not clear
|
||||
app data or uninstall merely to obtain a cold sample.
|
||||
Always pass `--keep-app-running`: Flutter drive otherwise uninstalls the Android
|
||||
application during cleanup, which also deletes its application data.
|
||||
On devices that deny access to ADB-created external app directories, copy the
|
||||
fixture into the installed debuggable development app's internal files using
|
||||
`run-as`, and export its report with `adb exec-out run-as PACKAGE cat PATH`.
|
||||
|
||||
## Desktop plugin registration
|
||||
|
||||
`native_desktop_plugins_test.dart` checks the real application's registration of
|
||||
@@ -13,7 +86,7 @@ window chrome, dynamically configured file destinations, and the macOS fullscree
|
||||
channel. It requires no media or models and does not simulate Finder/Explorer drops.
|
||||
|
||||
```sh
|
||||
flutter test integration_test/native_desktop_plugins_test.dart -d macos --flavor development
|
||||
fvm dart tool/flutter_local.dart test integration_test/native_desktop_plugins_test.dart -d macos --flavor development
|
||||
```
|
||||
|
||||
Use `-d windows` on Windows. Rebuild the normal application entry point afterwards.
|
||||
@@ -29,7 +102,7 @@ directory, and a short speech fixture. A local Dart-define JSON specifies
|
||||
`CUTDEX_PROCESSING_ROOT` and `CUTDEX_ASR_FIXTURE`:
|
||||
|
||||
```sh
|
||||
flutter test integration_test/processing_e2e_test.dart -d macos --flavor development \
|
||||
fvm dart tool/flutter_local.dart test integration_test/processing_e2e_test.dart -d macos --flavor development \
|
||||
--dart-define-from-file=/absolute/path/to/processing-e2e.json
|
||||
```
|
||||
|
||||
@@ -53,7 +126,7 @@ fault-injection checks with real media and native playback, not evidence that th
|
||||
native backend itself produced these failures.
|
||||
|
||||
```sh
|
||||
flutter drive --profile -d macos --flavor production \
|
||||
fvm dart tool/flutter_local.dart drive --profile -d macos --flavor production \
|
||||
--driver=test_driver/integration_test.dart \
|
||||
--target=integration_test/edit_diagnostics_test.dart \
|
||||
--dart-define=CUTDEX_TEST_SOURCE=/absolute/path/to/generated-720p30.mp4 \
|
||||
@@ -76,7 +149,7 @@ native diagnostics channel is compiled only in Debug, so its frame statistics
|
||||
must not be presented as Profile measurements.
|
||||
|
||||
```sh
|
||||
CUTDEX_PREVIEW_CADENCE_DIAGNOSTICS=1 flutter drive --debug -d macos --flavor development \
|
||||
CUTDEX_PREVIEW_CADENCE_DIAGNOSTICS=1 fvm dart tool/flutter_local.dart drive --debug -d macos --flavor development \
|
||||
--driver=test_driver/integration_test.dart \
|
||||
--target=integration_test/edit_diagnostics_test.dart \
|
||||
--dart-define=CUTDEX_DIAGNOSTIC_CADENCE=true \
|
||||
@@ -99,7 +172,7 @@ source clock, source duration and undo. No playback backend is mocked. ISO impor
|
||||
when the native backend can probe an unprotected video stream.
|
||||
|
||||
```powershell
|
||||
flutter test integration_test/windows_real_media_test.dart -d windows `
|
||||
fvm dart tool/flutter_local.dart test integration_test/windows_real_media_test.dart -d windows `
|
||||
--dart-define=CUTDEX_VALIDATION_SOURCE='D:\validation\media-originals' `
|
||||
--dart-define=CUTDEX_VALIDATION_ROOT='D:\validation\windows-editing'
|
||||
```
|
||||
@@ -112,10 +185,10 @@ native frames, delivered frames per second and the maximum frame gap. These
|
||||
measure native preview delivery, not physical monitor refresh or speaker sound.
|
||||
`CUTDEX_VALIDATION_SOURCE_ROOTS` accepts semicolon-separated source directories
|
||||
when validating multiple collections. For Flutter performance measurements use
|
||||
`flutter drive --profile -d windows --flavor production
|
||||
`fvm dart tool/flutter_local.dart drive --profile -d windows --flavor production
|
||||
--driver=test_driver/integration_test.dart
|
||||
--target=integration_test/windows_real_media_test.dart` with the same Dart
|
||||
defines: `flutter test` forces Debug mode. Playback observations additionally
|
||||
defines: `fvm dart tool/flutter_local.dart test` forces Debug mode. Playback observations additionally
|
||||
record process/time boundaries and Flutter build/raster timings for correlation
|
||||
with actual Windows audio-session peaks. Native textures can redraw without Dart
|
||||
frames, so the observation uses live frames and a continuous 16 ms viewport
|
||||
@@ -162,10 +235,10 @@ not play or export every frame of the original movies.
|
||||
playhead dragging with any playable video at least five seconds long. It probes the
|
||||
source duration and scales the seek points and drag spans to that duration. Provide
|
||||
`CUTDEX_SEEK_SOURCE` and `CUTDEX_SEEK_REPORT`; run it with the shared
|
||||
`test_driver/integration_test.dart` entry point using `flutter drive --profile`.
|
||||
`test_driver/integration_test.dart` entry point using `fvm dart tool/flutter_local.dart drive --profile`.
|
||||
|
||||
```powershell
|
||||
flutter drive --profile --flavor production -d windows `
|
||||
fvm dart tool/flutter_local.dart drive --profile --flavor production -d windows `
|
||||
--driver=test_driver/integration_test.dart `
|
||||
--target=integration_test/windows_seek_latency_test.dart `
|
||||
--dart-define=CUTDEX_SEEK_SOURCE='D:/validation/media-originals/video.mp4' `
|
||||
@@ -187,7 +260,7 @@ an incremental `results.json` report. The source should contain audio-only files
|
||||
longer than ten seconds, with audible content in the 2–6 second edit interval.
|
||||
|
||||
```powershell
|
||||
flutter test integration_test/windows_audio_media_test.dart -d windows `
|
||||
fvm dart tool/flutter_local.dart test integration_test/windows_audio_media_test.dart -d windows `
|
||||
--dart-define=CUTDEX_VALIDATION_SOURCE=D:/validation/audio-originals `
|
||||
--dart-define=CUTDEX_VALIDATION_ROOT=D:/validation/audio-results
|
||||
```
|
||||
@@ -225,19 +298,19 @@ after installing an ABI split, without deleting the app's data. Keep complete
|
||||
originals on the host. On a POSIX shell:
|
||||
|
||||
```sh
|
||||
flutter build apk --debug --flavor development
|
||||
fvm dart tool/flutter_local.dart build apk --debug --flavor development
|
||||
adb -s DEVICE_SERIAL install -r -d build/app/outputs/flutter-apk/app-development-debug.apk
|
||||
adb -s DEVICE_SERIAL shell run-as com.example.cutdex.dev mkdir -p files/real-media files/real-validation
|
||||
adb -s DEVICE_SERIAL shell -T run-as com.example.cutdex.dev tee files/real-media/source.mp4 \
|
||||
< /absolute/path/to/source.mp4 > /dev/null
|
||||
flutter test integration_test/android_real_media_test.dart -d DEVICE_SERIAL \
|
||||
fvm dart tool/flutter_local.dart test integration_test/android_real_media_test.dart -d DEVICE_SERIAL \
|
||||
--flavor development --no-uninstall \
|
||||
--dart-define=CUTDEX_VALIDATION_SOURCE=/data/user/0/com.example.cutdex.dev/files/real-media \
|
||||
--dart-define=CUTDEX_VALIDATION_ROOT=/data/user/0/com.example.cutdex.dev/files/real-validation
|
||||
```
|
||||
|
||||
Keep `--no-uninstall`: uninstalling also removes copied fixtures and validation
|
||||
reports. With `flutter drive`, use `--debug --keep-app-running` to retain them.
|
||||
reports. With `fvm dart tool/flutter_local.dart drive`, use `--debug --keep-app-running` to retain them.
|
||||
An optional
|
||||
`CUTDEX_VALIDATION_FILTER` selects filenames containing any comma-separated
|
||||
substring. `CUTDEX_VALIDATION_SAMPLE_START` selects the edit sample start in
|
||||
@@ -291,7 +364,7 @@ project. The test uses an in-memory recent-project registry and does not write
|
||||
to the normal application database. Without the required Dart defines, it skips.
|
||||
|
||||
```sh
|
||||
flutter test integration_test/downloads_workflow_test.dart -d macos \
|
||||
fvm dart tool/flutter_local.dart test integration_test/downloads_workflow_test.dart -d macos \
|
||||
--flavor development \
|
||||
--dart-define=CUTDEX_VALIDATION_SOURCE=/absolute/path/to/media \
|
||||
--dart-define=CUTDEX_VALIDATION_ROOT=/absolute/path/to/output
|
||||
@@ -335,7 +408,7 @@ Use an unlocked developer-enabled iPhone and a valid signing team. Select the iO
|
||||
other platforms. First install the test host using the shared empty-timeline test:
|
||||
|
||||
```sh
|
||||
flutter test integration_test/preview_startup_test.dart -d <iphone-udid> \
|
||||
fvm dart tool/flutter_local.dart test integration_test/preview_startup_test.dart -d <iphone-udid> \
|
||||
--flavor Runner --no-uninstall \
|
||||
--plain-name 'opening a timeline initializes native preview through App providers'
|
||||
```
|
||||
@@ -349,7 +422,7 @@ xcrun devicectl device copy to --device <iphone-udid> \
|
||||
--source /absolute/path/to/source.mp4 \
|
||||
--destination Documents/cutdex-validation-source.mp4 \
|
||||
--domain-type appDataContainer --domain-identifier com.example.cutdex
|
||||
flutter test integration_test/ios_device_test.dart -d <iphone-udid> \
|
||||
fvm dart tool/flutter_local.dart test integration_test/ios_device_test.dart -d <iphone-udid> \
|
||||
--flavor Runner --no-uninstall --reporter expanded \
|
||||
--dart-define=CUTDEX_TEST_SOURCE_DOCUMENT=cutdex-validation-source.mp4 \
|
||||
--dart-define=CUTDEX_TEST_OUTPUT=ios-keyframes
|
||||
@@ -379,7 +452,7 @@ seconds of usable video. Supply a file outside the repository with
|
||||
`CUTDEX_TEST_SOURCE`; `CUTDEX_TEST_OUTPUT` optionally preserves the export.
|
||||
|
||||
```sh
|
||||
flutter test integration_test/media_timebase_drop_test.dart -d macos \
|
||||
fvm dart tool/flutter_local.dart test integration_test/media_timebase_drop_test.dart -d macos \
|
||||
--flavor production \
|
||||
--dart-define=CUTDEX_TEST_SOURCE=/absolute/path/to/source.mp4 \
|
||||
--dart-define=CUTDEX_TEST_OUTPUT=/absolute/path/to/export.mp4
|
||||
@@ -396,7 +469,7 @@ streamed import into managed project storage, duplicate selection, byte identity
|
||||
native probing, thumbnails, playback, seeking and a video/audio export.
|
||||
|
||||
```sh
|
||||
flutter drive --debug --keep-app-running \
|
||||
fvm dart tool/flutter_local.dart drive --debug --keep-app-running \
|
||||
--driver=test_driver/integration_test.dart \
|
||||
--target=integration_test/android_document_import_test.dart \
|
||||
-d DEVICE_SERIAL --flavor development \
|
||||
@@ -416,3 +489,41 @@ remove the test's own project and exports afterward.
|
||||
Some devices disconnect the host driver while DocumentsUI is foreground. In
|
||||
that case, inspect the original application's log and private JSON reports; a
|
||||
driver disconnection alone does not establish whether the import succeeded.
|
||||
|
||||
## Android native Surface preview comparison
|
||||
|
||||
The development build can enable the experimental native source with the Gradle
|
||||
property `cutdexNativeSurfacePreview=true` or environment variable
|
||||
`CUTDEX_NATIVE_SURFACE_PREVIEW=true`. Production and default development builds
|
||||
leave it disabled. `android_decoder_material_performance_test.dart` uses the real
|
||||
EditorWorkspace with the whole original clip fitted into the timeline viewport.
|
||||
Set `CUTDEX_TEST_DECODER=media3-surface` to fail if the source falls back; use
|
||||
`ffmpeg` for the paired baseline. `CUTDEX_TEST_PLAYBACK=true` additionally records
|
||||
three seconds of unique frame changes, play/pause acknowledgments and a frozen
|
||||
paused frame. The existing seek/drag assertions independently check every observed
|
||||
frame against original rational packet PTS and require zero extra release seek
|
||||
or presentation for an already precise held picture.
|
||||
|
||||
Use a separate validation application ID to preserve the installed development
|
||||
application and its projects. Supply media and PTS files inside that validation
|
||||
app's sandbox; no personal fixture or benchmark report is committed here.
|
||||
For example, an explicitly admitted 60 fps / 90000 Hz source can be measured with:
|
||||
|
||||
```powershell
|
||||
$env:CUTDEX_VALIDATION_APPLICATION_ID = 'com.example.cutdex.decoder_validation'
|
||||
$env:CUTDEX_NATIVE_SURFACE_PREVIEW = 'true'
|
||||
fvm dart tool/flutter_local.dart drive --profile --flavor development -d DEVICE_ID --keep-app-running `
|
||||
--driver=test_driver/integration_test.dart `
|
||||
--target=integration_test/android_decoder_material_performance_test.dart `
|
||||
--dart-define=CUTDEX_TEST_SOURCE=/data/user/0/com.example.cutdex.decoder_validation.dev/files/source.mp4 `
|
||||
--dart-define=CUTDEX_TEST_SOURCE_PTS=/data/user/0/com.example.cutdex.decoder_validation.dev/files/source-pts.txt `
|
||||
--dart-define=CUTDEX_TEST_SOURCE_TIMESCALE=90000 --dart-define=CUTDEX_TEST_FRAME_STEP_US=16667 `
|
||||
--dart-define=CUTDEX_TEST_DECODER=media3-surface --dart-define=CUTDEX_TEST_PLAYBACK=true `
|
||||
--dart-define=CUTDEX_TEST_REPORT=/data/user/0/com.example.cutdex.decoder_validation.dev/files/native-results.json
|
||||
```
|
||||
|
||||
Repeat with `CUTDEX_NATIVE_SURFACE_PREVIEW=false`, `CUTDEX_TEST_DECODER=ffmpeg`
|
||||
and another report path for the software baseline. Restore the default environment
|
||||
and normal application entry point after testing. Record first-source indexing
|
||||
separately from warm seek timings. Only compare inputs with matching source clocks,
|
||||
targets, drag trajectories, audio/UI workloads and achieved input cadence.
|
||||
@@ -0,0 +1,730 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/app/editor_theme.dart';
|
||||
import 'package:cutdex/features/editor/editor_page.dart';
|
||||
import 'package:cutdex/features/preview/preview_panel.dart';
|
||||
import 'package:cutdex/integrations/platform/device_experience.dart';
|
||||
import 'package:cutdex/l10n/app_localizations.dart';
|
||||
import 'package:cutdex/persistence/app_database.dart';
|
||||
import 'package:cutdex/workspace/project_state.dart';
|
||||
import 'package:cutdex/workspace/projects.dart';
|
||||
import 'package:cutdex/workspace/timeline_provider.dart';
|
||||
import 'package:cutdex_core/editor.dart';
|
||||
import 'package:cutdex_preview/cutdex_preview.dart';
|
||||
import 'package:cutdex_core/project.dart';
|
||||
import 'package:cutdex_native_flutter/cutdex_native_flutter.dart';
|
||||
import 'package:cutdex_core/timeline/layout.dart';
|
||||
import 'package:cutdex_core/timeline/model.dart';
|
||||
import 'package:cutdex_timeline_ui/cutdex_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,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,8 @@ import 'package:cutdex/workspace/external_media_import.dart';
|
||||
import 'package:cutdex/workspace/media_import.dart';
|
||||
import 'package:cutdex/workspace/persistence/project_workspace.dart';
|
||||
import 'package:cutdex/workspace/persistence/timeline_creation_names.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_core/project.dart';
|
||||
import 'package:cutdex_native_flutter/cutdex_native_flutter.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:integration_test/integration_test.dart';
|
||||
|
||||
@@ -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_core/editor.dart';
|
||||
import 'package:cutdex_preview/cutdex_preview.dart';
|
||||
import 'package:cutdex_core/project.dart';
|
||||
import 'package:cutdex_native_flutter/cutdex_native_flutter.dart';
|
||||
import 'package:cutdex_core/timeline/layout.dart';
|
||||
import 'package:cutdex_core/timeline/model.dart';
|
||||
import 'package:cutdex_timeline_ui/cutdex_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,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -16,12 +16,14 @@ import 'package:cutdex/workspace/projects.dart';
|
||||
import 'package:cutdex/workspace/preview_controller_registry.dart';
|
||||
import 'package:cutdex/workspace/timeline_provider.dart';
|
||||
import 'package:cutdex_native/cutdex_native.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline/engine.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:cutdex_core/editor.dart';
|
||||
import 'package:cutdex_core/execution.dart';
|
||||
import 'package:cutdex_native_flutter/cutdex_native_flutter.dart';
|
||||
import 'package:cutdex_core/timeline/engine.dart';
|
||||
import 'package:cutdex_core/timeline/model.dart';
|
||||
import 'package:drift/native.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:integration_test/integration_test.dart';
|
||||
@@ -215,7 +217,12 @@ void main() {
|
||||
try {
|
||||
info = await runtime.probe(media);
|
||||
} catch (_) {
|
||||
final raw = await runtime.invoke('probe', {'media': media.toMap()});
|
||||
// This diagnostic test deliberately inspects the native wire response.
|
||||
final raw = await const MethodChannel('cutdex_runtime')
|
||||
.invokeMethod<Object?>('probe', {
|
||||
'contractVersion': 1,
|
||||
'media': media.toMap(),
|
||||
});
|
||||
result['rawProbeMetadata'] = raw;
|
||||
// Preserve the actual wire-contract failure in the device report.
|
||||
MediaInfo.fromMap(raw! as Map);
|
||||
|
||||
@@ -8,10 +8,11 @@ import 'package:cutdex/workspace/timeline_provider.dart';
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:cutdex/features/preview/preview_panel.dart';
|
||||
import 'package:cutdex_sdk/preview.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:cutdex_preview/cutdex_preview.dart';
|
||||
import 'package:cutdex_core/editor.dart';
|
||||
import 'package:cutdex_core/execution.dart';
|
||||
import 'package:cutdex_native_flutter/cutdex_native_flutter.dart';
|
||||
import 'package:cutdex_core/timeline/model.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
@@ -15,8 +15,8 @@ import 'package:cutdex/persistence/app_database.dart';
|
||||
import 'package:cutdex/workspace/media_file_extensions.dart';
|
||||
import 'package:cutdex/workspace/preview_target.dart';
|
||||
import 'package:cutdex/workspace/projects.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:cutdex_core/editor.dart';
|
||||
import 'package:cutdex_core/timeline/model.dart';
|
||||
import 'package:drift/native.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
@@ -19,10 +19,10 @@ import 'package:cutdex/workspace/media_file_extensions.dart';
|
||||
import 'package:cutdex/workspace/preview_target.dart';
|
||||
import 'package:cutdex/workspace/projects.dart';
|
||||
import 'package:cutdex/workspace/timeline_provider.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline/layout.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:cutdex_core/editor.dart';
|
||||
import 'package:cutdex_native_flutter/cutdex_native_flutter.dart';
|
||||
import 'package:cutdex_core/timeline/layout.dart';
|
||||
import 'package:cutdex_core/timeline/model.dart';
|
||||
import 'package:drift/native.dart';
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
@@ -13,11 +13,11 @@ import 'package:cutdex/l10n/app_localizations.dart';
|
||||
import 'package:cutdex/persistence/app_database.dart';
|
||||
import 'package:cutdex/workspace/timeline_provider.dart';
|
||||
import 'package:cutdex/workspace/timeline_session.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/preview.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:cutdex_core/editor.dart';
|
||||
import 'package:cutdex_preview/cutdex_preview.dart';
|
||||
import 'package:cutdex_core/project.dart';
|
||||
import 'package:cutdex_native_flutter/cutdex_native_flutter.dart';
|
||||
import 'package:cutdex_core/timeline/model.dart';
|
||||
import 'package:drift/native.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
@@ -6,11 +6,12 @@ import 'package:cutdex/workspace/persistence/project_workspace.dart';
|
||||
import 'package:cutdex/workspace/project_state.dart';
|
||||
import 'package:cutdex/workspace/projects.dart';
|
||||
import 'package:cutdex/workspace/timeline_session.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/preview.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:cutdex_core/project.dart';
|
||||
import 'package:cutdex_core/editor.dart';
|
||||
import 'package:cutdex_preview/cutdex_preview.dart';
|
||||
import 'package:cutdex_core/execution.dart';
|
||||
import 'package:cutdex_native_flutter/cutdex_native_flutter.dart';
|
||||
import 'package:cutdex_core/timeline/model.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
@@ -4,12 +4,13 @@ import 'package:cutdex/l10n/app_localizations.dart';
|
||||
import 'dart:io';
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_core/editor.dart';
|
||||
import 'package:cutdex/features/preview/preview_panel.dart';
|
||||
import 'package:cutdex/features/properties/picture_properties.dart';
|
||||
import 'package:cutdex_sdk/preview.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:cutdex_preview/cutdex_preview.dart';
|
||||
import 'package:cutdex_core/execution.dart';
|
||||
import 'package:cutdex_native_flutter/cutdex_native_flutter.dart';
|
||||
import 'package:cutdex_core/timeline/model.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/rendering.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
@@ -7,11 +7,12 @@ import 'package:cutdex/features/preview/preview_panel.dart';
|
||||
import 'package:cutdex/persistence/app_database.dart';
|
||||
import 'package:cutdex/workspace/projects.dart';
|
||||
import 'package:cutdex/workspace/timeline_provider.dart';
|
||||
import 'package:cutdex_sdk/preview.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:cutdex_sdk/timeline_ui.dart';
|
||||
import 'package:cutdex_preview/cutdex_preview.dart';
|
||||
import 'package:cutdex_native_flutter/cutdex_native_flutter.dart';
|
||||
import 'package:cutdex_core/timeline/model.dart';
|
||||
import 'package:cutdex_timeline_ui/cutdex_timeline_ui.dart';
|
||||
import 'package:drift/native.dart';
|
||||
import 'package:cutdex_ui/icons.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
@@ -161,9 +162,7 @@ void main() {
|
||||
|
||||
final panel = find.byType(EditorPreviewPanel);
|
||||
await tester.tap(
|
||||
find
|
||||
.descendant(of: panel, matching: find.byIcon(Icons.play_arrow))
|
||||
.first,
|
||||
find.descendant(of: panel, matching: find.byIcon(AppIcons.play)).first,
|
||||
);
|
||||
await until(() => preview.playing, label: 'UI play');
|
||||
await Future<void>.delayed(const Duration(milliseconds: 700));
|
||||
@@ -173,7 +172,7 @@ void main() {
|
||||
greaterThan(0),
|
||||
);
|
||||
await tester.tap(
|
||||
find.descendant(of: panel, matching: find.byIcon(Icons.pause)).first,
|
||||
find.descendant(of: panel, matching: find.byIcon(AppIcons.pause)).first,
|
||||
);
|
||||
await until(() => !preview.playing, label: 'UI pause');
|
||||
mark('real play and pause buttons advanced native media clock');
|
||||
|
||||
@@ -8,11 +8,11 @@ import 'package:cutdex/workspace/timeline_provider.dart';
|
||||
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:cutdex_sdk/preview.dart';
|
||||
import 'package:cutdex_preview/cutdex_preview.dart';
|
||||
import 'package:cutdex/features/preview/preview_panel.dart';
|
||||
import 'package:cutdex/features/properties/properties_panel.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:cutdex_native_flutter/cutdex_native_flutter.dart';
|
||||
import 'package:cutdex_core/timeline/model.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
@@ -3,9 +3,9 @@ import '../test/support/creation_names.dart';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/workspace/persistence/project_workspace.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_core/project.dart';
|
||||
import 'package:cutdex_core/timeline/model.dart';
|
||||
import 'package:cutdex_core/editor.dart';
|
||||
|
||||
import '../test/support/processing_fixture.dart';
|
||||
|
||||
|
||||
@@ -9,11 +9,11 @@ import 'dart:ui' as ui;
|
||||
|
||||
import 'package:cutdex/features/preview/preview_panel.dart';
|
||||
import 'package:cutdex/features/timeline/timeline_panel.dart';
|
||||
import 'package:cutdex_sdk/preview.dart';
|
||||
import 'package:cutdex_preview/cutdex_preview.dart';
|
||||
import 'package:cutdex/integrations/runtime/timeline_thumbnails.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:cutdex_sdk/timeline_ui.dart';
|
||||
import 'package:cutdex_native_flutter/cutdex_native_flutter.dart';
|
||||
import 'package:cutdex_core/timeline/model.dart';
|
||||
import 'package:cutdex_timeline_ui/cutdex_timeline_ui.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
@@ -6,10 +6,10 @@ import 'dart:convert';
|
||||
import 'package:cutdex/integrations/runtime/processing_configuration.dart';
|
||||
import 'package:cutdex/workspace/persistence/project_workspace.dart';
|
||||
import 'package:cutdex/workspace/timeline_session.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/preview.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:cutdex_core/editor.dart';
|
||||
import 'package:cutdex_preview/cutdex_preview.dart';
|
||||
import 'package:cutdex_native_flutter/cutdex_native_flutter.dart';
|
||||
import 'package:cutdex_core/timeline/model.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:integration_test/integration_test.dart';
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import 'dart:async';
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_native_flutter/cutdex_native_flutter.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import 'dart:math' as math;
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_native_flutter/cutdex_native_flutter.dart';
|
||||
import 'package:flutter/painting.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:cutdex_core/editor.dart';
|
||||
import 'package:cutdex_core/project.dart';
|
||||
import 'package:cutdex_core/timeline/model.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
class SavedEditValidation {
|
||||
|
||||
@@ -4,9 +4,9 @@ import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex/integrations/runtime/timeline_thumbnails.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline/engine.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:cutdex_native_flutter/cutdex_native_flutter.dart';
|
||||
import 'package:cutdex_core/timeline/engine.dart';
|
||||
import 'package:cutdex_core/timeline/model.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
@@ -17,11 +17,12 @@ import 'package:cutdex/workspace/media_import.dart';
|
||||
import 'package:cutdex/workspace/preview_controller_registry.dart';
|
||||
import 'package:cutdex/workspace/projects.dart';
|
||||
import 'package:cutdex/workspace/timeline_provider.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/preview.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline/engine.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:cutdex_core/editor.dart';
|
||||
import 'package:cutdex_preview/cutdex_preview.dart';
|
||||
import 'package:cutdex_core/execution.dart';
|
||||
import 'package:cutdex_native_flutter/cutdex_native_flutter.dart';
|
||||
import 'package:cutdex_core/timeline/engine.dart';
|
||||
import 'package:cutdex_core/timeline/model.dart';
|
||||
import 'package:drift/native.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
@@ -17,10 +17,11 @@ import 'package:cutdex/workspace/media_import.dart';
|
||||
import 'package:cutdex/workspace/projects.dart';
|
||||
import 'package:cutdex/workspace/preview_controller_registry.dart';
|
||||
import 'package:cutdex/workspace/timeline_provider.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline/engine.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:cutdex_core/editor.dart';
|
||||
import 'package:cutdex_core/execution.dart';
|
||||
import 'package:cutdex_native_flutter/cutdex_native_flutter.dart';
|
||||
import 'package:cutdex_core/timeline/engine.dart';
|
||||
import 'package:cutdex_core/timeline/model.dart';
|
||||
import 'package:drift/native.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
@@ -7,10 +7,10 @@ import 'dart:math' as math;
|
||||
import 'package:cutdex/features/preview/preview_panel.dart';
|
||||
import 'package:cutdex/l10n/app_localizations.dart';
|
||||
import 'package:cutdex/workspace/timeline_provider.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/preview.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:cutdex_core/editor.dart';
|
||||
import 'package:cutdex_preview/cutdex_preview.dart';
|
||||
import 'package:cutdex_native_flutter/cutdex_native_flutter.dart';
|
||||
import 'package:cutdex_core/timeline/model.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:cutdex/app/app.dart';
|
||||
import 'package:cutdex/integrations/agent/conversation_repository.dart';
|
||||
import 'package:cutdex/integrations/platform/device_experience.dart';
|
||||
import 'package:cutdex/persistence/app_database.dart';
|
||||
import 'package:cutdex/persistence/settings/view_settings_repositories.dart';
|
||||
import 'package:cutdex/workspace/projects.dart';
|
||||
import 'package:cutdex/workspace/view_settings.dart';
|
||||
import 'package:cutdex/workspace/workspace_mode.dart';
|
||||
import 'package:cutdex_core/project.dart';
|
||||
import 'package:cutdex_core/timeline/model.dart';
|
||||
import 'package:drift/native.dart';
|
||||
import 'package:flutter/foundation.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/empty_conversation_repository.dart';
|
||||
import '../test/support/preview_fixture.dart';
|
||||
|
||||
/// Run with flutter drive --profile on macOS and test_driver/integration_test.dart.
|
||||
/// Define CUTDEX_RESIZE_SOURCE (an image) and CUTDEX_RESIZE_REPORT (JSON output).
|
||||
/// Widget-test timings are not comparable to these real-engine measurements.
|
||||
void main() {
|
||||
final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();
|
||||
binding.framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.fullyLive;
|
||||
const source = String.fromEnvironment('CUTDEX_RESIZE_SOURCE');
|
||||
const output = String.fromEnvironment('CUTDEX_RESIZE_REPORT');
|
||||
const rounds = int.fromEnvironment('CUTDEX_RESIZE_ROUNDS', defaultValue: 3);
|
||||
const inputHz = 120;
|
||||
const inputCount = 240;
|
||||
const clipCount = 64;
|
||||
const assetCount = 100;
|
||||
|
||||
testWidgets('profile full desktop workspace split and junction dragging', (
|
||||
tester,
|
||||
) async {
|
||||
expect(kProfileMode, isTrue, reason: 'Use flutter drive --profile');
|
||||
expect(Platform.isMacOS, isTrue);
|
||||
expect(await File(source).exists(), isTrue);
|
||||
final ids = List.generate(clipCount, (i) => ElementId('clip-$i'));
|
||||
final fixture = await createPreviewFixture(
|
||||
File(source).uri,
|
||||
mediaType: 'image',
|
||||
renderSize: {'width': 1280, 'height': 720},
|
||||
timelineOverride: TimelineDto(
|
||||
id: SequenceId('one'),
|
||||
name: 'Resize profiling',
|
||||
format: TimelineFormat.fps30,
|
||||
primaryStorylineId: StorylineId('primary'),
|
||||
storylines: [StorylineDto(id: StorylineId('primary'), elementIds: ids)],
|
||||
elements: [
|
||||
for (final (i, id) in ids.indexed)
|
||||
ElementDto(
|
||||
id: id,
|
||||
name: 'Clip $i',
|
||||
structure: ElementStructure.content,
|
||||
payloadRef: PayloadRef('source'),
|
||||
duration: RationalTime.seconds(2),
|
||||
sourceRange: TimeRange(
|
||||
start: RationalTime.zero,
|
||||
duration: RationalTime.seconds(2),
|
||||
),
|
||||
mediaRange: TimeRange(
|
||||
start: RationalTime.zero,
|
||||
duration: RationalTime.seconds(2),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
for (var i = 0; i < assetCount; i++) {
|
||||
await fixture.workspace.project!.saveAsset(
|
||||
AssetDocument(
|
||||
id: i == 0 ? 'media' : 'media-$i',
|
||||
name: 'Image $i',
|
||||
storage: AssetStorage.external,
|
||||
location: File(source).uri.toString(),
|
||||
metadata: {'kind': 'image'},
|
||||
),
|
||||
);
|
||||
}
|
||||
final projectPath = '${fixture.directory.path}/Preview.cutdex';
|
||||
await fixture.workspace.close();
|
||||
final database = AppDatabase(
|
||||
NativeDatabase(File('${fixture.directory.path}/settings.sqlite')),
|
||||
);
|
||||
final workspaceWrites = _CountWorkspaceWrites(
|
||||
DriftWorkspaceViewSettingsRepository(database),
|
||||
);
|
||||
final projectWrites = _CountProjectWrites(
|
||||
DriftProjectViewSettingsRepository(database),
|
||||
);
|
||||
final container = ProviderContainer(
|
||||
overrides: [
|
||||
appDatabaseProvider.overrideWithValue(database),
|
||||
deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop),
|
||||
workspaceViewSettingsRepositoryProvider.overrideWithValue(
|
||||
workspaceWrites,
|
||||
),
|
||||
projectViewSettingsRepositoryProvider.overrideWithValue(projectWrites),
|
||||
conversationRepositoryProvider.overrideWith(
|
||||
(ref) async => EmptyConversationRepository(),
|
||||
),
|
||||
],
|
||||
);
|
||||
addTearDown(() async {
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
await container.read(projectsProvider.notifier).prepareToQuit();
|
||||
container.dispose();
|
||||
await database.close();
|
||||
await fixture.directory.delete(recursive: true);
|
||||
});
|
||||
await container.read(workspaceViewSettingsProvider.future);
|
||||
container
|
||||
.read(workspaceViewSettingsProvider.notifier)
|
||||
.setMode(WorkspaceMode.cut);
|
||||
expect(
|
||||
await container.read(projectsProvider.notifier).open(projectPath),
|
||||
isTrue,
|
||||
);
|
||||
// This is the normal app/router/editor, with only isolated storage and chat.
|
||||
// ignore: riverpod_lint/provider_scope_placement
|
||||
await tester.pumpWidget(
|
||||
UncontrolledProviderScope(container: container, child: const CutdexApp()),
|
||||
);
|
||||
await const MethodChannel('cutdex_native/window')
|
||||
.invokeMethod<void>('toggleMaximize');
|
||||
final readyClock = Stopwatch()..start();
|
||||
final junction = find.byKey(const Key('desktop-chat-timeline-junction'));
|
||||
while (junction.evaluate().isEmpty) {
|
||||
if (readyClock.elapsed.inSeconds > 60) {
|
||||
throw TimeoutException('Desktop editor did not open');
|
||||
}
|
||||
await tester.pump();
|
||||
await Future<void>.delayed(const Duration(milliseconds: 16));
|
||||
}
|
||||
await Future<void>.delayed(const Duration(seconds: 3));
|
||||
final size = tester.view.physicalSize / tester.view.devicePixelRatio;
|
||||
expect(size.width, greaterThan(1100));
|
||||
final results = <String, dynamic>{
|
||||
'mode': 'profile',
|
||||
'platform': Platform.operatingSystemVersion,
|
||||
'logicalSize': [size.width, size.height],
|
||||
'pixelRatio': tester.view.devicePixelRatio,
|
||||
'displayRefreshHz': tester.view.display.refreshRate,
|
||||
'inputHz': inputHz,
|
||||
'inputsPerDrag': inputCount,
|
||||
'clips': clipCount,
|
||||
'assets': assetCount,
|
||||
'scope': 'Full app, native still-image preview, file-backed SQLite; synthetic mouse input',
|
||||
'runs': <Map<String, dynamic>>[],
|
||||
};
|
||||
final report = File(output);
|
||||
await report.parent.create(recursive: true);
|
||||
Future<void> save() => report.writeAsString(
|
||||
const JsonEncoder.withIndent(' ').convert(results),
|
||||
);
|
||||
await save();
|
||||
const scenarios = {
|
||||
'sidebar': ('project-sidebar-resize', Offset(55, 0)),
|
||||
'media': ('editor-media-resize', Offset(65, 0)),
|
||||
'timeline': ('editor-timeline-resize', Offset(0, 80)),
|
||||
'mediaJunction': ('editor-media-timeline-junction', Offset(65, 80)),
|
||||
'chatJunction': ('desktop-chat-timeline-junction', Offset(55, 80)),
|
||||
};
|
||||
for (var round = 0; round < rounds; round++) {
|
||||
for (final entry in scenarios.entries) {
|
||||
final (key, amplitude) = entry.value;
|
||||
final reportKey = '${entry.key}-$round';
|
||||
final start = tester.getCenter(find.byKey(Key(key)));
|
||||
final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
|
||||
await mouse.addPointer(location: start);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 250));
|
||||
final writesBefore = workspaceWrites.count;
|
||||
final projectWritesBefore = projectWrites.count;
|
||||
final dispatchTimes = <int>[];
|
||||
await binding.watchPerformance(() async {
|
||||
await mouse.down(start);
|
||||
final clock = Stopwatch()..start();
|
||||
for (var i = 1; i <= inputCount; i++) {
|
||||
final dueUs = (i * 1000000 / inputHz).round();
|
||||
final waitUs = dueUs - clock.elapsedMicroseconds;
|
||||
if (waitUs > 0) {
|
||||
await Future<void>.delayed(Duration(microseconds: waitUs));
|
||||
}
|
||||
final dispatch = Stopwatch()..start();
|
||||
await mouse.moveTo(
|
||||
start + amplitude * math.sin(2 * math.pi * i / inputCount),
|
||||
);
|
||||
dispatchTimes.add(dispatch.elapsedMicroseconds);
|
||||
}
|
||||
await mouse.up();
|
||||
await mouse.removePointer();
|
||||
}, reportKey: reportKey);
|
||||
// Allow queued persistence writes and batched engine timings to arrive.
|
||||
await Future<void>.delayed(const Duration(seconds: 1));
|
||||
final timings = Map<String, dynamic>.from(
|
||||
binding.reportData![reportKey] as Map,
|
||||
);
|
||||
final build = List<int>.from(timings['frame_build_times'] as List);
|
||||
final raster = List<int>.from(
|
||||
timings['frame_rasterizer_times'] as List,
|
||||
);
|
||||
int overBudget(int budgetUs) => List.generate(
|
||||
build.length,
|
||||
(i) => i,
|
||||
).where((i) => build[i] > budgetUs || raster[i] > budgetUs).length;
|
||||
final row = <String, dynamic>{
|
||||
'scenario': entry.key,
|
||||
'round': round,
|
||||
'workspaceWrites': workspaceWrites.count - writesBefore,
|
||||
'projectWrites': projectWrites.count - projectWritesBefore,
|
||||
'over16ms': overBudget(16667),
|
||||
'over8ms': overBudget(8333),
|
||||
'dispatchUs': dispatchTimes,
|
||||
'timings': timings,
|
||||
};
|
||||
(results['runs'] as List).add(row);
|
||||
await save();
|
||||
debugPrint(
|
||||
'RESIZE_PROFILE ${entry.key} $round frames=${build.length} '
|
||||
'over16ms=${row['over16ms']} writes=${row['workspaceWrites']}',
|
||||
);
|
||||
}
|
||||
}
|
||||
results['status'] = 'passed';
|
||||
await save();
|
||||
expect(tester.takeException(), isNull);
|
||||
}, skip: !Platform.isMacOS || source.isEmpty || output.isEmpty);
|
||||
}
|
||||
|
||||
class _CountWorkspaceWrites implements WorkspaceViewSettingsRepository {
|
||||
_CountWorkspaceWrites(this.delegate);
|
||||
final WorkspaceViewSettingsRepository delegate;
|
||||
int count = 0;
|
||||
@override
|
||||
Future<WorkspaceViewSettingsData> load() => delegate.load();
|
||||
@override
|
||||
Future<void> save(WorkspaceViewSettingsData settings) {
|
||||
count++;
|
||||
return delegate.save(settings);
|
||||
}
|
||||
}
|
||||
|
||||
class _CountProjectWrites implements ProjectViewSettingsRepository {
|
||||
_CountProjectWrites(this.delegate);
|
||||
final ProjectViewSettingsRepository delegate;
|
||||
int count = 0;
|
||||
@override
|
||||
Future<ProjectViewSettingsData> load(String id) => delegate.load(id);
|
||||
@override
|
||||
Future<void> save(String id, ProjectViewSettingsData settings) {
|
||||
count++;
|
||||
return delegate.save(id, settings);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
enum DesktopContent { workspace, library, resourceLibrary, workflow, 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.
|
||||
class DesktopWorkspaceController extends ChangeNotifier {
|
||||
double? _agentWidth;
|
||||
bool _editorCollapsedByAgent = false;
|
||||
bool _agentFullscreen = false;
|
||||
bool _agentFloating = false;
|
||||
bool _agentFloatingExpanded = false;
|
||||
bool _agentVisible = false;
|
||||
|
||||
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;
|
||||
_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();
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,7 @@ abstract final class WorkspaceLayoutPolicy {
|
||||
width >=
|
||||
WorkspaceLayoutMetrics.sidebarMinimumWidth +
|
||||
WorkspaceLayoutMetrics.contentMinimumWidth +
|
||||
1;
|
||||
WorkspaceLayoutMetrics.desktopSpacing;
|
||||
|
||||
static bool showAgentBesideEditor(double width) =>
|
||||
width >= WorkspaceLayoutMetrics.dualPaneMinimumWidth;
|
||||
@@ -23,8 +23,7 @@ final class DesktopWorkspaceGeometry {
|
||||
required this.editorHidden,
|
||||
});
|
||||
|
||||
static const editorCollapseWidth = 480.0;
|
||||
static const editorCollapseDragBuffer = editorCollapseWidth / 3;
|
||||
static const editorMinimumWidth = 480.0;
|
||||
static const editorRestoreWidth = 560.0;
|
||||
|
||||
final double sidebarWidth;
|
||||
@@ -42,7 +41,7 @@ final class DesktopWorkspaceGeometry {
|
||||
required bool sidebarCollapsed,
|
||||
double? sidebarWidth,
|
||||
double? agentWidth,
|
||||
bool editorCollapsedByAgent = false,
|
||||
bool agentFullscreen = false,
|
||||
}) {
|
||||
final navigationWidth =
|
||||
(sidebarWidth ?? WorkspaceLayoutMetrics.sidebarDefaultWidth)
|
||||
@@ -57,19 +56,17 @@ final class DesktopWorkspaceGeometry {
|
||||
.clamp(220.0, math.max(220.0, width - navigationSpace - 1))
|
||||
.toDouble()
|
||||
: 0.0;
|
||||
final remaining = width - navigationSpace - requestedAgentWidth - 1;
|
||||
final hidden =
|
||||
mode == WorkspaceMode.agent &&
|
||||
(width - navigationSpace - 1 < 220 + editorCollapseWidth ||
|
||||
(editorCollapsedByAgent && remaining < editorRestoreWidth) ||
|
||||
remaining <= editorCollapseWidth - editorCollapseDragBuffer);
|
||||
(width - navigationSpace - 1 < 220 + editorMinimumWidth ||
|
||||
agentFullscreen);
|
||||
return DesktopWorkspaceGeometry(
|
||||
sidebarWidth: navigationWidth,
|
||||
agentWidth: hidden
|
||||
? width - navigationSpace
|
||||
: mode == WorkspaceMode.agent
|
||||
? requestedAgentWidth
|
||||
.clamp(220.0, width - navigationSpace - editorCollapseWidth - 1)
|
||||
.clamp(220.0, width - navigationSpace - editorMinimumWidth - 1)
|
||||
.toDouble()
|
||||
: 0,
|
||||
editorHidden: hidden,
|
||||
|
||||
+17
-4
@@ -10,26 +10,39 @@ import 'router/app_router.dart';
|
||||
import '../integrations/app_updates.dart';
|
||||
import '../integrations/editor_tools.dart';
|
||||
import '../features/settings/appearance_settings.dart';
|
||||
import '../shared/widgets/error_notification_host.dart';
|
||||
import '../integrations/platform/device_experience.dart';
|
||||
|
||||
class CutdexApp extends ConsumerWidget {
|
||||
const CutdexApp({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
ref.watch(applicationMcpConnectionProvider);
|
||||
ref.watch(appUpdateLifecycleProvider);
|
||||
ref.watch(applicationMcpConnectionProvider.select((_) => null));
|
||||
ref.watch(appUpdateLifecycleProvider.select((_) => null));
|
||||
final appearance =
|
||||
ref.watch(appearanceSettingsProvider).asData?.value ??
|
||||
AppAppearance.system;
|
||||
final palette =
|
||||
ref.watch(paletteSettingsProvider).asData?.value ?? AppPalette.graphite;
|
||||
final desktop =
|
||||
ref.watch(deviceExperienceProvider) == DeviceExperience.desktop;
|
||||
ThemeData theme(Brightness brightness) {
|
||||
final base = EditorTheme.forPalette(palette, brightness);
|
||||
return desktop ? EditorTheme.desktop(base) : base;
|
||||
}
|
||||
|
||||
return MaterialApp.router(
|
||||
builder: (context, child) =>
|
||||
ErrorNotificationHost(child: child ?? const SizedBox.shrink()),
|
||||
title: 'Cutdex',
|
||||
locale: ref.watch(languageSettingsProvider).asData?.value.locale,
|
||||
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
||||
supportedLocales: AppLocalizations.supportedLocales,
|
||||
localeListResolutionCallback: resolveAppLocale,
|
||||
debugShowCheckedModeBanner: false,
|
||||
theme: EditorTheme.penLight,
|
||||
darkTheme: EditorTheme.penDark,
|
||||
theme: theme(Brightness.light),
|
||||
darkTheme: theme(Brightness.dark),
|
||||
themeMode: appearance.themeMode,
|
||||
routerConfig: ref.watch(appRouterProvider),
|
||||
);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
import 'package:cutdex_sdk/timeline_ui.dart';
|
||||
import 'package:cutdex_timeline_ui/cutdex_timeline_ui.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Connects the application palette to the SDK timeline presentation.
|
||||
@@ -7,10 +7,39 @@ abstract final class EditorTheme {
|
||||
static ThemeData get penLight => adapt(AppTheme.penLight);
|
||||
static ThemeData get penDark => adapt(AppTheme.penDark);
|
||||
|
||||
static ThemeData forPalette(AppPalette palette, Brightness brightness) =>
|
||||
adapt(AppTheme.forPalette(palette, brightness));
|
||||
|
||||
static ThemeData desktop(ThemeData theme) {
|
||||
final desktop = AppTheme.desktopWorkspaceTheme(theme);
|
||||
final timeline = desktop.extension<TimelineThemeData>();
|
||||
if (timeline == null) return desktop;
|
||||
return desktop.copyWith(
|
||||
extensions: [
|
||||
...desktop.extensions.values.where(
|
||||
(value) => value is! TimelineThemeData,
|
||||
),
|
||||
timeline.copyWith(
|
||||
rulerHeight: AppDesktopMetrics.timelineRuler,
|
||||
rulerTextStyle: timeline.rulerTextStyle.copyWith(
|
||||
fontSize: 12,
|
||||
height: 16 / 12,
|
||||
fontFeatures: const [FontFeature.tabularFigures()],
|
||||
),
|
||||
playheadColor: desktop.colorScheme.primary,
|
||||
clipHeaderHeight: 20,
|
||||
clipHeaderPadding: 4,
|
||||
clipNameTextStyle: timeline.clipNameTextStyle.copyWith(
|
||||
fontSize: 11,
|
||||
height: 16 / 11,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
static ThemeData adapt(ThemeData theme) {
|
||||
final palette = theme.brightness == Brightness.dark
|
||||
? AppColors.penDark
|
||||
: AppColors.penLight;
|
||||
final palette = AppColors.of(theme);
|
||||
final dark = theme.brightness == Brightness.dark;
|
||||
final text = theme.textTheme;
|
||||
final timelineBorder = palette.divider;
|
||||
@@ -27,8 +56,8 @@ abstract final class EditorTheme {
|
||||
backgroundColor: palette.background,
|
||||
primaryLaneBackgroundColor: palette.sidebar,
|
||||
visualClipColor: palette.visualClip,
|
||||
audioClipColor: palette.popover,
|
||||
audioAccentColor: timelineSecondary,
|
||||
audioClipColor: palette.audioClip,
|
||||
audioAccentColor: palette.audioWaveform,
|
||||
gapColor: timelineBorder,
|
||||
gapBorderColor: timelineBorder,
|
||||
containerAccentColor: timelineSecondary,
|
||||
@@ -37,7 +66,7 @@ abstract final class EditorTheme {
|
||||
connectionLineWidth: 3,
|
||||
clipBorderColor: timelineBorder,
|
||||
clipBorderWidth: 1,
|
||||
selectionOutlineColor: palette.foreground,
|
||||
selectionOutlineColor: palette.selection,
|
||||
selectionOutlineWidth: 2,
|
||||
keyframeColor: timelineSecondary,
|
||||
keyframeBorderColor: palette.background,
|
||||
|
||||
@@ -4,6 +4,7 @@ import 'package:go_router/go_router.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
import '../../features/projects/projects_page.dart';
|
||||
import '../../features/settings/settings_page.dart';
|
||||
|
||||
part 'app_router.g.dart';
|
||||
|
||||
@@ -12,7 +13,23 @@ part 'app_router.g.dart';
|
||||
GoRouter appRouter(Ref ref) {
|
||||
final router = GoRouter(
|
||||
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(
|
||||
body: Center(
|
||||
|
||||
@@ -48,4 +48,4 @@ final class AppRouterProvider
|
||||
}
|
||||
}
|
||||
|
||||
String _$appRouterHash() => r'ebb3f9239a43568767def98552081806bd614bb4';
|
||||
String _$appRouterHash() => r'ea1ed83ca5ca1f7079b268b1a94940d575b6ddf9';
|
||||
@@ -0,0 +1,251 @@
|
||||
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.workflowSelected = false,
|
||||
required this.onHomePressed,
|
||||
required this.onWorkflowPressed,
|
||||
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 workflowSelected;
|
||||
final VoidCallback onHomePressed;
|
||||
final VoidCallback onWorkflowPressed;
|
||||
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: [
|
||||
SizedBox(
|
||||
key: const Key('desktop-navigation-rail'),
|
||||
width: railWidth,
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) => SingleChildScrollView(
|
||||
child: ConstrainedBox(
|
||||
constraints: BoxConstraints(
|
||||
minHeight: constraints.maxHeight,
|
||||
),
|
||||
child: IntrinsicHeight(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 10),
|
||||
child: Column(
|
||||
children: [
|
||||
IconButton.filledTonal(
|
||||
key: const ValueKey('desktop-rail-home'),
|
||||
tooltip: context.l10n.navigationHome,
|
||||
isSelected:
|
||||
!settingsSelected && !workflowSelected,
|
||||
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 || workflowSelected
|
||||
? Colors.transparent
|
||||
: null,
|
||||
),
|
||||
onPressed: onHomePressed,
|
||||
icon: const Icon(AppIcons.home),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
IconButton.filledTonal(
|
||||
key: const ValueKey('desktop-rail-workflow'),
|
||||
tooltip: context.l10n.workflow,
|
||||
isSelected: workflowSelected,
|
||||
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: workflowSelected
|
||||
? null
|
||||
: Colors.transparent,
|
||||
),
|
||||
onPressed: onWorkflowPressed,
|
||||
icon: const Icon(AppIcons.timeline),
|
||||
),
|
||||
const Spacer(),
|
||||
IconButton(
|
||||
key: const Key('desktop-rail-settings'),
|
||||
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: const EdgeInsets.only(
|
||||
left: contentInset,
|
||||
right: contentInset,
|
||||
bottom: contentInset,
|
||||
),
|
||||
child: SizedBox(
|
||||
key: const Key('desktop-content-container'),
|
||||
child: WindowHeaderPane(
|
||||
offset: const Offset(
|
||||
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,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -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 '../../workspace/workspace_mode.dart';
|
||||
import '../../shared/layout/workspace_layout_metrics.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
import 'package:cutdex_native/cutdex_native.dart';
|
||||
import 'package:cutdex_ui/widgets.dart';
|
||||
|
||||
import '../adaptive/desktop_workspace_controller.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(
|
||||
DesktopWorkspaceGeometry geometry,
|
||||
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 {
|
||||
const DesktopWorkspaceShell({
|
||||
super.key,
|
||||
@@ -27,11 +27,19 @@ class DesktopWorkspaceShell extends StatefulWidget {
|
||||
required this.onSidebarCollapsedChanged,
|
||||
required this.onSidebarWidthChanged,
|
||||
required this.sidebarBuilder,
|
||||
required this.agentBuilder,
|
||||
required this.editor,
|
||||
required this.scaffoldKey,
|
||||
required this.navigationDrawer,
|
||||
this.projectTabsLayout = false,
|
||||
this.timelineHeight,
|
||||
this.onTimelineHeightChanged,
|
||||
this.onJunctionResizeEnd,
|
||||
this.onSidebarResizeEnd,
|
||||
this.sidebarCanExpand = true,
|
||||
});
|
||||
|
||||
static const gutterWidth = WorkspaceLayoutMetrics.desktopSpacing;
|
||||
final WorkspaceMode mode;
|
||||
final DesktopWorkspaceController controller;
|
||||
final bool sidebarCollapsed;
|
||||
@@ -39,17 +47,57 @@ class DesktopWorkspaceShell extends StatefulWidget {
|
||||
final ValueChanged<bool> onSidebarCollapsedChanged;
|
||||
final ValueChanged<double> onSidebarWidthChanged;
|
||||
final WorkspaceSidebarBuilder sidebarBuilder;
|
||||
final WorkspaceSidebarBuilder agentBuilder;
|
||||
final Widget editor;
|
||||
final GlobalKey<ScaffoldState> scaffoldKey;
|
||||
final Widget navigationDrawer;
|
||||
final bool projectTabsLayout;
|
||||
final double? timelineHeight;
|
||||
final ValueChanged<double>? onTimelineHeightChanged;
|
||||
final VoidCallback? onJunctionResizeEnd;
|
||||
final VoidCallback? onSidebarResizeEnd;
|
||||
final bool sidebarCanExpand;
|
||||
|
||||
@override
|
||||
State<DesktopWorkspaceShell> createState() => _DesktopWorkspaceShellState();
|
||||
}
|
||||
|
||||
class _DesktopWorkspaceShellState extends State<DesktopWorkspaceShell> {
|
||||
double? get _agentWidth => widget.controller.agentWidth;
|
||||
bool get _editorCollapsedByAgent => widget.controller.editorCollapsedByAgent;
|
||||
double? _sidebarRestoreWidth;
|
||||
bool _sidebarJunctionDragging = false;
|
||||
|
||||
void _startSidebarResize(double width, {bool junction = false}) {
|
||||
_sidebarRestoreWidth = width;
|
||||
if (junction) setState(() => _sidebarJunctionDragging = true);
|
||||
}
|
||||
|
||||
void _resizeSidebar(double requestedWidth, double maximum) {
|
||||
if (!widget.sidebarCanExpand || widget.controller.agentFloating) return;
|
||||
if (requestedWidth < WorkspaceLayoutMetrics.sidebarSnapThreshold) {
|
||||
if (!widget.sidebarCollapsed) {
|
||||
final restoreWidth = _sidebarRestoreWidth;
|
||||
if (restoreWidth != null && widget.sidebarWidth != restoreWidth) {
|
||||
widget.onSidebarWidthChanged(restoreWidth);
|
||||
}
|
||||
widget.onSidebarCollapsedChanged(true);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (widget.sidebarCollapsed) widget.onSidebarCollapsedChanged(false);
|
||||
widget.onSidebarWidthChanged(
|
||||
requestedWidth.clamp(WorkspaceLayoutMetrics.sidebarMinimumWidth, maximum),
|
||||
);
|
||||
}
|
||||
|
||||
void _finishSidebarResize() {
|
||||
_sidebarRestoreWidth = null;
|
||||
if (_sidebarJunctionDragging) {
|
||||
setState(() => _sidebarJunctionDragging = false);
|
||||
widget.onJunctionResizeEnd?.call();
|
||||
} else {
|
||||
widget.onSidebarResizeEnd?.call();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
@@ -62,6 +110,11 @@ class _DesktopWorkspaceShellState extends State<DesktopWorkspaceShell> {
|
||||
@override
|
||||
void didUpdateWidget(covariant DesktopWorkspaceShell oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (widget.controller.agentFloating ||
|
||||
!widget.sidebarCanExpand ||
|
||||
widget.onTimelineHeightChanged == null) {
|
||||
_sidebarJunctionDragging = false;
|
||||
}
|
||||
if (oldWidget.controller != widget.controller) {
|
||||
oldWidget.controller.removeListener(_changed);
|
||||
widget.controller.addListener(_changed);
|
||||
@@ -74,197 +127,383 @@ class _DesktopWorkspaceShellState extends State<DesktopWorkspaceShell> {
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
double? _sidebarDragStart;
|
||||
double _sidebarDragWidth = 0;
|
||||
double? _agentDragStart;
|
||||
double _agentDragWidth = 0;
|
||||
Widget _card(String name, Widget child) =>
|
||||
WorkspaceCard(key: Key('desktop-$name-card'), child: child);
|
||||
|
||||
Widget _gutter({
|
||||
required String name,
|
||||
required double initialWidth,
|
||||
required ValueChanged<double> onResize,
|
||||
double direction = 1,
|
||||
VoidCallback? onEnd,
|
||||
VoidCallback? onStart,
|
||||
Set<WorkspaceResizeBoundary> highlightTargets = const {},
|
||||
Offset highlightOffset = Offset.zero,
|
||||
}) => SizedBox(
|
||||
width: WorkspaceLayoutMetrics.desktopResizeHitExtent,
|
||||
height: double.infinity,
|
||||
child: WorkspaceResizeHandle(
|
||||
key: Key('$name-resize'),
|
||||
axis: Axis.horizontal,
|
||||
initialValue: initialWidth,
|
||||
direction: direction,
|
||||
onResize: onResize,
|
||||
onEnd: onEnd,
|
||||
onStart: onStart,
|
||||
highlightTargets: highlightTargets,
|
||||
highlightOffset: highlightOffset,
|
||||
),
|
||||
);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final width = constraints.maxWidth;
|
||||
final geometry = DesktopWorkspaceGeometry.resolve(
|
||||
width: width,
|
||||
mode: widget.mode,
|
||||
sidebarCollapsed: widget.sidebarCollapsed,
|
||||
sidebarWidth: widget.sidebarWidth,
|
||||
agentWidth: _agentWidth,
|
||||
editorCollapsedByAgent: _editorCollapsedByAgent,
|
||||
);
|
||||
final navigationSpace = widget.sidebarCollapsed
|
||||
? 0.0
|
||||
: geometry.sidebarWidth;
|
||||
void expandEditor() {
|
||||
final collapseNavigation = width - navigationSpace - 1 < 780;
|
||||
if (collapseNavigation) widget.onSidebarCollapsedChanged(true);
|
||||
widget.controller.setSplit(
|
||||
width -
|
||||
(collapseNavigation ? 0 : navigationSpace) -
|
||||
DesktopWorkspaceGeometry.editorRestoreWidth -
|
||||
1,
|
||||
editorCollapsed: false,
|
||||
);
|
||||
}
|
||||
Widget build(BuildContext context) =>
|
||||
WorkspaceResizeHighlightScope(child: _workspace(context));
|
||||
|
||||
return Scaffold(
|
||||
key: widget.scaffoldKey,
|
||||
drawer: Drawer(
|
||||
width: 320,
|
||||
child: SafeArea(child: widget.navigationDrawer),
|
||||
),
|
||||
body: Stack(
|
||||
key: const Key('desktop-workspace-shell'),
|
||||
fit: StackFit.expand,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
if (!widget.sidebarCollapsed ||
|
||||
widget.mode == WorkspaceMode.agent)
|
||||
SizedBox(
|
||||
width: navigationSpace + geometry.agentWidth,
|
||||
child: widget.sidebarBuilder(geometry, expandEditor),
|
||||
),
|
||||
if (!widget.sidebarCollapsed && !geometry.editorHidden)
|
||||
SizedBox(
|
||||
width: 1,
|
||||
height: double.infinity,
|
||||
child: ColoredBox(
|
||||
key: const Key('project-sidebar-separator'),
|
||||
color: AppTheme.sidebarDividerColor(context),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: Offstage(
|
||||
key: const Key('editor-auto-collapse'),
|
||||
offstage: geometry.editorHidden,
|
||||
child: TickerMode(
|
||||
enabled: !geometry.editorHidden,
|
||||
child: OverflowBox(
|
||||
alignment: Alignment.topLeft,
|
||||
minWidth: geometry.editorHidden
|
||||
? DesktopWorkspaceGeometry.editorRestoreWidth
|
||||
: null,
|
||||
maxWidth: geometry.editorHidden
|
||||
? DesktopWorkspaceGeometry.editorRestoreWidth
|
||||
: null,
|
||||
child: WindowHeaderPane(
|
||||
offset: Offset(
|
||||
navigationSpace +
|
||||
geometry.agentWidth +
|
||||
(!widget.sidebarCollapsed &&
|
||||
!geometry.editorHidden
|
||||
? 1
|
||||
: 0),
|
||||
0,
|
||||
Widget _workspace(BuildContext context) => widget.projectTabsLayout
|
||||
? _projectWorkspace(context)
|
||||
: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
const gap = DesktopWorkspaceShell.gutterWidth;
|
||||
final width = constraints.maxWidth;
|
||||
final requestedFloating = widget.controller.agentFloating;
|
||||
final showAgent =
|
||||
widget.mode == WorkspaceMode.agent ||
|
||||
widget.controller.agentVisible;
|
||||
final navigationGap = widget.sidebarCollapsed ? 0.0 : gap;
|
||||
final resolved = DesktopWorkspaceGeometry.resolve(
|
||||
// The geometry policy accounts for a one-pixel divider; reserve gutters.
|
||||
width: width - navigationGap - gap + 1,
|
||||
mode: requestedFloating || !showAgent
|
||||
? WorkspaceMode.cut
|
||||
: WorkspaceMode.agent,
|
||||
sidebarCollapsed: widget.sidebarCollapsed,
|
||||
sidebarWidth: widget.sidebarWidth,
|
||||
agentWidth: widget.controller.agentWidth,
|
||||
agentFullscreen: widget.controller.agentFullscreen,
|
||||
);
|
||||
final navigationSpace = widget.sidebarCollapsed
|
||||
? 0.0
|
||||
: resolved.sidebarWidth;
|
||||
final floating =
|
||||
requestedFloating ||
|
||||
(showAgent &&
|
||||
widget.mode == WorkspaceMode.cut &&
|
||||
resolved.editorHidden &&
|
||||
!widget.controller.agentFullscreen);
|
||||
final agentHidden =
|
||||
floating ||
|
||||
!showAgent ||
|
||||
resolved.editorHidden &&
|
||||
widget.mode == WorkspaceMode.cut &&
|
||||
!widget.controller.agentFullscreen;
|
||||
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(
|
||||
key: widget.scaffoldKey,
|
||||
drawerEnableOpenDragGesture: false,
|
||||
backgroundColor: Colors.transparent,
|
||||
drawer: Drawer(
|
||||
width: 320,
|
||||
child: SafeArea(child: widget.navigationDrawer),
|
||||
),
|
||||
body: Stack(
|
||||
key: const Key('desktop-workspace-shell'),
|
||||
children: [
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
if (!widget.sidebarCollapsed) ...[
|
||||
SizedBox(
|
||||
width: navigationSpace,
|
||||
child: _card(
|
||||
'project',
|
||||
widget.sidebarBuilder(geometry, expandEditor),
|
||||
),
|
||||
child: widget.editor,
|
||||
),
|
||||
const SizedBox(
|
||||
key: Key('project-sidebar-divider'),
|
||||
width: gap,
|
||||
),
|
||||
],
|
||||
Expanded(
|
||||
child: Offstage(
|
||||
key: const Key('editor-auto-collapse'),
|
||||
offstage: geometry.editorHidden,
|
||||
child: TickerMode(
|
||||
enabled: !geometry.editorHidden,
|
||||
child: OverflowBox(
|
||||
alignment: Alignment.topLeft,
|
||||
minWidth: geometry.editorHidden
|
||||
? DesktopWorkspaceGeometry.editorRestoreWidth
|
||||
: null,
|
||||
maxWidth: geometry.editorHidden
|
||||
? DesktopWorkspaceGeometry.editorRestoreWidth
|
||||
: null,
|
||||
child: SizedBox(
|
||||
key: const Key('desktop-editor-card'),
|
||||
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)
|
||||
Positioned(
|
||||
left:
|
||||
navigationSpace -
|
||||
WorkspaceLayoutMetrics.desktopResizeSlop,
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
child: _gutter(
|
||||
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 -
|
||||
gap -
|
||||
WorkspaceLayoutMetrics.desktopResizeSlop,
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
child: _gutter(
|
||||
name: 'agent-panel',
|
||||
initialWidth: geometry.agentWidth,
|
||||
direction: -1,
|
||||
onResize: resizeAgent,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
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;
|
||||
double resolveTimelineHeight(double? height) =>
|
||||
WorkspaceLayoutMetrics.resolveTimelineHeight(
|
||||
constraints.maxHeight,
|
||||
height,
|
||||
);
|
||||
final timelineHeight = resolveTimelineHeight(widget.timelineHeight);
|
||||
final geometry = DesktopWorkspaceGeometry(
|
||||
sidebarWidth: sidebarWidth,
|
||||
agentWidth: 0,
|
||||
editorHidden: false,
|
||||
);
|
||||
return Scaffold(
|
||||
key: widget.scaffoldKey,
|
||||
drawerEnableOpenDragGesture: false,
|
||||
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 (!widget.sidebarCollapsed)
|
||||
Positioned(
|
||||
key: const Key('project-sidebar-divider'),
|
||||
top: AppControlSize.panelHeader,
|
||||
bottom: 0,
|
||||
left: geometry.sidebarWidth - 4,
|
||||
width: 8,
|
||||
child: MouseRegion(
|
||||
cursor: SystemMouseCursors.resizeColumn,
|
||||
child: GestureDetector(
|
||||
key: const Key('project-sidebar-resize'),
|
||||
behavior: HitTestBehavior.opaque,
|
||||
dragStartBehavior: DragStartBehavior.down,
|
||||
onHorizontalDragStart: (details) {
|
||||
_sidebarDragStart = details.globalPosition.dx;
|
||||
_sidebarDragWidth = geometry.sidebarWidth;
|
||||
},
|
||||
onHorizontalDragUpdate: (details) {
|
||||
final start = _sidebarDragStart;
|
||||
if (start == null) return;
|
||||
widget.onSidebarWidthChanged(
|
||||
(_sidebarDragWidth + details.globalPosition.dx - start)
|
||||
.clamp(
|
||||
WorkspaceLayoutMetrics.sidebarMinimumWidth,
|
||||
DesktopWorkspaceGeometry.sidebarMaximum(
|
||||
width,
|
||||
widget.mode,
|
||||
),
|
||||
)
|
||||
.toDouble(),
|
||||
);
|
||||
},
|
||||
onHorizontalDragEnd: (_) => _sidebarDragStart = null,
|
||||
onHorizontalDragCancel: () => _sidebarDragStart = null,
|
||||
child: const SizedBox.expand(),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (widget.mode == WorkspaceMode.agent &&
|
||||
width - navigationSpace - 1 >= 220)
|
||||
if (!floating &&
|
||||
widget.sidebarCanExpand &&
|
||||
WorkspaceLayoutPolicy.desktopNavigationFits(width))
|
||||
Positioned(
|
||||
left: collapsed
|
||||
? 0
|
||||
: sidebarWidth - WorkspaceLayoutMetrics.desktopResizeSlop,
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
left:
|
||||
navigationSpace +
|
||||
geometry.agentWidth -
|
||||
(geometry.editorHidden ? 8 : 4),
|
||||
width: 8,
|
||||
child: MouseRegion(
|
||||
cursor: SystemMouseCursors.resizeColumn,
|
||||
child: GestureDetector(
|
||||
key: const Key('agent-panel-resize'),
|
||||
behavior: HitTestBehavior.opaque,
|
||||
dragStartBehavior: DragStartBehavior.down,
|
||||
onHorizontalDragStart: (details) {
|
||||
_agentDragStart = details.globalPosition.dx;
|
||||
_agentDragWidth = geometry.agentWidth;
|
||||
},
|
||||
onHorizontalDragUpdate: (details) {
|
||||
final start = _agentDragStart;
|
||||
if (start == null) return;
|
||||
final agentWidth =
|
||||
(_agentDragWidth + details.globalPosition.dx - start)
|
||||
.clamp(220.0, width - navigationSpace - 1);
|
||||
final remaining =
|
||||
width - navigationSpace - agentWidth - 1;
|
||||
widget.controller.setSplit(
|
||||
agentWidth,
|
||||
editorCollapsed: geometry.editorHidden
|
||||
? remaining <
|
||||
DesktopWorkspaceGeometry.editorRestoreWidth
|
||||
: remaining <=
|
||||
DesktopWorkspaceGeometry.editorCollapseWidth -
|
||||
DesktopWorkspaceGeometry
|
||||
.editorCollapseDragBuffer,
|
||||
);
|
||||
},
|
||||
onHorizontalDragEnd: (_) {
|
||||
_agentDragStart = null;
|
||||
if (!_editorCollapsedByAgent &&
|
||||
_agentWidth != null &&
|
||||
width -
|
||||
navigationSpace -
|
||||
DesktopWorkspaceGeometry.editorCollapseWidth -
|
||||
1 >=
|
||||
220) {
|
||||
widget.controller.setSplit(
|
||||
_agentWidth!.clamp(
|
||||
220.0,
|
||||
width -
|
||||
navigationSpace -
|
||||
DesktopWorkspaceGeometry.editorCollapseWidth -
|
||||
1,
|
||||
),
|
||||
editorCollapsed: false,
|
||||
);
|
||||
}
|
||||
},
|
||||
onHorizontalDragCancel: () => _agentDragStart = null,
|
||||
child: const SizedBox.expand(),
|
||||
child: _gutter(
|
||||
name: 'project-sidebar',
|
||||
highlightTargets: const {WorkspaceResizeBoundary.sidebar},
|
||||
highlightOffset: collapsed
|
||||
? const Offset(
|
||||
-WorkspaceLayoutMetrics.desktopResizeHitExtent / 2,
|
||||
0,
|
||||
)
|
||||
: Offset.zero,
|
||||
initialWidth: collapsed ? 0 : sidebarWidth,
|
||||
onStart: () => _startSidebarResize(sidebarWidth),
|
||||
onResize: (value) => _resizeSidebar(value, maximum),
|
||||
onEnd: _finishSidebarResize,
|
||||
),
|
||||
),
|
||||
if (!floating &&
|
||||
widget.sidebarCanExpand &&
|
||||
WorkspaceLayoutPolicy.desktopNavigationFits(width) &&
|
||||
widget.onTimelineHeightChanged != null)
|
||||
Positioned(
|
||||
left: collapsed
|
||||
? 0
|
||||
: sidebarWidth - WorkspaceLayoutMetrics.desktopResizeSlop,
|
||||
bottom:
|
||||
timelineHeight - WorkspaceLayoutMetrics.desktopResizeSlop,
|
||||
width: WorkspaceLayoutMetrics.desktopResizeHitExtent,
|
||||
height: WorkspaceLayoutMetrics.desktopResizeHitExtent,
|
||||
child: WorkspaceResizeHandle.junction(
|
||||
key: const Key('desktop-chat-timeline-junction'),
|
||||
highlightOffset: collapsed
|
||||
? const Offset(
|
||||
-WorkspaceLayoutMetrics.desktopResizeHitExtent / 2,
|
||||
0,
|
||||
)
|
||||
: Offset.zero,
|
||||
highlightTargets: const {
|
||||
WorkspaceResizeBoundary.sidebar,
|
||||
WorkspaceResizeBoundary.timeline,
|
||||
},
|
||||
initialWidth: collapsed ? 0 : sidebarWidth,
|
||||
initialHeight: timelineHeight,
|
||||
verticalDirection: -1,
|
||||
onStart: () =>
|
||||
_startSidebarResize(sidebarWidth, junction: true),
|
||||
onWidthChanged: (value) => _resizeSidebar(value, maximum),
|
||||
onHeightChanged: (value) => widget.onTimelineHeightChanged!(
|
||||
resolveTimelineHeight(value),
|
||||
),
|
||||
onEnd: _finishSidebarResize,
|
||||
),
|
||||
),
|
||||
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, () {}),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'package:cutdex_ui/icons.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../l10n/l10n.dart';
|
||||
@@ -43,12 +44,12 @@ class PhoneWorkspaceShell extends StatelessWidget {
|
||||
destinations: [
|
||||
NavigationDestination(
|
||||
key: const Key('workspace-agent-destination'),
|
||||
icon: const Icon(Icons.chat_bubble_outline),
|
||||
icon: const Icon(AppIcons.chat),
|
||||
label: context.l10n.workspaceAgent,
|
||||
),
|
||||
NavigationDestination(
|
||||
key: const Key('workspace-cut-destination'),
|
||||
icon: const Icon(Icons.movie_outlined),
|
||||
icon: const Icon(AppIcons.video),
|
||||
label: context.l10n.workspaceCut,
|
||||
),
|
||||
],
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:cutdex_ui/icons.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../l10n/l10n.dart';
|
||||
@@ -55,14 +56,14 @@ class TabletWorkspaceShell extends StatelessWidget {
|
||||
destinations: [
|
||||
NavigationRailDestination(
|
||||
icon: const Icon(
|
||||
Icons.chat_bubble_outline,
|
||||
AppIcons.chat,
|
||||
key: Key('workspace-agent-destination'),
|
||||
),
|
||||
label: Text(context.l10n.workspaceAgent),
|
||||
),
|
||||
NavigationRailDestination(
|
||||
icon: const Icon(
|
||||
Icons.movie_outlined,
|
||||
AppIcons.video,
|
||||
key: Key('workspace-cut-destination'),
|
||||
),
|
||||
label: Text(context.l10n.workspaceCut),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'package:cutdex_ui/icons.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../integrations/platform/editor_window_chrome.dart';
|
||||
@@ -45,7 +46,7 @@ class WorkspaceFrame extends StatelessWidget {
|
||||
key: const Key('workspace-navigation-button'),
|
||||
tooltip: context.l10n.expandSidebar,
|
||||
onPressed: () => Scaffold.of(context).openDrawer(),
|
||||
icon: const Icon(Icons.menu),
|
||||
icon: const Icon(AppIcons.menu),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_native_flutter/cutdex_native_flutter.dart';
|
||||
import 'package:cutdex_native/cutdex_native.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
@@ -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,66 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex_native_flutter/cutdex_native_flutter.dart';
|
||||
|
||||
/// Native QPC clock calibration and bounded asynchronous diagnostics sampling.
|
||||
class BenchDiagnostics {
|
||||
BenchDiagnostics(this.session, this.clock);
|
||||
final RuntimeSession session;
|
||||
final Stopwatch clock;
|
||||
double uncertaintyMs = double.infinity, _offset = 0;
|
||||
Timer? _timer;
|
||||
Future<void>? _pending;
|
||||
Object? _sampleError;
|
||||
|
||||
double now() => _offset + clock.elapsedMicroseconds / 1000;
|
||||
Future<Map<String, Object?>> read() => session.previewDiagnostics();
|
||||
|
||||
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_core/timeline/model.dart';
|
||||
import 'package:cutdex_core/timeline/layout.dart';
|
||||
import 'package:cutdex_timeline_ui/cutdex_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_core/editor.dart';
|
||||
import 'package:cutdex_native_flutter/cutdex_native_flutter.dart';
|
||||
import 'package:cutdex_core/timeline/model.dart';
|
||||
import 'package:cutdex_core/timeline/layout.dart';
|
||||
import 'package:cutdex_timeline_ui/cutdex_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!, 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,
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,220 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex_core/timeline/layout.dart';
|
||||
import 'package:cutdex_timeline_ui/cutdex_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}));
|
||||
}
|
||||
@@ -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!,
|
||||
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}));
|
||||
}
|
||||
@@ -18,6 +18,7 @@ enum AppErrorCode {
|
||||
openMatchingProject,
|
||||
openTimelineFailed,
|
||||
projectMismatch,
|
||||
projectAlreadyExists,
|
||||
openProjectFirst,
|
||||
localFilesOnly,
|
||||
foldersUnsupported,
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_core/project.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../media/media_asset_cover.dart';
|
||||
|
||||
import 'package:cutdex_ui/icons.dart';
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
|
||||
import '../media/audio_asset_tile.dart';
|
||||
@@ -25,13 +26,13 @@ class AgentAttachmentCard extends StatelessWidget {
|
||||
fit: BoxFit.cover,
|
||||
fallback: Center(
|
||||
child: Icon(
|
||||
kind == 'image' ? Icons.image_outlined : Icons.movie_outlined,
|
||||
kind == 'image' ? AppIcons.image : AppIcons.video,
|
||||
color: colors.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
errorFallback: Center(
|
||||
child: Icon(
|
||||
Icons.broken_image_outlined,
|
||||
AppIcons.imageUnavailable,
|
||||
color: colors.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
@@ -42,12 +43,7 @@ class AgentAttachmentCard extends StatelessWidget {
|
||||
showName: false,
|
||||
aspectRatio: 132 / 96,
|
||||
),
|
||||
_ => Center(
|
||||
child: Icon(
|
||||
Icons.insert_drive_file_outlined,
|
||||
color: colors.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
_ => Center(child: Icon(AppIcons.file, color: colors.onSurfaceVariant)),
|
||||
};
|
||||
return SizedBox(
|
||||
width: 132,
|
||||
@@ -93,7 +89,7 @@ class AgentAttachmentCard extends StatelessWidget {
|
||||
backgroundColor: colors.surface,
|
||||
foregroundColor: colors.onSurface,
|
||||
),
|
||||
icon: const Icon(Icons.close, size: 13),
|
||||
icon: const Icon(AppIcons.close, size: 13),
|
||||
),
|
||||
),
|
||||
],
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../integrations/platform/platform_capabilities.dart';
|
||||
import '../../integrations/platform/native_project_drop_region.dart';
|
||||
import '../../integrations/platform/native_file_drop_policy.dart';
|
||||
import '../../workspace/projects.dart';
|
||||
import '../../workspace/media_import.dart';
|
||||
import '../../workspace/external_media_import.dart';
|
||||
import '../../shared/widgets/drop_to_add_overlay.dart';
|
||||
import '../media/media_asset_drag.dart';
|
||||
import 'agent_composer_controller.dart';
|
||||
|
||||
/// Shared attachment drop handling for docked and floating chat presentations.
|
||||
class AgentAttachmentDropRegion extends ConsumerStatefulWidget {
|
||||
const AgentAttachmentDropRegion({
|
||||
super.key,
|
||||
required this.projectId,
|
||||
required this.composer,
|
||||
required this.child,
|
||||
this.shrinkWrap = false,
|
||||
});
|
||||
final String? projectId;
|
||||
final AgentComposerController composer;
|
||||
final Widget child;
|
||||
final bool shrinkWrap;
|
||||
@override
|
||||
ConsumerState<AgentAttachmentDropRegion> createState() =>
|
||||
_AgentAttachmentDropRegionState();
|
||||
}
|
||||
|
||||
class _AgentAttachmentDropRegionState
|
||||
extends ConsumerState<AgentAttachmentDropRegion> {
|
||||
bool _hovering = false;
|
||||
bool _canAttach(MediaAssetDrag drag) {
|
||||
final workspace = ref.read(projectsProvider).value;
|
||||
return widget.projectId == drag.projectId &&
|
||||
workspace?.activeProject?.id == drag.projectId &&
|
||||
!widget.composer.attachments.any((item) => item.id == drag.assetId) &&
|
||||
workspace!.assets.any((asset) => asset.id == drag.assetId);
|
||||
}
|
||||
|
||||
bool _canAttachFiles(List<ExternalMediaFile> files) {
|
||||
if (files.isEmpty) return true;
|
||||
final assets = ref.read(projectsProvider).value?.assets;
|
||||
if (assets == null) return false;
|
||||
final ids = {for (final item in widget.composer.attachments) item.id};
|
||||
final locations = {
|
||||
for (final asset in assets)
|
||||
if (ids.contains(asset.id)) ?mediaSourceLocation(asset),
|
||||
};
|
||||
return files.any((file) => !locations.contains(file.sourceUri.toString()));
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final workspace = ref.watch(
|
||||
projectsProvider.select(
|
||||
(value) => value.value?.copyWith(
|
||||
recent: const [],
|
||||
timelines: const [],
|
||||
error: null,
|
||||
creatingTimeline: false,
|
||||
),
|
||||
),
|
||||
);
|
||||
final native = ref.watch(platformCapabilitiesProvider).nativeFileDrop;
|
||||
final importing =
|
||||
widget.composer.busy ||
|
||||
widget.projectId != null &&
|
||||
ref.watch(
|
||||
externalMediaImportProvider(widget.projectId!)
|
||||
.select((value) => value.isLoading),
|
||||
);
|
||||
final internal = DragTarget<MediaAssetDrag>(
|
||||
key: const Key('agent-panel-drop-target'),
|
||||
onWillAcceptWithDetails: (details) => _canAttach(details.data),
|
||||
onAcceptWithDetails: (details) {
|
||||
if (_canAttach(details.data)) {
|
||||
widget.composer.attach(
|
||||
ref
|
||||
.read(projectsProvider)
|
||||
.value!
|
||||
.assets
|
||||
.firstWhere((asset) => asset.id == details.data.assetId),
|
||||
);
|
||||
}
|
||||
},
|
||||
builder: (context, candidates, _) => Stack(
|
||||
fit: widget.shrinkWrap ? StackFit.loose : StackFit.expand,
|
||||
children: [
|
||||
widget.child,
|
||||
if (candidates.isNotEmpty || _hovering)
|
||||
const Positioned.fill(
|
||||
child: DropToAddOverlay(key: Key('agent-drop-overlay')),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (!native) return internal;
|
||||
return NativeProjectDropRegion(
|
||||
regionId: 'attachments',
|
||||
policy: NativeFileDropPolicy.attachments,
|
||||
enabled:
|
||||
widget.projectId != null &&
|
||||
workspace?.activeProject?.id == widget.projectId &&
|
||||
(workspace?.projectBusy == false || importing),
|
||||
onEnter: (files) {
|
||||
if (!importing && _canAttachFiles(files)) {
|
||||
setState(() => _hovering = true);
|
||||
}
|
||||
},
|
||||
onExit: () {
|
||||
if (mounted && _hovering) setState(() => _hovering = false);
|
||||
},
|
||||
onDrop: (files) async {
|
||||
setState(() => _hovering = false);
|
||||
try {
|
||||
await widget.composer.importAttachments(files);
|
||||
} catch (_) {
|
||||
/* Shared composer publishes import feedback. */
|
||||
}
|
||||
},
|
||||
child: internal,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import '../../l10n/l10n.dart';
|
||||
import 'chat_state.dart';
|
||||
import 'agent_composer_controller.dart';
|
||||
import 'composer_document.dart';
|
||||
import 'agent_message_codec.dart';
|
||||
|
||||
/// Consume one draft after the shared chat controller's send preconditions pass.
|
||||
String takeAgentDraft(
|
||||
ComposerDocumentController input,
|
||||
AgentComposerController composer,
|
||||
) {
|
||||
final text = AgentComposerMessage.encodeDocument(
|
||||
input.segments,
|
||||
composer.attachments,
|
||||
);
|
||||
input.clearDocument();
|
||||
composer.clear();
|
||||
return text;
|
||||
}
|
||||
|
||||
String agentChatErrorMessage(BuildContext context, AgentChatError error) =>
|
||||
switch (error) {
|
||||
AgentChatError.configurationReadFailed =>
|
||||
context.l10n.agentConfigurationReadFailed,
|
||||
AgentChatError.configurationRequired =>
|
||||
context.l10n.agentConfigurationRequired,
|
||||
AgentChatError.sessionRestoreFailed =>
|
||||
context.l10n.agentSessionRestoreFailed,
|
||||
AgentChatError.contextBudget => context.l10n.agentContextBudgetExceeded,
|
||||
AgentChatError.authentication => context.l10n.agentAuthenticationFailed,
|
||||
AgentChatError.exportReplyFailed => context.l10n.agentExportReplyFailed,
|
||||
AgentChatError.connection => context.l10n.agentConnectionFailed,
|
||||
AgentChatError.protocol => context.l10n.agentProtocolFailed,
|
||||
AgentChatError.turnLimit => context.l10n.agentTurnLimitReached,
|
||||
AgentChatError.interrupted => context.l10n.agentTaskInterrupted,
|
||||
AgentChatError.recoveryRequired => context.l10n.agentRecoveryRequired,
|
||||
AgentChatError.replyFailed => context.l10n.replyFailed,
|
||||
AgentChatError.requestFailed => context.l10n.chatFailed,
|
||||
};
|
||||
@@ -1,12 +1,18 @@
|
||||
import 'agent_reply_region.dart';
|
||||
|
||||
import 'package:cutdex/shared/widgets/error_notification_host.dart';
|
||||
|
||||
import '../../shared/layout/composer_layout.dart';
|
||||
import '../../shared/theme/composer_style.dart';
|
||||
|
||||
import 'package:cutdex/l10n/l10n.dart';
|
||||
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_core/project.dart';
|
||||
|
||||
import '../../integrations/platform/platform_capabilities.dart';
|
||||
import 'agent_composer_controller.dart';
|
||||
import 'agent_attachment_drop_region.dart';
|
||||
import 'agent_chat_actions.dart';
|
||||
import 'agent_composer_store.dart';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
@@ -14,21 +20,17 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../integrations/agent/agent_provider.dart';
|
||||
|
||||
import 'package:cutdex_ui/icons.dart';
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
import 'package:cutdex_ui/widgets.dart';
|
||||
|
||||
import '../../shared/widgets/drop_to_add_overlay.dart';
|
||||
import '../settings/settings_dialog.dart';
|
||||
import '../settings/settings_page.dart';
|
||||
import 'chat_controller.dart';
|
||||
import 'chat_state.dart';
|
||||
import '../../integrations/agent/conversation_repository.dart';
|
||||
import '../../integrations/platform/native_project_drop_region.dart';
|
||||
import '../../integrations/platform/native_file_drop_policy.dart';
|
||||
import '../../workspace/media_import.dart';
|
||||
import '../../workspace/external_media_import.dart';
|
||||
import '../../settings/settings_operation.dart';
|
||||
import '../../workspace/projects.dart';
|
||||
import '../media/media_asset_drag.dart';
|
||||
import '../media/media_browser_feedback.dart';
|
||||
import 'agent_attachment_card.dart';
|
||||
import 'agent_media_attachments.dart';
|
||||
@@ -95,8 +97,7 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
|
||||
'agent-model-${widget.projectId}-${widget.conversationId ?? widget.draftKey ?? 'new'}';
|
||||
bool get _choosingModel =>
|
||||
ref.read(settingsOperationProvider(_modelOperation)).isLoading;
|
||||
bool _usingDraftModel = false;
|
||||
bool _dropHovering = false;
|
||||
bool get _usingDraftModel => _composer.usingDraftModel;
|
||||
bool get _importingAttachments =>
|
||||
_composer.busy ||
|
||||
widget.projectId != null &&
|
||||
@@ -141,33 +142,12 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
|
||||
if (oldWidget.conversationId != widget.conversationId ||
|
||||
oldWidget.projectId != widget.projectId ||
|
||||
oldWidget.draftKey != widget.draftKey) {
|
||||
_usingDraftModel = false;
|
||||
_composer.removeListener(_composerChanged);
|
||||
_composer = _resolveComposer();
|
||||
_composer.addListener(_composerChanged);
|
||||
}
|
||||
}
|
||||
|
||||
String _errorMessage(BuildContext context, AgentChatError error) =>
|
||||
switch (error) {
|
||||
AgentChatError.configurationReadFailed =>
|
||||
context.l10n.agentConfigurationReadFailed,
|
||||
AgentChatError.configurationRequired =>
|
||||
context.l10n.agentConfigurationRequired,
|
||||
AgentChatError.sessionRestoreFailed =>
|
||||
context.l10n.agentSessionRestoreFailed,
|
||||
AgentChatError.contextBudget => context.l10n.agentContextBudgetExceeded,
|
||||
AgentChatError.authentication => context.l10n.agentAuthenticationFailed,
|
||||
AgentChatError.exportReplyFailed => context.l10n.agentExportReplyFailed,
|
||||
AgentChatError.connection => context.l10n.agentConnectionFailed,
|
||||
AgentChatError.protocol => context.l10n.agentProtocolFailed,
|
||||
AgentChatError.turnLimit => context.l10n.agentTurnLimitReached,
|
||||
AgentChatError.interrupted => context.l10n.agentTaskInterrupted,
|
||||
AgentChatError.recoveryRequired => context.l10n.agentRecoveryRequired,
|
||||
AgentChatError.replyFailed => context.l10n.replyFailed,
|
||||
AgentChatError.requestFailed => context.l10n.chatFailed,
|
||||
};
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
@@ -187,41 +167,6 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
bool _canAttach(MediaAssetDrag drag) {
|
||||
final workspace = ref.read(projectsProvider).asData?.value;
|
||||
return widget.projectId == drag.projectId &&
|
||||
workspace?.activeProject?.id == drag.projectId &&
|
||||
!_attachments.any((item) => item.id == drag.assetId) &&
|
||||
workspace!.assets.any((asset) => asset.id == drag.assetId);
|
||||
}
|
||||
|
||||
bool _canAttachExternalFiles(List<ExternalMediaFile> files) {
|
||||
if (files.isEmpty) return true;
|
||||
final assets = ref.read(projectsProvider).asData?.value.assets;
|
||||
if (assets == null) return false;
|
||||
final attachedIds = {for (final item in _attachments) item.id};
|
||||
final attachedLocations = {
|
||||
for (final asset in assets)
|
||||
if (attachedIds.contains(asset.id)) ?mediaSourceLocation(asset),
|
||||
};
|
||||
return files.any(
|
||||
(file) => !attachedLocations.contains(file.sourceUri.toString()),
|
||||
);
|
||||
}
|
||||
|
||||
void _attachAsset(AssetDocument asset) => _composer.attach(asset);
|
||||
|
||||
bool get _desktop => ref.read(platformCapabilitiesProvider).nativeFileDrop;
|
||||
|
||||
Future<void> _dropExternalFiles(List<ExternalMediaFile> files) async {
|
||||
setState(() => _dropHovering = false);
|
||||
try {
|
||||
await _composer.importAttachments(files);
|
||||
} catch (_) {
|
||||
// Feedback belongs to the composer even if this panel is hidden.
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _pickAttachments() async {
|
||||
try {
|
||||
await _composer.pickAttachments();
|
||||
@@ -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
|
||||
Widget build(BuildContext context) {
|
||||
ref.watch(settingsOperationProvider(_modelOperation));
|
||||
ref.watch(
|
||||
settingsOperationProvider(_modelOperation)
|
||||
.select((value) => value.isLoading),
|
||||
);
|
||||
if (widget.projectId != null) {
|
||||
ref.watch(externalMediaImportProvider(widget.projectId!));
|
||||
ref.watch(
|
||||
externalMediaImportProvider(widget.projectId!)
|
||||
.select((value) => value.isLoading),
|
||||
);
|
||||
}
|
||||
final workspace = ref.watch(projectsProvider).asData?.value;
|
||||
final workspace = ref.watch(
|
||||
projectsProvider.select(
|
||||
(value) => value.asData?.value.copyWith(
|
||||
recent: const [],
|
||||
error: null,
|
||||
creatingTimeline: false,
|
||||
),
|
||||
),
|
||||
);
|
||||
final referenceValidator = ComposerReferenceValidator(
|
||||
workspace: workspace,
|
||||
projectId: widget.projectId,
|
||||
@@ -303,7 +211,9 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
|
||||
draftKey: widget.draftKey,
|
||||
)
|
||||
: null;
|
||||
final state = provider == null ? const ChatState() : ref.watch(provider);
|
||||
final state = provider == null
|
||||
? const ChatState()
|
||||
: ref.watch(provider.select(chatChrome));
|
||||
final settings = ref.watch(agentSettingsProvider).asData?.value;
|
||||
final available =
|
||||
settings?.providers
|
||||
@@ -358,10 +268,12 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
|
||||
});
|
||||
if (!mounted || !context.mounted) return;
|
||||
if (saved) {
|
||||
setState(() => _usingDraftModel = true);
|
||||
_composer.useDraftModel();
|
||||
} else {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(context.l10n.agentSaveSettingsFailed)),
|
||||
ErrorNotificationHost.of(context).show(
|
||||
ErrorNotification(
|
||||
content: Text(context.l10n.agentSaveSettingsFailed),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -374,8 +286,8 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
|
||||
return TextButton.icon(
|
||||
key: const Key('agent-configure-model'),
|
||||
style: compactButtonStyle,
|
||||
onPressed: () => showSettingsDialog(context, initialTab: 1),
|
||||
icon: const Icon(Icons.tune, size: 16),
|
||||
onPressed: () => showSettingsPage(context, initialTab: 1),
|
||||
icon: const Icon(AppIcons.tune, size: 16),
|
||||
label: Text(context.l10n.agentConfigureModel),
|
||||
);
|
||||
}
|
||||
@@ -398,11 +310,11 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
|
||||
AppMenuItem(
|
||||
label: context.l10n.agentConfigureModel,
|
||||
selectOption: true,
|
||||
onPressed: () => showSettingsDialog(context, initialTab: 1),
|
||||
onPressed: () => showSettingsPage(context, initialTab: 1),
|
||||
),
|
||||
],
|
||||
builder: (context, toggle, focus) => TextButton(
|
||||
key: const Key('agent-model-picker'),
|
||||
builder: (context, toggle, focus) => AppToolbarDropdownButton(
|
||||
buttonKey: const Key('agent-model-picker'),
|
||||
focusNode: focus,
|
||||
onPressed: () {
|
||||
if (!state.busy && !_choosingModel) toggle?.call();
|
||||
@@ -419,14 +331,14 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
const Icon(Icons.expand_more, size: 14),
|
||||
const Icon(AppIcons.expandMore, size: 14),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (provider != null) {
|
||||
if (provider != null && TickerMode.valuesOf(context).enabled) {
|
||||
ref.listen(provider, (previous, next) {
|
||||
if (_follow) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
@@ -449,12 +361,7 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
|
||||
(_input.text.trim().isEmpty && _attachments.isEmpty)) {
|
||||
return;
|
||||
}
|
||||
final text = AgentComposerMessage.encodeDocument(
|
||||
_input.segments,
|
||||
_attachments,
|
||||
);
|
||||
_input.clearDocument();
|
||||
_composer.clear();
|
||||
final text = takeAgentDraft(_input, _composer);
|
||||
_follow = true;
|
||||
ref
|
||||
.read(provider.notifier)
|
||||
@@ -467,8 +374,10 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
|
||||
}
|
||||
|
||||
final theme = Theme.of(context);
|
||||
final content = _agentDropRegion(
|
||||
LayoutBuilder(
|
||||
final content = AgentAttachmentDropRegion(
|
||||
projectId: widget.projectId,
|
||||
composer: _composer,
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final panelWidth =
|
||||
(constraints.maxWidth - ComposerLayout.horizontalInset * 2)
|
||||
@@ -558,8 +467,8 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
|
||||
),
|
||||
),
|
||||
Icon(
|
||||
Icons
|
||||
.chevron_right,
|
||||
AppIcons
|
||||
.chevronRight,
|
||||
size: 14,
|
||||
color:
|
||||
AppTheme.chatMetaTextStyle(
|
||||
@@ -571,7 +480,6 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
|
||||
),
|
||||
Divider(
|
||||
height: 1,
|
||||
thickness: 1,
|
||||
color:
|
||||
theme.dividerColor,
|
||||
),
|
||||
@@ -636,32 +544,39 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
|
||||
in AgentComposerMessage.decode(
|
||||
message.text,
|
||||
).attachments)
|
||||
if (ref
|
||||
.watch(
|
||||
projectsProvider,
|
||||
)
|
||||
.asData
|
||||
?.value
|
||||
.assets
|
||||
.where(
|
||||
(
|
||||
asset,
|
||||
) =>
|
||||
asset.id ==
|
||||
attachment.id,
|
||||
)
|
||||
.firstOrNull
|
||||
case final asset?)
|
||||
AgentAttachmentCard(
|
||||
asset: asset,
|
||||
)
|
||||
else
|
||||
Chip(
|
||||
label: Text(
|
||||
attachment
|
||||
.name,
|
||||
),
|
||||
),
|
||||
Consumer(
|
||||
builder: (context, ref, _) {
|
||||
final asset = ref.watch(
|
||||
projectsProvider.select(
|
||||
(
|
||||
value,
|
||||
) => value
|
||||
.asData
|
||||
?.value
|
||||
.assets
|
||||
.where(
|
||||
(
|
||||
asset,
|
||||
) =>
|
||||
asset.id ==
|
||||
attachment.id,
|
||||
)
|
||||
.firstOrNull,
|
||||
),
|
||||
);
|
||||
return asset ==
|
||||
null
|
||||
? Chip(
|
||||
label: Text(
|
||||
attachment.name,
|
||||
),
|
||||
)
|
||||
: AgentAttachmentCard(
|
||||
asset:
|
||||
asset,
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -677,44 +592,12 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
|
||||
],
|
||||
),
|
||||
),
|
||||
if (state.busy) ...[
|
||||
if (state
|
||||
.partialResponse
|
||||
.isNotEmpty)
|
||||
SelectableText(
|
||||
state.partialResponse,
|
||||
style:
|
||||
AppTheme.chatMessageTextStyle(
|
||||
context,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
state.stopping
|
||||
? context.l10n.stopping
|
||||
: switch (state.activity) {
|
||||
AgentChatActivity
|
||||
.compacting =>
|
||||
context
|
||||
.l10n
|
||||
.agentCompacting,
|
||||
AgentChatActivity
|
||||
.editing =>
|
||||
context
|
||||
.l10n
|
||||
.agentEditing,
|
||||
AgentChatActivity
|
||||
.verifying =>
|
||||
context
|
||||
.l10n
|
||||
.agentVerifying,
|
||||
AgentChatActivity
|
||||
.replying =>
|
||||
context.l10n.replying,
|
||||
},
|
||||
style:
|
||||
theme.textTheme.bodySmall,
|
||||
),
|
||||
],
|
||||
AgentReplyRegion(
|
||||
projectId: widget.projectId,
|
||||
conversationId:
|
||||
widget.conversationId,
|
||||
draftKey: widget.draftKey,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
@@ -747,7 +630,7 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
|
||||
horizontal: AppSpacing.compact,
|
||||
),
|
||||
child: Text(
|
||||
_errorMessage(context, error),
|
||||
agentChatErrorMessage(context, error),
|
||||
style: theme.textTheme.bodySmall,
|
||||
),
|
||||
),
|
||||
@@ -1041,7 +924,7 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
|
||||
? _pickAttachments
|
||||
: null,
|
||||
icon: const Icon(
|
||||
Icons.add,
|
||||
AppIcons.add,
|
||||
),
|
||||
),
|
||||
const SizedBox(
|
||||
@@ -1081,7 +964,7 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
|
||||
)
|
||||
.stop,
|
||||
icon: const Icon(
|
||||
Icons.stop,
|
||||
AppIcons.stop,
|
||||
),
|
||||
)
|
||||
else
|
||||
@@ -1116,7 +999,7 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
|
||||
? send
|
||||
: null,
|
||||
icon: const Icon(
|
||||
Icons.arrow_upward,
|
||||
AppIcons.arrowUp,
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_core/project.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../../workspace/external_media_import.dart';
|
||||
@@ -22,6 +22,14 @@ class AgentComposerController extends ChangeNotifier {
|
||||
final List<AgentMediaAttachment> attachments;
|
||||
final feedback = MediaImportFeedbackController();
|
||||
bool _busy = false;
|
||||
bool _usingDraftModel = false;
|
||||
bool get usingDraftModel => _usingDraftModel;
|
||||
void useDraftModel() {
|
||||
if (_disposed) return;
|
||||
_usingDraftModel = true;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
bool _disposed = false;
|
||||
bool get busy => _busy;
|
||||
|
||||
|
||||
@@ -37,12 +37,24 @@ final class AgentComposerStore {
|
||||
final AgentComposerController Function(String?) createComposer;
|
||||
ComposerDocumentController _draft = ComposerDocumentController();
|
||||
ComposerDocumentController get draft => _draft;
|
||||
final _projectDrafts = <String?, ComposerDocumentController>{};
|
||||
final _inputs = <(String?, String), ComposerDocumentController>{};
|
||||
final _composers = <(String?, String), AgentComposerController>{};
|
||||
|
||||
ComposerDocumentController input(String? projectId, String? conversationId) =>
|
||||
conversationId == null
|
||||
? draft
|
||||
ComposerDocumentController input(
|
||||
String? projectId,
|
||||
String? conversationId, {
|
||||
bool projectScoped = false,
|
||||
}) => conversationId == null
|
||||
? projectScoped
|
||||
? _projectDrafts.putIfAbsent(
|
||||
projectId,
|
||||
() => projectId == null
|
||||
? ComposerDocumentController()
|
||||
: _projectDrafts.remove(null) ??
|
||||
ComposerDocumentController(),
|
||||
)
|
||||
: draft
|
||||
: _inputs.putIfAbsent((
|
||||
projectId,
|
||||
conversationId,
|
||||
@@ -57,8 +69,9 @@ final class AgentComposerStore {
|
||||
void promoteDraft(String projectId, String draftKey, String conversationId) {
|
||||
final destination = (projectId, conversationId);
|
||||
_inputs.remove(destination)?.dispose();
|
||||
_inputs[destination] = _draft;
|
||||
_draft = ComposerDocumentController();
|
||||
final scoped = _projectDrafts.remove(projectId);
|
||||
_inputs[destination] = scoped ?? _draft;
|
||||
if (scoped == null) _draft = ComposerDocumentController();
|
||||
final composer = _composers.remove((projectId, draftKey));
|
||||
if (composer != null) {
|
||||
_composers.remove(destination)?.dispose();
|
||||
@@ -77,6 +90,10 @@ final class AgentComposerStore {
|
||||
|
||||
void dispose() {
|
||||
draft.dispose();
|
||||
for (final input in _projectDrafts.values) {
|
||||
input.dispose();
|
||||
}
|
||||
_projectDrafts.clear();
|
||||
for (final input in _inputs.values) {
|
||||
input.dispose();
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import 'dart:convert';
|
||||
import 'package:cutdex_agent/cutdex_agent.dart';
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:cutdex_native_flutter/cutdex_native_flutter.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
import '../../diagnostics/agent_request_diagnostics.dart';
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_core/project.dart';
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
|
||||
part 'agent_media_attachments.freezed.dart';
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
class AgentPanelPresentation extends InheritedWidget {
|
||||
const AgentPanelPresentation({
|
||||
super.key,
|
||||
required this.compact,
|
||||
this.expanded = false,
|
||||
this.onToggleExpanded,
|
||||
this.onDock,
|
||||
required super.child,
|
||||
});
|
||||
final bool compact;
|
||||
final bool expanded;
|
||||
final VoidCallback? onToggleExpanded;
|
||||
final VoidCallback? onDock;
|
||||
static AgentPanelPresentation? of(BuildContext context) =>
|
||||
context.dependOnInheritedWidgetOfExactType<AgentPanelPresentation>();
|
||||
static bool compactOf(BuildContext context) =>
|
||||
context
|
||||
.dependOnInheritedWidgetOfExactType<AgentPanelPresentation>()
|
||||
?.compact ??
|
||||
false;
|
||||
@override
|
||||
bool updateShouldNotify(AgentPanelPresentation oldWidget) =>
|
||||
compact != oldWidget.compact || expanded != oldWidget.expanded;
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
|
||||
import '../../l10n/l10n.dart';
|
||||
import 'chat_controller.dart';
|
||||
import 'chat_state.dart';
|
||||
|
||||
/// Streaming output observes its conversation independently of history/composer.
|
||||
class AgentReplyRegion extends ConsumerWidget {
|
||||
const AgentReplyRegion({
|
||||
super.key,
|
||||
required this.projectId,
|
||||
this.conversationId,
|
||||
this.draftKey,
|
||||
});
|
||||
|
||||
final String? projectId;
|
||||
final String? conversationId;
|
||||
final String? draftKey;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
if (projectId == null) return const SizedBox.shrink();
|
||||
final provider =
|
||||
chatControllerProvider(
|
||||
projectId!,
|
||||
conversationId: conversationId,
|
||||
draftKey: draftKey,
|
||||
).select(
|
||||
(state) => (
|
||||
state.busy,
|
||||
state.partialResponse,
|
||||
state.stopping,
|
||||
state.activity,
|
||||
),
|
||||
);
|
||||
final state = TickerMode.valuesOf(context).enabled
|
||||
? ref.watch(provider)
|
||||
: ref.read(provider);
|
||||
if (!state.$1) return const SizedBox.shrink();
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
if (state.$2.isNotEmpty)
|
||||
SelectionArea(
|
||||
child: Text(
|
||||
state.$2,
|
||||
style: AppTheme.chatMessageTextStyle(context),
|
||||
),
|
||||
),
|
||||
Text(
|
||||
state.$3
|
||||
? context.l10n.stopping
|
||||
: switch (state.$4) {
|
||||
AgentChatActivity.compacting => context.l10n.agentCompacting,
|
||||
AgentChatActivity.editing => context.l10n.agentEditing,
|
||||
AgentChatActivity.verifying => context.l10n.agentVerifying,
|
||||
AgentChatActivity.replying => context.l10n.replying,
|
||||
},
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Stable chrome/history snapshot; each streamed token belongs to reply region.
|
||||
ChatState chatChrome(ChatState state) =>
|
||||
state.copyWith(partialResponse: '', activity: AgentChatActivity.replying);
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
|
||||
import 'package:cutdex_ui/icons.dart';
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
|
||||
part 'composer_document.freezed.dart';
|
||||
@@ -322,8 +323,8 @@ class ComposerDocumentController extends TextEditingController {
|
||||
padding: const EdgeInsets.only(right: 4),
|
||||
child: Icon(
|
||||
mark.reference.kind == ComposerReferenceKind.timeline
|
||||
? Icons.view_timeline_outlined
|
||||
: Icons.attach_file,
|
||||
? AppIcons.timeline
|
||||
: AppIcons.attachment,
|
||||
size: 14,
|
||||
color: color,
|
||||
),
|
||||
|
||||
@@ -4,6 +4,7 @@ import '../../l10n/l10n.dart';
|
||||
import '../../shared/layout/composer_layout.dart';
|
||||
import '../../shared/theme/composer_style.dart';
|
||||
|
||||
import 'package:cutdex_ui/icons.dart';
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
|
||||
import '../../workspace/project_state.dart';
|
||||
@@ -72,7 +73,7 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
|
||||
if (selected == true) ...[
|
||||
const SizedBox(width: ComposerLayout.menuIconGap),
|
||||
Icon(
|
||||
Icons.check,
|
||||
AppIcons.check,
|
||||
size: ComposerLayout.menuIconSize,
|
||||
color: colors.onSurfaceVariant,
|
||||
),
|
||||
@@ -85,10 +86,7 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
|
||||
|
||||
Widget _separator() => const Padding(
|
||||
padding: AppComposerStyle.menuSeparatorPadding,
|
||||
child: Divider(
|
||||
height: 1,
|
||||
thickness: AppComposerStyle.menuSeparatorThickness,
|
||||
),
|
||||
child: Divider(height: 1),
|
||||
);
|
||||
|
||||
@override
|
||||
@@ -97,6 +95,18 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
|
||||
final projects = widget.projects
|
||||
.where((project) => project.name.toLowerCase().contains(query))
|
||||
.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(
|
||||
key: const Key('composer-project-bar'),
|
||||
color: widget.backgroundColor,
|
||||
@@ -109,12 +119,15 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
child: MenuAnchor(
|
||||
controller: _menu,
|
||||
alignmentOffset: Offset(0, -menuHeight - 4),
|
||||
consumeOutsideTap: false,
|
||||
onClose: () => setState(_search.clear),
|
||||
style: AppComposerStyle.projectMenu(context),
|
||||
style: AppComposerStyle.projectMenu(context)
|
||||
.copyWith(alignment: AlignmentDirectional.topStart),
|
||||
menuChildren: [
|
||||
SizedBox(
|
||||
width: ComposerLayout.menuContentWidth,
|
||||
height: contentHeight,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
@@ -126,6 +139,8 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
|
||||
controller: _search,
|
||||
autofocus: true,
|
||||
style: AppTheme.composerTextStyle(context),
|
||||
cursorHeight: AppTheme.composerCursorHeight(context),
|
||||
textAlignVertical: TextAlignVertical.center,
|
||||
onChanged: (_) => setState(() {}),
|
||||
decoration: AppComposerStyle.projectSearchDecoration(
|
||||
context,
|
||||
@@ -134,10 +149,7 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
|
||||
),
|
||||
),
|
||||
_separator(),
|
||||
ConstrainedBox(
|
||||
constraints: const BoxConstraints(
|
||||
maxHeight: ComposerLayout.menuListMaxHeight,
|
||||
),
|
||||
Expanded(
|
||||
child: SingleChildScrollView(
|
||||
primary: false,
|
||||
child: Column(
|
||||
@@ -157,7 +169,7 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
|
||||
_item(
|
||||
key: ValueKey('composer-project-${project.id}'),
|
||||
label: project.name,
|
||||
icon: Icons.folder_outlined,
|
||||
icon: AppIcons.folder,
|
||||
selected: project.id == widget.selected?.id,
|
||||
onPressed:
|
||||
widget.busy || !project.availability.canOpen
|
||||
@@ -176,7 +188,7 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
|
||||
key: const Key('composer-new-project'),
|
||||
secondary: true,
|
||||
label: context.l10n.newProject,
|
||||
icon: Icons.add,
|
||||
icon: AppIcons.add,
|
||||
onPressed: widget.busy || widget.onCreate == null
|
||||
? null
|
||||
: () {
|
||||
@@ -197,7 +209,7 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
|
||||
: controller.open(),
|
||||
style: AppComposerStyle.projectTrigger(context),
|
||||
icon: const Icon(
|
||||
Icons.folder_outlined,
|
||||
AppIcons.folder,
|
||||
size: ComposerLayout.menuIconSize,
|
||||
),
|
||||
label: Text(
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_core/project.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_core/project.dart';
|
||||
import 'package:cutdex_ui/icons.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../l10n/app_localizations.dart';
|
||||
@@ -62,10 +63,10 @@ abstract final class ComposerOptionCatalog {
|
||||
title: asset.name,
|
||||
subtitle: l10n.materials,
|
||||
icon: switch (asset.metadata['kind']) {
|
||||
'video' => Icons.movie_outlined,
|
||||
'audio' => Icons.audiotrack_outlined,
|
||||
'image' => Icons.image_outlined,
|
||||
_ => Icons.insert_drive_file_outlined,
|
||||
'video' => AppIcons.video,
|
||||
'audio' => AppIcons.audio,
|
||||
'image' => AppIcons.image,
|
||||
_ => AppIcons.file,
|
||||
},
|
||||
group: ComposerOptionGroup.media,
|
||||
reference: ComposerReference(
|
||||
@@ -80,7 +81,7 @@ abstract final class ComposerOptionCatalog {
|
||||
trigger: '@',
|
||||
title: timeline.name,
|
||||
subtitle: l10n.timelines,
|
||||
icon: Icons.view_timeline_outlined,
|
||||
icon: AppIcons.timeline,
|
||||
group: ComposerOptionGroup.timeline,
|
||||
reference: ComposerReference(
|
||||
kind: ComposerReferenceKind.timeline,
|
||||
|
||||
@@ -0,0 +1,792 @@
|
||||
import 'agent_reply_region.dart';
|
||||
import '../../workspace/projects.dart';
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:cutdex_ui/icons.dart';
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
import 'package:cutdex_ui/widgets.dart';
|
||||
|
||||
import '../../shared/layout/composer_layout.dart';
|
||||
import '../../shared/theme/composer_style.dart';
|
||||
import '../../shared/widgets/workspace_resize_handle.dart';
|
||||
|
||||
import '../../l10n/l10n.dart';
|
||||
import '../../workspace/project_state.dart';
|
||||
import '../../workspace/external_media_import.dart';
|
||||
import '../../integrations/agent/agent_provider.dart';
|
||||
import '../../integrations/agent/conversation_repository.dart';
|
||||
import '../projects/conversation_sidebar.dart';
|
||||
import '../media/media_browser_feedback.dart';
|
||||
import '../settings/settings_page.dart';
|
||||
import '../../settings/settings_operation.dart';
|
||||
import '../../shared/widgets/error_notification_host.dart';
|
||||
import 'agent_chat_actions.dart';
|
||||
import 'agent_attachment_card.dart';
|
||||
import 'agent_attachment_drop_region.dart';
|
||||
import 'agent_composer_controller.dart';
|
||||
import 'agent_message_codec.dart';
|
||||
import 'breakable_selectable_text.dart';
|
||||
import 'chat_controller.dart';
|
||||
import 'chat_state.dart';
|
||||
import 'composer_document.dart';
|
||||
import 'composer_reference_validator.dart';
|
||||
import 'composer_suggestion_surface.dart';
|
||||
|
||||
/// Independent floating presentation of the same conversation and draft stores.
|
||||
class FloatingAgentPanel extends ConsumerStatefulWidget {
|
||||
const FloatingAgentPanel({
|
||||
super.key,
|
||||
required this.state,
|
||||
required this.selection,
|
||||
required this.input,
|
||||
required this.composer,
|
||||
required this.expanded,
|
||||
required this.onToggleExpanded,
|
||||
required this.onDock,
|
||||
required this.onConversationCreated,
|
||||
required this.onConversationUpdated,
|
||||
});
|
||||
final ProjectState state;
|
||||
final ConversationSelectionState selection;
|
||||
final ComposerDocumentController input;
|
||||
final AgentComposerController composer;
|
||||
final bool expanded;
|
||||
final VoidCallback onToggleExpanded;
|
||||
final VoidCallback onDock;
|
||||
final ValueChanged<ConversationMetadata> onConversationCreated;
|
||||
final ValueChanged<ConversationMetadata> onConversationUpdated;
|
||||
@override
|
||||
ConsumerState<FloatingAgentPanel> createState() => _FloatingAgentPanelState();
|
||||
}
|
||||
|
||||
class _FloatingAgentPanelState extends ConsumerState<FloatingAgentPanel>
|
||||
with SingleTickerProviderStateMixin {
|
||||
final _scroll = ScrollController();
|
||||
late final AnimationController _reveal;
|
||||
bool _resizing = false;
|
||||
|
||||
void _animateReveal(bool expanded) {
|
||||
_reveal.animateTo(expanded ? 1 : 0, curve: Curves.easeOutCubic);
|
||||
}
|
||||
|
||||
void _startResize() {
|
||||
_reveal.stop();
|
||||
setState(() => _resizing = true);
|
||||
}
|
||||
|
||||
void _finishResize() {
|
||||
if (!_resizing) return;
|
||||
final expanded = _reveal.value >= .35;
|
||||
setState(() => _resizing = false);
|
||||
if (expanded != widget.expanded) {
|
||||
widget.onToggleExpanded();
|
||||
} else {
|
||||
_animateReveal(expanded);
|
||||
}
|
||||
}
|
||||
|
||||
void _changed() {
|
||||
if (mounted) setState(() {});
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_reveal = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(milliseconds: 220),
|
||||
value: widget.expanded ? 1 : 0,
|
||||
);
|
||||
widget.composer.addListener(_changed);
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(FloatingAgentPanel oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (widget.expanded != oldWidget.expanded) {
|
||||
_animateReveal(widget.expanded);
|
||||
}
|
||||
if (oldWidget.input != widget.input) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (mounted && _scroll.hasClients) {
|
||||
_scroll.jumpTo(_scroll.position.maxScrollExtent);
|
||||
}
|
||||
});
|
||||
}
|
||||
if (oldWidget.composer != widget.composer) {
|
||||
oldWidget.composer.removeListener(_changed);
|
||||
widget.composer.addListener(_changed);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
widget.composer.removeListener(_changed);
|
||||
_reveal.dispose();
|
||||
_scroll.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final assets =
|
||||
ref.watch(
|
||||
projectsProvider.select(
|
||||
(value) =>
|
||||
value.asData?.value.activeProject?.id ==
|
||||
widget.state.activeProject?.id
|
||||
? value.asData?.value.assets
|
||||
: null,
|
||||
),
|
||||
) ??
|
||||
widget.state.assets;
|
||||
final workspace = widget.state.copyWith(assets: assets);
|
||||
final projectId = workspace.activeProject?.id;
|
||||
final timelineId = widget.state.timeline?.id;
|
||||
final selection = widget.selection;
|
||||
final provider = projectId == null
|
||||
? null
|
||||
: chatControllerProvider(
|
||||
projectId,
|
||||
conversationId: selection.selectedId,
|
||||
draftKey: selection.selectedId == null ? selection.draftKey : null,
|
||||
);
|
||||
final chat = provider == null
|
||||
? const ChatState()
|
||||
: ref.watch(provider.select(chatChrome));
|
||||
final settings = ref.watch(agentSettingsProvider).value;
|
||||
final available =
|
||||
settings?.providers
|
||||
.where(
|
||||
(p) =>
|
||||
p.enabled &&
|
||||
AgentApiType.values.any((type) => type.name == p.apiType) &&
|
||||
p.models.isNotEmpty,
|
||||
)
|
||||
.toList() ??
|
||||
[];
|
||||
final conversation = chat.conversation;
|
||||
final providerId = conversation?.providerId ?? settings?.selectedProviderId;
|
||||
final modelId = conversation?.modelId ?? settings?.selectedModelId;
|
||||
final selectedProvider = available
|
||||
.where((p) => p.id == providerId)
|
||||
.firstOrNull;
|
||||
final selectedModel = selectedProvider?.models
|
||||
.where((m) => m.id == modelId)
|
||||
.firstOrNull;
|
||||
final configured =
|
||||
conversation != null ||
|
||||
(selection.selectedId != null && !widget.composer.usingDraftModel)
|
||||
? conversation != null &&
|
||||
settings?.enabled == true &&
|
||||
selectedModel != null
|
||||
: ref.watch(agentRuntimeProvider).value != null;
|
||||
final importing =
|
||||
widget.composer.busy ||
|
||||
(projectId != null &&
|
||||
ref.watch(
|
||||
externalMediaImportProvider(projectId)
|
||||
.select((value) => value.isLoading),
|
||||
));
|
||||
final operation =
|
||||
'agent-model-$projectId-${selection.selectedId ?? selection.draftKey}';
|
||||
final choosingModel = ref.watch(
|
||||
settingsOperationProvider(operation).select((value) => value.isLoading),
|
||||
);
|
||||
final validator = ComposerReferenceValidator(
|
||||
workspace: workspace,
|
||||
projectId: projectId,
|
||||
);
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (mounted) validator.validate(widget.input);
|
||||
});
|
||||
if (provider != null && TickerMode.valuesOf(context).enabled) {
|
||||
ref.listen(provider, (old, next) {
|
||||
if (_scroll.hasClients && _scroll.position.extentAfter < 80) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (mounted && _scroll.hasClients) {
|
||||
_scroll.jumpTo(_scroll.position.maxScrollExtent);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
void send() {
|
||||
validator.validate(widget.input);
|
||||
if (provider == null ||
|
||||
timelineId == null ||
|
||||
!configured ||
|
||||
choosingModel ||
|
||||
chat.busy ||
|
||||
importing ||
|
||||
widget.input.hasInvalidReferences ||
|
||||
(widget.input.text.trim().isEmpty &&
|
||||
widget.composer.attachments.isEmpty)) {
|
||||
return;
|
||||
}
|
||||
final text = takeAgentDraft(widget.input, widget.composer);
|
||||
if (!widget.expanded) widget.onToggleExpanded();
|
||||
unawaited(
|
||||
ref
|
||||
.read(provider.notifier)
|
||||
.send(
|
||||
text,
|
||||
timelineId: timelineId,
|
||||
onCreated: widget.onConversationCreated,
|
||||
onUpdated: widget.onConversationUpdated,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> chooseModel(String p, String m) async {
|
||||
if (chat.busy || choosingModel) return;
|
||||
final composer = widget.composer;
|
||||
final saved = await ref
|
||||
.read(settingsOperationProvider(operation).notifier)
|
||||
.run(() async {
|
||||
if (provider == null) {
|
||||
await ref.read(agentSettingsProvider.notifier).selectModel(p, m);
|
||||
} else {
|
||||
await ref.read(provider.notifier).selectModel(p, m);
|
||||
}
|
||||
});
|
||||
if (!mounted || !context.mounted) return;
|
||||
if (saved) composer.useDraftModel();
|
||||
if (!saved && context.mounted) {
|
||||
ErrorNotificationHost.of(context).show(
|
||||
ErrorNotification(
|
||||
content: Text(context.l10n.agentSaveSettingsFailed),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
final groups = ref.watch(conversationSidebarProvider).value?.groups;
|
||||
final items = groups?[projectId] ?? const <ConversationMetadata>[];
|
||||
final title =
|
||||
conversation?.title ??
|
||||
items.where((c) => c.id == selection.selectedId).firstOrNull?.title ??
|
||||
context.l10n.agentNewConversation;
|
||||
final inputDecoration = AppComposerStyle.inputDecoration(
|
||||
context,
|
||||
hintText: context.l10n.assistantHint,
|
||||
);
|
||||
Widget modelButton() => AppDropdownMenu(
|
||||
enabled: !chat.busy && !choosingModel,
|
||||
minWidth: ComposerLayout.menuWidth,
|
||||
maxHeight: ComposerLayout.menuListMaxHeight,
|
||||
items: [
|
||||
for (final p in available) ...[
|
||||
AppMenuLabel(p.name),
|
||||
for (final m in p.models)
|
||||
AppMenuItem(
|
||||
label: m.id,
|
||||
selectOption: true,
|
||||
selected: p.id == providerId && m.id == modelId,
|
||||
onPressed: () => unawaited(chooseModel(p.id, m.id)),
|
||||
),
|
||||
],
|
||||
const Divider(height: 1),
|
||||
AppMenuItem(
|
||||
label: context.l10n.agentConfigureModel,
|
||||
onPressed: () => showSettingsPage(context, initialTab: 1),
|
||||
),
|
||||
],
|
||||
builder: (context, toggle, focus) => Tooltip(
|
||||
message: selectedModel?.id ?? context.l10n.agentConfigureModel,
|
||||
child: AppToolbarDropdownButton(
|
||||
buttonKey: const Key('floating-agent-model-picker'),
|
||||
focusNode: focus,
|
||||
onPressed: toggle,
|
||||
style: AppComposerStyle.controlButton(context),
|
||||
child: const Icon(AppIcons.model, size: ComposerLayout.iconSize),
|
||||
),
|
||||
),
|
||||
);
|
||||
final conversationView = ExcludeFocus(
|
||||
excluding: !widget.expanded && !_resizing,
|
||||
child: IgnorePointer(
|
||||
ignoring: !widget.expanded && !_resizing,
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final height = constraints.maxHeight.clamp(
|
||||
AppControlSize.panelToolbar + 1,
|
||||
double.infinity,
|
||||
);
|
||||
return ClipRect(
|
||||
child: OverflowBox(
|
||||
alignment: Alignment.topCenter,
|
||||
minHeight: height,
|
||||
maxHeight: height,
|
||||
child: Column(
|
||||
children: [
|
||||
SizedBox(
|
||||
height: AppControlSize.panelToolbar,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: AppSpacing.small,
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
IconButton(
|
||||
key: const Key('floating-agent-collapse'),
|
||||
style: AppComposerStyle.controlIcon(context),
|
||||
tooltip: context.l10n.agentCollapseConversation,
|
||||
onPressed: widget.onToggleExpanded,
|
||||
icon: const Icon(
|
||||
AppIcons.remove,
|
||||
size: AppIconSize.header,
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: AppDropdownMenu(
|
||||
minWidth: ComposerLayout.menuWidth,
|
||||
maxHeight: ComposerLayout.menuListMaxHeight,
|
||||
items: [
|
||||
AppMenuItem(
|
||||
label: context.l10n.agentNewConversation,
|
||||
onPressed: () => ref
|
||||
.read(
|
||||
conversationSidebarProvider.notifier,
|
||||
)
|
||||
.newConversation(),
|
||||
),
|
||||
for (final item in items)
|
||||
AppMenuItem(
|
||||
label: item.title,
|
||||
selectOption: true,
|
||||
selected: item.id == selection.selectedId,
|
||||
onPressed: () {
|
||||
final controller = ref.read(
|
||||
conversationSidebarProvider.notifier,
|
||||
);
|
||||
controller.activate(item);
|
||||
unawaited(
|
||||
controller.rememberSelection(item),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
builder: (context, toggle, focus) =>
|
||||
AppToolbarDropdownButton(
|
||||
focusNode: focus,
|
||||
onPressed: toggle,
|
||||
child: Row(
|
||||
children: [
|
||||
Flexible(
|
||||
child: Text(
|
||||
title,
|
||||
key: const Key(
|
||||
'agent-floating-title',
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
const SizedBox(
|
||||
width: AppSpacing.tiny,
|
||||
),
|
||||
const Icon(
|
||||
AppIcons.expandMore,
|
||||
size: AppIconSize.header,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
key: const Key('floating-agent-dock'),
|
||||
style: AppComposerStyle.controlIcon(context),
|
||||
tooltip: context.l10n.agentDock,
|
||||
onPressed: widget.onDock,
|
||||
icon: const Icon(
|
||||
AppIcons.exitFullscreen,
|
||||
size: AppIconSize.header,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: ListView(
|
||||
controller: _scroll,
|
||||
key: const Key('floating-agent-messages'),
|
||||
padding: const EdgeInsets.all(AppSpacing.medium),
|
||||
children: [
|
||||
for (final message in chat.messages)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(
|
||||
bottom: AppSpacing.large,
|
||||
),
|
||||
child: Align(
|
||||
alignment: message.isUser
|
||||
? Alignment.centerRight
|
||||
: Alignment.centerLeft,
|
||||
child: Container(
|
||||
constraints: const BoxConstraints(
|
||||
maxWidth: ComposerLayout.maxWidth,
|
||||
),
|
||||
padding: message.isUser
|
||||
? const EdgeInsets.symmetric(
|
||||
horizontal: AppSpacing.medium,
|
||||
vertical: AppSpacing.itemVertical,
|
||||
)
|
||||
: EdgeInsets.zero,
|
||||
decoration: message.isUser
|
||||
? AppTheme.userMessageDecoration(context)
|
||||
: null,
|
||||
child: Column(
|
||||
crossAxisAlignment:
|
||||
CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (message.elapsedMs case final elapsed?)
|
||||
Text(
|
||||
context.l10n.agentElapsedTime(
|
||||
context.l10n.durationSeconds(
|
||||
(elapsed / 1000).ceil(),
|
||||
),
|
||||
),
|
||||
style: AppTheme.chatMetaTextStyle(
|
||||
context,
|
||||
),
|
||||
),
|
||||
if (message.isUser)
|
||||
BreakableSelectableText(
|
||||
text: AgentComposerMessage.decode(
|
||||
message.text,
|
||||
).text,
|
||||
style: AppTheme.chatMessageTextStyle(
|
||||
context,
|
||||
),
|
||||
)
|
||||
else
|
||||
SelectableText(
|
||||
AgentComposerMessage.decode(
|
||||
message.text,
|
||||
).text,
|
||||
style: AppTheme.chatMessageTextStyle(
|
||||
context,
|
||||
),
|
||||
),
|
||||
for (final attachment
|
||||
in AgentComposerMessage.decode(
|
||||
message.text,
|
||||
).attachments)
|
||||
Chip(label: Text(attachment.name)),
|
||||
if (message.interrupted)
|
||||
Text(context.l10n.replyInterrupted),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
AgentReplyRegion(
|
||||
projectId: projectId,
|
||||
conversationId: selection.selectedId,
|
||||
draftKey: selection.selectedId == null
|
||||
? selection.draftKey
|
||||
: null,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
final composerView = Padding(
|
||||
key: const Key('floating-agent-input-area'),
|
||||
padding: const EdgeInsets.all(AppSpacing.small),
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) => ComposerSuggestionSurface(
|
||||
controller: widget.input,
|
||||
width: constraints.maxWidth,
|
||||
projectId: projectId,
|
||||
assets: assets,
|
||||
timelines: widget.state.timelines,
|
||||
onSend: send,
|
||||
builder: (context, focus) {
|
||||
final attachment = IconButton(
|
||||
style: AppComposerStyle.controlIcon(context),
|
||||
tooltip: context.l10n.addAttachment,
|
||||
onPressed:
|
||||
projectId == null || importing || widget.state.projectBusy
|
||||
? null
|
||||
: () async {
|
||||
try {
|
||||
await widget.composer.pickAttachments();
|
||||
} catch (_) {
|
||||
/* Shared composer publishes import feedback. */
|
||||
}
|
||||
},
|
||||
icon: const Icon(AppIcons.add),
|
||||
);
|
||||
final input = TextField(
|
||||
key: const Key('floating-agent-input'),
|
||||
controller: widget.input,
|
||||
focusNode: focus,
|
||||
minLines: 1,
|
||||
maxLines: 5,
|
||||
style: AppTheme.composerTextStyle(context),
|
||||
cursorHeight: AppTheme.composerCursorHeight(context),
|
||||
decoration: inputDecoration.copyWith(
|
||||
constraints: const BoxConstraints(
|
||||
minHeight: ComposerLayout.controlSize,
|
||||
),
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
horizontal: AppSpacing.small,
|
||||
vertical: AppSpacing.tiny,
|
||||
),
|
||||
),
|
||||
onTap: () {
|
||||
if (!widget.expanded) {
|
||||
widget.onToggleExpanded();
|
||||
}
|
||||
},
|
||||
);
|
||||
final submit = ValueListenableBuilder<TextEditingValue>(
|
||||
valueListenable: widget.input,
|
||||
builder: (context, value, _) => IconButton.filled(
|
||||
style: AppTheme.accentIconButtonStyle(context)
|
||||
.merge(AppComposerStyle.controlIcon(context)),
|
||||
tooltip: chat.busy
|
||||
? context.l10n.stopReply
|
||||
: context.l10n.sendMessage,
|
||||
onPressed: chat.busy
|
||||
? (chat.stopping ? null : ref.read(provider!.notifier).stop)
|
||||
: provider != null &&
|
||||
timelineId != null &&
|
||||
configured &&
|
||||
!importing &&
|
||||
!choosingModel &&
|
||||
!widget.input.hasInvalidReferences &&
|
||||
(value.text.trim().isNotEmpty ||
|
||||
widget.composer.attachments.isNotEmpty)
|
||||
? send
|
||||
: null,
|
||||
icon: Icon(
|
||||
chat.busy ? AppIcons.squareFilled : AppIcons.arrowUp,
|
||||
size: chat.busy ? 12 : ComposerLayout.iconSize,
|
||||
),
|
||||
),
|
||||
);
|
||||
// Keep the editor at the same tree position and bottom
|
||||
// anchor while the conversation opens above it.
|
||||
return Row(
|
||||
key: const Key('floating-agent-composer'),
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
attachment,
|
||||
Expanded(child: input),
|
||||
modelButton(),
|
||||
submit,
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
final content = LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final conversationHeight =
|
||||
(constraints.maxHeight -
|
||||
ComposerLayout.controlSize -
|
||||
AppSpacing.small * 2)
|
||||
.clamp(0.0, double.infinity);
|
||||
return AnimatedBuilder(
|
||||
animation: _reveal,
|
||||
builder: (context, _) => MediaImportFeedbackListener(
|
||||
feedback: widget.composer.feedback,
|
||||
child: Material(
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
child: Stack(
|
||||
children: [
|
||||
Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Flexible(
|
||||
child: SizedBox(
|
||||
key: const Key('floating-agent-conversation-region'),
|
||||
height: conversationHeight * _reveal.value,
|
||||
child: ClipRect(
|
||||
child: Stack(
|
||||
children: [
|
||||
Offstage(
|
||||
offstage: _reveal.value == 0,
|
||||
child: conversationView,
|
||||
),
|
||||
Positioned(
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
child: Divider(
|
||||
key: const Key(
|
||||
'floating-agent-input-divider',
|
||||
),
|
||||
height: 1,
|
||||
thickness: 1,
|
||||
color: AppTheme.floatingDialogDividerColor(
|
||||
context,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (chat.error case final error?)
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(AppSpacing.small),
|
||||
child: Text(
|
||||
agentChatErrorMessage(context, error),
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
),
|
||||
if ({
|
||||
AgentChatError.recoveryRequired,
|
||||
AgentChatError.interrupted,
|
||||
AgentChatError.turnLimit,
|
||||
AgentChatError.exportReplyFailed,
|
||||
}.contains(chat.error))
|
||||
TextButton(
|
||||
onPressed:
|
||||
provider == null ||
|
||||
timelineId == null ||
|
||||
chat.busy
|
||||
? null
|
||||
: () => ref
|
||||
.read(provider.notifier)
|
||||
.send(
|
||||
chat.error ==
|
||||
AgentChatError.exportReplyFailed
|
||||
? context.l10n.agentRetrySummary
|
||||
: context.l10n.agentResumeTask,
|
||||
timelineId: timelineId,
|
||||
summaryOnly:
|
||||
chat.error ==
|
||||
AgentChatError.exportReplyFailed,
|
||||
resumeOnly:
|
||||
chat.error !=
|
||||
AgentChatError.exportReplyFailed,
|
||||
onUpdated: widget.onConversationUpdated,
|
||||
),
|
||||
child: Text(
|
||||
chat.error == AgentChatError.exportReplyFailed
|
||||
? context.l10n.agentRetrySummary
|
||||
: context.l10n.agentResumeTask,
|
||||
),
|
||||
),
|
||||
ValueListenableBuilder<TextEditingValue>(
|
||||
valueListenable: widget.input,
|
||||
builder: (context, _, _) =>
|
||||
widget.input.hasInvalidReferences
|
||||
? Padding(
|
||||
padding: const EdgeInsets.all(AppSpacing.small),
|
||||
child: Text(
|
||||
context.l10n.composerReferenceInvalid,
|
||||
style: AppSurfaces.of(context).errorText,
|
||||
),
|
||||
)
|
||||
: const SizedBox.shrink(),
|
||||
),
|
||||
if (widget.composer.attachments.isNotEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(AppSpacing.small),
|
||||
child: Wrap(
|
||||
spacing: AppSpacing.gap,
|
||||
children: [
|
||||
for (final asset in widget.composer.attachments)
|
||||
if (assets
|
||||
.where((item) => item.id == asset.id)
|
||||
.firstOrNull
|
||||
case final document?)
|
||||
AgentAttachmentCard(
|
||||
asset: document,
|
||||
onRemove: () =>
|
||||
widget.composer.remove(asset.id),
|
||||
)
|
||||
else
|
||||
InputChip(
|
||||
label: Text(asset.name),
|
||||
onDeleted: () =>
|
||||
widget.composer.remove(asset.id),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
composerView,
|
||||
],
|
||||
),
|
||||
Positioned(
|
||||
top: 0,
|
||||
left: ComposerLayout.radius,
|
||||
right: ComposerLayout.radius,
|
||||
height: AppSpacing.small,
|
||||
child: Semantics(
|
||||
button: true,
|
||||
label: widget.expanded
|
||||
? context.l10n.agentCollapseConversation
|
||||
: context.l10n.agentExpandConversation,
|
||||
onTap: widget.onToggleExpanded,
|
||||
child: Stack(
|
||||
fit: StackFit.expand,
|
||||
children: [
|
||||
Center(
|
||||
child: Container(
|
||||
width: ComposerLayout.controlSize,
|
||||
height: 2,
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context)
|
||||
.colorScheme
|
||||
.onSurfaceVariant
|
||||
.withValues(alpha: .35),
|
||||
borderRadius: BorderRadius.circular(
|
||||
AppRadius.pill,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
WorkspaceResizeHandle(
|
||||
key: const Key('floating-agent-resize-handle'),
|
||||
axis: Axis.vertical,
|
||||
direction: -1,
|
||||
initialValue: _reveal.value * conversationHeight,
|
||||
onStart: _startResize,
|
||||
onResize: (height) {
|
||||
if (conversationHeight > 0) {
|
||||
_reveal.value = (height / conversationHeight)
|
||||
.clamp(0.0, 1.0);
|
||||
}
|
||||
},
|
||||
onEnd: _finishResize,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
return AgentAttachmentDropRegion(
|
||||
projectId: projectId,
|
||||
composer: widget.composer,
|
||||
shrinkWrap: true,
|
||||
child: content,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,8 @@ import '../../workspace/project_state.dart';
|
||||
|
||||
import '../projects/conversation_sidebar.dart';
|
||||
import 'agent_chat_panel.dart';
|
||||
import 'agent_panel_presentation.dart';
|
||||
import 'floating_agent_panel.dart';
|
||||
import 'agent_composer_store.dart';
|
||||
import 'composer_project_selector.dart';
|
||||
|
||||
@@ -19,11 +21,13 @@ class WorkspaceAgentSurface extends ConsumerWidget {
|
||||
required this.state,
|
||||
required this.onSelectProject,
|
||||
required this.onCreateProject,
|
||||
this.showProjectSelector = true,
|
||||
});
|
||||
|
||||
final ProjectState state;
|
||||
final ValueChanged<RecentProject>? onSelectProject;
|
||||
final VoidCallback? onCreateProject;
|
||||
final bool showProjectSelector;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
@@ -34,21 +38,54 @@ class WorkspaceAgentSurface extends ConsumerWidget {
|
||||
final composers = ref.watch(agentComposerStoreProvider);
|
||||
final projectId = state.activeProject?.id;
|
||||
final conversationId = selection.selectedId;
|
||||
final presentation = AgentPanelPresentation.of(context);
|
||||
if (presentation?.compact == true) {
|
||||
return FloatingAgentPanel(
|
||||
state: state,
|
||||
selection: selection,
|
||||
input: composers.input(
|
||||
projectId,
|
||||
conversationId,
|
||||
projectScoped: !showProjectSelector,
|
||||
),
|
||||
composer: composers.composer(
|
||||
projectId,
|
||||
conversationId ?? selection.draftKey,
|
||||
),
|
||||
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),
|
||||
inputController: composers.input(
|
||||
projectId,
|
||||
conversationId,
|
||||
projectScoped: !showProjectSelector,
|
||||
),
|
||||
composer: composers.composer(
|
||||
projectId,
|
||||
conversationId ?? selection.draftKey,
|
||||
),
|
||||
projectSelector: ComposerProjectSelector(
|
||||
backgroundColor: AppTheme.composerUtilityBackground(context),
|
||||
projects: state.recent,
|
||||
selected: state.activeProject,
|
||||
busy: state.projectBusy,
|
||||
onSelect: (project) => onSelectProject?.call(project),
|
||||
onCreate: onCreateProject,
|
||||
),
|
||||
projectSelector: showProjectSelector
|
||||
? ComposerProjectSelector(
|
||||
backgroundColor: AppTheme.composerUtilityBackground(context),
|
||||
projects: state.recent,
|
||||
selected: state.activeProject,
|
||||
busy: state.projectBusy,
|
||||
onSelect: (project) => onSelectProject?.call(project),
|
||||
onCreate: onCreateProject,
|
||||
)
|
||||
: null,
|
||||
composerColor: AppSurfaces.of(context).composerBackground,
|
||||
projectId: projectId,
|
||||
timelineId: state.timeline?.id,
|
||||
|
||||
@@ -2,11 +2,12 @@ import 'package:cutdex/l10n/l10n.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import 'package:cutdex_ui/icons.dart';
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
|
||||
import '../../integrations/runtime/processing_resource_repository.dart';
|
||||
import '../../workspace/background_task_registry.dart';
|
||||
import '../../workspace/background_task_state.dart';
|
||||
import '../../shared/widgets/listenable_selector.dart';
|
||||
import '../../integrations/runtime/processing_resource_state.dart';
|
||||
|
||||
import 'package:cutdex_ui/widgets.dart';
|
||||
@@ -14,7 +15,14 @@ import 'package:cutdex_ui/widgets.dart';
|
||||
import '../media/background_tasks_dialog.dart';
|
||||
|
||||
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
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
@@ -23,30 +31,39 @@ class BackgroundTasksButton extends ConsumerWidget {
|
||||
.watch(processingResourceRepositoryProvider)
|
||||
.asData
|
||||
?.value;
|
||||
final tasks = ref.watch(backgroundTasksProvider(registry: registry));
|
||||
final downloads = resources == null
|
||||
? null
|
||||
: ref.watch(processingResourcesProvider(resources));
|
||||
bool hasRunningTasks() =>
|
||||
tasks.runningCount > 0 ||
|
||||
downloads?.subtitleDownloading == true ||
|
||||
(downloads?.installs.any(
|
||||
(install) => install.state == ProcessingResourceState.downloading,
|
||||
) ??
|
||||
false);
|
||||
Widget button(VoidCallback toggle) => IconButton(
|
||||
: ref.watch(
|
||||
processingResourcesProvider(resources).select(
|
||||
(downloads) =>
|
||||
downloads.subtitleDownloading ||
|
||||
downloads.installs.any(
|
||||
(install) =>
|
||||
install.state == ProcessingResourceState.downloading,
|
||||
),
|
||||
),
|
||||
);
|
||||
Widget button(VoidCallback toggle, bool running) => IconButton(
|
||||
key: const ValueKey('background-tasks-button'),
|
||||
tooltip: context.l10n.backgroundTasks,
|
||||
onPressed: toggle,
|
||||
icon: Badge(
|
||||
isLabelVisible: hasRunningTasks(),
|
||||
child: const Icon(Icons.task_alt_outlined, size: AppIconSize.header),
|
||||
isLabelVisible: running || downloads == true,
|
||||
child: Icon(AppIcons.success, size: iconSize),
|
||||
),
|
||||
);
|
||||
return AppPopover(
|
||||
width: 384,
|
||||
builder: (_, toggle) => button(toggle),
|
||||
child: BackgroundTasksContent(registry: registry, repository: resources),
|
||||
return ListenableSelector<bool>(
|
||||
listenable: registry,
|
||||
select: () => registry.runningCount > 0,
|
||||
builder: (context, running) => AppPopover(
|
||||
width: 384,
|
||||
alignment: alignment,
|
||||
builder: (_, toggle) => button(toggle, running),
|
||||
child: BackgroundTasksContent(
|
||||
registry: registry,
|
||||
repository: resources,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import '../../shared/widgets/listenable_selector.dart';
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:cutdex/l10n/l10n.dart';
|
||||
@@ -11,9 +13,12 @@ import 'package:cutdex_native/cutdex_native.dart';
|
||||
import '../../persistence/app_settings_repositories.dart';
|
||||
import '../../shared/layout/workspace_layout_metrics.dart';
|
||||
|
||||
import 'package:cutdex_ui/icons.dart';
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
|
||||
import '../../workspace/timeline_provider.dart';
|
||||
import '../../workspace/preview_target.dart';
|
||||
import '../../workspace/projects.dart';
|
||||
import '../../workspace/view_settings.dart';
|
||||
import '../media/media_browser_page.dart';
|
||||
import '../media/media_panel.dart';
|
||||
@@ -22,6 +27,8 @@ import '../properties/properties_editor_page.dart';
|
||||
import '../properties/properties_panel.dart';
|
||||
import '../timeline/timeline_panel.dart';
|
||||
import 'editor_presentation_controller.dart';
|
||||
import 'editor_panel_defaults.dart';
|
||||
import 'timeline_operation_region.dart';
|
||||
import 'layouts/bounded_editor_layout.dart';
|
||||
import 'layouts/expanded_editor_layout.dart';
|
||||
|
||||
@@ -34,10 +41,16 @@ class EditorWorkspace extends ConsumerStatefulWidget {
|
||||
required this.projectName,
|
||||
required this.integratedTitlebar,
|
||||
required this.headerLeading,
|
||||
this.projectLoading = false,
|
||||
this.timelineLoading = false,
|
||||
this.showProjectName = true,
|
||||
this.experience = DeviceExperience.desktop,
|
||||
});
|
||||
|
||||
final bool projectLoading;
|
||||
|
||||
/// Navigation is preparing another timeline; the current content stays visible.
|
||||
final bool timelineLoading;
|
||||
final String projectId;
|
||||
final String timelineId;
|
||||
final String projectName;
|
||||
@@ -52,6 +65,13 @@ class EditorWorkspace extends ConsumerStatefulWidget {
|
||||
|
||||
class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
|
||||
final _previewKey = GlobalKey();
|
||||
bool get _timelinePending => widget.projectLoading;
|
||||
|
||||
Widget _timelineInteraction(Widget child) => TimelineOperationRegion(
|
||||
projectId: widget.projectId,
|
||||
loading: widget.timelineLoading,
|
||||
child: child,
|
||||
);
|
||||
EditorPresentationController get _presentation =>
|
||||
ref.read(editorPresentationProvider(widget.projectId));
|
||||
ProjectViewSettingsData get _viewSettings =>
|
||||
@@ -60,10 +80,10 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
|
||||
ProjectViewSettings get _viewController =>
|
||||
ref.read(projectViewSettingsProvider(widget.projectId).notifier);
|
||||
bool get _propertiesOpen => _viewSettings.propertiesOpen;
|
||||
double? get _timelineHeight => _viewSettings.timelineHeight;
|
||||
|
||||
void _saveViewSettings() {
|
||||
if (!ref.read(projectViewSettingsProvider(widget.projectId)).hasValue) {
|
||||
if (widget.projectId.isEmpty ||
|
||||
!ref.read(projectViewSettingsProvider(widget.projectId)).hasValue) {
|
||||
return;
|
||||
}
|
||||
unawaited(_viewController.save());
|
||||
@@ -72,192 +92,246 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final viewSettings = ref.watch(
|
||||
projectViewSettingsProvider(widget.projectId),
|
||||
projectViewSettingsProvider(widget.projectId)
|
||||
.select((value) => (value.hasValue, value.value?.propertiesOpen)),
|
||||
);
|
||||
final preview = KeyedSubtree(
|
||||
key: _previewKey,
|
||||
child: EditorPreviewPanel(
|
||||
projectId: widget.projectId,
|
||||
timelineId: widget.timelineId,
|
||||
child: _timelineInteraction(
|
||||
EditorPreviewPanel(
|
||||
projectId: widget.projectId,
|
||||
timelineId: widget.timelineId,
|
||||
pending: _timelinePending,
|
||||
),
|
||||
),
|
||||
);
|
||||
final timeline = EditorTimelinePanel(
|
||||
projectId: widget.projectId,
|
||||
timelineId: widget.timelineId,
|
||||
pending: widget.projectLoading,
|
||||
timelineLoading: widget.timelineLoading,
|
||||
);
|
||||
final properties = EditorPropertiesPanel(
|
||||
projectId: widget.projectId,
|
||||
timelineId: widget.timelineId,
|
||||
final properties = _timelineInteraction(
|
||||
_timelinePending
|
||||
? const EditorEmptyPanel()
|
||||
: EditorPropertiesPanel(
|
||||
projectId: widget.projectId,
|
||||
timelineId: widget.timelineId,
|
||||
),
|
||||
);
|
||||
final media = MediaPanel(projectId: widget.projectId);
|
||||
final media = widget.projectLoading
|
||||
? const EditorEmptyPanel()
|
||||
: MediaPanel(projectId: widget.projectId, projectScoped: true);
|
||||
return ListenableBuilder(
|
||||
listenable: ref.watch(editorPresentationProvider(widget.projectId)),
|
||||
builder: (context, _) => LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final desktop = widget.experience == DeviceExperience.desktop;
|
||||
final sideWidth =
|
||||
(_presentation.mediaOpen
|
||||
? WorkspaceLayoutMetrics.mediaPanelWidth + 1
|
||||
: 0) +
|
||||
(_propertiesOpen
|
||||
? WorkspaceLayoutMetrics.propertiesPanelWidth + 1
|
||||
: 0);
|
||||
final dockPanels =
|
||||
desktop &&
|
||||
constraints.maxWidth >=
|
||||
WorkspaceLayoutMetrics.previewMinimumWidth + sideWidth;
|
||||
final desktopTool = sideWidth == 0
|
||||
? null
|
||||
: _presentation.desktopTool(propertiesOpen: _propertiesOpen);
|
||||
final headerHeight = desktop ? AppControlSize.panelHeader : 48.0;
|
||||
final mediaOpen = desktop
|
||||
? dockPanels
|
||||
? _presentation.mediaOpen
|
||||
: desktopTool == EditorTool.media
|
||||
? _presentation.mediaOpen
|
||||
: _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
|
||||
? dockPanels
|
||||
? dockProperties
|
||||
? _propertiesOpen
|
||||
: desktopTool == EditorTool.properties
|
||||
: _presentation.activeTool == EditorTool.properties;
|
||||
Widget dockedEditing({required bool showTools}) =>
|
||||
ExpandedEditorLayout(
|
||||
final mediaButton = HeaderControlRegion(
|
||||
child: SizedBox.square(
|
||||
dimension: desktop ? AppControlSize.headerButton : 48,
|
||||
child: IconButton(
|
||||
key: const Key('editor-media-button'),
|
||||
tooltip: context.l10n.materials,
|
||||
isSelected: mediaOpen,
|
||||
onPressed: () {
|
||||
if (desktop) {
|
||||
if (!dockMedia &&
|
||||
desktopTool != EditorTool.media &&
|
||||
_presentation.mediaOpen) {
|
||||
_presentation.preferDesktopTool(EditorTool.media);
|
||||
} else {
|
||||
_presentation.toggleMedia();
|
||||
}
|
||||
} else {
|
||||
_presentation.toggleTool(EditorTool.media);
|
||||
}
|
||||
},
|
||||
icon: const Icon(AppIcons.mediaLibrary),
|
||||
),
|
||||
),
|
||||
);
|
||||
final header = Material(
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
child: SizedBox(
|
||||
key: const Key('editor-content-header'),
|
||||
height: headerHeight,
|
||||
child: Padding(
|
||||
padding: desktop
|
||||
? const EdgeInsets.symmetric(
|
||||
horizontal: AppSidebarMetrics.outerPadding,
|
||||
vertical: AppSpacing.tiny,
|
||||
)
|
||||
: EdgeInsets.zero,
|
||||
child: WindowHeaderPadding(
|
||||
child: Row(
|
||||
children: [
|
||||
widget.headerLeading,
|
||||
if (desktop) mediaButton,
|
||||
Expanded(
|
||||
child: desktop
|
||||
? Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: AppSpacing.small,
|
||||
),
|
||||
child: _PreviewHeaderTitle(
|
||||
projectId: widget.projectId,
|
||||
timelineId: widget.timelineId,
|
||||
pending: _timelinePending,
|
||||
),
|
||||
)
|
||||
: widget.showProjectName
|
||||
? Row(
|
||||
children: [
|
||||
Flexible(
|
||||
fit: FlexFit.loose,
|
||||
child: Text(
|
||||
widget.projectName,
|
||||
key: const Key('workspace-project-title'),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.titleSmall,
|
||||
),
|
||||
),
|
||||
Flexible(
|
||||
fit: FlexFit.loose,
|
||||
child: _timelinePending
|
||||
? const SizedBox.shrink()
|
||||
: _TimelineSaveStatus(
|
||||
projectId: widget.projectId,
|
||||
timelineId: widget.timelineId,
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
: const SizedBox.shrink(),
|
||||
),
|
||||
if (!desktop) mediaButton,
|
||||
if (!desktop) const SizedBox(width: AppSpacing.tiny),
|
||||
HeaderControlRegion(
|
||||
child: SizedBox.square(
|
||||
dimension: desktop ? AppControlSize.headerButton : 48,
|
||||
child: IconButton(
|
||||
key: const Key('editor-properties-button'),
|
||||
tooltip: propertiesOpen
|
||||
? context.l10n.collapseProperties
|
||||
: context.l10n.expandProperties,
|
||||
isSelected: propertiesOpen,
|
||||
onPressed: !viewSettings.$1
|
||||
? null
|
||||
: () {
|
||||
if (desktop) {
|
||||
if (dockProperties ||
|
||||
desktopTool ==
|
||||
EditorTool.properties ||
|
||||
!_propertiesOpen) {
|
||||
_viewController.setPropertiesOpen(
|
||||
!_propertiesOpen,
|
||||
);
|
||||
_saveViewSettings();
|
||||
}
|
||||
_presentation.preferDesktopTool(
|
||||
EditorTool.properties,
|
||||
);
|
||||
} else {
|
||||
_presentation.toggleTool(
|
||||
EditorTool.properties,
|
||||
);
|
||||
}
|
||||
},
|
||||
icon: const Icon(
|
||||
AppIcons.tune,
|
||||
size: AppIconSize.header,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (!desktop) const SizedBox(width: AppSpacing.compact),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
Widget dockedEditing({required bool showTools}) => Consumer(
|
||||
builder: (context, ref, _) {
|
||||
final dimensions = ref.watch(
|
||||
projectViewSettingsProvider(widget.projectId).select(
|
||||
(value) =>
|
||||
(value.value?.mediaWidth, value.value?.timelineHeight),
|
||||
),
|
||||
);
|
||||
return ExpandedEditorLayout(
|
||||
preview: preview,
|
||||
header: header,
|
||||
properties: properties,
|
||||
media: media,
|
||||
showMedia: showTools && _presentation.mediaOpen,
|
||||
showProperties: showTools && _propertiesOpen,
|
||||
timelineHeight: _timelineHeight,
|
||||
showMedia: dockMedia,
|
||||
showProperties: showTools && dockProperties,
|
||||
mediaWidth: dimensions.$1,
|
||||
onMediaWidthChanged: (width) {
|
||||
if (viewSettings.$1) {
|
||||
_viewController.setMediaWidth(width);
|
||||
}
|
||||
},
|
||||
onMediaWidthChangeEnd: _saveViewSettings,
|
||||
timelineHeight: dimensions.$2,
|
||||
onTimelineHeightChanged: (height) {
|
||||
if (viewSettings.hasValue) {
|
||||
if (viewSettings.$1) {
|
||||
_viewController.setTimelineHeight(height);
|
||||
}
|
||||
},
|
||||
onTimelineHeightChangeEnd: _saveViewSettings,
|
||||
onJunctionResizeEnd: _saveViewSettings,
|
||||
timeline: timeline,
|
||||
);
|
||||
},
|
||||
);
|
||||
return Stack(
|
||||
fit: StackFit.expand,
|
||||
children: [
|
||||
Column(
|
||||
children: [
|
||||
Material(
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
child: SizedBox(
|
||||
key: const Key('editor-content-header'),
|
||||
height: headerHeight,
|
||||
child: WindowHeaderPadding(
|
||||
child: Row(
|
||||
children: [
|
||||
widget.headerLeading,
|
||||
Expanded(
|
||||
child: widget.showProjectName
|
||||
? Row(
|
||||
children: [
|
||||
Flexible(
|
||||
fit: FlexFit.loose,
|
||||
child: Text(
|
||||
widget.projectName,
|
||||
key: const Key(
|
||||
'workspace-project-title',
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.titleSmall,
|
||||
),
|
||||
),
|
||||
Flexible(
|
||||
fit: FlexFit.loose,
|
||||
child: _TimelineSaveStatus(
|
||||
projectId: widget.projectId,
|
||||
timelineId: widget.timelineId,
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
: const SizedBox.shrink(),
|
||||
),
|
||||
HeaderControlRegion(
|
||||
child: SizedBox.square(
|
||||
dimension: desktop
|
||||
? AppControlSize.headerButton
|
||||
: 48,
|
||||
child: IconButton(
|
||||
key: const Key('editor-media-button'),
|
||||
tooltip: context.l10n.materials,
|
||||
isSelected: mediaOpen,
|
||||
onPressed: () {
|
||||
if (desktop) {
|
||||
if (!dockPanels &&
|
||||
desktopTool != EditorTool.media &&
|
||||
_presentation.mediaOpen) {
|
||||
_presentation.preferDesktopTool(
|
||||
EditorTool.media,
|
||||
);
|
||||
} else {
|
||||
_presentation.toggleMedia();
|
||||
}
|
||||
} else {
|
||||
_presentation.toggleTool(
|
||||
EditorTool.media,
|
||||
);
|
||||
}
|
||||
},
|
||||
icon: const Icon(Icons.perm_media_outlined),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: AppSpacing.tiny),
|
||||
HeaderControlRegion(
|
||||
child: SizedBox.square(
|
||||
dimension: desktop
|
||||
? AppControlSize.headerButton
|
||||
: 48,
|
||||
child: IconButton(
|
||||
key: const Key('editor-properties-button'),
|
||||
tooltip: propertiesOpen
|
||||
? context.l10n.collapseProperties
|
||||
: context.l10n.expandProperties,
|
||||
isSelected: propertiesOpen,
|
||||
onPressed: !viewSettings.hasValue
|
||||
? null
|
||||
: () {
|
||||
if (desktop) {
|
||||
if (dockPanels ||
|
||||
desktopTool ==
|
||||
EditorTool.properties ||
|
||||
!_propertiesOpen) {
|
||||
_viewController.setPropertiesOpen(
|
||||
!_propertiesOpen,
|
||||
);
|
||||
_saveViewSettings();
|
||||
}
|
||||
_presentation.preferDesktopTool(
|
||||
EditorTool.properties,
|
||||
);
|
||||
} else {
|
||||
_presentation.toggleTool(
|
||||
EditorTool.properties,
|
||||
);
|
||||
}
|
||||
},
|
||||
icon: const Icon(
|
||||
Icons.tune,
|
||||
size: AppIconSize.header,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: AppSpacing.compact),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (!desktop) header,
|
||||
Expanded(
|
||||
child: dockPanels
|
||||
child: desktop && desktopTool == null
|
||||
? dockedEditing(showTools: true)
|
||||
: BoundedEditorLayout(
|
||||
experience: widget.experience,
|
||||
@@ -270,26 +344,37 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
|
||||
tool: desktop
|
||||
? desktopTool
|
||||
: _presentation.activeTool,
|
||||
media: switch (widget.experience) {
|
||||
DeviceExperience.desktop => media,
|
||||
DeviceExperience.tablet => MediaBrowserDrawer(
|
||||
projectId: widget.projectId,
|
||||
),
|
||||
DeviceExperience.phone => MediaBrowserPage(
|
||||
projectId: widget.projectId,
|
||||
),
|
||||
},
|
||||
properties: switch (widget.experience) {
|
||||
DeviceExperience.desktop => properties,
|
||||
DeviceExperience.tablet => PropertiesToolPanel(
|
||||
projectId: widget.projectId,
|
||||
timelineId: widget.timelineId,
|
||||
),
|
||||
DeviceExperience.phone => PropertiesEditorPage(
|
||||
projectId: widget.projectId,
|
||||
timelineId: widget.timelineId,
|
||||
),
|
||||
},
|
||||
media: widget.projectLoading
|
||||
? media
|
||||
: switch (widget.experience) {
|
||||
DeviceExperience.desktop => media,
|
||||
DeviceExperience.tablet =>
|
||||
MediaBrowserDrawer(
|
||||
projectId: widget.projectId,
|
||||
),
|
||||
DeviceExperience.phone => MediaBrowserPage(
|
||||
projectId: widget.projectId,
|
||||
),
|
||||
},
|
||||
properties: _timelinePending
|
||||
? properties
|
||||
: switch (widget.experience) {
|
||||
DeviceExperience.desktop => properties,
|
||||
DeviceExperience.tablet =>
|
||||
_timelineInteraction(
|
||||
PropertiesToolPanel(
|
||||
projectId: widget.projectId,
|
||||
timelineId: widget.timelineId,
|
||||
),
|
||||
),
|
||||
DeviceExperience.phone =>
|
||||
_timelineInteraction(
|
||||
PropertiesEditorPage(
|
||||
projectId: widget.projectId,
|
||||
timelineId: widget.timelineId,
|
||||
),
|
||||
),
|
||||
},
|
||||
onCloseTool: () {
|
||||
if (!desktop) {
|
||||
_presentation.closeTool();
|
||||
@@ -304,14 +389,15 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
|
||||
),
|
||||
],
|
||||
),
|
||||
Positioned(
|
||||
key: const Key('editing-top-divider'),
|
||||
top: headerHeight,
|
||||
left: 0,
|
||||
right: 0,
|
||||
height: 1,
|
||||
child: const Divider(height: 1),
|
||||
),
|
||||
if (!desktop)
|
||||
Positioned(
|
||||
key: const Key('editing-top-divider'),
|
||||
top: headerHeight,
|
||||
left: 0,
|
||||
right: 0,
|
||||
height: 1,
|
||||
child: const Divider(height: 1),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
@@ -320,6 +406,73 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
|
||||
}
|
||||
}
|
||||
|
||||
class _PreviewHeaderTitle extends ConsumerWidget {
|
||||
const _PreviewHeaderTitle({
|
||||
required this.projectId,
|
||||
required this.timelineId,
|
||||
required this.pending,
|
||||
});
|
||||
|
||||
final String projectId;
|
||||
final String timelineId;
|
||||
final bool pending;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final navigation = pending
|
||||
? const PreviewTargetState.timeline()
|
||||
: ref.watch(previewNavigationProvider(projectId, timelineId));
|
||||
final name = pending
|
||||
? context.l10n.preview
|
||||
: ref.watch(
|
||||
projectsProvider.select((value) {
|
||||
final workspace = value.value;
|
||||
return switch (navigation) {
|
||||
SourcePreviewTarget(:final asset) =>
|
||||
workspace?.assets
|
||||
.where((item) => item.id == asset.id)
|
||||
.firstOrNull
|
||||
?.name ??
|
||||
asset.name,
|
||||
_ =>
|
||||
workspace?.timeline?.id == timelineId
|
||||
? workspace!.timeline!.name
|
||||
: context.l10n.preview,
|
||||
};
|
||||
}),
|
||||
);
|
||||
final session = pending
|
||||
? null
|
||||
: ref.watch(editorTimelineProvider(projectId, timelineId)).value;
|
||||
Widget title(String? saveStatus) => Tooltip(
|
||||
message: saveStatus == null ? name : '$name\n$saveStatus',
|
||||
child: Text(
|
||||
name,
|
||||
key: const Key('editor-preview-title'),
|
||||
textAlign: TextAlign.center,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context).textTheme.titleSmall,
|
||||
),
|
||||
);
|
||||
if (session == null) return title(null);
|
||||
return ListenableSelector<(bool, bool, bool)>(
|
||||
listenable: session,
|
||||
select: () => (session.error != null, session.saving, session.dirty),
|
||||
builder: (context, value) => title(_timelineSaveLabel(context, value)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _timelineSaveLabel(BuildContext context, (bool, bool, bool) value) =>
|
||||
value.$1
|
||||
? context.l10n.unsaved
|
||||
: value.$2
|
||||
? context.l10n.saving
|
||||
: value.$3
|
||||
? context.l10n.pendingSave
|
||||
: context.l10n.saved;
|
||||
|
||||
class _TimelineSaveStatus extends ConsumerWidget {
|
||||
const _TimelineSaveStatus({
|
||||
required this.projectId,
|
||||
@@ -336,22 +489,19 @@ class _TimelineSaveStatus extends ConsumerWidget {
|
||||
.asData
|
||||
?.value;
|
||||
if (session == null) return const SizedBox.shrink();
|
||||
return ListenableBuilder(
|
||||
return ListenableSelector<(bool, bool, bool)>(
|
||||
listenable: session,
|
||||
builder: (context, _) => Padding(
|
||||
select: () => (session.error != null, session.saving, session.dirty),
|
||||
builder: (context, value) => Padding(
|
||||
padding: const EdgeInsets.only(left: AppSpacing.small),
|
||||
child: Text(
|
||||
session.error != null
|
||||
? context.l10n.unsaved
|
||||
: session.saving
|
||||
? context.l10n.saving
|
||||
: session.dirty
|
||||
? context.l10n.pendingSave
|
||||
: context.l10n.saved,
|
||||
_timelineSaveLabel(context, value),
|
||||
key: const Key('timeline-save-status'),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(fontSize: 10),
|
||||
style: AppTheme.isDesktop(context)
|
||||
? Theme.of(context).textTheme.bodySmall
|
||||
: Theme.of(context).textTheme.bodySmall?.copyWith(fontSize: 10),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
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.small : 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: AppSpacing.medium,
|
||||
),
|
||||
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.
|
||||
class EditorPresentationController extends ChangeNotifier {
|
||||
bool _mediaOpen = false;
|
||||
bool _mediaOpen = true;
|
||||
EditorTool? _activeTool;
|
||||
EditorTool _preferredDesktopTool = EditorTool.properties;
|
||||
bool _desktopToolRequested = false;
|
||||
|
||||
bool get mediaOpen => _mediaOpen;
|
||||
EditorTool? get activeTool => _activeTool;
|
||||
bool get desktopToolRequested => _desktopToolRequested;
|
||||
EditorTool desktopTool({required bool propertiesOpen}) =>
|
||||
_preferredDesktopTool == EditorTool.media && _mediaOpen
|
||||
? EditorTool.media
|
||||
@@ -26,12 +28,14 @@ class EditorPresentationController extends ChangeNotifier {
|
||||
: EditorTool.media;
|
||||
|
||||
void preferDesktopTool(EditorTool tool) {
|
||||
_desktopToolRequested = true;
|
||||
_preferredDesktopTool = tool;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void toggleMedia() {
|
||||
_mediaOpen = !_mediaOpen;
|
||||
_desktopToolRequested = _mediaOpen;
|
||||
if (_mediaOpen) _preferredDesktopTool = EditorTool.media;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
@@ -4,7 +4,9 @@ import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../integrations/platform/device_experience.dart';
|
||||
import '../../../l10n/l10n.dart';
|
||||
import '../../../shared/layout/workspace_layout_metrics.dart';
|
||||
|
||||
import 'package:cutdex_ui/icons.dart';
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
|
||||
import '../editor_presentation_controller.dart';
|
||||
@@ -36,29 +38,39 @@ class BoundedEditorLayout extends StatelessWidget {
|
||||
Widget toolSurface() => Column(
|
||||
children: [
|
||||
SizedBox(
|
||||
height: desktop ? AppControlSize.panelHeader : 48,
|
||||
child: Row(
|
||||
children: [
|
||||
SizedBox.square(
|
||||
dimension: desktop ? AppControlSize.headerButton : 48,
|
||||
child: IconButton(
|
||||
key: const Key('editor-tool-close'),
|
||||
tooltip: MaterialLocalizations.of(context)
|
||||
.closeButtonTooltip,
|
||||
onPressed: onCloseTool,
|
||||
icon: Icon(page ? Icons.arrow_back : Icons.close),
|
||||
height: desktop ? AppDesktopMetrics.panelHeader : 48,
|
||||
child: Padding(
|
||||
padding: EdgeInsets.symmetric(
|
||||
horizontal: desktop ? AppSpacing.small : 0,
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
SizedBox.square(
|
||||
dimension: desktop ? AppControlSize.headerButton : 48,
|
||||
child: IconButton(
|
||||
key: const Key('editor-tool-close'),
|
||||
tooltip: MaterialLocalizations.of(context)
|
||||
.closeButtonTooltip,
|
||||
onPressed: onCloseTool,
|
||||
icon: Icon(page ? AppIcons.arrowBack : AppIcons.close),
|
||||
),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: Text(
|
||||
tool == EditorTool.media
|
||||
? context.l10n.materials
|
||||
: context.l10n.expandProperties,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
Expanded(
|
||||
child: Text(
|
||||
tool == EditorTool.media
|
||||
? context.l10n.materials
|
||||
: context.l10n.expandProperties,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: desktop && tool == EditorTool.properties
|
||||
? AppTheme.propertiesPanelTheme(Theme.of(context))
|
||||
.textTheme
|
||||
.titleSmall
|
||||
: null,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
const Divider(height: 1),
|
||||
@@ -92,12 +104,17 @@ class BoundedEditorLayout extends StatelessWidget {
|
||||
),
|
||||
if (tool != null)
|
||||
Positioned(
|
||||
top: 0,
|
||||
top: desktop ? AppDesktopMetrics.panelHeader + 1 : 0,
|
||||
bottom: 0,
|
||||
right: 0,
|
||||
width: page
|
||||
? constraints.maxWidth
|
||||
: math.min(320, constraints.maxWidth),
|
||||
: math.min(
|
||||
desktop && tool == EditorTool.properties
|
||||
? WorkspaceLayoutMetrics.propertiesPanelWidth
|
||||
: 320,
|
||||
constraints.maxWidth,
|
||||
),
|
||||
child: Material(
|
||||
key: const Key('editor-tool-surface'),
|
||||
elevation: page ? 0 : 8,
|
||||
|
||||
@@ -1,32 +1,43 @@
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'package:flutter/material.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 {
|
||||
const ExpandedEditorLayout({
|
||||
super.key,
|
||||
required this.preview,
|
||||
required this.header,
|
||||
required this.properties,
|
||||
required this.media,
|
||||
required this.showMedia,
|
||||
required this.showProperties,
|
||||
required this.mediaWidth,
|
||||
required this.onMediaWidthChanged,
|
||||
required this.onMediaWidthChangeEnd,
|
||||
required this.timelineHeight,
|
||||
required this.onTimelineHeightChanged,
|
||||
required this.onTimelineHeightChangeEnd,
|
||||
required this.onJunctionResizeEnd,
|
||||
required this.timeline,
|
||||
});
|
||||
|
||||
final Widget preview;
|
||||
final Widget header;
|
||||
final Widget properties;
|
||||
final Widget media;
|
||||
final bool showMedia;
|
||||
final bool showProperties;
|
||||
final double? mediaWidth;
|
||||
final ValueChanged<double> onMediaWidthChanged;
|
||||
final VoidCallback onMediaWidthChangeEnd;
|
||||
final double? timelineHeight;
|
||||
final ValueChanged<double> onTimelineHeightChanged;
|
||||
final VoidCallback onTimelineHeightChangeEnd;
|
||||
final VoidCallback onJunctionResizeEnd;
|
||||
final Widget timeline;
|
||||
|
||||
@override
|
||||
@@ -34,32 +45,48 @@ class ExpandedEditorLayout extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _ExpandedEditorLayoutState extends State<ExpandedEditorLayout> {
|
||||
double? _timelineDragStartY;
|
||||
double _timelineDragStartHeight = 0;
|
||||
static const gap = WorkspaceLayoutMetrics.desktopSpacing;
|
||||
late bool _mediaVisited = widget.showMedia;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => LayoutBuilder(
|
||||
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
|
||||
Widget build(BuildContext context) =>
|
||||
WorkspaceResizeHighlightScope(child: _layout());
|
||||
|
||||
Widget _layout() => LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final maximum = math.max(
|
||||
0.0,
|
||||
constraints.maxHeight - WorkspaceLayoutMetrics.timelineMinimumHeight,
|
||||
);
|
||||
final minimum = math.min(
|
||||
WorkspaceLayoutMetrics.timelineMinimumHeight,
|
||||
maximum,
|
||||
);
|
||||
final timelineHeight =
|
||||
(widget.timelineHeight ??
|
||||
constraints.maxHeight *
|
||||
WorkspaceLayoutMetrics.timelineDefaultHeightFraction)
|
||||
.clamp(minimum, maximum)
|
||||
.toDouble();
|
||||
final mediaWidth = widget.showMedia
|
||||
? WorkspaceLayoutMetrics.mediaPanelWidth
|
||||
: 0.0;
|
||||
double resolveTimelineHeight(double? height) =>
|
||||
WorkspaceLayoutMetrics.resolveTimelineHeight(
|
||||
constraints.maxHeight,
|
||||
height,
|
||||
);
|
||||
final timelineHeight = resolveTimelineHeight(widget.timelineHeight);
|
||||
final propertiesWidth = widget.showProperties
|
||||
? WorkspaceLayoutMetrics.propertiesPanelWidth
|
||||
: 0.0;
|
||||
final mediaMaximumWidth = math.max(
|
||||
0.0,
|
||||
constraints.maxWidth -
|
||||
WorkspaceLayoutMetrics.previewMinimumWidth -
|
||||
gap -
|
||||
(widget.showProperties ? propertiesWidth + gap : 0),
|
||||
);
|
||||
final mediaMinimumWidth = math.min(
|
||||
WorkspaceLayoutMetrics.mediaPanelMinimumWidth,
|
||||
mediaMaximumWidth,
|
||||
);
|
||||
final mediaWidth =
|
||||
(widget.mediaWidth ?? WorkspaceLayoutMetrics.mediaPanelWidth)
|
||||
.clamp(mediaMinimumWidth, mediaMaximumWidth)
|
||||
.toDouble();
|
||||
return Stack(
|
||||
fit: StackFit.expand,
|
||||
children: [
|
||||
@@ -69,75 +96,114 @@ class _ExpandedEditorLayoutState extends State<ExpandedEditorLayout> {
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
if (widget.showMedia) ...[
|
||||
SizedBox(
|
||||
key: const Key('editor-media-region'),
|
||||
width: mediaWidth,
|
||||
child: widget.media,
|
||||
if (_mediaVisited)
|
||||
Offstage(
|
||||
offstage: !widget.showMedia,
|
||||
child: ExcludeFocus(
|
||||
excluding: !widget.showMedia,
|
||||
child: TickerMode(
|
||||
enabled: widget.showMedia,
|
||||
child: SizedBox(
|
||||
key: const Key('editor-media-region'),
|
||||
width: mediaWidth,
|
||||
child: _card('media', widget.media),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const VerticalDivider(width: 1),
|
||||
],
|
||||
Expanded(child: widget.preview),
|
||||
if (widget.showMedia) const SizedBox(width: gap),
|
||||
Expanded(
|
||||
child: _card(
|
||||
'preview',
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
widget.header,
|
||||
Expanded(child: widget.preview),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
if (widget.showProperties) ...[
|
||||
const VerticalDivider(width: 1),
|
||||
const SizedBox(
|
||||
key: Key('editor-properties-divider'),
|
||||
width: gap,
|
||||
),
|
||||
SizedBox(
|
||||
key: const Key('editor-properties-region'),
|
||||
width: propertiesWidth,
|
||||
child: widget.properties,
|
||||
child: _card('properties', widget.properties),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 1),
|
||||
SizedBox(height: timelineHeight, child: widget.timeline),
|
||||
const SizedBox(height: gap),
|
||||
SizedBox(
|
||||
height: timelineHeight,
|
||||
child: _card('timeline', widget.timeline),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (widget.showMedia)
|
||||
Positioned(
|
||||
key: const Key('editor-media-divider'),
|
||||
left: mediaWidth - WorkspaceLayoutMetrics.desktopResizeSlop,
|
||||
top: 0,
|
||||
bottom: timelineHeight + gap,
|
||||
width: WorkspaceLayoutMetrics.desktopResizeHitExtent,
|
||||
child: WorkspaceResizeHandle(
|
||||
key: const Key('editor-media-resize'),
|
||||
highlightTargets: const {WorkspaceResizeBoundary.media},
|
||||
axis: Axis.horizontal,
|
||||
initialValue: mediaWidth,
|
||||
onResize: (width) => widget.onMediaWidthChanged(
|
||||
width.clamp(mediaMinimumWidth, mediaMaximumWidth).toDouble(),
|
||||
),
|
||||
onEnd: widget.onMediaWidthChangeEnd,
|
||||
),
|
||||
),
|
||||
Positioned(
|
||||
key: const Key('editor-timeline-divider'),
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: timelineHeight - 4,
|
||||
height: 8,
|
||||
child: MouseRegion(
|
||||
cursor: SystemMouseCursors.resizeRow,
|
||||
child: GestureDetector(
|
||||
key: const Key('editor-timeline-resize'),
|
||||
behavior: HitTestBehavior.opaque,
|
||||
dragStartBehavior: DragStartBehavior.down,
|
||||
onVerticalDragStart: (details) {
|
||||
_timelineDragStartY = details.globalPosition.dy;
|
||||
_timelineDragStartHeight = timelineHeight;
|
||||
},
|
||||
onVerticalDragUpdate: (details) {
|
||||
final start = _timelineDragStartY;
|
||||
if (start == null) return;
|
||||
widget.onTimelineHeightChanged(
|
||||
(_timelineDragStartHeight +
|
||||
start -
|
||||
details.globalPosition.dy)
|
||||
.clamp(minimum, maximum)
|
||||
.toDouble(),
|
||||
);
|
||||
},
|
||||
onVerticalDragEnd: (_) {
|
||||
_timelineDragStartY = null;
|
||||
widget.onTimelineHeightChangeEnd();
|
||||
},
|
||||
onVerticalDragCancel: () {
|
||||
_timelineDragStartY = null;
|
||||
widget.onTimelineHeightChangeEnd();
|
||||
},
|
||||
child: const Center(
|
||||
child: SizedBox(
|
||||
height: 1,
|
||||
width: double.infinity,
|
||||
child: Divider(height: 1),
|
||||
),
|
||||
),
|
||||
),
|
||||
bottom: timelineHeight - WorkspaceLayoutMetrics.desktopResizeSlop,
|
||||
height: WorkspaceLayoutMetrics.desktopResizeHitExtent,
|
||||
child: WorkspaceResizeHandle(
|
||||
key: const Key('editor-timeline-resize'),
|
||||
highlightTargets: const {WorkspaceResizeBoundary.timeline},
|
||||
axis: Axis.vertical,
|
||||
initialValue: timelineHeight,
|
||||
direction: -1,
|
||||
onResize: (height) =>
|
||||
widget.onTimelineHeightChanged(resolveTimelineHeight(height)),
|
||||
onEnd: widget.onTimelineHeightChangeEnd,
|
||||
),
|
||||
),
|
||||
if (widget.showMedia)
|
||||
Positioned(
|
||||
left: mediaWidth - WorkspaceLayoutMetrics.desktopResizeSlop,
|
||||
bottom: timelineHeight - WorkspaceLayoutMetrics.desktopResizeSlop,
|
||||
width: WorkspaceLayoutMetrics.desktopResizeHitExtent,
|
||||
height: WorkspaceLayoutMetrics.desktopResizeHitExtent,
|
||||
child: WorkspaceResizeHandle.junction(
|
||||
key: const Key('editor-media-timeline-junction'),
|
||||
highlightTargets: const {
|
||||
WorkspaceResizeBoundary.media,
|
||||
WorkspaceResizeBoundary.timeline,
|
||||
},
|
||||
initialWidth: mediaWidth,
|
||||
initialHeight: timelineHeight,
|
||||
verticalDirection: -1,
|
||||
onWidthChanged: (width) => widget.onMediaWidthChanged(
|
||||
width.clamp(mediaMinimumWidth, mediaMaximumWidth).toDouble(),
|
||||
),
|
||||
onHeightChanged: (height) => widget.onTimelineHeightChanged(
|
||||
resolveTimelineHeight(height),
|
||||
),
|
||||
onEnd: widget.onJunctionResizeEnd,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
|
||||
@@ -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),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,14 @@
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:cutdex_sdk/timeline_ui.dart';
|
||||
import 'package:cutdex_core/project.dart';
|
||||
import 'package:cutdex_core/timeline/model.dart';
|
||||
import 'package:cutdex_timeline_ui/cutdex_timeline_ui.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../integrations/runtime/media_presentations.dart';
|
||||
|
||||
import 'package:cutdex_ui/icons.dart';
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
|
||||
class AudioAssetTile extends StatelessWidget {
|
||||
@@ -63,7 +64,7 @@ class _AudioWaveformCover extends ConsumerWidget {
|
||||
if (waveform == null) {
|
||||
return Center(
|
||||
child: Icon(
|
||||
Icons.audio_file_outlined,
|
||||
AppIcons.audioFile,
|
||||
size: AppIconSize.emptyState,
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import 'package:cutdex/diagnostics/app_diagnostics.dart';
|
||||
import 'package:cutdex/errors/app_failure.dart';
|
||||
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_core/editor.dart';
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import 'package:cutdex_ui/theme.dart';
|
||||
import 'package:cutdex_ui/widgets.dart';
|
||||
|
||||
import '../../shared/widgets/confirm_resource_download_cancel.dart';
|
||||
import '../../shared/widgets/error_notification_host.dart';
|
||||
import '../../shared/widgets/processing_resource_download_dialog.dart';
|
||||
import '../../workspace/timeline_session.dart';
|
||||
|
||||
@@ -76,10 +77,10 @@ class _BackgroundRemovalDialogState
|
||||
_closing = true;
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted) return;
|
||||
final messenger = ScaffoldMessenger.maybeOf(context);
|
||||
final notifications = ErrorNotificationHost.maybeOf(context);
|
||||
final message = context.l10n.backgroundRemovalTaskStarted;
|
||||
Navigator.of(context).pop();
|
||||
messenger?.showSnackBar(SnackBar(content: Text(message)));
|
||||
notifications?.showMessage(content: Text(message));
|
||||
});
|
||||
});
|
||||
return ref
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import '../../shared/widgets/presentation_list.dart';
|
||||
|
||||
import 'package:cutdex/shared/widgets/error_notification_host.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import 'subtitle_download.dart';
|
||||
import 'subtitle_task_actions.dart';
|
||||
|
||||
import 'package:cutdex/l10n/l10n.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_core/editor.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../integrations/runtime/processing_resource_repository.dart';
|
||||
@@ -43,12 +46,50 @@ class BackgroundTasksContent extends ConsumerWidget {
|
||||
final ProcessingResourceRepository? repository;
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final snapshot = ref.watch(
|
||||
backgroundTasksProvider(registry: registry, session: session),
|
||||
final tasksProvider = backgroundTasksProvider(
|
||||
registry: registry,
|
||||
session: session,
|
||||
);
|
||||
ref.watch(
|
||||
tasksProvider.select(
|
||||
(snapshot) => (
|
||||
PresentationList(
|
||||
snapshot.subtitles.map(
|
||||
(entry) => (entry.owner.session, entry.job.id),
|
||||
),
|
||||
),
|
||||
PresentationList(
|
||||
snapshot.removals.map(
|
||||
(entry) => (entry.owner.session, entry.task.id),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
final snapshot = ref.read(tasksProvider);
|
||||
if (repository != null) {
|
||||
ref.watch(
|
||||
processingResourcesProvider(repository!).select(
|
||||
(snapshot) => (
|
||||
snapshot.subtitleDownloading,
|
||||
PresentationList(
|
||||
snapshot.installs
|
||||
.where(
|
||||
(install) =>
|
||||
install.state == ProcessingResourceState.downloading ||
|
||||
install.state == ProcessingResourceState.failed,
|
||||
)
|
||||
.map(
|
||||
(install) => (install.package.capability, install.state),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
final resources = repository == null
|
||||
? null
|
||||
: ref.watch(processingResourcesProvider(repository!));
|
||||
: ref.read(processingResourcesProvider(repository!));
|
||||
final subtitleEntries = snapshot.subtitles;
|
||||
final removalEntries = snapshot.removals;
|
||||
final subtitleDownloading = resources?.subtitleDownloading == true;
|
||||
@@ -117,9 +158,11 @@ class BackgroundTasksContent extends ConsumerWidget {
|
||||
resourceDownloads.isNotEmpty ||
|
||||
subtitleDownloading)
|
||||
const SizedBox(height: 2),
|
||||
_BackgroundRemovalTaskCard(
|
||||
key: ValueKey(entry.task.id),
|
||||
_ObservedRemovalTask(
|
||||
key: ValueKey((entry.owner.session, entry.task.id)),
|
||||
entry: entry,
|
||||
registry: registry,
|
||||
session: session,
|
||||
),
|
||||
],
|
||||
for (final (index, entry)
|
||||
@@ -129,9 +172,14 @@ class BackgroundTasksContent extends ConsumerWidget {
|
||||
removalEntries.isNotEmpty ||
|
||||
subtitleDownloading)
|
||||
const SizedBox(height: 2),
|
||||
_SubtitleTaskCard(
|
||||
key: ValueKey(entry.job.recognition.id),
|
||||
_ObservedSubtitleTask(
|
||||
key: ValueKey((
|
||||
entry.owner.session,
|
||||
entry.job.recognition.id,
|
||||
)),
|
||||
entry: entry,
|
||||
registry: registry,
|
||||
session: session,
|
||||
),
|
||||
],
|
||||
],
|
||||
@@ -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
|
||||
? owner.timelineName
|
||||
: '${owner.projectName} · ${owner.timelineName}';
|
||||
@@ -386,7 +498,31 @@ class _ResourceDownloadCard extends ConsumerWidget {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final snapshot = ref.watch(processingResourcesProvider(repository));
|
||||
final snapshot = ref.watch(
|
||||
processingResourcesProvider(repository).select((snapshot) {
|
||||
final capability = this.install?.package.capability;
|
||||
return snapshot.copyWith(
|
||||
installs: snapshot.installs
|
||||
.where((install) => install.package.capability == capability)
|
||||
.toList(),
|
||||
paused: capability == null
|
||||
? const {}
|
||||
: snapshot.paused.where((item) => item == capability).toSet(),
|
||||
rates: capability == null
|
||||
? const {}
|
||||
: {capability: snapshot.rates[capability] ?? 0},
|
||||
subtitleDownloading: subtitleBundle && snapshot.subtitleDownloading,
|
||||
subtitlePaused: subtitleBundle && snapshot.subtitlePaused,
|
||||
subtitleDownloadedBytes: subtitleBundle
|
||||
? snapshot.subtitleDownloadedBytes
|
||||
: 0,
|
||||
subtitleTotalBytes: subtitleBundle ? snapshot.subtitleTotalBytes : 0,
|
||||
subtitleBytesPerSecond: subtitleBundle
|
||||
? snapshot.subtitleBytesPerSecond
|
||||
: 0,
|
||||
);
|
||||
}),
|
||||
);
|
||||
final install = this.install == null
|
||||
? null
|
||||
: snapshot.installs
|
||||
@@ -691,8 +827,8 @@ class _SubtitleTaskCardState extends ConsumerState<_SubtitleTaskCard> {
|
||||
setState(() => _validationError = null);
|
||||
await action();
|
||||
if (mounted && !widget.details && _error != null) {
|
||||
ScaffoldMessenger.maybeOf(context)
|
||||
?.showSnackBar(SnackBar(content: Text(_error!)));
|
||||
ErrorNotificationHost.maybeOf(context)
|
||||
?.show(ErrorNotification(content: Text(_error!)));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Loaded 100 of 653 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user