18 Commits
126 changed files with 7459 additions and 2071 deletions

No files matched your search

+69
View File
@@ -0,0 +1,69 @@
# 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. It also saves
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)`.
Windows compilation and packaging are separate jobs. Compilation saves the
unpackaged Release directory as `cutdex-windows-app` for 30 days; packaging
downloads it and runs the existing PE audit and Velopack tools. Rerunning a failed
packaging job reuses this app without recompiling. Assembly and Release jobs
similarly reuse their upstream artifacts. Use the failed-job rerun option: a
whole-workflow rerun executes compilation again. A job always restarts from its
first step. Saving the Windows app adds one artifact transfer between the jobs.
CI artifact uploads attempt at most three times, waiting 5 and 15 seconds between
attempts and replacing incomplete artifacts of the same job-owned name. Release
attachment uploads use the same bounded delays for temporary HTTP/network errors,
and check for already saved filenames before repeating a POST. Permanent errors
fail immediately and final attachment byte verification remains required. If the
Windows app cannot be saved after all attempts, its build job still needs to be
rerun. Draft creation and final publication are not automatically retried.
After main CI succeeds, create v<pubspec version> at that exact commit, or manually
dispatch the Release workflow with the existing tag. Release preparation selects
a successful main ci.yml run for the exact tagged commit and requires unexpired
cutdex-android-build, cutdex-windows-build and cutdex-release-metadata artifacts. It creates a draft bound to both that commit and
that CI run. Release jobs never rebuild the app or reinstall Flutter dependencies.
Android and Windows independently download their platform artifacts from the
selected CI run and immediately upload them to the draft. These jobs run in
parallel. The final job accepts only the compact metadata artifact from that same
CI run. Complete binary archives cannot substitute for platform packages or
metadata. Missing, expired or duplicate required artifacts block preparation
before any draft is created. Platform uploads check attachment presence without
reading back their bytes. Before publication, every attachment is read back once
and verified against trusted SHA256 checksums; the full update package also
matches its index SHA1 and size. Upload and verification batches use at most two
requests per job. Verification reads in 1 MiB chunks. Tag, CI, draft and attachment
ID/name bindings are rechecked before the Release is made public.
A failed upload leaves the draft unpublished with successful uploads retained.
Manual dispatch with the same tag resumes the original CI run, even if another CI
for that commit has since succeeded. Matching attachments are reused; changed or
unrelated attachments block publication rather than being replaced. If the
original platform or metadata artifacts have expired, release preparation fails and requires
operator attention. Published Releases are never overwritten. The built-in
GITEA_TOKEN handles release writes and Actions artifact reads; no separate
release-write PAT is required. Do not commit credentials or keystores.
PR/main 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.
+103
View File
@@ -0,0 +1,103 @@
# CI build performance
The workflow runs checks first, then Android and Windows compilation concurrently.
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.
Build commands keep Flutter's default Pub preparation after the explicit locked
resolution. Do not use `--no-pub`: Flutter also regenerates release plugin
registrants in that preparation, removing dev-only plugins such as integration_test.
The runner needs at least two execution slots. The local runner configuration at
`D:/workspace/gitea-stack/runner/config.yaml` currently has `capacity: 2`. The host
has 12 logical processors and approximately 16 GB RAM; the Android job retains its
3 GB heap and four-worker limit to leave room for concurrent Windows compilation.
`prepare-package-tools.ps1` installs pinned `pefile` and `vpk` on first use under
the runner user's `%LOCALAPPDATA%/Cutdex/ci-tools/`. Later builds reuse them after
version checks. Python interpreter identity and tool versions isolate the cache,
and a mutex protects installation across concurrent workflows. .NET setup remains
in the Windows packaging job to provide SDK 10 and the runtime required by `vpk`.
The .NET installation uses the runner user's `Cutdex/ci-tools/dotnet` directory
through `DOTNET_INSTALL_DIR` and `DOTNET_ROOT`, so setup needs no administrator
access and later jobs reuse the installed SDK and runtime.
The Windows build verifies that the resolved deskup native SDK matches the pinned
Velopack version before saving the app. Packaging imports no Flutter package
configuration and independently verifies the installed vpk version.
APK and Windows package uploads use `compression-level: 0` to avoid recompressing
already compressed artifacts. The saved Windows app uses compression level 1,
preserves nested and hidden runtime assets, and excludes the same debug files and
optional workers omitted by packaging. The saved app, platform packages, compact
metadata and validated release artifact all retain 30 days.
This host runs both Gitea and the runner. The workflows set
`CUTDEX_GITEA_INTERNAL_URL=http://127.0.0.1:3000` and override `ACTIONS_RESULTS_URL`
on artifact upload/download steps, so those transfers stay on the host instead of
looping through the public FRP tunnel. Release API uploads and byte verification
also use this loopback endpoint; tooling rewrites only the validated public Gitea
origin. The server's public URL remains `https://git.orangraph.com`, and the runner
registration is unchanged. These workflow labels require this shared-host layout;
configure a reachable private endpoint before using runners on other hosts.
Checkout uses the same endpoint through its `github-server-url` input, retaining
the requested commit/tag and disabling persisted credentials. Release requests
retain the public Host header so Gitea response links pass the public-origin checks.
CI artifact ZIP download requests retain the loopback Host instead: Gitea returns
a signed redirect to the raw archive, and its Host must remain local for that
second request to avoid the public tunnel. Release attachment links stay public.
Compare warm CI runs after the first cache fill. Measure checks, Android compile,
Windows compile, packaging and artifact transfer separately. Total duration follows
the slower platform branch, plus checks and final assembly; no fixed speedup is
assumed. Release audits and artifact validation remain mandatory.
## Failure recovery
Use Gitea's failed-job rerun rather than rerunning the entire workflow. A job
reruns from its first step, including downstream dependent jobs. Once the Windows
app artifact has been saved, a Windows packaging failure can be retried without
recompilation. Assembly failures reuse the saved Android and Windows packages;
Release failures reuse the successful main CI. Splitting Windows adds one app
upload/download on successful runs in exchange for this recovery point.
Every CI artifact upload uses the local `upload-artifact` composite, with at most
three action attempts and 5/15-second delays. Attempts replace incomplete
artifacts with the same name; each name belongs to one producing job. Exhausted
retries fail the job. If the first Windows app checkpoint cannot be uploaded,
the build job must still be rerun; it has no saved app to restore.
Release attachment uploads retry temporary network errors, HTTP 408/429 and
500/502/503/504 up to three POST attempts per file, also with 5/15-second delays.
The specific FRP HTML "Not Found" page observed during tunnel reconnection is
also treated as temporary; ordinary Gitea API or HTML 404 responses still fail.
Before retrying a POST, the uploader checks whether Gitea already saved the named
attachment, including after the final response is lost. This avoids duplicate
uploads after a timeout. Authorization, invalid-input and other permanent errors
fail immediately. No draft creation or publication PATCH is automatically retried.
Attachment-list reads have their own bounded retries. Final byte verification
remains mandatory even when an existing filename is reused.
The tag/manual Release workflow reuses a successful main CI for the exact tagged
commit; it performs no Flutter builds, dependency resolution or Windows packaging.
A prepare job binds the draft and both platform upload jobs to one CI run. Android
and Windows independently fetch and upload their existing packages in parallel.
Publication requires the small cutdex-release-metadata artifact; it never
downloads the combined binary artifact. Missing or expired metadata/platform
artifacts fail preparation, with no old-format fallback. Every remote file is read and verified once, immediately
before publication, with two verification workers and 1 MiB chunks. Platform
upload steps check presence without repeating binary readbacks. Each upload
batch also uses at most two workers; while both platform jobs run, Android can
have one upload in flight alongside two Windows uploads.
Retries retain the original CI-run binding. Ordinary CI never creates
drafts. Wait for main CI success before tagging or retry Release after it finishes;
platform Release uploads overlap each other, not the original main builds.
-26
View File
@@ -1,26 +0,0 @@
# Gitea Windows and Android builds
The Windows x64 host runner needs Flutter 3.47.5, Python, Node, Visual Studio C++,
JDK 21 and Android SDK 36. The native cutdex_windows Release and cutdex_android
Maven packages must be published before building this app. The SDK Git dependency
is pinned to Gitea; the runner account needs SSH access to that private repository.
Set CUTDEX_GITEA_TOKEN in repository Actions Secrets with repository read and
package read access. It authenticates private Gitea native package downloads.
The Android APK includes ARM64 and x86_64, uses the production flavor and currently
uses the project's debug signing configuration. Configure formal signing before
shipping a production signed Android release. The Windows ZIP includes the whole
Flutter Release directory and passes the PE dependency audit. Processing workers
and optional models are separate; these four repositories contain no worker bundle.
PR/main CI analyzes and tests the app, builds both platforms, and uploads
cutdex-release-packages including SHA256SUMS and a release manifest. Protect main
with `Gitea CI / Gitea CI passed (pull_request)`.
After main CI succeeds, create v<pubspec version> at that exact commit. The Release
workflow downloads the existing CI artifact, requires both APK and Windows ZIP,
checks their digests, uploads to a draft Release, verifies remote bytes, then
publishes it. It refuses to overwrite a published Release. A manual dispatch with
the existing tag can retry an interrupted draft publication. The built-in GITEA_TOKEN
handles release writes and Actions artifact reads; no separate release-write PAT
is required. Do not commit credentials or keystores.
+69
View File
@@ -0,0 +1,69 @@
name: Upload CI artifact with bounded retries
description: Save an artifact with at most three attempts, replacing incomplete uploads of the same name.
inputs:
name:
description: Artifact name, unique to this job in the workflow run
required: true
path:
description: Files and directories to upload
required: true
compression-level:
description: ZIP compression level
default: '0'
retention-days:
description: Artifact retention in days
default: '30'
runs:
using: composite
steps:
- name: Upload artifact (attempt 1 of 3)
id: first
continue-on-error: true
uses: https://github.com/actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
env:
ACTIONS_RESULTS_URL: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
with:
name: ${{ inputs.name }}
path: ${{ inputs.path }}
compression-level: ${{ inputs.compression-level }}
retention-days: ${{ inputs.retention-days }}
if-no-files-found: error
include-hidden-files: true
overwrite: true
- name: Wait before second upload attempt
if: ${{ !cancelled() && steps.first.outcome == 'failure' }}
shell: pwsh
run: Start-Sleep -Seconds 5
- name: Upload artifact (attempt 2 of 3)
id: second
if: ${{ !cancelled() && steps.first.outcome == 'failure' }}
continue-on-error: true
uses: https://github.com/actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
env:
ACTIONS_RESULTS_URL: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
with:
name: ${{ inputs.name }}
path: ${{ inputs.path }}
compression-level: ${{ inputs.compression-level }}
retention-days: ${{ inputs.retention-days }}
if-no-files-found: error
include-hidden-files: true
overwrite: true
- name: Wait before final upload attempt
if: ${{ !cancelled() && steps.first.outcome == 'failure' && steps.second.outcome == 'failure' }}
shell: pwsh
run: Start-Sleep -Seconds 15
- name: Upload artifact (attempt 3 of 3)
id: third
if: ${{ !cancelled() && steps.first.outcome == 'failure' && steps.second.outcome == 'failure' }}
uses: https://github.com/actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
env:
ACTIONS_RESULTS_URL: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
with:
name: ${{ inputs.name }}
path: ${{ inputs.path }}
compression-level: ${{ inputs.compression-level }}
retention-days: ${{ inputs.retention-days }}
if-no-files-found: error
include-hidden-files: true
overwrite: true
+179 -22
View File
@@ -13,57 +13,213 @@ concurrency:
cancel-in-progress: true cancel-in-progress: true
env: env:
PYTHONUTF8: '1' PYTHONUTF8: '1'
CUTDEX_GITEA_INTERNAL_URL: http://127.0.0.1:3000
GIT_CONFIG_COUNT: '2' GIT_CONFIG_COUNT: '2'
GIT_CONFIG_KEY_0: core.autocrlf GIT_CONFIG_KEY_0: core.autocrlf
GIT_CONFIG_VALUE_0: 'false' GIT_CONFIG_VALUE_0: 'false'
GIT_CONFIG_KEY_1: core.eol GIT_CONFIG_KEY_1: core.eol
GIT_CONFIG_VALUE_1: lf GIT_CONFIG_VALUE_1: lf
jobs: jobs:
build: quality:
name: Windows x64 and Android name: Check code and tests
runs-on: cutdex-windows-x64 runs-on: cutdex-windows-x64
env: env:
GITEA_ACTOR: lingjhf GITEA_ACTOR: lingjhf
CUTDEX_GITEA_TOKEN: ${{ secrets.CUTDEX_GITEA_TOKEN }} CUTDEX_GITEA_TOKEN: ${{ secrets.CUTDEX_GITEA_TOKEN }}
steps: steps:
- uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 - name: Check out source
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with: with:
persist-credentials: false persist-credentials: false
- name: Verify toolchains github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
- name: Configure persistent build caches
run: ./tool/gitea/prepare-build-cache.ps1
- name: Verify Flutter version and configure Java
run: | run: |
$version = flutter --version --machine | ConvertFrom-Json $version = flutter --version --machine | ConvertFrom-Json
if ($version.frameworkVersion -ne '3.47.5') { throw 'Flutter 3.47.5 required.' } if ($version.frameworkVersion -ne '3.47.5') { throw 'Flutter 3.47.5 required.' }
flutter config --jdk-dir=$env:JAVA_HOME flutter config --jdk-dir=$env:JAVA_HOME
if ($LASTEXITCODE -ne 0) { throw 'Flutter JDK setup failed.' } if ($LASTEXITCODE -ne 0) { throw 'Flutter JDK setup failed.' }
- run: flutter pub get --enforce-lockfile - name: Resolve locked Flutter dependencies
- run: dart analyze --fatal-infos run: flutter pub get --enforce-lockfile
- run: flutter test --reporter expanded test packages/cutdex_ui/test packages/cutdex_native/test - name: Analyze Dart code
- name: Bound Android build memory on the shared runner run: dart analyze --fatal-infos
- name: Run Flutter tests
run: flutter test --reporter expanded test packages/cutdex_ui/test packages/cutdex_native/test
- name: Test update and release tools
run: |
python -m unittest discover -s tool/gitea -p 'test_*.py'
if ($LASTEXITCODE -ne 0) { throw 'Release tooling tests failed.' }
python -m unittest discover -s tool/windows -p '*_unit.py'
if ($LASTEXITCODE -ne 0) { throw 'Update tooling tests failed.' }
android:
name: Build Android APK
needs: quality
runs-on: cutdex-windows-x64
env:
GITEA_ACTOR: lingjhf
CUTDEX_GITEA_TOKEN: ${{ secrets.CUTDEX_GITEA_TOKEN }}
steps:
- name: Check out source
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with:
persist-credentials: false
github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
- name: Configure persistent build caches
run: ./tool/gitea/prepare-build-cache.ps1
- name: Verify Flutter version and configure Java
run: |
$version = flutter --version --machine | ConvertFrom-Json
if ($version.frameworkVersion -ne '3.47.5') { throw 'Flutter 3.47.5 required.' }
flutter config --jdk-dir=$env:JAVA_HOME
if ($LASTEXITCODE -ne 0) { throw 'Flutter JDK setup failed.' }
- name: Resolve locked Flutter dependencies
run: flutter pub get --enforce-lockfile
- name: Configure Gradle memory and build cache
run: | run: |
$file = 'android/gradle.properties' $file = 'android/gradle.properties'
$properties = [IO.File]::ReadAllText($file).Replace('-Xmx8G', '-Xmx3G').Replace('MaxMetaspaceSize=4G', 'MaxMetaspaceSize=768m') $properties = [IO.File]::ReadAllText($file).Replace('-Xmx8G', '-Xmx3G').Replace('MaxMetaspaceSize=4G', 'MaxMetaspaceSize=768m')
[IO.File]::WriteAllText($file, $properties + "`norg.gradle.workers.max=4`n") [IO.File]::WriteAllText($file, $properties + "`norg.gradle.workers.max=4`norg.gradle.caching=true`n")
- run: flutter build apk --release --flavor production --target-platform android-arm64,android-x64 - name: Build production Android APK
- name: Build Windows from the pinned Gitea native release run: flutter build apk --release --flavor production --target-platform android-arm64,android-x64
- name: Upload Android CI artifact
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
runs-on: cutdex-windows-x64
env:
GITEA_ACTOR: lingjhf
CUTDEX_GITEA_TOKEN: ${{ secrets.CUTDEX_GITEA_TOKEN }}
steps:
- name: Check out source
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with:
persist-credentials: false
github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
- name: Configure persistent build caches
run: ./tool/gitea/prepare-build-cache.ps1
- name: Verify Flutter version
run: |
$version = flutter --version --machine | ConvertFrom-Json
if ($version.frameworkVersion -ne '3.47.5') { throw 'Flutter 3.47.5 required.' }
- name: Resolve locked Flutter dependencies
run: flutter pub get --enforce-lockfile
- name: Build production Windows app
run: | run: |
Remove-Item Env:CUTDEX_WINDOWS_PATH, Env:CUTDEX_WINDOWS_PACKAGE_PATH -ErrorAction SilentlyContinue Remove-Item Env:CUTDEX_WINDOWS_PATH, Env:CUTDEX_WINDOWS_PACKAGE_PATH -ErrorAction SilentlyContinue
flutter build windows --release --flavor production flutter build windows --release --flavor production
if ($LASTEXITCODE -ne 0) { throw 'Windows build failed.' } if ($LASTEXITCODE -ne 0) { throw 'Windows build failed.' }
- name: Prepare isolated packaging tools - name: Verify native SDK matches pinned packaging tools
run: | run: |
python -m venv .build/package-tools python tool/windows/windows_updates.py verify-sdk
if ($LASTEXITCODE -ne 0) { throw 'Packaging environment setup failed.' } if ($LASTEXITCODE -ne 0) { throw 'Windows native SDK version validation failed.' }
& ./.build/package-tools/Scripts/python.exe -m pip install pefile==2024.8.26 - name: Save Windows app for independent packaging retries
if ($LASTEXITCODE -ne 0) { throw 'Packaging dependency installation failed.' } uses: ./.gitea/actions/upload-artifact
- name: Package application 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: windows-build
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: Configure user .NET installation
run: | run: |
& ./.build/package-tools/Scripts/python.exe tool/gitea/package-app.py $directory = Join-Path $env:LOCALAPPDATA 'Cutdex/ci-tools/dotnet'
- name: Upload Android and Windows packages [IO.Directory]::CreateDirectory($directory) | Out-Null
uses: https://github.com/actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 "DOTNET_INSTALL_DIR=$directory" | Out-File -LiteralPath $env:GITHUB_ENV -Encoding utf8 -Append
"DOTNET_ROOT=$directory" | Out-File -LiteralPath $env:GITHUB_ENV -Encoding utf8 -Append
- name: Set up .NET SDK
uses: https://github.com/actions/setup-dotnet@26b0ec14cb23fa6904739307f278c14f94c95bf1
with:
dotnet-version: '10.0.x'
- name: Prepare pinned packaging tools
run: ./tool/gitea/prepare-package-tools.ps1
- name: Audit and package Windows release
run: |
& $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: [android, windows]
runs-on: cutdex-windows-x64
env:
GITEA_ACTOR: lingjhf
CUTDEX_GITEA_TOKEN: ${{ secrets.CUTDEX_GITEA_TOKEN }}
steps:
- name: Check out source
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with:
persist-credentials: false
github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
- name: Download Android CI artifact
uses: https://github.com/actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093
env:
ACTIONS_RESULTS_URL: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
with:
name: cutdex-android-build
path: build/app/outputs/flutter-apk/
- name: Download Windows CI artifact
uses: https://github.com/actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093
env:
ACTIONS_RESULTS_URL: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
with:
name: cutdex-windows-build
path: .build/windows-packages/
- name: Validate packages and generate metadata
run: |
python tool/gitea/package-app.py --platform assemble --windows-packages .build/windows-packages
if ($LASTEXITCODE -ne 0) { throw 'Application artifact validation failed.' }
- name: Upload combined CI artifact
uses: ./.gitea/actions/upload-artifact
with: with:
name: cutdex-release-packages name: cutdex-release-packages
path: dist/* path: dist/*
if-no-files-found: error compression-level: 0
retention-days: 30
- name: Upload release verification metadata
uses: ./.gitea/actions/upload-artifact
with:
name: cutdex-release-metadata
path: .build/release-metadata/*
compression-level: 0
retention-days: 30 retention-days: 30
checks: checks:
name: Gitea CI passed name: Gitea CI passed
@@ -71,7 +227,8 @@ jobs:
needs: build needs: build
runs-on: cutdex-windows-x64 runs-on: cutdex-windows-x64
steps: steps:
- env: - name: Verify CI result
env:
RESULT: ${{ needs.build.result }} RESULT: ${{ needs.build.result }}
run: | run: |
if ($env:RESULT -ne 'success') { throw "App build: $env:RESULT" } if ($env:RESULT -ne 'success') { throw "App build: $env:RESULT" }
+110 -10
View File
@@ -13,21 +13,121 @@ permissions:
concurrency: concurrency:
group: cutdex-release group: cutdex-release
cancel-in-progress: false cancel-in-progress: false
defaults:
run:
shell: pwsh
env:
PYTHONUTF8: '1'
CUTDEX_GITEA_INTERNAL_URL: http://127.0.0.1:3000
GIT_CONFIG_COUNT: '2'
GIT_CONFIG_KEY_0: core.autocrlf
GIT_CONFIG_VALUE_0: 'false'
GIT_CONFIG_KEY_1: core.eol
GIT_CONFIG_VALUE_1: lf
RELEASE_TAG: ${{ gitea.event.inputs.tag || gitea.ref_name }}
GITEA_REPOSITORY: ${{ gitea.repository }}
jobs: jobs:
release: prepare:
name: Prepare draft Release
runs-on: cutdex-windows-x64 runs-on: cutdex-windows-x64
outputs:
sha: ${{ steps.draft.outputs.sha }}
release-id: ${{ steps.draft.outputs.release-id }}
ci-run-id: ${{ steps.draft.outputs.ci-run-id }}
artifact-id: ${{ steps.draft.outputs.artifact-id }}
android-artifact-id: ${{ steps.draft.outputs.android-artifact-id }}
windows-artifact-id: ${{ steps.draft.outputs.windows-artifact-id }}
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
steps: steps:
- uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 - name: Check out release tag
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with: with:
ref: ${{ gitea.event.inputs.tag || gitea.ref_name }} ref: ${{ gitea.event.inputs.tag || gitea.ref_name }}
persist-credentials: false persist-credentials: false
- name: Publish validated Android and Windows packages github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
shell: pwsh - name: Select successful CI and prepare draft
env: id: draft
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
GITEA_REPOSITORY: ${{ gitea.repository }}
RELEASE_TAG: ${{ gitea.event.inputs.tag || gitea.ref_name }}
run: | run: |
$env:GITEA_SHA = git rev-parse HEAD $env:GITEA_SHA = git rev-parse HEAD
python tool/gitea/promote-release.py if ($LASTEXITCODE -ne 0) { throw 'Release source resolution failed.' }
if ($LASTEXITCODE -ne 0) { throw 'Release promotion failed.' } python tool/gitea/stage-release.py prepare-ci
if ($LASTEXITCODE -ne 0) { throw 'CI selection or draft preparation failed.' }
android:
name: Upload Android to draft Release
needs: prepare
runs-on: cutdex-windows-x64
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
GITEA_SHA: ${{ needs.prepare.outputs.sha }}
RELEASE_ID: ${{ needs.prepare.outputs.release-id }}
CI_RUN_ID: ${{ needs.prepare.outputs.ci-run-id }}
CI_ARTIFACT_ID: ${{ needs.prepare.outputs.android-artifact-id }}
steps:
- name: Check out release commit
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with:
ref: ${{ needs.prepare.outputs.sha }}
persist-credentials: false
github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
- name: Download Android CI artifact
run: |
python tool/gitea/stage-release.py fetch-android --path .build/android
if ($LASTEXITCODE -ne 0) { throw 'android CI artifact download failed.' }
- name: Upload Android packages to draft
run: |
python tool/gitea/stage-release.py android --path .build/android
if ($LASTEXITCODE -ne 0) { throw 'android draft upload failed.' }
windows:
name: Upload Windows to draft Release
needs: prepare
runs-on: cutdex-windows-x64
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
GITEA_SHA: ${{ needs.prepare.outputs.sha }}
RELEASE_ID: ${{ needs.prepare.outputs.release-id }}
CI_RUN_ID: ${{ needs.prepare.outputs.ci-run-id }}
CI_ARTIFACT_ID: ${{ needs.prepare.outputs.windows-artifact-id }}
steps:
- name: Check out release commit
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with:
ref: ${{ needs.prepare.outputs.sha }}
persist-credentials: false
github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
- name: Download Windows CI artifact
run: |
python tool/gitea/stage-release.py fetch-windows --path .build/windows
if ($LASTEXITCODE -ne 0) { throw 'windows CI artifact download failed.' }
- name: Upload Windows packages to draft
run: |
python tool/gitea/stage-release.py windows --path .build/windows
if ($LASTEXITCODE -ne 0) { throw 'windows draft upload failed.' }
publish:
name: Verify and publish Release
needs: [prepare, android, windows]
runs-on: cutdex-windows-x64
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
GITEA_SHA: ${{ needs.prepare.outputs.sha }}
RELEASE_ID: ${{ needs.prepare.outputs.release-id }}
CI_RUN_ID: ${{ needs.prepare.outputs.ci-run-id }}
CI_ARTIFACT_ID: ${{ needs.prepare.outputs.artifact-id }}
steps:
- name: Check out release commit
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with:
ref: ${{ needs.prepare.outputs.sha }}
persist-credentials: false
github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
- name: Download release verification metadata
run: |
python tool/gitea/stage-release.py fetch-release --path dist
if ($LASTEXITCODE -ne 0) { throw 'CI verification metadata validation failed.' }
- name: Verify attachments and publish Release
run: |
python tool/gitea/stage-release.py publish --path dist
if ($LASTEXITCODE -ne 0) { throw 'Release publication failed.' }
+81
View File
@@ -0,0 +1,81 @@
# 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
flutter build windows --release --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` 环境变量指定。
```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 独立分发策略沿用现有流水线。
@@ -0,0 +1,53 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
enum DesktopContent { workspace, library, settings }
typedef DesktopContentSelection = ({
DesktopContent surface,
int settingsTab,
int settingsRequest,
(String, String)? workspace,
bool settingsVisited,
bool resourcesSelected,
});
final desktopContentProvider =
NotifierProvider<DesktopContentController, DesktopContentSelection>(
DesktopContentController.new,
);
/// Navigation changes visibility without disposing any visited content.
class DesktopContentController extends Notifier<DesktopContentSelection> {
@override
DesktopContentSelection build() => (
surface: DesktopContent.workspace,
settingsTab: 0,
settingsRequest: 0,
workspace: null,
settingsVisited: false,
resourcesSelected: 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,
);
}
void showSettings({int? tab, (String, String)? workspace}) {
state = (
surface: DesktopContent.settings,
settingsTab: tab ?? state.settingsTab,
settingsRequest: state.settingsRequest + (tab == null ? 0 : 1),
workspace: workspace ?? state.workspace,
settingsVisited: true,
resourcesSelected: state.resourcesSelected,
);
}
}
@@ -3,14 +3,19 @@ import 'package:flutter/foundation.dart';
/// Desktop split preferences outlive the desktop shell when a window narrows. /// Desktop split preferences outlive the desktop shell when a window narrows.
class DesktopWorkspaceController extends ChangeNotifier { class DesktopWorkspaceController extends ChangeNotifier {
double? _agentWidth; double? _agentWidth;
bool _editorCollapsedByAgent = false; bool _agentFullscreen = false;
double? get agentWidth => _agentWidth; double? get agentWidth => _agentWidth;
bool get editorCollapsedByAgent => _editorCollapsedByAgent; bool get agentFullscreen => _agentFullscreen;
void setSplit(double? width, {required bool editorCollapsed}) { void setAgentWidth(double width) {
_agentWidth = width; _agentWidth = width;
_editorCollapsedByAgent = editorCollapsed; notifyListeners();
}
void setAgentFullscreen(bool value) {
if (_agentFullscreen == value) return;
_agentFullscreen = value;
notifyListeners(); notifyListeners();
} }
} }
@@ -23,8 +23,7 @@ final class DesktopWorkspaceGeometry {
required this.editorHidden, required this.editorHidden,
}); });
static const editorCollapseWidth = 480.0; static const editorMinimumWidth = 480.0;
static const editorCollapseDragBuffer = editorCollapseWidth / 3;
static const editorRestoreWidth = 560.0; static const editorRestoreWidth = 560.0;
final double sidebarWidth; final double sidebarWidth;
@@ -42,7 +41,7 @@ final class DesktopWorkspaceGeometry {
required bool sidebarCollapsed, required bool sidebarCollapsed,
double? sidebarWidth, double? sidebarWidth,
double? agentWidth, double? agentWidth,
bool editorCollapsedByAgent = false, bool agentFullscreen = false,
}) { }) {
final navigationWidth = final navigationWidth =
(sidebarWidth ?? WorkspaceLayoutMetrics.sidebarDefaultWidth) (sidebarWidth ?? WorkspaceLayoutMetrics.sidebarDefaultWidth)
@@ -57,19 +56,17 @@ final class DesktopWorkspaceGeometry {
.clamp(220.0, math.max(220.0, width - navigationSpace - 1)) .clamp(220.0, math.max(220.0, width - navigationSpace - 1))
.toDouble() .toDouble()
: 0.0; : 0.0;
final remaining = width - navigationSpace - requestedAgentWidth - 1;
final hidden = final hidden =
mode == WorkspaceMode.agent && mode == WorkspaceMode.agent &&
(width - navigationSpace - 1 < 220 + editorCollapseWidth || (width - navigationSpace - 1 < 220 + editorMinimumWidth ||
(editorCollapsedByAgent && remaining < editorRestoreWidth) || agentFullscreen);
remaining <= editorCollapseWidth - editorCollapseDragBuffer);
return DesktopWorkspaceGeometry( return DesktopWorkspaceGeometry(
sidebarWidth: navigationWidth, sidebarWidth: navigationWidth,
agentWidth: hidden agentWidth: hidden
? width - navigationSpace ? width - navigationSpace
: mode == WorkspaceMode.agent : mode == WorkspaceMode.agent
? requestedAgentWidth ? requestedAgentWidth
.clamp(220.0, width - navigationSpace - editorCollapseWidth - 1) .clamp(220.0, width - navigationSpace - editorMinimumWidth - 1)
.toDouble() .toDouble()
: 0, : 0,
editorHidden: hidden, editorHidden: hidden,
+3
View File
@@ -10,6 +10,7 @@ import 'router/app_router.dart';
import '../integrations/app_updates.dart'; import '../integrations/app_updates.dart';
import '../integrations/editor_tools.dart'; import '../integrations/editor_tools.dart';
import '../features/settings/appearance_settings.dart'; import '../features/settings/appearance_settings.dart';
import '../shared/widgets/error_notification_host.dart';
class CutdexApp extends ConsumerWidget { class CutdexApp extends ConsumerWidget {
const CutdexApp({super.key}); const CutdexApp({super.key});
@@ -22,6 +23,8 @@ class CutdexApp extends ConsumerWidget {
ref.watch(appearanceSettingsProvider).asData?.value ?? ref.watch(appearanceSettingsProvider).asData?.value ??
AppAppearance.system; AppAppearance.system;
return MaterialApp.router( return MaterialApp.router(
builder: (context, child) =>
ErrorNotificationHost(child: child ?? const SizedBox.shrink()),
title: 'Cutdex', title: 'Cutdex',
locale: ref.watch(languageSettingsProvider).asData?.value.locale, locale: ref.watch(languageSettingsProvider).asData?.value.locale,
localizationsDelegates: AppLocalizations.localizationsDelegates, localizationsDelegates: AppLocalizations.localizationsDelegates,
+18 -1
View File
@@ -4,6 +4,7 @@ import 'package:go_router/go_router.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../../features/projects/projects_page.dart'; import '../../features/projects/projects_page.dart';
import '../../features/settings/settings_page.dart';
part 'app_router.g.dart'; part 'app_router.g.dart';
@@ -12,7 +13,23 @@ part 'app_router.g.dart';
GoRouter appRouter(Ref ref) { GoRouter appRouter(Ref ref) {
final router = GoRouter( final router = GoRouter(
routes: [ routes: [
GoRoute(path: '/', builder: (context, state) => const EditingPage()), GoRoute(
path: '/',
builder: (context, state) => const EditingPage(),
routes: [
GoRoute(
path: 'settings',
builder: (context, state) => SettingsPage(
initialTab:
(int.tryParse(state.uri.queryParameters['tab'] ?? '') ?? 0)
.clamp(0, 2),
workspace: state.extra is (String, String)
? state.extra as (String, String)
: null,
),
),
],
),
], ],
errorBuilder: (context, state) => Scaffold( errorBuilder: (context, state) => Scaffold(
body: Center( body: Center(
+1 -1
View File
@@ -48,4 +48,4 @@ final class AppRouterProvider
} }
} }
String _$appRouterHash() => r'ebb3f9239a43568767def98552081806bd614bb4'; String _$appRouterHash() => r'00e948f9d82c1f07ecdfc62b3c1ec833cb03edfe';
+163
View File
@@ -0,0 +1,163 @@
import 'package:cutdex_native/cutdex_native.dart';
import 'package:flutter/material.dart';
import '../../integrations/platform/editor_window_chrome.dart';
import '../../l10n/l10n.dart';
import '../../shared/layout/workspace_layout_metrics.dart';
import '../../workspace/workspace_mode.dart';
/// Keeps window chrome outside the shared workspace surface.
class DesktopWindowFrame extends StatelessWidget {
const DesktopWindowFrame({
super.key,
required this.integratedTitlebar,
required this.headerControls,
required this.librarySelected,
this.settingsSelected = false,
required this.onModeChanged,
required this.onLibraryPressed,
required this.onSettingsPressed,
required this.child,
});
static const railWidth = 44.0;
static const railButtonSize = 32.0;
static const railIconSize = 22.0;
static const headerHeight = 40.0;
static const contentInset = WorkspaceLayoutMetrics.desktopSpacing;
final bool integratedTitlebar;
final Widget headerControls;
final bool librarySelected;
final bool settingsSelected;
final ValueChanged<WorkspaceMode> onModeChanged;
final VoidCallback? onLibraryPressed;
final VoidCallback onSettingsPressed;
final Widget child;
@override
Widget build(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: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
if (integratedTitlebar)
SizedBox(
key: const Key('native-window-controls-space'),
width: EditorWindowChrome.leadingWidth,
height: headerHeight,
),
headerControls,
],
),
),
),
),
Expanded(
child: Row(
children: [
SizedBox(
key: const Key('desktop-navigation-rail'),
width: railWidth,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 10),
child: Column(
children: [
for (final library in [false, true])
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: IconButton.filledTonal(
key: ValueKey(
library
? 'desktop-rail-library'
: 'desktop-rail-cut',
),
tooltip: library
? context.l10n.navigationLibrary
: context.l10n.navigationChat,
isSelected:
!settingsSelected && library == librarySelected,
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 &&
library == librarySelected
? null
: Colors.transparent,
),
onPressed: library
? onLibraryPressed
: () => onModeChanged(WorkspaceMode.cut),
icon: Icon(
library
? Icons.video_library_outlined
: Icons.chat_bubble_outline,
),
),
),
const Spacer(),
IconButton(
key: const Key('project-settings-button'),
tooltip: context.l10n.settings,
isSelected: settingsSelected,
onPressed: onSettingsPressed,
style: IconButton.styleFrom(
fixedSize: const Size.square(railButtonSize),
minimumSize: const Size.square(railButtonSize),
maximumSize: const Size.square(railButtonSize),
padding: EdgeInsets.zero,
iconSize: railIconSize,
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
icon: const Icon(Icons.settings_outlined),
),
],
),
),
),
Expanded(
child: Padding(
padding: const EdgeInsets.only(
right: contentInset,
bottom: contentInset,
),
child: SizedBox(
key: const Key('desktop-content-container'),
child: WindowHeaderPane(
offset: const Offset(railWidth, headerHeight),
child: LayoutBuilder(
builder: (context, constraints) =>
constraints.maxWidth < 200
? SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: SizedBox(
width: 200,
height: constraints.maxHeight,
child: child,
),
)
: child,
),
),
),
),
),
],
),
),
],
),
);
}
+124 -151
View File
@@ -1,22 +1,18 @@
import '../adaptive/desktop_workspace_controller.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../../workspace/workspace_mode.dart'; import '../adaptive/desktop_workspace_controller.dart';
import '../../shared/layout/workspace_layout_metrics.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_native/cutdex_native.dart';
import '../adaptive/workspace_layout_policy.dart'; import '../adaptive/workspace_layout_policy.dart';
import '../../shared/layout/workspace_layout_metrics.dart';
import '../../shared/widgets/workspace_card.dart';
import '../../shared/widgets/workspace_resize_handle.dart';
import '../../workspace/workspace_mode.dart';
typedef WorkspaceSidebarBuilder = Widget Function( typedef WorkspaceSidebarBuilder = Widget Function(
DesktopWorkspaceGeometry geometry, DesktopWorkspaceGeometry geometry,
VoidCallback expandEditor, VoidCallback expandEditor,
); );
/// Arranges slots and handles splitters; it does not own editing sessions. /// Three independent desktop surfaces with resize gutters between them.
class DesktopWorkspaceShell extends StatefulWidget { class DesktopWorkspaceShell extends StatefulWidget {
const DesktopWorkspaceShell({ const DesktopWorkspaceShell({
super.key, super.key,
@@ -27,11 +23,13 @@ class DesktopWorkspaceShell extends StatefulWidget {
required this.onSidebarCollapsedChanged, required this.onSidebarCollapsedChanged,
required this.onSidebarWidthChanged, required this.onSidebarWidthChanged,
required this.sidebarBuilder, required this.sidebarBuilder,
required this.agentBuilder,
required this.editor, required this.editor,
required this.scaffoldKey, required this.scaffoldKey,
required this.navigationDrawer, required this.navigationDrawer,
}); });
static const gutterWidth = WorkspaceLayoutMetrics.desktopSpacing;
final WorkspaceMode mode; final WorkspaceMode mode;
final DesktopWorkspaceController controller; final DesktopWorkspaceController controller;
final bool sidebarCollapsed; final bool sidebarCollapsed;
@@ -39,6 +37,7 @@ class DesktopWorkspaceShell extends StatefulWidget {
final ValueChanged<bool> onSidebarCollapsedChanged; final ValueChanged<bool> onSidebarCollapsedChanged;
final ValueChanged<double> onSidebarWidthChanged; final ValueChanged<double> onSidebarWidthChanged;
final WorkspaceSidebarBuilder sidebarBuilder; final WorkspaceSidebarBuilder sidebarBuilder;
final WorkspaceSidebarBuilder agentBuilder;
final Widget editor; final Widget editor;
final GlobalKey<ScaffoldState> scaffoldKey; final GlobalKey<ScaffoldState> scaffoldKey;
final Widget navigationDrawer; final Widget navigationDrawer;
@@ -48,9 +47,6 @@ class DesktopWorkspaceShell extends StatefulWidget {
} }
class _DesktopWorkspaceShellState extends State<DesktopWorkspaceShell> { class _DesktopWorkspaceShellState extends State<DesktopWorkspaceShell> {
double? get _agentWidth => widget.controller.agentWidth;
bool get _editorCollapsedByAgent => widget.controller.editorCollapsedByAgent;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
@@ -74,65 +70,101 @@ class _DesktopWorkspaceShellState extends State<DesktopWorkspaceShell> {
super.dispose(); super.dispose();
} }
double? _sidebarDragStart; Widget _card(String name, Widget child) =>
double _sidebarDragWidth = 0; WorkspaceCard(key: Key('desktop-$name-card'), child: child);
double? _agentDragStart;
double _agentDragWidth = 0; Widget _gutter({
required String name,
required double initialWidth,
required ValueChanged<double> onResize,
double direction = 1,
VoidCallback? onEnd,
}) => SizedBox(
width: WorkspaceLayoutMetrics.desktopResizeHitExtent,
height: double.infinity,
child: WorkspaceResizeHandle(
key: Key('$name-resize'),
axis: Axis.horizontal,
initialValue: initialWidth,
direction: direction,
onResize: onResize,
onEnd: onEnd,
),
);
@override @override
Widget build(BuildContext context) => LayoutBuilder( Widget build(BuildContext context) => LayoutBuilder(
builder: (context, constraints) { builder: (context, constraints) {
const gap = DesktopWorkspaceShell.gutterWidth;
final width = constraints.maxWidth; final width = constraints.maxWidth;
final geometry = DesktopWorkspaceGeometry.resolve( final navigationGap = widget.sidebarCollapsed ? 0.0 : gap;
width: width, final resolved = DesktopWorkspaceGeometry.resolve(
mode: widget.mode, // The geometry policy accounts for a one-pixel divider; reserve gutters.
width: width - navigationGap - gap + 1,
mode: WorkspaceMode.agent,
sidebarCollapsed: widget.sidebarCollapsed, sidebarCollapsed: widget.sidebarCollapsed,
sidebarWidth: widget.sidebarWidth, sidebarWidth: widget.sidebarWidth,
agentWidth: _agentWidth, agentWidth: widget.controller.agentWidth,
editorCollapsedByAgent: _editorCollapsedByAgent, agentFullscreen: widget.controller.agentFullscreen,
); );
final navigationSpace = widget.sidebarCollapsed final navigationSpace = widget.sidebarCollapsed
? 0.0 ? 0.0
: geometry.sidebarWidth; : resolved.sidebarWidth;
void expandEditor() { final agentHidden =
final collapseNavigation = width - navigationSpace - 1 < 780; resolved.editorHidden &&
if (collapseNavigation) widget.onSidebarCollapsedChanged(true); widget.mode == WorkspaceMode.cut &&
widget.controller.setSplit( !widget.controller.agentFullscreen;
width - final geometry = DesktopWorkspaceGeometry(
(collapseNavigation ? 0 : navigationSpace) - sidebarWidth: resolved.sidebarWidth,
DesktopWorkspaceGeometry.editorRestoreWidth - agentWidth: agentHidden
1, ? 0
editorCollapsed: false, : resolved.editorHidden
? width - navigationSpace - navigationGap
: resolved.agentWidth,
editorHidden: resolved.editorHidden && !agentHidden,
); );
final available = width - navigationSpace - navigationGap;
void expandEditor() {
final collapseNavigation =
available < 220 + gap + DesktopWorkspaceGeometry.editorMinimumWidth;
if (collapseNavigation) widget.onSidebarCollapsedChanged(true);
widget.controller.setAgentFullscreen(false);
}
void resizeAgent(double requested) {
final maximum =
available - gap - DesktopWorkspaceGeometry.editorMinimumWidth;
if (maximum < 220) return;
final agentWidth = requested.clamp(220.0, maximum);
widget.controller.setAgentWidth(agentWidth);
} }
return Scaffold( return Scaffold(
key: widget.scaffoldKey, key: widget.scaffoldKey,
backgroundColor: Colors.transparent,
drawer: Drawer( drawer: Drawer(
width: 320, width: 320,
child: SafeArea(child: widget.navigationDrawer), child: SafeArea(child: widget.navigationDrawer),
), ),
body: Stack( body: Stack(
key: const Key('desktop-workspace-shell'), key: const Key('desktop-workspace-shell'),
fit: StackFit.expand,
children: [ children: [
Row( Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
if (!widget.sidebarCollapsed || if (!widget.sidebarCollapsed) ...[
widget.mode == WorkspaceMode.agent)
SizedBox( SizedBox(
width: navigationSpace + geometry.agentWidth, width: navigationSpace,
child: widget.sidebarBuilder(geometry, expandEditor), child: _card(
), 'project',
if (!widget.sidebarCollapsed && !geometry.editorHidden) widget.sidebarBuilder(geometry, expandEditor),
SizedBox(
width: 1,
height: double.infinity,
child: ColoredBox(
key: const Key('project-sidebar-separator'),
color: AppTheme.sidebarDividerColor(context),
), ),
), ),
const SizedBox(
key: Key('project-sidebar-divider'),
width: gap,
),
],
Expanded( Expanded(
child: Offstage( child: Offstage(
key: const Key('editor-auto-collapse'), key: const Key('editor-auto-collapse'),
@@ -147,125 +179,66 @@ class _DesktopWorkspaceShellState extends State<DesktopWorkspaceShell> {
maxWidth: geometry.editorHidden maxWidth: geometry.editorHidden
? DesktopWorkspaceGeometry.editorRestoreWidth ? DesktopWorkspaceGeometry.editorRestoreWidth
: null, : null,
child: WindowHeaderPane( child: SizedBox(
offset: Offset( key: const Key('desktop-editor-card'),
navigationSpace +
geometry.agentWidth +
(!widget.sidebarCollapsed &&
!geometry.editorHidden
? 1
: 0),
0,
),
child: widget.editor, child: widget.editor,
), ),
), ),
), ),
), ),
), ),
if (!agentHidden && !geometry.editorHidden)
const SizedBox(width: gap),
if (!agentHidden)
SizedBox(
key: const Key('desktop-agent-slot'),
width: geometry.agentWidth,
child: _card(
'agent',
widget.agentBuilder(geometry, expandEditor),
),
),
], ],
), ),
if (!widget.sidebarCollapsed) if (!widget.sidebarCollapsed)
Positioned( Positioned(
key: const Key('project-sidebar-divider'), left:
top: AppControlSize.panelHeader, navigationSpace - WorkspaceLayoutMetrics.desktopResizeSlop,
bottom: 0,
left: geometry.sidebarWidth - 4,
width: 8,
child: MouseRegion(
cursor: SystemMouseCursors.resizeColumn,
child: GestureDetector(
key: const Key('project-sidebar-resize'),
behavior: HitTestBehavior.opaque,
dragStartBehavior: DragStartBehavior.down,
onHorizontalDragStart: (details) {
_sidebarDragStart = details.globalPosition.dx;
_sidebarDragWidth = geometry.sidebarWidth;
},
onHorizontalDragUpdate: (details) {
final start = _sidebarDragStart;
if (start == null) return;
widget.onSidebarWidthChanged(
(_sidebarDragWidth + details.globalPosition.dx - start)
.clamp(
WorkspaceLayoutMetrics.sidebarMinimumWidth,
DesktopWorkspaceGeometry.sidebarMaximum(
width,
widget.mode,
),
)
.toDouble(),
);
},
onHorizontalDragEnd: (_) => _sidebarDragStart = null,
onHorizontalDragCancel: () => _sidebarDragStart = null,
child: const SizedBox.expand(),
),
),
),
if (widget.mode == WorkspaceMode.agent &&
width - navigationSpace - 1 >= 220)
Positioned(
top: 0, top: 0,
bottom: 0, bottom: 0,
left: child: _gutter(
navigationSpace + name: 'project-sidebar',
initialWidth: navigationSpace,
onResize: (value) => widget.onSidebarWidthChanged(
value.clamp(
WorkspaceLayoutMetrics.sidebarMinimumWidth,
DesktopWorkspaceGeometry.sidebarMaximum(
width - 2 * gap + 1,
WorkspaceMode.agent,
),
),
),
),
),
if (!agentHidden && !geometry.editorHidden)
Positioned(
left: geometry.editorHidden
? navigationSpace +
navigationGap +
(widget.sidebarCollapsed
? 0
: WorkspaceLayoutMetrics.desktopResizeSlop)
: width -
geometry.agentWidth - geometry.agentWidth -
(geometry.editorHidden ? 8 : 4), gap -
width: 8, WorkspaceLayoutMetrics.desktopResizeSlop,
child: MouseRegion( top: 0,
cursor: SystemMouseCursors.resizeColumn, bottom: 0,
child: GestureDetector( child: _gutter(
key: const Key('agent-panel-resize'), name: 'agent-panel',
behavior: HitTestBehavior.opaque, initialWidth: geometry.agentWidth,
dragStartBehavior: DragStartBehavior.down, direction: -1,
onHorizontalDragStart: (details) { onResize: resizeAgent,
_agentDragStart = details.globalPosition.dx;
_agentDragWidth = geometry.agentWidth;
},
onHorizontalDragUpdate: (details) {
final start = _agentDragStart;
if (start == null) return;
final agentWidth =
(_agentDragWidth + details.globalPosition.dx - start)
.clamp(220.0, width - navigationSpace - 1);
final remaining =
width - navigationSpace - agentWidth - 1;
widget.controller.setSplit(
agentWidth,
editorCollapsed: geometry.editorHidden
? remaining <
DesktopWorkspaceGeometry.editorRestoreWidth
: remaining <=
DesktopWorkspaceGeometry.editorCollapseWidth -
DesktopWorkspaceGeometry
.editorCollapseDragBuffer,
);
},
onHorizontalDragEnd: (_) {
_agentDragStart = null;
if (!_editorCollapsedByAgent &&
_agentWidth != null &&
width -
navigationSpace -
DesktopWorkspaceGeometry.editorCollapseWidth -
1 >=
220) {
widget.controller.setSplit(
_agentWidth!.clamp(
220.0,
width -
navigationSpace -
DesktopWorkspaceGeometry.editorCollapseWidth -
1,
),
editorCollapsed: false,
);
}
},
onHorizontalDragCancel: () => _agentDragStart = null,
child: const SizedBox.expand(),
),
), ),
), ),
], ],
+11 -7
View File
@@ -1,3 +1,5 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import '../../shared/layout/composer_layout.dart'; import '../../shared/layout/composer_layout.dart';
import '../../shared/theme/composer_style.dart'; import '../../shared/theme/composer_style.dart';
@@ -18,7 +20,7 @@ import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart'; import 'package:cutdex_ui/widgets.dart';
import '../../shared/widgets/drop_to_add_overlay.dart'; import '../../shared/widgets/drop_to_add_overlay.dart';
import '../settings/settings_dialog.dart'; import '../settings/settings_page.dart';
import 'chat_controller.dart'; import 'chat_controller.dart';
import 'chat_state.dart'; import 'chat_state.dart';
import '../../integrations/agent/conversation_repository.dart'; import '../../integrations/agent/conversation_repository.dart';
@@ -360,8 +362,10 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
if (saved) { if (saved) {
setState(() => _usingDraftModel = true); setState(() => _usingDraftModel = true);
} else { } else {
ScaffoldMessenger.of(context).showSnackBar( ErrorNotificationHost.of(context).show(
SnackBar(content: Text(context.l10n.agentSaveSettingsFailed)), ErrorNotification(
content: Text(context.l10n.agentSaveSettingsFailed),
),
); );
} }
} }
@@ -374,7 +378,7 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
return TextButton.icon( return TextButton.icon(
key: const Key('agent-configure-model'), key: const Key('agent-configure-model'),
style: compactButtonStyle, style: compactButtonStyle,
onPressed: () => showSettingsDialog(context, initialTab: 1), onPressed: () => showSettingsPage(context, initialTab: 1),
icon: const Icon(Icons.tune, size: 16), icon: const Icon(Icons.tune, size: 16),
label: Text(context.l10n.agentConfigureModel), label: Text(context.l10n.agentConfigureModel),
); );
@@ -398,11 +402,11 @@ class _AgentChatPanelState extends ConsumerState<AgentChatPanel> {
AppMenuItem( AppMenuItem(
label: context.l10n.agentConfigureModel, label: context.l10n.agentConfigureModel,
selectOption: true, selectOption: true,
onPressed: () => showSettingsDialog(context, initialTab: 1), onPressed: () => showSettingsPage(context, initialTab: 1),
), ),
], ],
builder: (context, toggle, focus) => TextButton( builder: (context, toggle, focus) => AppToolbarDropdownButton(
key: const Key('agent-model-picker'), buttonKey: const Key('agent-model-picker'),
focusNode: focus, focusNode: focus,
onPressed: () { onPressed: () {
if (!state.busy && !_choosingModel) toggle?.call(); if (!state.busy && !_choosingModel) toggle?.call();
@@ -97,6 +97,18 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
final projects = widget.projects final projects = widget.projects
.where((project) => project.name.toLowerCase().contains(query)) .where((project) => project.name.toLowerCase().contains(query))
.toList(); .toList();
final listHeight = projects.isEmpty
? ComposerLayout.menuRowHeight +
AppComposerStyle.menuEmptyPadding.vertical
: (projects.length * ComposerLayout.menuRowHeight).clamp(
0.0,
ComposerLayout.menuListMaxHeight,
);
final contentHeight =
ComposerLayout.menuRowHeight * 2 +
(AppComposerStyle.menuSeparatorPadding.vertical + 1) * 2 +
listHeight;
final menuHeight = contentHeight + ComposerLayout.menuGutter * 2;
return Material( return Material(
key: const Key('composer-project-bar'), key: const Key('composer-project-bar'),
color: widget.backgroundColor, color: widget.backgroundColor,
@@ -109,12 +121,15 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
alignment: AlignmentDirectional.centerStart, alignment: AlignmentDirectional.centerStart,
child: MenuAnchor( child: MenuAnchor(
controller: _menu, controller: _menu,
alignmentOffset: Offset(0, -menuHeight - 4),
consumeOutsideTap: false, consumeOutsideTap: false,
onClose: () => setState(_search.clear), onClose: () => setState(_search.clear),
style: AppComposerStyle.projectMenu(context), style: AppComposerStyle.projectMenu(context)
.copyWith(alignment: AlignmentDirectional.topStart),
menuChildren: [ menuChildren: [
SizedBox( SizedBox(
width: ComposerLayout.menuContentWidth, width: ComposerLayout.menuContentWidth,
height: contentHeight,
child: Column( child: Column(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
@@ -134,10 +149,7 @@ class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
), ),
), ),
_separator(), _separator(),
ConstrainedBox( Expanded(
constraints: const BoxConstraints(
maxHeight: ComposerLayout.menuListMaxHeight,
),
child: SingleChildScrollView( child: SingleChildScrollView(
primary: false, primary: false,
child: Column( child: Column(
@@ -14,7 +14,9 @@ import 'package:cutdex_ui/widgets.dart';
import '../media/background_tasks_dialog.dart'; import '../media/background_tasks_dialog.dart';
class BackgroundTasksButton extends ConsumerWidget { class BackgroundTasksButton extends ConsumerWidget {
const BackgroundTasksButton({super.key}); const BackgroundTasksButton({super.key, this.iconSize = AppIconSize.header});
final double iconSize;
@override @override
Widget build(BuildContext context, WidgetRef ref) { Widget build(BuildContext context, WidgetRef ref) {
@@ -40,7 +42,7 @@ class BackgroundTasksButton extends ConsumerWidget {
onPressed: toggle, onPressed: toggle,
icon: Badge( icon: Badge(
isLabelVisible: hasRunningTasks(), isLabelVisible: hasRunningTasks(),
child: const Icon(Icons.task_alt_outlined, size: AppIconSize.header), child: Icon(Icons.task_alt_outlined, size: iconSize),
), ),
); );
return AppPopover( return AppPopover(
+69 -55
View File
@@ -22,6 +22,7 @@ import '../properties/properties_editor_page.dart';
import '../properties/properties_panel.dart'; import '../properties/properties_panel.dart';
import '../timeline/timeline_panel.dart'; import '../timeline/timeline_panel.dart';
import 'editor_presentation_controller.dart'; import 'editor_presentation_controller.dart';
import 'editor_panel_defaults.dart';
import 'layouts/bounded_editor_layout.dart'; import 'layouts/bounded_editor_layout.dart';
import 'layouts/expanded_editor_layout.dart'; import 'layouts/expanded_editor_layout.dart';
@@ -34,10 +35,12 @@ class EditorWorkspace extends ConsumerStatefulWidget {
required this.projectName, required this.projectName,
required this.integratedTitlebar, required this.integratedTitlebar,
required this.headerLeading, required this.headerLeading,
this.projectLoading = false,
this.showProjectName = true, this.showProjectName = true,
this.experience = DeviceExperience.desktop, this.experience = DeviceExperience.desktop,
}); });
final bool projectLoading;
final String projectId; final String projectId;
final String timelineId; final String timelineId;
final String projectName; final String projectName;
@@ -79,73 +82,55 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
child: EditorPreviewPanel( child: EditorPreviewPanel(
projectId: widget.projectId, projectId: widget.projectId,
timelineId: widget.timelineId, timelineId: widget.timelineId,
pending: widget.projectLoading,
), ),
); );
final timeline = EditorTimelinePanel( final timeline = EditorTimelinePanel(
projectId: widget.projectId, projectId: widget.projectId,
timelineId: widget.timelineId, timelineId: widget.timelineId,
pending: widget.projectLoading,
); );
final properties = EditorPropertiesPanel( final properties = widget.projectLoading
? const EditorEmptyPanel()
: EditorPropertiesPanel(
projectId: widget.projectId, projectId: widget.projectId,
timelineId: widget.timelineId, timelineId: widget.timelineId,
); );
final media = MediaPanel(projectId: widget.projectId); final media = widget.projectLoading
? const EditorEmptyPanel()
: MediaPanel(projectId: widget.projectId);
return ListenableBuilder( return ListenableBuilder(
listenable: ref.watch(editorPresentationProvider(widget.projectId)), listenable: ref.watch(editorPresentationProvider(widget.projectId)),
builder: (context, _) => LayoutBuilder( builder: (context, _) => LayoutBuilder(
builder: (context, constraints) { builder: (context, constraints) {
final desktop = widget.experience == DeviceExperience.desktop; final desktop = widget.experience == DeviceExperience.desktop;
final sideWidth = final sideWidth = (_propertiesOpen
(_presentation.mediaOpen
? WorkspaceLayoutMetrics.mediaPanelWidth + 1
: 0) +
(_propertiesOpen
? WorkspaceLayoutMetrics.propertiesPanelWidth + 1 ? WorkspaceLayoutMetrics.propertiesPanelWidth + 1
: 0); : 0);
final dockPanels = final dockPanels =
desktop && desktop &&
constraints.maxWidth >= constraints.maxWidth >=
WorkspaceLayoutMetrics.previewMinimumWidth + sideWidth; WorkspaceLayoutMetrics.previewMinimumWidth + sideWidth;
final desktopTool = sideWidth == 0 final desktopTool = _propertiesOpen ? EditorTool.properties : null;
? null final headerHeight = desktop ? AppControlSize.panelToolbar : 48.0;
: _presentation.desktopTool(propertiesOpen: _propertiesOpen); final mediaOpen = _presentation.activeTool == EditorTool.media;
final headerHeight = desktop ? AppControlSize.panelHeader : 48.0;
final mediaOpen = desktop
? dockPanels
? _presentation.mediaOpen
: desktopTool == EditorTool.media
: _presentation.activeTool == EditorTool.media;
final propertiesOpen = desktop final propertiesOpen = desktop
? dockPanels ? dockPanels
? _propertiesOpen ? _propertiesOpen
: desktopTool == EditorTool.properties : desktopTool == EditorTool.properties
: _presentation.activeTool == EditorTool.properties; : _presentation.activeTool == EditorTool.properties;
Widget dockedEditing({required bool showTools}) => final header = Material(
ExpandedEditorLayout(
preview: preview,
properties: properties,
media: media,
showMedia: showTools && _presentation.mediaOpen,
showProperties: showTools && _propertiesOpen,
timelineHeight: _timelineHeight,
onTimelineHeightChanged: (height) {
if (viewSettings.hasValue) {
_viewController.setTimelineHeight(height);
}
},
onTimelineHeightChangeEnd: _saveViewSettings,
timeline: timeline,
);
return Stack(
fit: StackFit.expand,
children: [
Column(
children: [
Material(
color: Theme.of(context).colorScheme.surface, color: Theme.of(context).colorScheme.surface,
child: SizedBox( child: SizedBox(
key: const Key('editor-content-header'), key: const Key('editor-content-header'),
height: headerHeight, height: headerHeight,
child: Padding(
padding: desktop
? const EdgeInsets.symmetric(
horizontal: AppSidebarMetrics.outerPadding,
vertical: AppSpacing.gap,
)
: EdgeInsets.zero,
child: WindowHeaderPadding( child: WindowHeaderPadding(
child: Row( child: Row(
children: [ children: [
@@ -158,9 +143,7 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
fit: FlexFit.loose, fit: FlexFit.loose,
child: Text( child: Text(
widget.projectName, widget.projectName,
key: const Key( key: const Key('workspace-project-title'),
'workspace-project-title',
),
maxLines: 1, maxLines: 1,
overflow: TextOverflow.ellipsis, overflow: TextOverflow.ellipsis,
style: Theme.of(context) style: Theme.of(context)
@@ -170,7 +153,9 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
), ),
Flexible( Flexible(
fit: FlexFit.loose, fit: FlexFit.loose,
child: _TimelineSaveStatus( child: widget.projectLoading
? const SizedBox.shrink()
: _TimelineSaveStatus(
projectId: widget.projectId, projectId: widget.projectId,
timelineId: widget.timelineId, timelineId: widget.timelineId,
), ),
@@ -179,6 +164,7 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
) )
: const SizedBox.shrink(), : const SizedBox.shrink(),
), ),
if (!desktop)
HeaderControlRegion( HeaderControlRegion(
child: SizedBox.square( child: SizedBox.square(
dimension: desktop dimension: desktop
@@ -200,21 +186,17 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
_presentation.toggleMedia(); _presentation.toggleMedia();
} }
} else { } else {
_presentation.toggleTool( _presentation.toggleTool(EditorTool.media);
EditorTool.media,
);
} }
}, },
icon: const Icon(Icons.perm_media_outlined), icon: const Icon(Icons.perm_media_outlined),
), ),
), ),
), ),
const SizedBox(width: AppSpacing.tiny), if (!desktop) const SizedBox(width: AppSpacing.tiny),
HeaderControlRegion( HeaderControlRegion(
child: SizedBox.square( child: SizedBox.square(
dimension: desktop dimension: desktop ? AppControlSize.headerButton : 48,
? AppControlSize.headerButton
: 48,
child: IconButton( child: IconButton(
key: const Key('editor-properties-button'), key: const Key('editor-properties-button'),
tooltip: propertiesOpen tooltip: propertiesOpen
@@ -250,12 +232,36 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
), ),
), ),
), ),
const SizedBox(width: AppSpacing.compact), if (!desktop) const SizedBox(width: AppSpacing.compact),
], ],
), ),
), ),
), ),
), ),
);
Widget dockedEditing({required bool showTools}) =>
ExpandedEditorLayout(
preview: preview,
header: header,
properties: properties,
media: media,
showMedia: false,
showProperties: showTools && _propertiesOpen,
timelineHeight: _timelineHeight,
onTimelineHeightChanged: (height) {
if (viewSettings.hasValue) {
_viewController.setTimelineHeight(height);
}
},
onTimelineHeightChangeEnd: _saveViewSettings,
timeline: timeline,
);
return Stack(
fit: StackFit.expand,
children: [
Column(
children: [
if (!desktop) header,
Expanded( Expanded(
child: dockPanels child: dockPanels
? dockedEditing(showTools: true) ? dockedEditing(showTools: true)
@@ -270,22 +276,29 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
tool: desktop tool: desktop
? desktopTool ? desktopTool
: _presentation.activeTool, : _presentation.activeTool,
media: switch (widget.experience) { media: widget.projectLoading
? media
: switch (widget.experience) {
DeviceExperience.desktop => media, DeviceExperience.desktop => media,
DeviceExperience.tablet => MediaBrowserDrawer( DeviceExperience.tablet =>
MediaBrowserDrawer(
projectId: widget.projectId, projectId: widget.projectId,
), ),
DeviceExperience.phone => MediaBrowserPage( DeviceExperience.phone => MediaBrowserPage(
projectId: widget.projectId, projectId: widget.projectId,
), ),
}, },
properties: switch (widget.experience) { properties: widget.projectLoading
? properties
: switch (widget.experience) {
DeviceExperience.desktop => properties, DeviceExperience.desktop => properties,
DeviceExperience.tablet => PropertiesToolPanel( DeviceExperience.tablet =>
PropertiesToolPanel(
projectId: widget.projectId, projectId: widget.projectId,
timelineId: widget.timelineId, timelineId: widget.timelineId,
), ),
DeviceExperience.phone => PropertiesEditorPage( DeviceExperience.phone =>
PropertiesEditorPage(
projectId: widget.projectId, projectId: widget.projectId,
timelineId: widget.timelineId, timelineId: widget.timelineId,
), ),
@@ -304,6 +317,7 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
), ),
], ],
), ),
if (!desktop)
Positioned( Positioned(
key: const Key('editing-top-divider'), key: const Key('editing-top-divider'),
top: headerHeight, top: headerHeight,
@@ -0,0 +1,62 @@
import 'package:cutdex_ui/widgets.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) ...[
const SizedBox(
key: Key('timeline-tabs-bar'),
height: 26,
child: Row(
children: [
IconButton(onPressed: null, icon: Icon(Icons.add, size: 16)),
],
),
),
const Divider(height: 1),
],
Expanded(
child: WorkspacePanel(
headerHeight: 32,
headerPadding: EdgeInsets.zero,
controls: SizedBox(
key: const Key('timeline-toolbar'),
height: 32,
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
for (final icon in [
Icons.undo,
Icons.redo,
Icons.content_cut,
Icons.align_horizontal_left,
Icons.align_horizontal_right,
Icons.delete_outline,
])
IconButton(onPressed: null, icon: Icon(icon, size: 16)),
],
),
),
),
child: const SizedBox.expand(key: Key('timeline-default-tracks')),
),
),
],
);
}
@@ -36,7 +36,7 @@ class BoundedEditorLayout extends StatelessWidget {
Widget toolSurface() => Column( Widget toolSurface() => Column(
children: [ children: [
SizedBox( SizedBox(
height: desktop ? AppControlSize.panelHeader : 48, height: desktop ? AppControlSize.panelToolbar : 48,
child: Row( child: Row(
children: [ children: [
SizedBox.square( SizedBox.square(
@@ -92,7 +92,7 @@ class BoundedEditorLayout extends StatelessWidget {
), ),
if (tool != null) if (tool != null)
Positioned( Positioned(
top: 0, top: desktop ? AppControlSize.panelToolbar + 1 : 0,
bottom: 0, bottom: 0,
right: 0, right: 0,
width: page width: page
@@ -1,14 +1,17 @@
import 'dart:math' as math; import 'dart:math' as math;
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:cutdex_ui/theme.dart';
import '../../../shared/layout/workspace_layout_metrics.dart'; import '../../../shared/layout/workspace_layout_metrics.dart';
import '../../../shared/widgets/workspace_card.dart';
import '../../../shared/widgets/workspace_resize_handle.dart';
class ExpandedEditorLayout extends StatefulWidget { class ExpandedEditorLayout extends StatefulWidget {
const ExpandedEditorLayout({ const ExpandedEditorLayout({
super.key, super.key,
required this.preview, required this.preview,
required this.header,
required this.properties, required this.properties,
required this.media, required this.media,
required this.showMedia, required this.showMedia,
@@ -20,6 +23,7 @@ class ExpandedEditorLayout extends StatefulWidget {
}); });
final Widget preview; final Widget preview;
final Widget header;
final Widget properties; final Widget properties;
final Widget media; final Widget media;
final bool showMedia; final bool showMedia;
@@ -34,15 +38,20 @@ class ExpandedEditorLayout extends StatefulWidget {
} }
class _ExpandedEditorLayoutState extends State<ExpandedEditorLayout> { class _ExpandedEditorLayoutState extends State<ExpandedEditorLayout> {
double? _timelineDragStartY; static const gap = WorkspaceLayoutMetrics.desktopSpacing;
double _timelineDragStartHeight = 0;
Widget _card(String name, Widget child) =>
WorkspaceCard(key: Key('editor-$name-card'), child: child);
@override @override
Widget build(BuildContext context) => LayoutBuilder( Widget build(BuildContext context) => LayoutBuilder(
builder: (context, constraints) { builder: (context, constraints) {
final maximum = math.max( final maximum = math.max(
0.0, 0.0,
constraints.maxHeight - WorkspaceLayoutMetrics.timelineMinimumHeight, constraints.maxHeight -
gap -
AppControlSize.panelToolbar -
WorkspaceLayoutMetrics.timelineMinimumHeight,
); );
final minimum = math.min( final minimum = math.min(
WorkspaceLayoutMetrics.timelineMinimumHeight, WorkspaceLayoutMetrics.timelineMinimumHeight,
@@ -65,6 +74,17 @@ class _ExpandedEditorLayoutState extends State<ExpandedEditorLayout> {
children: [ children: [
Column( Column(
children: [ children: [
Expanded(
child: _card(
'preview',
Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
widget.header,
Expanded( Expanded(
child: Row( child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
@@ -78,8 +98,17 @@ class _ExpandedEditorLayoutState extends State<ExpandedEditorLayout> {
const VerticalDivider(width: 1), const VerticalDivider(width: 1),
], ],
Expanded(child: widget.preview), Expanded(child: widget.preview),
],
),
),
],
),
),
if (widget.showProperties) ...[ if (widget.showProperties) ...[
const VerticalDivider(width: 1), const VerticalDivider(
key: Key('editor-properties-divider'),
width: 1,
),
SizedBox( SizedBox(
key: const Key('editor-properties-region'), key: const Key('editor-properties-region'),
width: propertiesWidth, width: propertiesWidth,
@@ -89,53 +118,29 @@ class _ExpandedEditorLayoutState extends State<ExpandedEditorLayout> {
], ],
), ),
), ),
const SizedBox(height: 1), ),
SizedBox(height: timelineHeight, child: widget.timeline), const SizedBox(height: gap),
SizedBox(
height: timelineHeight,
child: _card('timeline', widget.timeline),
),
], ],
), ),
Positioned( Positioned(
key: const Key('editor-timeline-divider'), key: const Key('editor-timeline-divider'),
left: 0, left: 0,
right: 0, right: 0,
bottom: timelineHeight - 4, bottom: timelineHeight - WorkspaceLayoutMetrics.desktopResizeSlop,
height: 8, height: WorkspaceLayoutMetrics.desktopResizeHitExtent,
child: MouseRegion( child: WorkspaceResizeHandle(
cursor: SystemMouseCursors.resizeRow,
child: GestureDetector(
key: const Key('editor-timeline-resize'), key: const Key('editor-timeline-resize'),
behavior: HitTestBehavior.opaque, axis: Axis.vertical,
dragStartBehavior: DragStartBehavior.down, initialValue: timelineHeight,
onVerticalDragStart: (details) { direction: -1,
_timelineDragStartY = details.globalPosition.dy; onResize: (height) => widget.onTimelineHeightChanged(
_timelineDragStartHeight = timelineHeight; height.clamp(minimum, maximum).toDouble(),
},
onVerticalDragUpdate: (details) {
final start = _timelineDragStartY;
if (start == null) return;
widget.onTimelineHeightChanged(
(_timelineDragStartHeight +
start -
details.globalPosition.dy)
.clamp(minimum, maximum)
.toDouble(),
);
},
onVerticalDragEnd: (_) {
_timelineDragStartY = null;
widget.onTimelineHeightChangeEnd();
},
onVerticalDragCancel: () {
_timelineDragStartY = null;
widget.onTimelineHeightChangeEnd();
},
child: const Center(
child: SizedBox(
height: 1,
width: double.infinity,
child: Divider(height: 1),
),
),
), ),
onEnd: widget.onTimelineHeightChangeEnd,
), ),
), ),
], ],
@@ -1,3 +1,4 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'subtitle_download.dart'; import 'subtitle_download.dart';
@@ -691,8 +692,8 @@ class _SubtitleTaskCardState extends ConsumerState<_SubtitleTaskCard> {
setState(() => _validationError = null); setState(() => _validationError = null);
await action(); await action();
if (mounted && !widget.details && _error != null) { if (mounted && !widget.details && _error != null) {
ScaffoldMessenger.maybeOf(context) ErrorNotificationHost.maybeOf(context)
?.showSnackBar(SnackBar(content: Text(_error!))); ?.show(ErrorNotification(content: Text(_error!)));
} }
} }
+42 -23
View File
@@ -1,3 +1,4 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:cutdex/errors/app_failure.dart'; import 'package:cutdex/errors/app_failure.dart';
import 'dart:math' as math; import 'dart:math' as math;
@@ -34,6 +35,7 @@ extension MediaFilterLabel on MediaFilter {
} }
const maximumMediaGridTileWidth = 160.0; const maximumMediaGridTileWidth = 160.0;
const maximumCompactMediaGridTileWidth = 120.0;
class MediaBrowserBody extends ConsumerStatefulWidget { class MediaBrowserBody extends ConsumerStatefulWidget {
const MediaBrowserBody({ const MediaBrowserBody({
@@ -41,10 +43,12 @@ class MediaBrowserBody extends ConsumerStatefulWidget {
required this.projectId, required this.projectId,
required this.grid, required this.grid,
this.draggable = false, this.draggable = false,
this.compact = false,
}); });
final String projectId; final String projectId;
final bool grid; final bool grid;
final bool draggable; final bool draggable;
final bool compact;
@override @override
ConsumerState<MediaBrowserBody> createState() => _MediaBrowserBodyState(); ConsumerState<MediaBrowserBody> createState() => _MediaBrowserBodyState();
} }
@@ -82,16 +86,11 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
Future<void> _action(Future<bool> Function() action) async { Future<void> _action(Future<bool> Function() action) async {
final ok = await action(); final ok = await action();
if (!mounted || ok) return; if (!mounted || ok) return;
ScaffoldMessenger.of(context).showSnackBar( final failure =
SnackBar(
content: Text(
context.l10n.failureMessage(
ref.read(projectsProvider).asData?.value.error ?? ref.read(projectsProvider).asData?.value.error ??
const AppFailure(AppErrorCode.operationFailed), const AppFailure(AppErrorCode.operationFailed);
), ErrorNotificationHost.of(context)
), .showFailure(failure, context.l10n.failureMessage(failure));
),
);
} }
Future<void> _rename(AssetDocument asset) async { Future<void> _rename(AssetDocument asset) async {
@@ -166,7 +165,17 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
); );
Widget _buildBrowser(BuildContext context) { Widget _buildBrowser(BuildContext context) {
ref.watch(externalMediaImportProvider(widget.projectId)); ref.watch(externalMediaImportProvider(widget.projectId));
final workspace = ref.watch(projectsProvider).asData?.value; ref.watch(
projectsProvider.select(
(value) => (
value.value?.activeProject?.id,
value.value?.assets,
value.value?.timeline?.id,
value.value?.projectBusy,
),
),
);
final workspace = ref.read(projectsProvider).value;
final active = workspace?.activeProject?.id == widget.projectId; final active = workspace?.activeProject?.id == widget.projectId;
final allAssets = active ? workspace!.assets : <AssetDocument>[]; final allAssets = active ? workspace!.assets : <AssetDocument>[];
final assets = _filter == MediaFilter.all final assets = _filter == MediaFilter.all
@@ -197,14 +206,21 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
) )
: LayoutBuilder( : LayoutBuilder(
builder: (context, constraints) { builder: (context, constraints) {
const spacing = AppSpacing.small; final spacing = widget.compact
final width = math.max( ? AppSpacing.gap
1.0, : AppSpacing.small;
constraints.maxWidth - AppSpacing.compact * 2, final padding = widget.compact
); ? AppSidebarMetrics.outerPadding
: AppSpacing.compact;
final width = math.max(1.0, constraints.maxWidth - padding * 2);
final columns = math.max( final columns = math.max(
1, 1,
((width + spacing) / (maximumMediaGridTileWidth + spacing)) widget.compact
? ((width + spacing) /
(maximumCompactMediaGridTileWidth + spacing))
.ceil()
: ((width + spacing) /
(maximumMediaGridTileWidth + spacing))
.ceil(), .ceil(),
); );
final tileWidth = (width - spacing * (columns - 1)) / columns; final tileWidth = (width - spacing * (columns - 1)) / columns;
@@ -308,23 +324,26 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
? ListView.separated( ? ListView.separated(
key: PageStorageKey(('media-list', widget.projectId)), key: PageStorageKey(('media-list', widget.projectId)),
controller: controller, controller: controller,
padding: const EdgeInsets.all(AppSpacing.compact), padding: EdgeInsets.all(padding),
itemCount: assets.length, itemCount: assets.length,
itemBuilder: item, itemBuilder: item,
separatorBuilder: (_, _) => separatorBuilder: (_, _) => SizedBox(height: spacing),
const SizedBox(height: AppSpacing.small),
) )
: GridView.builder( : GridView.builder(
key: PageStorageKey(('media-grid', widget.projectId)), key: PageStorageKey(('media-grid', widget.projectId)),
controller: controller, controller: controller,
padding: const EdgeInsets.all(AppSpacing.compact), padding: EdgeInsets.all(padding),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: columns, crossAxisCount: columns,
crossAxisSpacing: spacing, crossAxisSpacing: spacing,
mainAxisSpacing: AppSpacing.compact, mainAxisSpacing: widget.compact
? spacing
: AppSpacing.compact,
mainAxisExtent: mainAxisExtent:
tileWidth * 9 / 16 + tileWidth * 9 / 16 +
AppSpacing.small + (widget.compact
? AppSpacing.gap
: AppSpacing.small) +
labelHeight + labelHeight +
2, 2,
), ),
@@ -403,7 +422,7 @@ class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
], ],
), ),
), ),
const SizedBox(height: AppSpacing.small), SizedBox(height: widget.compact ? AppSpacing.gap : AppSpacing.small),
name, name,
], ],
); );
@@ -1,3 +1,4 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../../l10n/l10n.dart'; import '../../l10n/l10n.dart';
@@ -74,7 +75,7 @@ class _MediaImportFeedbackListenerState
WidgetsBinding.instance.addPostFrameCallback((_) { WidgetsBinding.instance.addPostFrameCallback((_) {
_scheduled = false; _scheduled = false;
if (!mounted || !_visible || !widget.feedback.hasPending) return; if (!mounted || !_visible || !widget.feedback.hasPending) return;
final messenger = ScaffoldMessenger.maybeOf(context); final messenger = ErrorNotificationHost.maybeOf(context);
if (messenger == null) return; if (messenger == null) return;
for (final result in widget.feedback.takePending()) { for (final result in widget.feedback.takePending()) {
final messages = [ final messages = [
@@ -84,8 +85,13 @@ class _MediaImportFeedbackListenerState
'${failure.name}: ${context.l10n.failureMessage(failure.failure)}', '${failure.name}: ${context.l10n.failureMessage(failure.failure)}',
if (result?.failed == true) context.l10n.noImportableFiles, if (result?.failed == true) context.l10n.noImportableFiles,
]; ];
messenger.showSnackBar( messenger.show(
SnackBar( ErrorNotification(
details: [
for (final failure
in result?.result?.failures ?? <MediaImportFailure>[])
'${failure.name}: code=${failure.failure.code.name}\n${failure.failure.diagnostic ?? ''}',
].join('\n'),
content: ConstrainedBox( content: ConstrainedBox(
constraints: const BoxConstraints(maxHeight: 180), constraints: const BoxConstraints(maxHeight: 180),
child: SingleChildScrollView(child: Text(messages.join('\n'))), child: SingleChildScrollView(child: Text(messages.join('\n'))),
+3 -2
View File
@@ -1,3 +1,4 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
@@ -142,8 +143,8 @@ class TouchMediaBrowser extends ConsumerWidget {
selected, selected,
); );
if (!inserted && context.mounted) { if (!inserted && context.mounted) {
ScaffoldMessenger.of(context).showSnackBar( ErrorNotificationHost.of(context).show(
SnackBar( ErrorNotification(
content: Text(context.l10n.operationFailed), content: Text(context.l10n.operationFailed),
), ),
); );
@@ -0,0 +1,241 @@
import 'package:flutter/material.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import '../../l10n/l10n.dart';
import '../../workspace/project_state.dart';
import 'media_browser_body.dart';
import 'media_browser_controller.dart';
class MediaBrowserToolbar extends StatefulWidget {
const MediaBrowserToolbar({
super.key,
required this.canImport,
required this.onImport,
required this.filter,
required this.onFilterChanged,
required this.grid,
required this.onToggleGrid,
this.projects = const [],
this.selectedProjectId,
this.onProjectSelected,
});
final bool canImport;
final VoidCallback onImport;
final MediaFilter filter;
final ValueChanged<MediaFilter> onFilterChanged;
final bool grid;
final VoidCallback onToggleGrid;
final List<RecentProject> projects;
final String? selectedProjectId;
final ValueChanged<RecentProject>? onProjectSelected;
@override
State<MediaBrowserToolbar> createState() => _MediaBrowserToolbarState();
}
class _MediaBrowserToolbarState extends State<MediaBrowserToolbar> {
Object? _filterConfiguration;
Widget? _filterControls;
bool get canImport => widget.canImport;
VoidCallback get onImport => widget.onImport;
MediaFilter get filter => widget.filter;
ValueChanged<MediaFilter> get onFilterChanged =>
(value) => widget.onFilterChanged(value);
bool get grid => widget.grid;
VoidCallback get onToggleGrid =>
() => widget.onToggleGrid();
List<RecentProject> get projects => widget.projects;
String? get selectedProjectId => widget.selectedProjectId;
ValueChanged<RecentProject>? get onProjectSelected =>
widget.onProjectSelected;
@override
Widget build(BuildContext context) {
final configuration = (
filter,
grid,
Theme.of(context),
Localizations.localeOf(context),
MediaQuery.textScalerOf(context),
Directionality.of(context),
);
if (_filterConfiguration != configuration) {
_filterConfiguration = configuration;
_filterControls = null;
}
final selected = projects
.where((project) => project.id == selectedProjectId)
.firstOrNull;
Widget row(Key key, Widget child) => SizedBox(
key: key,
height: AppControlSize.panelToolbar,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: AppSidebarMetrics.outerPadding,
vertical: AppSpacing.gap,
),
child: child,
),
);
return Column(
key: const Key('media-panel-header'),
mainAxisSize: MainAxisSize.min,
children: [
row(
const Key('media-project-row'),
LayoutBuilder(
builder: (context, constraints) {
final painter = TextPainter(
text: TextSpan(
text: context.l10n.importMedia,
style: AppTheme.toolbarTextStyle(context),
),
textDirection: Directionality.of(context),
textScaler: MediaQuery.textScalerOf(context),
)..layout();
final compact = constraints.maxWidth < painter.width + 140;
painter.dispose();
return Row(
children: [
Expanded(
child: AppDropdownMenu(
enabled: onProjectSelected != null && projects.isNotEmpty,
maxHeight: 320,
items: [
for (final project in projects)
AppMenuItem(
key: ValueKey('media-project-${project.id}'),
label: project.name,
selected: project.id == selectedProjectId,
selectOption: true,
onPressed: onProjectSelected == null
? null
: () => onProjectSelected!(project),
),
],
builder: (context, toggle, focusNode) =>
AppToolbarDropdownButton(
buttonKey: const Key('media-project-button'),
focusNode: focusNode,
onPressed: toggle,
child: Row(
children: [
Expanded(
child: Text(
selected?.name ??
context.l10n.selectProject,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
const SizedBox(width: AppSpacing.tiny),
const Icon(
Icons.keyboard_arrow_down,
size: AppIconSize.header,
),
],
),
),
),
),
const SizedBox(width: AppSpacing.tiny),
if (compact)
SizedBox.square(
dimension: AppControlSize.headerButton,
child: IconButton(
key: const Key('media-import-button'),
tooltip: context.l10n.importMedia,
onPressed: canImport ? onImport : null,
icon: const Icon(Icons.add, size: AppIconSize.header),
),
)
else
SizedBox(
height: AppControlSize.headerButton,
child: TextButton.icon(
key: const Key('media-import-button'),
style: AppTheme.toolbarButtonStyle(context),
onPressed: canImport ? onImport : null,
icon: const Icon(Icons.add, size: AppIconSize.header),
label: Text(context.l10n.importMedia),
),
),
],
);
},
),
),
_filterControls ??= row(
const Key('media-filter-row'),
Row(
children: [
Expanded(
child: Align(
alignment: AlignmentDirectional.centerStart,
child: SizedBox(
width: 88,
height: AppControlSize.headerButton,
child: Semantics(
label: context.l10n.mediaCategory,
child: AppDropdownMenu(
items: [
for (final option in MediaFilter.values)
AppMenuItem(
label: option.label(context),
selected: option == filter,
selectOption: true,
onPressed: () => onFilterChanged(option),
),
],
builder: (context, toggle, focus) =>
AppToolbarDropdownButton(
buttonKey: const Key('media-category-button'),
focusNode: focus,
onPressed: toggle,
child: Row(
children: [
Expanded(
child: Text(
filter.label(context),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
const SizedBox(width: AppSpacing.tiny),
const Icon(
Icons.keyboard_arrow_down,
size: AppIconSize.header,
),
],
),
),
),
),
),
),
),
const SizedBox(width: AppSpacing.tiny),
SizedBox.square(
dimension: AppControlSize.headerButton,
child: IconButton(
key: const Key('media-layout-toggle'),
onPressed: onToggleGrid,
icon: Icon(
grid ? Icons.view_list_outlined : Icons.grid_view_outlined,
size: AppIconSize.header,
),
tooltip: grid
? context.l10n.listLayout
: context.l10n.gridLayout,
),
),
],
),
),
],
);
}
}
+79 -114
View File
@@ -1,17 +1,19 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../l10n/l10n.dart';
import '../../integrations/platform/native_project_drop_region.dart'; import '../../integrations/platform/native_project_drop_region.dart';
import '../../integrations/platform/platform_capabilities.dart'; import '../../integrations/platform/platform_capabilities.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart'; import 'package:cutdex_ui/widgets.dart';
import '../../shared/widgets/drop_to_add_overlay.dart'; import '../../shared/widgets/drop_to_add_overlay.dart';
import '../../shared/widgets/listenable_selector.dart';
import '../../workspace/external_media_import.dart'; import '../../workspace/external_media_import.dart';
import '../../workspace/projects.dart'; import '../../workspace/projects.dart';
import '../../workspace/project_state.dart';
import '../../l10n/l10n.dart';
import 'media_browser_body.dart'; import 'media_browser_body.dart';
import 'media_browser_toolbar.dart';
import 'media_browser_controller.dart'; import 'media_browser_controller.dart';
import 'media_browser_feedback.dart'; import 'media_browser_feedback.dart';
@@ -23,8 +25,10 @@ class MediaPanel extends ConsumerStatefulWidget {
this.backgroundColor, this.backgroundColor,
this.grid, this.grid,
this.onGridChanged, this.onGridChanged,
this.onSelectProject,
}) : assert((grid == null) == (onGridChanged == null)); }) : assert((grid == null) == (onGridChanged == null));
final String projectId; final String? projectId;
final ValueChanged<RecentProject>? onSelectProject;
final Color? backgroundColor; final Color? backgroundColor;
final bool? grid; final bool? grid;
final ValueChanged<bool>? onGridChanged; final ValueChanged<bool>? onGridChanged;
@@ -34,14 +38,70 @@ class MediaPanel extends ConsumerStatefulWidget {
class _MediaPanelState extends ConsumerState<MediaPanel> { class _MediaPanelState extends ConsumerState<MediaPanel> {
bool _hovering = false; bool _hovering = false;
(String, bool)? _bodyConfiguration;
Widget? _body;
Widget _browserBody(String projectId, bool grid) {
final configuration = (projectId, grid);
if (_bodyConfiguration != configuration) {
_bodyConfiguration = configuration;
_body = MediaBrowserBody(
projectId: projectId,
grid: grid,
draggable: true,
compact: true,
);
}
return _body!;
}
@override
void didUpdateWidget(covariant MediaPanel oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.projectId != widget.projectId) _hovering = false;
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
ref.watch(projectsProvider); final workspace = ref.watch(
final browser = ref.watch(mediaBrowserProvider(widget.projectId)); projectsProvider.select(
ref.watch(externalMediaImportProvider(widget.projectId)); (value) => (
value.value?.recent ?? const <RecentProject>[],
value.value?.projectBusy ?? false,
value.value?.activeProject?.id,
),
),
);
final projectId = widget.projectId;
final onSelectProject = workspace.$2 ? null : widget.onSelectProject;
if (projectId == null) {
return Material(
key: const Key('media-panel-surface'),
color: widget.backgroundColor ?? Colors.transparent,
child: Column(
children: [
MediaBrowserToolbar(
projects: workspace.$1,
onProjectSelected: onSelectProject,
canImport: false,
onImport: () {},
filter: MediaFilter.all,
onFilterChanged: (_) {},
grid: true,
onToggleGrid: () {},
),
Expanded(child: Center(child: Text(context.l10n.selectProject))),
],
),
);
}
final browser = ref.watch(mediaBrowserProvider(projectId));
ref.watch(externalMediaImportProvider(projectId));
final nativeDrop = ref.watch(platformCapabilitiesProvider).nativeFileDrop; final nativeDrop = ref.watch(platformCapabilitiesProvider).nativeFileDrop;
return ListenableBuilder( return ListenableSelector(
listenable: browser, listenable: browser,
select: () =>
(browser.filter, browser.grid, browser.busy, browser.canImport),
builder: (context, _) { builder: (context, _) {
final grid = widget.grid ?? browser.grid; final grid = widget.grid ?? browser.grid;
final visible = final visible =
@@ -61,121 +121,26 @@ class _MediaPanelState extends ConsumerState<MediaPanel> {
feedback: browser.feedback, feedback: browser.feedback,
child: Material( child: Material(
key: const Key('media-panel-surface'), key: const Key('media-panel-surface'),
color: widget.backgroundColor, color: widget.backgroundColor ?? Colors.transparent,
child: Stack( child: Stack(
fit: StackFit.expand, fit: StackFit.expand,
children: [ children: [
Column( Column(
children: [ children: [
SizedBox( MediaBrowserToolbar(
key: const Key('media-panel-header'), projects: workspace.$1,
height: AppControlSize.panelToolbar, selectedProjectId: projectId,
child: Padding( onProjectSelected: onSelectProject,
padding: const EdgeInsets.all(AppSpacing.gap), canImport: enabled,
child: LayoutBuilder( onImport: () => pickMediaFiles(browser),
builder: (context, constraints) { filter: browser.filter,
final compact = constraints.maxWidth < 180; onFilterChanged: (value) => browser.filter = value,
final controls = Row( grid: grid,
mainAxisSize: compact onToggleGrid: toggleGrid,
? MainAxisSize.min
: MainAxisSize.max,
children: [
if (compact)
SizedBox.square(
dimension: AppControlSize.headerButton,
child: IconButton(
key: const Key('media-import-button'),
tooltip: context.l10n.importMedia,
onPressed: enabled
? () => pickMediaFiles(browser)
: null,
icon: const Icon(
Icons.add,
size: AppIconSize.header,
),
),
)
else
SizedBox(
height: AppControlSize.headerButton,
child: TextButton.icon(
key: const Key('media-import-button'),
style: AppTheme.toolbarButtonStyle(
context,
),
onPressed: enabled
? () => pickMediaFiles(browser)
: null,
icon: const Icon(
Icons.add,
size: AppIconSize.header,
),
label: Text(context.l10n.importMedia),
),
),
if (compact)
const SizedBox(width: AppSpacing.tiny)
else
const Spacer(),
SizedBox(
width: 76,
child: AppSelect<MediaFilter>(
emptyLabel: context.l10n.noMatchingOptions,
label: context.l10n.mediaCategory,
outlined: false,
controlHeight: AppControlSize.headerButton,
textStyle: AppTheme.toolbarTextStyle(
context,
),
value: browser.filter,
onChanged: (value) =>
browser.filter = value,
options: [
for (final filter in MediaFilter.values)
AppSelectOption(
filter,
filter.label(context),
),
],
),
),
const SizedBox(width: AppSpacing.tiny),
SizedBox.square(
dimension: AppControlSize.headerButton,
child: IconButton(
key: const Key('media-layout-toggle'),
onPressed: toggleGrid,
icon: Icon(
grid
? Icons.view_list_outlined
: Icons.grid_view_outlined,
size: AppIconSize.header,
),
tooltip: grid
? context.l10n.listLayout
: context.l10n.gridLayout,
),
),
],
);
return compact
? SingleChildScrollView(
key: const Key('media-header-scroll'),
scrollDirection: Axis.horizontal,
child: controls,
)
: controls;
},
),
),
), ),
Expanded( Expanded(
key: const Key('media-panel-body'), key: const Key('media-panel-body'),
child: MediaBrowserBody( child: _browserBody(projectId, grid),
projectId: widget.projectId,
grid: grid,
draggable: true,
),
), ),
], ],
), ),
+181 -65
View File
@@ -1,3 +1,5 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import '../../diagnostics/app_diagnostics.dart'; import '../../diagnostics/app_diagnostics.dart';
import 'dart:async'; import 'dart:async';
@@ -17,6 +19,7 @@ import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:cutdex_ui/theme.dart'; import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart'; import 'package:cutdex_ui/widgets.dart';
import '../../shared/widgets/listenable_selector.dart';
import '../../workspace/media_availability.dart'; import '../../workspace/media_availability.dart';
import '../../workspace/preview_controller_registry.dart'; import '../../workspace/preview_controller_registry.dart';
import '../../workspace/preview_target.dart'; import '../../workspace/preview_target.dart';
@@ -148,13 +151,19 @@ class EditorPreviewPanel extends StatelessWidget {
super.key, super.key,
required this.projectId, required this.projectId,
required this.timelineId, required this.timelineId,
this.pending = false,
}); });
final String projectId; final String projectId;
final String timelineId; final String timelineId;
final bool pending;
@override @override
Widget build(BuildContext context) => PreviewFullscreenHost( Widget build(BuildContext context) => PreviewFullscreenHost(
child: _EditorPreviewContent(projectId: projectId, timelineId: timelineId), child: _EditorPreviewContent(
projectId: projectId,
timelineId: timelineId,
pending: pending,
),
); );
} }
@@ -162,18 +171,47 @@ class _EditorPreviewContent extends ConsumerWidget {
const _EditorPreviewContent({ const _EditorPreviewContent({
required this.projectId, required this.projectId,
required this.timelineId, required this.timelineId,
this.pending = false,
}); });
final String projectId; final String projectId;
final String timelineId; final String timelineId;
final bool pending;
@override @override
Widget build(BuildContext context, WidgetRef ref) { Widget build(BuildContext context, WidgetRef ref) {
final provider = editorPreviewProvider(projectId, timelineId); final provider = editorPreviewProvider(projectId, timelineId);
final state = ref.watch(provider); final watched = pending
? const AsyncData<PreviewController?>(null)
: ref.watch(provider);
final cached = watched.isLoading && !watched.hasError
? ref.read(previewControllerRegistryProvider).cached((
projectId,
timelineId,
))
: null;
final state = cached == null
? watched
: AsyncData<PreviewController?>(cached);
final controller = state.asData?.value; final controller = state.asData?.value;
Widget panel() { Widget panel() => WorkspacePanel(
headerHeight: 0,
showHeaderDivider: false,
child: PreviewFullscreenLayout(
canvas: ListenableSelector(
listenable: controller,
select: () => (
controller?.canvas,
controller?.session,
controller?.error,
(controller?.durationTick ?? 0) > 0,
),
builder: (context, _) {
final activeController = controller; final activeController = controller;
final defaultCanvas =
pending ||
(state.isLoading && !state.hasError && controller == null);
final showCanvas = final showCanvas =
defaultCanvas ||
state.hasError || state.hasError ||
(activeController != null && (activeController != null &&
(activeController.durationTick > 0 || (activeController.durationTick > 0 ||
@@ -193,15 +231,18 @@ class _EditorPreviewContent extends ConsumerWidget {
? MaskInteractionOverlay( ? MaskInteractionOverlay(
controller: activeController, controller: activeController,
canvasRect: rect, canvasRect: rect,
obscure: activeController.obscureEditingElement != null, obscure:
activeController.obscureEditingElement !=
null,
) )
: PreviewInteractionOverlay( : PreviewInteractionOverlay(
onError: (_) => ScaffoldMessenger.maybeOf(context) onError: (error) =>
?.showSnackBar( ErrorNotificationHost.maybeOf(context)?.show(
SnackBar( ErrorNotification(
content: Text( content: Text(
context.l10n.canvasTransformFailed, context.l10n.canvasTransformFailed,
), ),
details: error.toString(),
), ),
), ),
controller: activeController, controller: activeController,
@@ -210,11 +251,7 @@ class _EditorPreviewContent extends ConsumerWidget {
), ),
) )
: null; : null;
return WorkspacePanel( return showCanvas
headerHeight: 0,
showHeaderDivider: false,
child: PreviewFullscreenLayout(
canvas: showCanvas
? Padding( ? Padding(
padding: padding:
PreviewFullscreenScope.of(context)?.fullscreen == true PreviewFullscreenScope.of(context)?.fullscreen == true
@@ -223,7 +260,8 @@ class _EditorPreviewContent extends ConsumerWidget {
child: PreviewCanvas( child: PreviewCanvas(
alignment: Alignment.center, alignment: Alignment.center,
horizontalPadding: 0, horizontalPadding: 0,
backgroundColor: AppSurfaces.of(context).previewBackground, backgroundColor: AppSurfaces.of(context)
.previewBackground,
overlayBuilder: overlayBuilder, overlayBuilder: overlayBuilder,
aspectRatio: aspectRatio:
(activeController?.canvas ?? ProjectCanvas.widescreen) (activeController?.canvas ?? ProjectCanvas.widescreen)
@@ -231,9 +269,16 @@ class _EditorPreviewContent extends ConsumerWidget {
child: Theme( child: Theme(
data: AppTheme.previewCanvasTheme, data: AppTheme.previewCanvasTheme,
child: Builder( child: Builder(
builder: (context) => state.when( builder: (context) => defaultCanvas
loading: () => const DelayedLoadingIndicator( ? const ColoredBox(
child: Center(child: CircularProgressIndicator()), key: Key('preview-default-frame'),
color: Colors.black,
)
: state.when(
skipLoadingOnReload: true,
loading: () => const ColoredBox(
key: Key('preview-default-frame'),
color: Colors.black,
), ),
error: (error, _) => Center( error: (error, _) => Center(
child: SingleChildScrollView( child: SingleChildScrollView(
@@ -243,10 +288,15 @@ class _EditorPreviewContent extends ConsumerWidget {
children: [ children: [
Text( Text(
error is EditorSessionStartupException error is EditorSessionStartupException
? context.l10n.editorSessionStartFailed ? context
.l10n
.editorSessionStartFailed
: error is RuntimeException && : error is RuntimeException &&
error.code == 'unsupported' error.code ==
? context.l10n.nativePreviewUnsupported 'unsupported'
? context
.l10n
.nativePreviewUnsupported
: context.l10n.previewStartFailed, : context.l10n.previewStartFailed,
textAlign: TextAlign.center, textAlign: TextAlign.center,
), ),
@@ -291,8 +341,17 @@ class _EditorPreviewContent extends ConsumerWidget {
children: [ children: [
if (preview.session case final session?) if (preview.session case final session?)
RuntimePreview(session: session), RuntimePreview(session: session),
ListenableBuilder( ListenableSelector(
listenable: preview.positionChanges, listenable: Listenable.merge([
preview,
preview.positionChanges,
]),
select: () => (
preview.error,
preview.unavailableAtPlayhead.join(
', ',
),
),
builder: (context, _) { builder: (context, _) {
final unavailable = final unavailable =
preview.unavailableAtPlayhead; preview.unavailableAtPlayhead;
@@ -302,7 +361,8 @@ class _EditorPreviewContent extends ConsumerWidget {
} }
return IgnorePointer( return IgnorePointer(
child: Align( child: Align(
alignment: Alignment.bottomCenter, alignment:
Alignment.bottomCenter,
child: Padding( child: Padding(
padding: const EdgeInsets.all( padding: const EdgeInsets.all(
AppSpacing.medium, AppSpacing.medium,
@@ -312,7 +372,8 @@ class _EditorPreviewContent extends ConsumerWidget {
unavailable.join(', '), unavailable.join(', '),
), ),
maxLines: 2, maxLines: 2,
overflow: TextOverflow.ellipsis, overflow:
TextOverflow.ellipsis,
textAlign: TextAlign.center, textAlign: TextAlign.center,
), ),
), ),
@@ -332,7 +393,9 @@ class _EditorPreviewContent extends ConsumerWidget {
), ),
child: Text( child: Text(
preview.error == null preview.error == null
? context.l10n.noPreviewContent ? context
.l10n
.noPreviewContent
: previewErrorMessage( : previewErrorMessage(
preview.error!, preview.error!,
context.l10n, context.l10n,
@@ -350,11 +413,14 @@ class _EditorPreviewContent extends ConsumerWidget {
), ),
), ),
) )
: const SizedBox.expand(key: Key('empty-preview-area')), : const SizedBox.expand(key: Key('empty-preview-area'));
},
),
toolbar: _PreviewToolbar(controller: controller), toolbar: _PreviewToolbar(controller: controller),
), ),
); );
}
if (pending) return panel();
final target = ref.watch(previewTargetProvider(projectId, timelineId)); final target = ref.watch(previewTargetProvider(projectId, timelineId));
final navigation = ref.watch( final navigation = ref.watch(
@@ -381,12 +447,7 @@ class _EditorPreviewContent extends ConsumerWidget {
target.togglePlayback = controller == null target.togglePlayback = controller == null
? null ? null
: () => unawaited(controller.togglePlayback()); : () => unawaited(controller.togglePlayback());
return controller == null return panel();
? panel()
: ListenableBuilder(
listenable: controller,
builder: (_, _) => panel(),
);
}, },
), ),
}, },
@@ -410,8 +471,29 @@ class _SourcePreviewPanel extends ConsumerWidget {
.watch(mediaAvailabilityProvider(projectId, asset)) .watch(mediaAvailabilityProvider(projectId, asset))
.asData .asData
?.value; ?.value;
return ListenableBuilder( return CallbackShortcuts(
bindings: {
const SingleActivator(LogicalKeyboardKey.space): source.togglePlayback,
},
child: Focus(
autofocus: true,
child: WorkspacePanel(
title: asset.name,
showHeaderDivider: false,
headerHeight: PreviewFullscreenScope.of(context)?.fullscreen == true
? 0
: AppControlSize.panelHeader,
child: PreviewFullscreenLayout(
canvas: ListenableSelector(
listenable: source, listenable: source,
select: () => (
source.session,
source.image,
source.error,
source.busy,
source.aspectRatio,
source.audioOnly,
),
builder: (context, _) { builder: (context, _) {
// The availability probe can finish while a newly dropped file is // The availability probe can finish while a newly dropped file is
// still switching security-scoped leases. Once the runtime has opened // still switching security-scoped leases. Once the runtime has opened
@@ -422,22 +504,7 @@ class _SourcePreviewPanel extends ConsumerWidget {
availability != MediaAvailability.available && availability != MediaAvailability.available &&
source.session == null && source.session == null &&
source.image == null; source.image == null;
return CallbackShortcuts( return Padding(
bindings: {
const SingleActivator(LogicalKeyboardKey.space):
source.togglePlayback,
},
child: Focus(
autofocus: true,
child: WorkspacePanel(
title: asset.name,
showHeaderDivider: false,
headerHeight:
PreviewFullscreenScope.of(context)?.fullscreen == true
? 0
: AppControlSize.panelHeader,
child: PreviewFullscreenLayout(
canvas: Padding(
padding: padding:
PreviewFullscreenScope.of(context)?.fullscreen == true PreviewFullscreenScope.of(context)?.fullscreen == true
? EdgeInsets.zero ? EdgeInsets.zero
@@ -508,14 +575,14 @@ class _SourcePreviewPanel extends ConsumerWidget {
), ),
), ),
), ),
);
},
), ),
toolbar: _PreviewToolbar(controller: null, source: source), toolbar: _PreviewToolbar(controller: null, source: source),
), ),
), ),
), ),
); );
},
);
} }
} }
@@ -527,18 +594,33 @@ class _PreviewToolbar extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final listenable = source == null && controller != null if (PreviewFullscreenScope.of(context)?.fullscreen == true) {
? Listenable.merge([controller!, controller!.positionChanges]) return ListenableSelector(
: source; listenable: _clock,
if (listenable != null) { select: () => (
return ListenableBuilder( source?.positionTick ?? controller?.positionTick ?? 0,
listenable: listenable, source?.durationTick ?? controller?.durationTick ?? 0,
source?.frameDuration ?? controller?.frameDuration,
source?.playing ?? controller?.playing ?? false,
source?.canPlay ?? controller?.canPlay ?? false,
),
builder: (context, _) => _build(context), builder: (context, _) => _build(context),
); );
} }
return _build(context); return _build(context);
} }
Listenable? get _clock =>
source ??
(controller == null
? null
: Listenable.merge([controller!, controller!.positionChanges]));
RationalTime get _frameDuration =>
source?.frameDuration ??
controller?.frameDuration ??
TimelineFormat.fps30.frameDuration;
Widget _build(BuildContext context) { Widget _build(BuildContext context) {
final preview = controller; final preview = controller;
final playing = source?.playing ?? preview?.playing ?? false; final playing = source?.playing ?? preview?.playing ?? false;
@@ -569,8 +651,10 @@ class _PreviewToolbar extends StatelessWidget {
} }
} catch (error) { } catch (error) {
if (context.mounted) { if (context.mounted) {
ScaffoldMessenger.maybeOf(context)?.showSnackBar( ErrorNotificationHost.maybeOf(context)?.show(
SnackBar(content: Text(previewErrorMessage(error, context.l10n))), ErrorNotification(
content: Text(previewErrorMessage(error, context.l10n)),
),
); );
} }
} }
@@ -618,13 +702,21 @@ class _PreviewToolbar extends StatelessWidget {
child: Row( child: Row(
children: [ children: [
Expanded( Expanded(
child: Text.rich( child: ListenableSelector(
key: const Key('preview-time'),
listenable: _clock,
select: () => (
source?.positionTick ?? preview?.positionTick ?? 0,
source?.durationTick ?? preview?.durationTick ?? 0,
_frameDuration,
),
builder: (context, _) => Text.rich(
TextSpan( TextSpan(
children: [ children: [
TextSpan( TextSpan(
text: _time( text: _time(
source?.positionTick ?? preview?.positionTick ?? 0, source?.positionTick ?? preview?.positionTick ?? 0,
frameDuration, _frameDuration,
), ),
style: TextStyle( style: TextStyle(
color: Theme.of(context).colorScheme.onSurface, color: Theme.of(context).colorScheme.onSurface,
@@ -632,7 +724,7 @@ class _PreviewToolbar extends StatelessWidget {
), ),
TextSpan( TextSpan(
text: text:
' / ${_time(source?.durationTick ?? preview?.durationTick ?? 0, frameDuration)}', ' / ${_time(source?.durationTick ?? preview?.durationTick ?? 0, _frameDuration)}',
style: TextStyle( style: TextStyle(
color: Theme.of(context).colorScheme.onSurfaceVariant, color: Theme.of(context).colorScheme.onSurfaceVariant,
), ),
@@ -646,7 +738,16 @@ class _PreviewToolbar extends StatelessWidget {
), ),
), ),
), ),
IconButton( ),
ListenableSelector(
listenable: source ?? preview,
select: () => (
source?.playing ?? preview?.playing ?? false,
source?.canPlay ?? preview?.canPlay ?? false,
),
builder: (context, value) {
final playing = value.$1;
return IconButton(
tooltip: playing ? context.l10n.pause : context.l10n.play, tooltip: playing ? context.l10n.pause : context.l10n.play,
onPressed: source != null onPressed: source != null
? (source!.canPlay ? source!.togglePlayback : null) ? (source!.canPlay ? source!.togglePlayback : null)
@@ -654,9 +755,22 @@ class _PreviewToolbar extends StatelessWidget {
? preview.togglePlayback ? preview.togglePlayback
: null, : null,
icon: Icon(playing ? Icons.pause : Icons.play_arrow), icon: Icon(playing ? Icons.pause : Icons.play_arrow),
);
},
), ),
Expanded( Expanded(
child: Align( child: ListenableSelector(
listenable: source ?? preview,
select: () => (
preview?.canvas,
preview?.error,
preview?.hasUnavailableMedia,
preview?.busy,
preview?.session,
source?.session,
source?.image,
),
builder: (context, _) => Align(
alignment: Alignment.centerRight, alignment: Alignment.centerRight,
child: Row( child: Row(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
@@ -672,7 +786,8 @@ class _PreviewToolbar extends StatelessWidget {
const SizedBox(width: AppSpacing.gap), const SizedBox(width: AppSpacing.gap),
], ],
if (source == null && if (source == null &&
PreviewFullscreenScope.of(context)?.fullscreen != true) PreviewFullscreenScope.of(context)?.fullscreen !=
true)
Flexible( Flexible(
child: AppSelect<ProjectCanvas>( child: AppSelect<ProjectCanvas>(
emptyLabel: context.l10n.noMatchingOptions, emptyLabel: context.l10n.noMatchingOptions,
@@ -711,6 +826,7 @@ class _PreviewToolbar extends StatelessWidget {
), ),
), ),
), ),
),
], ],
), ),
), ),
@@ -1,3 +1,5 @@
import 'dart:async';
import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart';
@@ -97,17 +99,72 @@ class ConversationSidebar extends _$ConversationSidebar {
@override @override
Future<ConversationSnapshot> build() async { Future<ConversationSnapshot> build() async {
ref.listen(
projectsProvider.select((value) => value.value?.activeProject?.id),
(before, after) {
if (before != after) unawaited(_refreshContext(after));
},
);
await ref.watch( await ref.watch(
projectsProvider.selectAsync( projectsProvider.selectAsync(
(workspace) => ConversationWorkspaceKey( (workspace) => ConversationWorkspaceKey(
projectId: workspace.activeProject?.id,
projectIds: [for (final project in workspace.recent) project.id], projectIds: [for (final project in workspace.recent) project.id],
), ),
), ),
); );
_revision++; _revision++;
final workspace = ref.read(projectsProvider).requireValue; final workspace = ref.read(projectsProvider).requireValue;
return _load(workspace); final loaded = await _load(workspace);
if (!ref.mounted) return loaded;
final activeId = ref.read(projectsProvider).value?.activeProject?.id;
return activeId == loaded.projectId
? loaded
: _loadContext(loaded, activeId);
}
/// Project selection changes only contextual data, never the global groups.
Future<ConversationSnapshot> _loadContext(
ConversationSnapshot current,
String? projectId,
) async {
final repository = await ref.read(conversationRepositoryProvider.future);
final trashed = projectId == null
? const <ConversationMetadata>[]
: await repository.list(projectId, trash: true);
final selectedId = await ref.read(
savedConversationSelectionProvider(projectId).future,
);
return current.copyWith(
projectId: projectId,
trashed: List.unmodifiable(trashed),
selectedId: selectedId,
reloadFailed: false,
);
}
Future<void> _refreshContext(String? projectId) async {
final current = state.value;
if (current == null) return; // Initial loading resolves the latest context.
final revision = ++_revision;
state = AsyncData(
current.copyWith(
projectId: projectId,
trashed: const [],
selectedId: null,
),
);
try {
final next = await _loadContext(current, projectId);
if (ref.mounted &&
revision == _revision &&
ref.read(projectsProvider).value?.activeProject?.id == projectId) {
state = AsyncData(next);
}
} catch (_) {
if (ref.mounted && revision == _revision) {
state = AsyncData(state.requireValue.copyWith(reloadFailed: true));
}
}
} }
Future<ConversationSnapshot> _load(ProjectState workspace) async { Future<ConversationSnapshot> _load(ProjectState workspace) async {
@@ -220,7 +220,7 @@ final class ConversationSidebarProvider
} }
String _$conversationSidebarHash() => String _$conversationSidebarHash() =>
r'13122a844ce87622c8d4919042e4dbefc69b790f'; r'ccb6d44f3c675b664a0e0925f9257b351061a899';
abstract class _$ConversationSidebar abstract class _$ConversationSidebar
extends $AsyncNotifier<ConversationSnapshot> { extends $AsyncNotifier<ConversationSnapshot> {
@@ -5,7 +5,6 @@ import '../../l10n/l10n.dart';
import '../../workspace/project_state.dart'; import '../../workspace/project_state.dart';
import 'package:cutdex_ui/theme.dart'; import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
class EmptyEditor extends StatelessWidget { class EmptyEditor extends StatelessWidget {
const EmptyEditor({ const EmptyEditor({
@@ -13,17 +12,28 @@ class EmptyEditor extends StatelessWidget {
required this.state, required this.state,
required this.headerLeading, required this.headerLeading,
required this.showProjectName, required this.showProjectName,
this.desktop = false,
}); });
final ProjectState state; final ProjectState state;
final Widget headerLeading; final Widget headerLeading;
final bool showProjectName; final bool showProjectName;
final bool desktop;
@override @override
Widget build(BuildContext context) => Column( Widget build(BuildContext context) => Column(
children: [ children: [
SizedBox( SizedBox(
height: AppControlSize.panelHeader, height: desktop
? AppControlSize.panelToolbar
: AppControlSize.panelHeader,
child: Padding(
padding: desktop
? const EdgeInsets.symmetric(
horizontal: AppSidebarMetrics.outerPadding,
vertical: AppSpacing.gap,
)
: EdgeInsets.zero,
child: WindowHeaderPadding( child: WindowHeaderPadding(
child: Row( child: Row(
children: [ children: [
@@ -42,6 +52,7 @@ class EmptyEditor extends StatelessWidget {
), ),
), ),
), ),
),
Expanded( Expanded(
child: Center( child: Center(
child: SingleChildScrollView( child: SingleChildScrollView(
@@ -77,40 +88,3 @@ class EmptyEditor extends StatelessWidget {
], ],
); );
} }
class ProjectLoadingRegion extends StatelessWidget {
const ProjectLoadingRegion({
super.key,
required this.loading,
required this.child,
});
final bool loading;
final Widget child;
@override
Widget build(BuildContext context) => Stack(
fit: StackFit.expand,
children: [
ExcludeFocus(
excluding: loading,
child: IgnorePointer(ignoring: loading, child: child),
),
if (loading)
DelayedLoadingIndicator(
child: Positioned.fill(
child: ColoredBox(
key: const Key('editor-project-loading'),
color: Theme.of(context).colorScheme.surface,
child: const Center(
child: SizedBox.square(
dimension: 20,
child: CircularProgressIndicator(strokeWidth: 2),
),
),
),
),
),
],
);
}
+152 -28
View File
@@ -1,5 +1,8 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import '../../integrations/platform/device_experience.dart'; import '../../integrations/platform/device_experience.dart';
import 'touch_project_navigation.dart'; import 'touch_project_navigation.dart';
import '../media/media_panel.dart';
import 'package:cutdex_ui/theme.dart'; import 'package:cutdex_ui/theme.dart';
@@ -8,6 +11,9 @@ import 'dart:async';
import 'package:cutdex/l10n/l10n.dart'; import 'package:cutdex/l10n/l10n.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../../shared/widgets/listenable_selector.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../integrations/platform/editor_window_chrome.dart'; import '../../integrations/platform/editor_window_chrome.dart';
@@ -38,6 +44,8 @@ class ProjectSidebar extends ConsumerStatefulWidget {
super.key, super.key,
required this.agent, required this.agent,
this.navigationOnly = false, this.navigationOnly = false,
this.resourcesSelected = false,
this.externalWindowFrame = false,
this.experience = DeviceExperience.desktop, this.experience = DeviceExperience.desktop,
this.onNavigationComplete, this.onNavigationComplete,
required this.mode, required this.mode,
@@ -58,6 +66,8 @@ class ProjectSidebar extends ConsumerStatefulWidget {
final Widget agent; final Widget agent;
final bool navigationOnly; final bool navigationOnly;
final bool resourcesSelected;
final bool externalWindowFrame;
final DeviceExperience experience; final DeviceExperience experience;
final VoidCallback? onNavigationComplete; final VoidCallback? onNavigationComplete;
final ProjectState state; final ProjectState state;
@@ -80,6 +90,7 @@ class ProjectSidebar extends ConsumerStatefulWidget {
} }
class _ProjectSidebarState extends ConsumerState<ProjectSidebar> { class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
bool _resourcesVisited = false;
bool get _touch => widget.experience != DeviceExperience.desktop; bool get _touch => widget.experience != DeviceExperience.desktop;
bool _projectHeaderHovered = false; bool _projectHeaderHovered = false;
String? _hoveredProjectId; String? _hoveredProjectId;
@@ -87,6 +98,30 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
final Set<String> _expandedConversationProjects = {}; final Set<String> _expandedConversationProjects = {};
final Set<String> _collapsedProjects = {}; final Set<String> _collapsedProjects = {};
bool _showTrash = false; bool _showTrash = false;
late final ValueNotifier<String?> _projectSelection;
final _groupWidgets = <String, (Object, Widget)>{};
@override
void initState() {
super.initState();
_resourcesVisited = widget.resourcesSelected;
_projectSelection = ValueNotifier(widget.selectedProjectId);
}
@override
void didUpdateWidget(covariant ProjectSidebar oldWidget) {
super.didUpdateWidget(oldWidget);
_resourcesVisited |= widget.resourcesSelected;
_projectSelection.value = widget.selectedProjectId;
final ids = widget.state.recent.map((project) => project.id).toSet();
_groupWidgets.removeWhere((id, _) => !ids.contains(id));
}
@override
void dispose() {
_projectSelection.dispose();
super.dispose();
}
ConversationSidebar get _conversations => ConversationSidebar get _conversations =>
ref.read(conversationSidebarProvider.notifier); ref.read(conversationSidebarProvider.notifier);
@@ -98,11 +133,8 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
} }
Map<String, List<ConversationMetadata>> get _conversationsByProject => Map<String, List<ConversationMetadata>> get _conversationsByProject =>
_snapshot.groups; ref.read(conversationSidebarProvider).value?.groups ?? const {};
List<ConversationMetadata> get _trashed => _snapshot.trashed; List<ConversationMetadata> get _trashed => _snapshot.trashed;
String? get _selectedConversationId => ref
.read(conversationSelectionProvider(widget.state.activeProject?.id))
.selectedId;
String? get _conversationError => String? get _conversationError =>
(ref.read(conversationSidebarProvider).hasError || _snapshot.reloadFailed) (ref.read(conversationSidebarProvider).hasError || _snapshot.reloadFailed)
? context.l10n.agentSessionRestoreFailed ? context.l10n.agentSessionRestoreFailed
@@ -253,9 +285,9 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
await _conversations.delete(item); await _conversations.delete(item);
} catch (_) { } catch (_) {
if (mounted) { if (mounted) {
ScaffoldMessenger.of( ErrorNotificationHost.of(
context, context,
).showSnackBar(SnackBar(content: Text(context.l10n.operationFailed))); ).show(ErrorNotification(content: Text(context.l10n.operationFailed)));
} }
} }
} }
@@ -293,10 +325,19 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
) == ) ==
true; true;
Widget _conversationRow(ConversationMetadata item) { Widget _conversationRow(ConversationMetadata item) => Consumer(
builder: (context, ref, _) {
final active = ref.watch(
projectsProvider.select(
(value) => value.value?.activeProject?.id == item.projectId,
),
);
final selected = final selected =
widget.state.activeProject?.id == item.projectId && ref.watch(
_selectedConversationId == item.id; conversationSelectionProvider(item.projectId)
.select((value) => value.selectedId == item.id),
) &&
active;
List<Widget> actions(BuildContext context) => [ List<Widget> actions(BuildContext context) => [
AppMenuItem( AppMenuItem(
label: context.l10n.rename, label: context.l10n.rename,
@@ -370,9 +411,38 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
), ),
), ),
); );
} },
);
Widget _projectGroup(RecentProject project) { Widget _projectGroup(RecentProject project) {
final configuration = (
project,
_touch,
Localizations.localeOf(context),
Theme.of(context),
_expandedConversationProjects.contains(project.id),
_collapsedProjects.contains(project.id),
_hoveredProjectId == project.id,
widget.state.projectBusy,
);
final cached = _groupWidgets[project.id];
if (cached?.$1 == configuration) return cached!.$2;
final group = Consumer(
key: ValueKey('sidebar-project-binding-${project.id}'),
builder: (context, ref, _) {
ref.watch(
conversationSidebarProvider.select(
(value) => value.value?.groups[project.id],
),
);
return _buildProjectGroup(project);
},
);
_groupWidgets[project.id] = (configuration, group);
return group;
}
Widget _buildProjectGroup(RecentProject project) {
final conversations = _conversationsByProject[project.id] ?? const []; final conversations = _conversationsByProject[project.id] ?? const [];
final expanded = _expandedConversationProjects.contains(project.id); final expanded = _expandedConversationProjects.contains(project.id);
final collapsed = _collapsedProjects.contains(project.id); final collapsed = _collapsedProjects.contains(project.id);
@@ -382,6 +452,7 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
? conversations ? conversations
: conversations.take(5); : conversations.take(5);
return Column( return Column(
key: ValueKey('sidebar-project-group-${project.id}'),
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
MouseRegion( MouseRegion(
@@ -391,10 +462,13 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
setState(() => _hoveredProjectId = null); setState(() => _hoveredProjectId = null);
} }
}, },
child: _touch child: ListenableSelector(
listenable: _projectSelection,
select: () => _projectSelection.value == project.id,
builder: (context, selected) => _touch
? TouchProjectTile( ? TouchProjectTile(
project: project, project: project,
selected: widget.selectedProjectId == project.id, selected: selected,
expanded: !collapsed, expanded: !collapsed,
availabilityLabel: _availabilityLabel( availabilityLabel: _availabilityLabel(
context, context,
@@ -409,7 +483,8 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
} }
}), }),
onNewConversation: onNewConversation:
widget.state.projectBusy || !project.availability.canOpen widget.state.projectBusy ||
!project.availability.canOpen
? null ? null
: () => _newConversationForProject(project), : () => _newConversationForProject(project),
onRename: project.availability.canOpen onRename: project.availability.canOpen
@@ -423,7 +498,7 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
padding: AppSidebarMetrics.rowPadding, padding: AppSidebarMetrics.rowPadding,
child: _ProjectTile( child: _ProjectTile(
project: project, project: project,
active: widget.selectedProjectId == project.id, active: selected,
availabilityLabel: _availabilityLabel( availabilityLabel: _availabilityLabel(
context, context,
project.availability, project.availability,
@@ -451,6 +526,7 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
), ),
), ),
), ),
),
for (final item in visible) ...[ for (final item in visible) ...[
const SizedBox(height: AppSidebarMetrics.rowGap), const SizedBox(height: AppSidebarMetrics.rowGap),
_conversationRow(item), _conversationRow(item),
@@ -516,18 +592,21 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
ref.watch(conversationSidebarProvider);
ref.watch(conversationSelectionProvider(widget.state.activeProject?.id));
final compact = MediaQuery.sizeOf(context).height < 520; final compact = MediaQuery.sizeOf(context).height < 520;
final headerHeight = widget.navigationOnly final headerHeight = widget.externalWindowFrame
? 0.0
: widget.navigationOnly
? 48.0 ? 48.0
: widget.integratedTitlebar : widget.integratedTitlebar
? AppControlSize.panelHeader ? AppControlSize.panelHeader
: AppControlSize.headerButton; : AppControlSize.headerButton;
final modeTop = headerHeight; final modeTop = headerHeight;
final modeHeader = SizedBox( final modeHeader = SizedBox(
key: const Key('project-content-header'),
height: height:
modeTop + AppSidebarMetrics.modeHeight + AppSidebarMetrics.sectionGap, modeTop +
(_touch ? AppSidebarMetrics.modeHeight : 0) +
(widget.externalWindowFrame ? 0 : AppSidebarMetrics.sectionGap),
child: Stack( child: Stack(
children: [ children: [
Positioned( Positioned(
@@ -554,6 +633,7 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
), ),
), ),
), ),
if (_touch)
Positioned( Positioned(
top: modeTop, top: modeTop,
left: AppSidebarMetrics.outerPadding, left: AppSidebarMetrics.outerPadding,
@@ -656,9 +736,9 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
onEnter: (_) => setState(() => _projectHeaderHovered = true), onEnter: (_) => setState(() => _projectHeaderHovered = true),
onExit: (_) => setState(() => _projectHeaderHovered = false), onExit: (_) => setState(() => _projectHeaderHovered = false),
child: Padding( child: Padding(
padding: const EdgeInsets.fromLTRB( padding: EdgeInsets.fromLTRB(
AppSidebarMetrics.outerPadding, AppSidebarMetrics.outerPadding,
0, _touch ? 0 : AppSpacing.gap,
AppSidebarMetrics.outerPadding, AppSidebarMetrics.outerPadding,
AppSidebarMetrics.sectionGap, AppSidebarMetrics.sectionGap,
), ),
@@ -692,17 +772,35 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
if (index > 0) const SizedBox(height: AppSidebarMetrics.projectGap), if (index > 0) const SizedBox(height: AppSidebarMetrics.projectGap),
_projectGroup(widget.state.recent[index]), _projectGroup(widget.state.recent[index]),
], ],
if (_conversationError != null) Consumer(
Padding( builder: (context, ref, _) {
ref.watch(
conversationSidebarProvider.select(
(value) => (value.hasError, value.value?.reloadFailed),
),
);
return _conversationError == null
? const SizedBox.shrink()
: Padding(
padding: const EdgeInsets.all(AppSpacing.small), padding: const EdgeInsets.all(AppSpacing.small),
child: Text( child: Text(
_conversationError!, _conversationError!,
style: Theme.of(context).textTheme.bodySmall, style: Theme.of(context).textTheme.bodySmall,
), ),
);
},
), ),
if (widget.state.activeProject != null && Consumer(
(_trashed.isNotEmpty || _showTrash)) builder: (context, ref, _) {
ExpansionTile( ref.watch(
conversationSidebarProvider.select(
(value) => (value.value?.projectId, value.value?.trashed),
),
);
return widget.state.activeProject == null ||
(_trashed.isEmpty && !_showTrash)
? const SizedBox.shrink()
: ExpansionTile(
title: Text( title: Text(
context.l10n.agentTrash, context.l10n.agentTrash,
style: AppSidebarTypography.style( style: AppSidebarTypography.style(
@@ -712,7 +810,8 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
), ),
), ),
initiallyExpanded: _showTrash, initiallyExpanded: _showTrash,
onExpansionChanged: (value) => setState(() => _showTrash = value), onExpansionChanged: (value) =>
setState(() => _showTrash = value),
trailing: _trashed.isEmpty trailing: _trashed.isEmpty
? null ? null
: TextButton( : TextButton(
@@ -756,7 +855,9 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
PopupMenuItem( PopupMenuItem(
height: AppMenuMetrics.rowHeight, height: AppMenuMetrics.rowHeight,
value: 'delete', value: 'delete',
child: Text(context.l10n.agentDeleteForever), child: Text(
context.l10n.agentDeleteForever,
),
), ),
], ],
), ),
@@ -764,6 +865,8 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
}, },
), ),
], ],
);
},
), ),
], ],
), ),
@@ -776,7 +879,28 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
crossAxisAlignment: CrossAxisAlignment.stretch, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [ children: [
modeHeader, modeHeader,
Expanded(child: projectList), Expanded(
child: _touch
? projectList
: IndexedStack(
index: widget.resourcesSelected ? 1 : 0,
children: [
TickerMode(
enabled: !widget.resourcesSelected,
child: projectList,
),
TickerMode(
enabled: widget.resourcesSelected,
child: _resourcesVisited
? MediaPanel(
projectId: widget.state.activeProject?.id,
onSelectProject: widget.onSelectProject,
)
: Center(child: Text(context.l10n.projectsNone)),
),
],
),
),
], ],
), ),
); );
@@ -0,0 +1,60 @@
import 'dart:async';
import 'package:flutter/widgets.dart';
/// Keeps the current content during short switches without delaying completion.
class ProjectSwitchRegion extends StatefulWidget {
const ProjectSwitchRegion({
super.key,
required this.pendingProjectId,
required this.builder,
});
final String? pendingProjectId;
final Widget Function(BuildContext context, bool showDefaults) builder;
@override
State<ProjectSwitchRegion> createState() => _ProjectSwitchRegionState();
}
class _ProjectSwitchRegionState extends State<ProjectSwitchRegion> {
Timer? _timer;
bool _showDefaults = false;
@override
void initState() {
super.initState();
_reset();
}
@override
void didUpdateWidget(covariant ProjectSwitchRegion oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.pendingProjectId != widget.pendingProjectId) _reset();
}
void _reset() {
_timer?.cancel();
_showDefaults = false;
if (widget.pendingProjectId != null) {
_timer = Timer(const Duration(milliseconds: 150), () {
if (mounted) setState(() => _showDefaults = true);
});
}
}
@override
Widget build(BuildContext context) => ExcludeFocus(
excluding: widget.pendingProjectId != null,
child: IgnorePointer(
ignoring: widget.pendingProjectId != null,
child: widget.builder(context, _showDefaults),
),
);
@override
void dispose() {
_timer?.cancel();
super.dispose();
}
}
+287 -205
View File
@@ -1,3 +1,4 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:cutdex/errors/app_failure.dart'; import 'package:cutdex/errors/app_failure.dart';
import 'dart:async'; import 'dart:async';
@@ -7,9 +8,12 @@ import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../app/adaptive/desktop_workspace_controller.dart'; import '../../app/adaptive/desktop_workspace_controller.dart';
import '../../app/adaptive/desktop_content_controller.dart';
import '../settings/settings_content.dart';
import '../../app/adaptive/workspace_layout_policy.dart'; import '../../app/adaptive/workspace_layout_policy.dart';
import '../../app/shells/phone_workspace_shell.dart'; import '../../app/shells/phone_workspace_shell.dart';
import '../../app/shells/desktop_workspace_shell.dart'; import '../../app/shells/desktop_workspace_shell.dart';
import '../../app/shells/desktop_window_frame.dart';
import '../../app/shells/tablet_workspace_shell.dart'; import '../../app/shells/tablet_workspace_shell.dart';
import '../../integrations/platform/device_experience.dart'; import '../../integrations/platform/device_experience.dart';
import '../../integrations/platform/editor_window_chrome.dart'; import '../../integrations/platform/editor_window_chrome.dart';
@@ -30,8 +34,9 @@ import '../../workspace/workspace_session_scope.dart';
import '../assistant/workspace_agent_surface.dart'; import '../assistant/workspace_agent_surface.dart';
import '../editor/background_tasks_button.dart'; import '../editor/background_tasks_button.dart';
import '../editor/editor_page.dart'; import '../editor/editor_page.dart';
import '../settings/settings_dialog.dart'; import '../settings/settings_page.dart';
import 'editor_loading_region.dart'; import 'editor_loading_region.dart';
import 'project_switch_region.dart';
import 'project_sidebar.dart'; import 'project_sidebar.dart';
import 'widgets/name_dialog.dart'; import 'widgets/name_dialog.dart';
@@ -103,7 +108,7 @@ class _EditingPageState extends ConsumerState<EditingPage> {
if (!created && context.mounted) { if (!created && context.mounted) {
final error = ref.read(projectsProvider).value?.error; final error = ref.read(projectsProvider).value?.error;
if (error?.requiresProjectLocation == true) { if (error?.requiresProjectLocation == true) {
await showSettingsDialog(context); await showSettingsPage(context);
} }
} }
return; return;
@@ -113,10 +118,13 @@ class _EditingPageState extends ConsumerState<EditingPage> {
.pickDirectory(confirmButtonText: context.l10n.openProject); .pickDirectory(confirmButtonText: context.l10n.openProject);
if (directory == null || !context.mounted) return; if (directory == null || !context.mounted) return;
await ref.read(projectsProvider.notifier).open(directory); await ref.read(projectsProvider.notifier).open(directory);
} catch (_) { } catch (error) {
if (context.mounted) { if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar( ErrorNotificationHost.of(context).show(
SnackBar(content: Text(context.l10n.selectDirectoryFailed)), ErrorNotification(
content: Text(context.l10n.selectDirectoryFailed),
details: error.toString(),
),
); );
} }
} }
@@ -174,10 +182,11 @@ class _EditingPageState extends ConsumerState<EditingPage> {
ref.watch(workspaceNavigationProvider); ref.watch(workspaceNavigationProvider);
final experience = ref.watch(deviceExperienceProvider); final experience = ref.watch(deviceExperienceProvider);
final desktop = experience == DeviceExperience.desktop; final desktop = experience == DeviceExperience.desktop;
final contentSelection = ref.watch(desktopContentProvider);
final projects = ref.watch(projectsProvider); final projects = ref.watch(projectsProvider);
final state = projects.value ?? const ProjectState(); final state = projects.value ?? const ProjectState();
return EditorWindowChrome( return EditorWindowChrome(
headerHeight: desktop ? AppControlSize.panelHeader : 48, headerHeight: desktop ? DesktopWindowFrame.headerHeight : 48,
builder: (context, integrated) => Scaffold( builder: (context, integrated) => Scaffold(
body: SafeArea( body: SafeArea(
top: !integrated, top: !integrated,
@@ -195,21 +204,77 @@ class _EditingPageState extends ConsumerState<EditingPage> {
final navigationHiddenBySpace = final navigationHiddenBySpace =
desktop && desktop &&
!WorkspaceLayoutPolicy.desktopNavigationFits( !WorkspaceLayoutPolicy.desktopNavigationFits(
constraints.maxWidth, constraints.maxWidth -
DesktopWindowFrame.railWidth -
DesktopWindowFrame.contentInset,
); );
final navigationCollapsed = final navigationCollapsed =
_sidebarCollapsed || navigationHiddenBySpace; _sidebarCollapsed || navigationHiddenBySpace;
Widget controlSlot(Widget child) {
if (!desktop) {
return SizedBox.square(
dimension: 48,
child: child,
);
}
const buttonSize = AppControlSize.headerButton;
return SizedBox(
width: buttonSize,
height: buttonSize,
child: Center(
child: IconButtonTheme(
data: IconButtonThemeData(
style: Theme.of(context)
.iconButtonTheme
.style
?.copyWith(
fixedSize:
const WidgetStatePropertyAll(
Size.square(buttonSize),
),
minimumSize:
const WidgetStatePropertyAll(
Size.square(buttonSize),
),
maximumSize:
const WidgetStatePropertyAll(
Size.square(buttonSize),
),
padding:
const WidgetStatePropertyAll(
EdgeInsets.zero,
),
tapTargetSize: MaterialTapTargetSize
.shrinkWrap,
),
),
child: SizedBox.square(
dimension: buttonSize,
child: child,
),
),
),
);
}
Widget controls({ Widget controls({
bool navigationToggle = true, bool navigationToggle = true,
}) => HeaderControlRegion( }) => HeaderControlRegion(
child: Padding(
padding: EdgeInsets.only(
left: desktop
? (DesktopWindowFrame.railWidth -
AppControlSize.headerButton) /
2
: 0,
),
child: Row( child: Row(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
spacing: AppSpacing.tiny, spacing: AppSpacing.tiny,
children: [ children: [
if (navigationToggle) if (navigationToggle)
SizedBox.square( controlSlot(
dimension: AppControlSize.headerButton, IconButton(
child: IconButton(
key: const Key( key: const Key(
'project-sidebar-toggle', 'project-sidebar-toggle',
), ),
@@ -235,80 +300,42 @@ class _EditingPageState extends ConsumerState<EditingPage> {
), ),
), ),
), ),
if (desktop && if (!desktop)
navigationCollapsed &&
navigationToggle)
PopupMenuButton<WorkspaceMode>(
key: const Key('desktop-workspace-mode'),
initialValue: _mode,
onSelected: _setMode,
itemBuilder: (context) => [
for (final mode in WorkspaceMode.values)
PopupMenuItem(
key: ValueKey(
'desktop-mode-${mode.name}',
),
value: mode,
child: Text(
mode == WorkspaceMode.agent
? context.l10n.workspaceAgent
: context.l10n.workspaceCut,
),
),
],
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 6,
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(
_mode == WorkspaceMode.agent
? context.l10n.workspaceAgent
: context.l10n.workspaceCut,
),
const Icon(
Icons.keyboard_arrow_down,
size: 16,
),
],
),
),
),
SizedBox.square( SizedBox.square(
dimension: desktop dimension: desktop
? AppControlSize.headerButton ? AppControlSize.headerButton
: 48, : 48,
child: IconButton( child: IconButton(
key: const Key('project-settings-button'), key: const Key(
'project-settings-button',
),
tooltip: context.l10n.settings, tooltip: context.l10n.settings,
onPressed: () => onPressed: () =>
showSettingsDialog(context), showSettingsPage(context),
style: sidebarActionButtonStyle(context), style: sidebarActionButtonStyle(
context,
),
icon: const Icon( icon: const Icon(
Icons.settings_outlined, Icons.settings_outlined,
size: AppIconSize.header, size: AppIconSize.header,
), ),
), ),
), ),
SizedBox.square( controlSlot(const BackgroundTasksButton()),
dimension: desktop
? AppControlSize.headerButton
: 48,
child: const BackgroundTasksButton(),
),
], ],
), ),
),
); );
Widget leading() => Row( Widget leading() => Row(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
if (navigationCollapsed && integrated) if (!desktop &&
navigationCollapsed &&
integrated)
SizedBox( SizedBox(
width: EditorWindowChrome.leadingWidth, width: EditorWindowChrome.leadingWidth,
), ),
if (navigationCollapsed) controls(), if (!desktop && navigationCollapsed) controls(),
const SizedBox(width: AppSpacing.compact), const SizedBox(width: AppSpacing.compact),
], ],
); );
@@ -330,19 +357,43 @@ class _EditingPageState extends ConsumerState<EditingPage> {
onCreateProject: () => onCreateProject: () =>
_selectProject(context, ref, create: true), _selectProject(context, ref, create: true),
); );
void selectSidebar(bool resources) {
ref
.read(desktopContentProvider.notifier)
.select(
resources
? DesktopContent.library
: DesktopContent.workspace,
);
setState(() => _sidebarCollapsed = false);
_saveViewState();
if (navigationHiddenBySpace) {
WidgetsBinding.instance.addPostFrameCallback((
_,
) {
if (mounted) {
_desktopScaffoldKey.currentState
?.openDrawer();
}
});
}
}
Widget navigation({ Widget navigation({
DesktopWorkspaceGeometry? geometry, DesktopWorkspaceGeometry? geometry,
VoidCallback? expandEditor, VoidCallback? expandEditor,
bool drawer = false, bool drawer = false,
}) => ProjectSidebar( }) => ProjectSidebar(
experience: experience, experience: experience,
resourcesSelected:
desktop && contentSelection.resourcesSelected,
key: drawer key: drawer
? _drawerNavigationKey ? _drawerNavigationKey
: _navigationKey, : _navigationKey,
agent: desktop && !drawer agent: desktop && !drawer
? agent ? agent
: const SizedBox.shrink(), : const SizedBox.shrink(),
navigationOnly: !desktop || drawer, navigationOnly: true,
onNavigationComplete: desktop && !drawer onNavigationComplete: desktop && !drawer
? null ? null
: () => Navigator.of(context).maybePop(), : () => Navigator.of(context).maybePop(),
@@ -359,14 +410,15 @@ class _EditingPageState extends ConsumerState<EditingPage> {
state: state, state: state,
selectedProjectId: selectedProjectId:
_selectedProjectId ?? state.activeProject?.id, _selectedProjectId ?? state.activeProject?.id,
integratedTitlebar: integrated, integratedTitlebar: !desktop && integrated,
externalWindowFrame: desktop && !drawer,
onCreateProject: () => onCreateProject: () =>
_selectProject(context, ref, create: true), _selectProject(context, ref, create: true),
onSelectProject: selectProject, onSelectProject: selectProject,
onRenameProject: (project) => onRenameProject: (project) =>
_renameProject(context, ref, project), _renameProject(context, ref, project),
headerControls: desktop && !drawer headerControls: desktop && !drawer
? controls() ? const SizedBox.shrink()
: HeaderControlRegion( : HeaderControlRegion(
child: Row( child: Row(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
@@ -386,41 +438,131 @@ class _EditingPageState extends ConsumerState<EditingPage> {
), ),
), ),
); );
final editor = ProjectLoadingRegion( final pendingProject = _switchingProject
loading: _switchingProject, ? state.recent
child: .where(
state.activeProject != null && (item) => item.id == _selectedProjectId,
state.timeline != null )
.firstOrNull
: null;
final projectLoading =
pendingProject != null &&
pendingProject.id != state.activeProject?.id;
final editor = ProjectSwitchRegion(
pendingProjectId: projectLoading
? pendingProject.id
: null,
builder: (context, showDefaults) {
final displayDefaults =
projectLoading && showDefaults;
final visibleProject = displayDefaults
? pendingProject
: state.activeProject;
return visibleProject != null &&
(displayDefaults ||
state.timeline != null)
? EditorWorkspace( ? EditorWorkspace(
key: _editorKey, key: _editorKey,
experience: experience, experience: experience,
projectId: state.activeProject!.id, projectId: visibleProject.id,
timelineId: state.timeline!.id, timelineId: displayDefaults
projectName: state.activeProject!.name, ? ''
: state.timeline!.id,
projectName: visibleProject.name,
projectLoading: displayDefaults,
showProjectName: showProjectName:
desktop && _mode == WorkspaceMode.cut, desktop &&
integratedTitlebar: desktop && integrated, _mode == WorkspaceMode.cut,
headerLeading: integratedTitlebar: false,
desktop && _mode == WorkspaceMode.cut headerLeading: desktop
? leading() ? const SizedBox.shrink()
: const SizedBox( : const SizedBox(
width: AppSpacing.compact, width: AppSpacing.compact,
), ),
) )
: EmptyEditor( : EmptyEditor(
desktop: desktop,
state: state, state: state,
showProjectName: showProjectName:
desktop && _mode == WorkspaceMode.cut, desktop &&
headerLeading: _mode == WorkspaceMode.cut,
desktop && _mode == WorkspaceMode.cut headerLeading: desktop
? leading() ? const SizedBox.shrink()
: const SizedBox( : const SizedBox(
width: AppSpacing.compact, width: AppSpacing.compact,
), ),
);
},
);
Widget contentSurface(
DesktopContent surface,
Widget child,
) => ExcludeFocus(
excluding:
(contentSelection.surface ==
DesktopContent.settings) !=
(surface == DesktopContent.settings),
child: TickerMode(
enabled:
(contentSelection.surface ==
DesktopContent.settings) ==
(surface == DesktopContent.settings),
child: child,
), ),
); );
Widget desktopContents(
Widget workspace,
) => IndexedStack(
index:
contentSelection.surface ==
DesktopContent.settings
? 1
: 0,
children: [
contentSurface(
DesktopContent.workspace,
workspace,
),
contentSurface(
DesktopContent.settings,
contentSelection.settingsVisited
? SizedBox(
key: const Key(
'desktop-settings-workspace',
),
child: SettingsContent(
cardLayout: true,
initialTab:
contentSelection.settingsTab,
navigationRequest: contentSelection
.settingsRequest,
workspace:
contentSelection.workspace,
),
)
: const SizedBox.shrink(),
),
],
);
return switch (experience) { return switch (experience) {
DeviceExperience.desktop => DesktopWorkspaceShell( DeviceExperience.desktop => DesktopWindowFrame(
integratedTitlebar: integrated,
headerControls: controls(),
librarySelected:
contentSelection.surface ==
DesktopContent.library,
settingsSelected:
contentSelection.surface ==
DesktopContent.settings,
onModeChanged: (mode) {
selectSidebar(false);
_setMode(mode);
},
onLibraryPressed: () => selectSidebar(true),
onSettingsPressed: () =>
showSettingsPage(context),
child: desktopContents(
DesktopWorkspaceShell(
controller: _desktopSplits, controller: _desktopSplits,
scaffoldKey: _desktopScaffoldKey, scaffoldKey: _desktopScaffoldKey,
navigationDrawer: navigation(drawer: true), navigationDrawer: navigation(drawer: true),
@@ -440,8 +582,67 @@ class _EditingPageState extends ConsumerState<EditingPage> {
geometry: geometry, geometry: geometry,
expandEditor: expand, expandEditor: expand,
), ),
agentBuilder: (geometry, expand) => Column(
children: [
SizedBox(
key: const Key(
'agent-content-header',
),
height: AppControlSize.panelToolbar,
child: Padding(
padding: const EdgeInsets.all(
AppSpacing.gap,
),
child: Row(
children: [
const Spacer(),
HeaderControlRegion(
child: SizedBox.square(
dimension: AppControlSize
.headerButton,
child: IconButton(
key: const Key(
'agent-fullscreen-button',
),
isSelected:
geometry.editorHidden,
tooltip:
geometry.editorHidden
? context
.l10n
.exitPreviewFullscreen
: context
.l10n
.agentFullscreen,
onPressed:
geometry.editorHidden
? expand
: () => _desktopSplits
.setAgentFullscreen(
true,
),
icon: Icon(
size:
AppIconSize.header,
geometry.editorHidden
? Icons
.fullscreen_exit
: Icons.fullscreen,
),
),
),
),
],
),
),
),
Expanded(child: agent),
],
),
editor: editor, editor: editor,
), ),
),
),
DeviceExperience.tablet => TabletWorkspaceShell( DeviceExperience.tablet => TabletWorkspaceShell(
mode: _mode, mode: _mode,
onModeChanged: _setMode, onModeChanged: _setMode,
@@ -472,10 +673,11 @@ class _EditingPageState extends ConsumerState<EditingPage> {
PositionedDirectional( PositionedDirectional(
top: AppSpacing.compact, top: AppSpacing.compact,
end: AppSpacing.compact, end: AppSpacing.compact,
child: _SonnerErrorToast( child: ErrorFailureListener(
message: projects.hasError message: projects.hasError
? const AppFailure( ? AppFailure(
AppErrorCode.loadProjectsFailed, AppErrorCode.loadProjectsFailed,
diagnostic: projects.error.toString(),
) )
: state.error, : state.error,
), ),
@@ -542,123 +744,3 @@ class _StartupLoadingState extends State<_StartupLoading>
), ),
); );
} }
class _SonnerErrorToast extends StatefulWidget {
const _SonnerErrorToast({required this.message});
final AppFailure? message;
@override
State<_SonnerErrorToast> createState() => _SonnerErrorToastState();
}
class _SonnerErrorToastState extends State<_SonnerErrorToast> {
static const _displayDuration = Duration(seconds: 6);
Timer? _timer;
AppFailure? _displayedMessage;
bool _visible = false;
@override
void initState() {
super.initState();
_show(widget.message);
}
@override
void didUpdateWidget(covariant _SonnerErrorToast oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.message != null &&
(oldWidget.message == null || widget.message != oldWidget.message)) {
_show(widget.message);
}
}
void _show(AppFailure? message) {
if (message == null) return;
_timer?.cancel();
_displayedMessage = message;
_visible = true;
_timer = Timer(_displayDuration, _hide);
}
void _hide() {
if (mounted) setState(() => _visible = false);
}
@override
void dispose() {
_timer?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
final message = _displayedMessage;
if (message == null) return const SizedBox.shrink();
final theme = Theme.of(context);
return IgnorePointer(
ignoring: !_visible,
child: AnimatedSlide(
offset: _visible ? Offset.zero : const Offset(0.08, 0),
duration: const Duration(milliseconds: 180),
curve: Curves.easeOutCubic,
child: AnimatedOpacity(
opacity: _visible ? 1 : 0,
duration: const Duration(milliseconds: 160),
child: Semantics(
liveRegion: true,
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 360),
child: DecoratedBox(
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHigh,
border: Border.all(color: theme.colorScheme.outlineVariant),
borderRadius: BorderRadius.circular(AppRadius.large),
boxShadow: [
BoxShadow(
color: theme.colorScheme.shadow.withValues(alpha: .25),
blurRadius: 16,
offset: const Offset(0, 6),
),
],
),
child: Padding(
padding: const EdgeInsetsDirectional.only(
start: AppSpacing.compact,
top: AppSpacing.small,
bottom: AppSpacing.small,
end: AppSpacing.tiny,
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.error_outline,
size: AppIconSize.small,
color: theme.colorScheme.error,
),
const SizedBox(width: AppSpacing.small),
Flexible(
child: Text(
context.l10n.failureMessage(message),
style: theme.textTheme.bodyMedium,
),
),
IconButton(
tooltip: MaterialLocalizations.of(context)
.closeButtonTooltip,
onPressed: _hide,
icon: const Icon(Icons.close, size: AppIconSize.small),
),
],
),
),
),
),
),
),
),
);
}
}
@@ -1,3 +1,4 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:cutdex/l10n/l10n.dart'; import 'package:cutdex/l10n/l10n.dart';
import 'package:cutdex_sdk/editor.dart'; import 'package:cutdex_sdk/editor.dart';
import 'package:cutdex_sdk/timeline/model.dart'; import 'package:cutdex_sdk/timeline/model.dart';
@@ -54,8 +55,8 @@ class _CaptionPropertiesState extends State<CaptionProperties> {
widget.session.setCaption(widget.sequence, command); widget.session.setCaption(widget.sequence, command);
return true; return true;
} on CommandRejected catch (error) { } on CommandRejected catch (error) {
ScaffoldMessenger.maybeOf(context)?.showSnackBar( ErrorNotificationHost.maybeOf(context)?.show(
SnackBar( ErrorNotification(
content: Text( content: Text(
error.code == 'staleVersion' error.code == 'staleVersion'
? context.l10n.captionEditChanged ? context.l10n.captionEditChanged
@@ -487,10 +488,8 @@ class _CaptionPropertiesState extends State<CaptionProperties> {
), ),
); );
} on CommandRejected { } on CommandRejected {
ScaffoldMessenger.maybeOf( ErrorNotificationHost.maybeOf(context)?.show(
context, ErrorNotification(
)?.showSnackBar(
SnackBar(
content: Text(context.l10n.captionChanged), content: Text(context.l10n.captionChanged),
), ),
); );
+11 -5
View File
@@ -1,3 +1,5 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'dart:math' as math; import 'dart:math' as math;
import 'package:cutdex_sdk/editor.dart'; import 'package:cutdex_sdk/editor.dart';
@@ -120,9 +122,12 @@ class _SpeedPropertiesState extends State<SpeedProperties> {
void _showError(Object error) { void _showError(Object error) {
if (!mounted) return; if (!mounted) return;
ScaffoldMessenger.of( ErrorNotificationHost.of(context).show(
context, ErrorNotification(
).showSnackBar(SnackBar(content: Text(context.l10n.errorMessage(error)))); content: Text(context.l10n.errorMessage(error)),
details: error.toString(),
),
);
} }
@override @override
@@ -292,9 +297,10 @@ class _SpeedPropertiesState extends State<SpeedProperties> {
localPlayhead, localPlayhead,
); );
} catch (error) { } catch (error) {
ScaffoldMessenger.of(context).showSnackBar( ErrorNotificationHost.of(context).show(
SnackBar( ErrorNotification(
content: Text(context.l10n.errorMessage(error)), content: Text(context.l10n.errorMessage(error)),
details: error.toString(),
), ),
); );
} }
@@ -1,3 +1,4 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:freezed_annotation/freezed_annotation.dart'; import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart';
@@ -86,9 +87,9 @@ class _AgentSettingsPanelState extends ConsumerState<AgentSettingsPanel>
} }
} }
void _showSaveError() => ScaffoldMessenger.of( void _showSaveError() => ErrorNotificationHost.of(context).show(
context, ErrorNotification(content: Text(context.l10n.agentSaveSettingsFailed)),
).showSnackBar(SnackBar(content: Text(context.l10n.agentSaveSettingsFailed))); );
Future<void> _setProviderEnabled( Future<void> _setProviderEnabled(
AgentProviderSettings provider, AgentProviderSettings provider,
+537
View File
@@ -0,0 +1,537 @@
import 'package:cutdex/l10n/l10n.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../integrations/platform/file_picker.dart';
import '../../shared/widgets/workspace_card.dart';
import '../../shared/layout/workspace_layout_metrics.dart';
import '../../workspace/persistence/project_location_directory.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import 'appearance_settings.dart';
import 'language_settings.dart';
import 'location_settings.dart';
import 'mcp_settings_panel.dart';
import 'settings_layout.dart';
import '../../settings/settings_operation.dart';
import 'update_settings.dart';
import 'diagnostic_settings.dart';
import 'agent_settings_panel.dart';
const _settingsContentPadding = EdgeInsets.fromLTRB(20, 48, 20, 20);
class SettingsContent extends ConsumerStatefulWidget {
const SettingsContent({
super.key,
this.workspace,
this.initialTab = 0,
this.navigationRequest = 0,
this.cardLayout = false,
}) : assert(initialTab >= 0 && initialTab <= 2);
final int initialTab;
final int navigationRequest;
final bool cardLayout;
final (String, String)? workspace;
@override
ConsumerState<SettingsContent> createState() => _SettingsContentState();
}
class _SettingsContentState extends ConsumerState<SettingsContent> {
late int _tab = widget.initialTab;
Widget _surface(String name, Widget child) => widget.cardLayout
? WorkspaceCard(key: Key('settings-$name-card'), child: child)
: child;
@override
void didUpdateWidget(covariant SettingsContent oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.initialTab != oldWidget.initialTab ||
widget.navigationRequest != oldWidget.navigationRequest) {
_tab = widget.initialTab;
}
}
Future<void> _setMode(AppAppearance appearance) async {
await ref
.read(settingsOperationProvider('appearance').notifier)
.run(
() =>
ref.read(appearanceSettingsProvider.notifier).setMode(appearance),
);
}
Future<void> _setLanguage(AppLanguage language) async {
await ref
.read(settingsOperationProvider('language').notifier)
.run(
() =>
ref.read(languageSettingsProvider.notifier).setLanguage(language),
);
}
@override
Widget build(BuildContext context) => Theme(
data: AppTheme.settingsContentTheme(Theme.of(context)),
child: Builder(builder: _buildContent),
);
Widget _buildContent(BuildContext context) {
final appearanceSave = ref.watch(settingsOperationProvider('appearance'));
final languageSave = ref.watch(settingsOperationProvider('language'));
final appearance = ref.watch(appearanceSettingsProvider);
final language = ref.watch(languageSettingsProvider);
return LayoutBuilder(
builder: (context, constraints) => Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SizedBox(
width: constraints.maxWidth < 600
? 96
: widget.cardLayout
? WorkspaceLayoutMetrics.sidebarDefaultWidth
: 220,
child: _surface(
'navigation',
_SettingsNavigation(
value: _tab,
compact: constraints.maxWidth < 600,
onChanged: (value) => setState(() => _tab = value),
),
),
),
if (widget.cardLayout)
const SizedBox(
key: Key('settings-card-gap'),
width: WorkspaceLayoutMetrics.desktopSpacing,
)
else
VerticalDivider(
key: const Key('settings-sidebar-divider'),
width: 1,
thickness: 1,
color: Theme.of(context).colorScheme.outlineVariant,
),
Expanded(
child: _surface(
'content',
ColoredBox(
color: Theme.of(context).colorScheme.surface,
child: IndexedStack(
index: _tab,
children: [
ExcludeFocus(
excluding: _tab != 0,
child: TickerMode(
enabled: _tab == 0,
child: SingleChildScrollView(
primary: false,
padding: _settingsContentPadding,
child: SettingsPageSection(
title: context.l10n.general,
icon: Icons.settings_outlined,
children: [
AppField(
label: context.l10n.appearance,
orientation: AppFieldOrientation.horizontal,
error:
(appearanceSave.hasError
? context.l10n.saveAppearanceFailed
: null) ??
(appearance.hasError
? context.l10n.loadAppearanceFailed
: null),
child: SizedBox(
width: AppSettingsMetrics.controlWidth,
child: AppSelect<AppAppearance>(
emptyLabel: context.l10n.noMatchingOptions,
controlHeight:
AppSettingsMetrics.controlHeight,
value:
appearance.asData?.value ??
AppAppearance.system,
label: context.l10n.theme,
options: [
AppSelectOption(
AppAppearance.system,
context.l10n.system,
),
AppSelectOption(
AppAppearance.penLight,
'Pen · ${context.l10n.light}',
),
AppSelectOption(
AppAppearance.penDark,
'Pen · ${context.l10n.dark}',
),
],
onChanged:
appearanceSave.isLoading ||
appearance.isLoading
? null
: _setMode,
),
),
),
AppField(
label: context.l10n.language,
orientation: AppFieldOrientation.horizontal,
error:
(languageSave.hasError
? context.l10n.saveLanguageFailed
: null) ??
(language.hasError
? context.l10n.loadLanguageFailed
: null),
child: SizedBox(
width: AppSettingsMetrics.controlWidth,
child: AppSelect<AppLanguage>(
emptyLabel: context.l10n.noMatchingOptions,
controlHeight:
AppSettingsMetrics.controlHeight,
value:
language.asData?.value ??
AppLanguage.system,
label: context.l10n.language,
options: [
for (final option in AppLanguage.values)
AppSelectOption(
option,
option == AppLanguage.system
? context.l10n.system
: option.nativeName,
),
],
onChanged:
languageSave.isLoading ||
language.isLoading
? null
: _setLanguage,
),
),
),
const _ProjectLocationField(),
const _ResourceLocationField(),
const UpdateSettings(),
const DiagnosticSettings(),
],
),
),
),
),
ExcludeFocus(
excluding: _tab != 1,
child: TickerMode(
enabled: _tab == 1,
child: const AgentSettingsPanel(
contentPadding: _settingsContentPadding,
),
),
),
ExcludeFocus(
excluding: _tab != 2,
child: TickerMode(
enabled: _tab == 2,
child: SingleChildScrollView(
primary: false,
padding: _settingsContentPadding,
child: McpSettingsPanel(workspace: widget.workspace),
),
),
),
],
),
),
),
),
],
),
);
}
}
class _SettingsNavigation extends StatelessWidget {
const _SettingsNavigation({
required this.value,
required this.compact,
required this.onChanged,
});
final int value;
final bool compact;
final ValueChanged<int> onChanged;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final entries = [
(context.l10n.general, Icons.settings_outlined),
(context.l10n.agentSettings, Icons.auto_awesome_outlined),
('MCP', Icons.terminal_outlined),
];
return ColoredBox(
key: const Key('settings-sidebar'),
color: AppTheme.settingsSidebarBackground(context),
child: ListView(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 16),
children: [
Padding(
padding: const EdgeInsets.fromLTRB(8, 0, 8, 20),
child: Text(
context.l10n.settings,
style: theme.textTheme.titleSmall?.copyWith(fontSize: 16),
),
),
for (var index = 0; index < entries.length; index++)
Padding(
padding: const EdgeInsets.only(bottom: 1),
child: Semantics(
selected: value == index,
child: Tooltip(
message: entries[index].$1,
child: TextButton(
key: ValueKey('settings-navigation-$index'),
onPressed: () => onChanged(index),
style: TextButton.styleFrom(
minimumSize: const Size(0, 30),
padding: const EdgeInsets.symmetric(horizontal: 8),
foregroundColor: theme.colorScheme.onSurface,
backgroundColor: value == index
? theme.colorScheme.onSurface.withValues(alpha: .078)
: Colors.transparent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
alignment: AlignmentDirectional.centerStart,
),
child: Row(
children: [
if (!compact) ...[
Icon(entries[index].$2, size: 16),
const SizedBox(width: 8),
],
Expanded(
child: Text(
entries[index].$1,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
),
),
),
),
),
],
),
);
}
}
class _ResourceLocationField extends ConsumerWidget {
const _ResourceLocationField();
Future<void> _choose(
BuildContext context,
WidgetRef ref,
String? initialDirectory,
) async {
final directory = await ref
.read(filePickerProvider)
.pickDirectory(
initialDirectory: initialDirectory,
confirmButtonText: context.l10n.select,
);
if (directory == null || !context.mounted) return;
await ref.read(resourceLocationSettingsProvider.notifier).save(directory);
}
@override
Widget build(BuildContext context, WidgetRef ref) {
final settings = ref.watch(resourceLocationSettingsProvider);
final error = switch (settings.error) {
LocationSettingsError.load => context.l10n.loadResourceLocationFailed,
LocationSettingsError.save => context.l10n.saveResourceLocationFailed,
null => null,
};
return AppField(
label: context.l10n.resourceLocation,
orientation: AppFieldOrientation.horizontal,
error: error,
child: SizedBox(
width: 420,
child: Row(
children: [
Expanded(
child: Tooltip(
message:
settings.directory ?? context.l10n.resourceLocationNotSet,
child: _MiddleEllipsisText(
settings.directory ?? context.l10n.resourceLocationNotSet,
key: const Key('resource-location-value'),
textAlign: TextAlign.right,
),
),
),
const SizedBox(width: AppSpacing.compact),
OutlinedButton(
key: const Key('choose-resource-location'),
onPressed: settings.loading || settings.saving
? null
: () => _choose(context, ref, settings.directory),
child: Text(context.l10n.modify),
),
],
),
),
);
}
}
class _ProjectLocationField extends ConsumerWidget {
const _ProjectLocationField();
Future<void> _choose(
BuildContext context,
WidgetRef ref,
String? initialDirectory,
) async {
final directory = await ref
.read(filePickerProvider)
.pickDirectory(
initialDirectory: initialDirectory,
confirmButtonText: context.l10n.select,
);
if (directory == null || !context.mounted) return;
await ref.read(projectLocationSettingsProvider.notifier).save(directory);
}
@override
Widget build(BuildContext context, WidgetRef ref) {
final settings = ref.watch(projectLocationSettingsProvider);
final error = switch (settings.error) {
LocationSettingsError.load => context.l10n.loadProjectLocationFailed,
LocationSettingsError.save => context.l10n.saveProjectLocationFailed,
null => null,
};
return AppField(
label: context.l10n.projectLocation,
orientation: AppFieldOrientation.horizontal,
description: settings.status == ProjectLocationStatus.missing
? context.l10n.projectLocationMissing
: null,
error:
error ??
switch (settings.status) {
ProjectLocationStatus.unavailable =>
context.l10n.projectLocationUnavailable,
ProjectLocationStatus.notWritable =>
context.l10n.projectLocationNotWritable,
_ => null,
},
child: SizedBox(
width: 420,
child: Row(
children: [
Expanded(
child: Tooltip(
message:
settings.directory ?? context.l10n.projectLocationNotSet,
child: _MiddleEllipsisText(
settings.directory ?? context.l10n.projectLocationNotSet,
key: const Key('project-location-value'),
textAlign: TextAlign.right,
),
),
),
const SizedBox(width: AppSpacing.compact),
if (error != null ||
settings.status == ProjectLocationStatus.unavailable ||
settings.status == ProjectLocationStatus.notWritable)
TextButton(
key: const Key('retry-project-location'),
onPressed: settings.loading || settings.saving
? null
: ref.read(projectLocationSettingsProvider.notifier).reload,
child: Text(context.l10n.retry),
),
OutlinedButton(
key: const Key('choose-project-location'),
onPressed: settings.loading || settings.saving
? null
: () => _choose(context, ref, settings.directory),
child: Text(context.l10n.modify),
),
],
),
),
);
}
}
class _MiddleEllipsisText extends StatelessWidget {
const _MiddleEllipsisText(
this.text, {
super.key,
this.textAlign = TextAlign.start,
});
final String text;
final TextAlign textAlign;
@override
Widget build(BuildContext context) {
final style = DefaultTextStyle.of(context).style;
final direction = Directionality.of(context);
return LayoutBuilder(
builder: (context, constraints) => Text(
_ellipsize(text, constraints.maxWidth, style, direction),
maxLines: 1,
textAlign: textAlign,
),
);
}
static String _ellipsize(
String value,
double maxWidth,
TextStyle style,
TextDirection direction,
) {
bool fits(String candidate) {
final painter = TextPainter(
text: TextSpan(text: candidate, style: style),
maxLines: 1,
textDirection: direction,
)..layout(maxWidth: maxWidth);
return !painter.didExceedMaxLines && painter.width <= maxWidth;
}
if (!maxWidth.isFinite || fits(value)) return value;
var low = 0;
var high = value.length;
while (low < high) {
final keep = (low + high + 1) ~/ 2;
final leading = (keep + 1) ~/ 2;
final candidate =
'${value.substring(0, leading)}…'
'${value.substring(value.length - (keep - leading))}';
if (fits(candidate)) {
low = keep;
} else {
high = keep - 1;
}
}
final leading = (low + 1) ~/ 2;
return '${value.substring(0, leading)}…'
'${value.substring(value.length - (low - leading))}';
}
}
+11 -499
View File
@@ -1,519 +1,31 @@
import 'package:cutdex/l10n/l10n.dart';
import 'dart:math' as math; import 'dart:math' as math;
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../integrations/platform/file_picker.dart';
import '../../workspace/persistence/project_location_directory.dart';
import 'package:cutdex_ui/theme.dart'; import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart'; import 'package:cutdex_ui/widgets.dart';
import 'appearance_settings.dart'; import '../../l10n/l10n.dart';
import 'language_settings.dart'; import 'settings_content.dart';
import 'location_settings.dart';
import 'mcp_settings_panel.dart';
import 'settings_layout.dart';
import '../../settings/settings_operation.dart';
import 'update_settings.dart';
import 'diagnostic_settings.dart';
import 'agent_settings_panel.dart';
const _settingsContentPadding = EdgeInsets.fromLTRB(20, 48, 20, 20);
Future<void> showSettingsDialog(
BuildContext context, {
(String, String)? workspace,
int initialTab = 0,
}) => showAppDialog<void>(
context: Navigator.of(context, rootNavigator: true).context,
builder: (_) => SettingsDialog(workspace: workspace, initialTab: initialTab),
);
class SettingsDialog extends ConsumerStatefulWidget {
const SettingsDialog({super.key, this.workspace, this.initialTab = 0})
: assert(initialTab >= 0 && initialTab <= 2);
final int initialTab;
/// Dialog adapter for embedded settings hosts.
class SettingsDialog extends StatelessWidget {
const SettingsDialog({super.key, this.workspace, this.initialTab = 0});
final (String, String)? workspace; final (String, String)? workspace;
final int initialTab;
@override @override
ConsumerState<SettingsDialog> createState() => _SettingsDialogState(); Widget build(BuildContext context) {
}
class _SettingsDialogState extends ConsumerState<SettingsDialog> {
late int _tab = widget.initialTab;
Future<void> _setMode(AppAppearance appearance) async {
await ref
.read(settingsOperationProvider('appearance').notifier)
.run(
() =>
ref.read(appearanceSettingsProvider.notifier).setMode(appearance),
);
}
Future<void> _setLanguage(AppLanguage language) async {
await ref
.read(settingsOperationProvider('language').notifier)
.run(
() =>
ref.read(languageSettingsProvider.notifier).setLanguage(language),
);
}
@override
Widget build(BuildContext context) => Theme(
data: AppTheme.settingsContentTheme(Theme.of(context)),
child: Builder(builder: _buildDialog),
);
Widget _buildDialog(BuildContext context) {
final appearanceSave = ref.watch(settingsOperationProvider('appearance'));
final languageSave = ref.watch(settingsOperationProvider('language'));
final appearance = ref.watch(appearanceSettingsProvider);
final language = ref.watch(languageSettingsProvider);
final viewport = MediaQuery.sizeOf(context); final viewport = MediaQuery.sizeOf(context);
return AppDialog( return Theme(
data: AppTheme.settingsContentTheme(Theme.of(context)),
child: AppDialog(
title: context.l10n.settings, title: context.l10n.settings,
closeLabel: context.l10n.closeSettings, closeLabel: context.l10n.closeSettings,
width: math.min(1120, math.max(560, viewport.width * .9)), width: math.min(1120, math.max(560, viewport.width * .9)),
height: math.min(704, math.max(520, viewport.height * .88)), height: math.min(704, math.max(520, viewport.height * .88)),
contentOnly: true, contentOnly: true,
scrollContent: false, scrollContent: false,
child: LayoutBuilder( child: SettingsContent(workspace: workspace, initialTab: initialTab),
builder: (context, constraints) => Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SizedBox(
width: constraints.maxWidth < 600 ? 96 : 220,
child: _SettingsNavigation(
value: _tab,
compact: constraints.maxWidth < 600,
onChanged: (value) => setState(() => _tab = value),
),
),
VerticalDivider(
key: const Key('settings-sidebar-divider'),
width: 1,
thickness: 1,
color: Theme.of(context).colorScheme.outlineVariant,
),
Expanded(
child: ColoredBox(
color: Theme.of(context).colorScheme.surface,
child: IndexedStack(
index: _tab,
children: [
ExcludeFocus(
excluding: _tab != 0,
child: TickerMode(
enabled: _tab == 0,
child: SingleChildScrollView(
primary: false,
padding: _settingsContentPadding,
child: SettingsPageSection(
title: context.l10n.general,
icon: Icons.settings_outlined,
children: [
AppField(
label: context.l10n.appearance,
orientation: AppFieldOrientation.horizontal,
error:
(appearanceSave.hasError
? context.l10n.saveAppearanceFailed
: null) ??
(appearance.hasError
? context.l10n.loadAppearanceFailed
: null),
child: SizedBox(
width: AppSettingsMetrics.controlWidth,
child: AppSelect<AppAppearance>(
emptyLabel: context.l10n.noMatchingOptions,
controlHeight:
AppSettingsMetrics.controlHeight,
value:
appearance.asData?.value ??
AppAppearance.system,
label: context.l10n.theme,
options: [
AppSelectOption(
AppAppearance.system,
context.l10n.system,
),
AppSelectOption(
AppAppearance.penLight,
'Pen · ${context.l10n.light}',
),
AppSelectOption(
AppAppearance.penDark,
'Pen · ${context.l10n.dark}',
),
],
onChanged:
appearanceSave.isLoading ||
appearance.isLoading
? null
: _setMode,
),
),
),
AppField(
label: context.l10n.language,
orientation: AppFieldOrientation.horizontal,
error:
(languageSave.hasError
? context.l10n.saveLanguageFailed
: null) ??
(language.hasError
? context.l10n.loadLanguageFailed
: null),
child: SizedBox(
width: AppSettingsMetrics.controlWidth,
child: AppSelect<AppLanguage>(
emptyLabel: context.l10n.noMatchingOptions,
controlHeight:
AppSettingsMetrics.controlHeight,
value:
language.asData?.value ??
AppLanguage.system,
label: context.l10n.language,
options: [
for (final option in AppLanguage.values)
AppSelectOption(
option,
option == AppLanguage.system
? context.l10n.system
: option.nativeName,
),
],
onChanged:
languageSave.isLoading ||
language.isLoading
? null
: _setLanguage,
),
),
),
const _ProjectLocationField(),
const _ResourceLocationField(),
const UpdateSettings(),
const DiagnosticSettings(),
],
),
),
),
),
ExcludeFocus(
excluding: _tab != 1,
child: TickerMode(
enabled: _tab == 1,
child: const AgentSettingsPanel(
contentPadding: _settingsContentPadding,
),
),
),
ExcludeFocus(
excluding: _tab != 2,
child: TickerMode(
enabled: _tab == 2,
child: SingleChildScrollView(
primary: false,
padding: _settingsContentPadding,
child: McpSettingsPanel(workspace: widget.workspace),
),
),
),
],
),
),
),
],
),
), ),
); );
} }
} }
class _SettingsNavigation extends StatelessWidget {
const _SettingsNavigation({
required this.value,
required this.compact,
required this.onChanged,
});
final int value;
final bool compact;
final ValueChanged<int> onChanged;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final entries = [
(context.l10n.general, Icons.settings_outlined),
(context.l10n.agentSettings, Icons.auto_awesome_outlined),
('MCP', Icons.terminal_outlined),
];
return ColoredBox(
key: const Key('settings-sidebar'),
color: AppTheme.settingsSidebarBackground(context),
child: ListView(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 16),
children: [
Padding(
padding: const EdgeInsets.fromLTRB(8, 0, 8, 20),
child: Text(
context.l10n.settings,
style: theme.textTheme.titleSmall?.copyWith(fontSize: 16),
),
),
for (var index = 0; index < entries.length; index++)
Padding(
padding: const EdgeInsets.only(bottom: 1),
child: Semantics(
selected: value == index,
child: Tooltip(
message: entries[index].$1,
child: TextButton(
key: ValueKey('settings-navigation-$index'),
onPressed: () => onChanged(index),
style: TextButton.styleFrom(
minimumSize: const Size(0, 30),
padding: const EdgeInsets.symmetric(horizontal: 8),
foregroundColor: theme.colorScheme.onSurface,
backgroundColor: value == index
? theme.colorScheme.onSurface.withValues(alpha: .078)
: Colors.transparent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
alignment: AlignmentDirectional.centerStart,
),
child: Row(
children: [
if (!compact) ...[
Icon(entries[index].$2, size: 16),
const SizedBox(width: 8),
],
Expanded(
child: Text(
entries[index].$1,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
],
),
),
),
),
),
],
),
);
}
}
class _ResourceLocationField extends ConsumerWidget {
const _ResourceLocationField();
Future<void> _choose(
BuildContext context,
WidgetRef ref,
String? initialDirectory,
) async {
final directory = await ref
.read(filePickerProvider)
.pickDirectory(
initialDirectory: initialDirectory,
confirmButtonText: context.l10n.select,
);
if (directory == null || !context.mounted) return;
await ref.read(resourceLocationSettingsProvider.notifier).save(directory);
}
@override
Widget build(BuildContext context, WidgetRef ref) {
final settings = ref.watch(resourceLocationSettingsProvider);
final error = switch (settings.error) {
LocationSettingsError.load => context.l10n.loadResourceLocationFailed,
LocationSettingsError.save => context.l10n.saveResourceLocationFailed,
null => null,
};
return AppField(
label: context.l10n.resourceLocation,
orientation: AppFieldOrientation.horizontal,
error: error,
child: SizedBox(
width: 420,
child: Row(
children: [
Expanded(
child: Tooltip(
message:
settings.directory ?? context.l10n.resourceLocationNotSet,
child: _MiddleEllipsisText(
settings.directory ?? context.l10n.resourceLocationNotSet,
key: const Key('resource-location-value'),
textAlign: TextAlign.right,
),
),
),
const SizedBox(width: AppSpacing.compact),
OutlinedButton(
key: const Key('choose-resource-location'),
onPressed: settings.loading || settings.saving
? null
: () => _choose(context, ref, settings.directory),
child: Text(context.l10n.modify),
),
],
),
),
);
}
}
class _ProjectLocationField extends ConsumerWidget {
const _ProjectLocationField();
Future<void> _choose(
BuildContext context,
WidgetRef ref,
String? initialDirectory,
) async {
final directory = await ref
.read(filePickerProvider)
.pickDirectory(
initialDirectory: initialDirectory,
confirmButtonText: context.l10n.select,
);
if (directory == null || !context.mounted) return;
await ref.read(projectLocationSettingsProvider.notifier).save(directory);
}
@override
Widget build(BuildContext context, WidgetRef ref) {
final settings = ref.watch(projectLocationSettingsProvider);
final error = switch (settings.error) {
LocationSettingsError.load => context.l10n.loadProjectLocationFailed,
LocationSettingsError.save => context.l10n.saveProjectLocationFailed,
null => null,
};
return AppField(
label: context.l10n.projectLocation,
orientation: AppFieldOrientation.horizontal,
description: settings.status == ProjectLocationStatus.missing
? context.l10n.projectLocationMissing
: null,
error:
error ??
switch (settings.status) {
ProjectLocationStatus.unavailable =>
context.l10n.projectLocationUnavailable,
ProjectLocationStatus.notWritable =>
context.l10n.projectLocationNotWritable,
_ => null,
},
child: SizedBox(
width: 420,
child: Row(
children: [
Expanded(
child: Tooltip(
message:
settings.directory ?? context.l10n.projectLocationNotSet,
child: _MiddleEllipsisText(
settings.directory ?? context.l10n.projectLocationNotSet,
key: const Key('project-location-value'),
textAlign: TextAlign.right,
),
),
),
const SizedBox(width: AppSpacing.compact),
if (error != null ||
settings.status == ProjectLocationStatus.unavailable ||
settings.status == ProjectLocationStatus.notWritable)
TextButton(
key: const Key('retry-project-location'),
onPressed: settings.loading || settings.saving
? null
: ref.read(projectLocationSettingsProvider.notifier).reload,
child: Text(context.l10n.retry),
),
OutlinedButton(
key: const Key('choose-project-location'),
onPressed: settings.loading || settings.saving
? null
: () => _choose(context, ref, settings.directory),
child: Text(context.l10n.modify),
),
],
),
),
);
}
}
class _MiddleEllipsisText extends StatelessWidget {
const _MiddleEllipsisText(
this.text, {
super.key,
this.textAlign = TextAlign.start,
});
final String text;
final TextAlign textAlign;
@override
Widget build(BuildContext context) {
final style = DefaultTextStyle.of(context).style;
final direction = Directionality.of(context);
return LayoutBuilder(
builder: (context, constraints) => Text(
_ellipsize(text, constraints.maxWidth, style, direction),
maxLines: 1,
textAlign: textAlign,
),
);
}
static String _ellipsize(
String value,
double maxWidth,
TextStyle style,
TextDirection direction,
) {
bool fits(String candidate) {
final painter = TextPainter(
text: TextSpan(text: candidate, style: style),
maxLines: 1,
textDirection: direction,
)..layout(maxWidth: maxWidth);
return !painter.didExceedMaxLines && painter.width <= maxWidth;
}
if (!maxWidth.isFinite || fits(value)) return value;
var low = 0;
var high = value.length;
while (low < high) {
final keep = (low + high + 1) ~/ 2;
final leading = (keep + 1) ~/ 2;
final candidate =
'${value.substring(0, leading)}…'
'${value.substring(value.length - (keep - leading))}';
if (fits(candidate)) {
low = keep;
} else {
high = keep - 1;
}
}
final leading = (low + 1) ~/ 2;
return '${value.substring(0, leading)}…'
'${value.substring(value.length - (low - leading))}';
}
}
+97
View File
@@ -0,0 +1,97 @@
import 'package:cutdex_native/cutdex_native.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../app/shells/desktop_window_frame.dart';
import '../../app/adaptive/desktop_content_controller.dart';
import '../../integrations/platform/device_experience.dart';
import '../../integrations/platform/editor_window_chrome.dart';
import '../../l10n/l10n.dart';
import 'settings_content.dart';
Future<void> showSettingsPage(
BuildContext context, {
(String, String)? workspace,
int? initialTab,
}) {
final container = ProviderScope.containerOf(context, listen: false);
if (container.read(deviceExperienceProvider) == DeviceExperience.desktop) {
container
.read(desktopContentProvider.notifier)
.showSettings(tab: initialTab, workspace: workspace);
return Future<void>.value();
}
return context.push<void>(
'/settings?tab=${initialTab ?? 0}',
extra: workspace,
);
}
/// A pushed route keeps the editor and its session mounted underneath.
class SettingsPage extends ConsumerWidget {
const SettingsPage({super.key, this.workspace, this.initialTab = 0});
final (String, String)? workspace;
final int initialTab;
@override
Widget build(BuildContext context, WidgetRef ref) {
final desktop =
ref.watch(deviceExperienceProvider) == DeviceExperience.desktop;
void back() {
if (context.canPop()) {
context.pop();
} else {
context.go('/');
}
}
final content = SettingsContent(
workspace: workspace,
initialTab: initialTab,
);
if (!desktop) {
return Scaffold(
key: const Key('settings-page'),
appBar: AppBar(
leading: BackButton(
key: const Key('settings-page-back'),
onPressed: back,
),
title: Text(context.l10n.settings),
),
body: content,
);
}
return EditorWindowChrome(
headerHeight: DesktopWindowFrame.headerHeight,
builder: (context, integrated) => Scaffold(
key: const Key('settings-page'),
backgroundColor: Theme.of(context).colorScheme.surfaceContainer,
body: Column(
children: [
SizedBox(
height: DesktopWindowFrame.headerHeight,
child: WindowHeaderPadding(
child: Row(
children: [
if (integrated)
SizedBox(width: EditorWindowChrome.leadingWidth),
HeaderControlRegion(
child: BackButton(
key: const Key('settings-page-back'),
onPressed: back,
),
),
Text(context.l10n.settings),
],
),
),
),
Expanded(child: content),
],
),
),
);
}
}
@@ -1,3 +1,4 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:cutdex/errors/app_failure.dart'; import 'package:cutdex/errors/app_failure.dart';
import 'dart:async'; import 'dart:async';
@@ -352,9 +353,12 @@ class TimelineExternalDropTargetState
); );
} catch (e) { } catch (e) {
if (mounted) { if (mounted) {
ScaffoldMessenger.of( ErrorNotificationHost.of(context).show(
context, ErrorNotification(
).showSnackBar(SnackBar(content: Text(context.l10n.errorMessage(e)))); content: Text(context.l10n.errorMessage(e)),
details: e.toString(),
),
);
} }
} finally { } finally {
if (mounted && g == generation) { if (mounted && g == generation) {
+95 -89
View File
@@ -1,3 +1,4 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:cutdex/l10n/l10n.dart'; import 'package:cutdex/l10n/l10n.dart';
import 'package:cutdex_sdk/timeline/engine.dart'; import 'package:cutdex_sdk/timeline/engine.dart';
import 'package:cutdex_sdk/timeline/layout.dart'; import 'package:cutdex_sdk/timeline/layout.dart';
@@ -7,6 +8,7 @@ import 'package:cutdex_sdk/project.dart';
import 'package:cutdex_sdk/timeline_ui.dart'; import 'package:cutdex_sdk/timeline_ui.dart';
import '../../shared/widgets/listenable_selector.dart';
import '../../workspace/timeline_provider.dart'; import '../../workspace/timeline_provider.dart';
import '../../workspace/projects.dart'; import '../../workspace/projects.dart';
@@ -20,6 +22,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:cutdex_ui/theme.dart'; import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart'; import 'package:cutdex_ui/widgets.dart';
import '../editor/editor_panel_defaults.dart';
import '../media/transcription_dialog.dart'; import '../media/transcription_dialog.dart';
import '../media/background_removal_dialog.dart'; import '../media/background_removal_dialog.dart';
import '../projects/widgets/name_dialog.dart'; import '../projects/widgets/name_dialog.dart';
@@ -28,41 +31,85 @@ import '../../workspace/preview_target.dart';
import 'timeline_asset_drop_target.dart'; import 'timeline_asset_drop_target.dart';
import 'timeline_speed_editor.dart'; import 'timeline_speed_editor.dart';
class EditorTimelinePanel extends ConsumerWidget { class EditorTimelinePanel extends StatelessWidget {
const EditorTimelinePanel({ const EditorTimelinePanel({
super.key, super.key,
required this.projectId, required this.projectId,
required this.timelineId, required this.timelineId,
this.pending = false,
});
final String projectId;
final String timelineId;
final bool pending;
@override
Widget build(BuildContext context) => Theme(
data: AppTheme.timelinePanelTheme(Theme.of(context)),
child: pending
? const EditorTimelineDefaults()
: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_TimelineTabsContent(
projectId: projectId,
timelineId: timelineId,
),
const Divider(height: 1),
Expanded(
child: _TimelineSessionContent(
projectId: projectId,
timelineId: timelineId,
),
),
],
),
);
}
class _TimelineTabsContent extends ConsumerWidget {
const _TimelineTabsContent({
required this.projectId,
required this.timelineId,
}); });
final String projectId; final String projectId;
final String timelineId; final String timelineId;
@override @override
Widget build(BuildContext context, WidgetRef ref) { Widget build(BuildContext context, WidgetRef ref) {
final provider = editorTimelineProvider(projectId, timelineId);
final timeline = ref.watch(provider);
final projectState = ref.watch(projectsProvider).asData?.value; final projectState = ref.watch(projectsProvider).asData?.value;
final timelines = projectState?.activeProject?.id == projectId final timelines = projectState?.activeProject?.id == projectId
? projectState!.timelines ? projectState!.timelines
: const <TimelineSummary>[]; : const <TimelineSummary>[];
return Theme( return _TimelineTabsBar(
data: AppTheme.timelinePanelTheme(Theme.of(context)),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_TimelineTabsBar(
projectId: projectId, projectId: projectId,
timelineId: timelineId, timelineId: timelineId,
timelines: timelines, timelines: timelines,
creating: projectState?.creatingTimeline ?? false, creating: projectState?.creatingTimeline ?? false,
openingTimelineId: projectState?.openingTimelineId, openingTimelineId: projectState?.openingTimelineId,
), );
const Divider(height: 1), }
Expanded( }
child: timeline.when(
loading: () => const WorkspacePanel( class _TimelineSessionContent extends ConsumerWidget {
const _TimelineSessionContent({
required this.projectId,
required this.timelineId,
});
final String projectId;
final String timelineId;
@override
Widget build(BuildContext context, WidgetRef ref) {
final provider = editorTimelineProvider(projectId, timelineId);
final watched = ref.watch(provider);
final cached = watched.isLoading && !watched.hasError
? ref
.read(projectsProvider.notifier)
.cachedTimelineSession(projectId, timelineId)
: null;
final timeline = cached == null ? watched : AsyncData(cached);
return timeline.when(
loading: () => const EditorTimelineDefaults(
key: Key('timeline-pending'), key: Key('timeline-pending'),
child: SizedBox.expand(), showTabs: false,
), ),
error: (_, _) => WorkspacePanel( error: (_, _) => WorkspacePanel(
child: Center( child: Center(
@@ -95,20 +142,11 @@ class EditorTimelinePanel extends ConsumerWidget {
); );
} }
ref ref
.read( .read(previewNavigationProvider(projectId, timelineId).notifier)
previewNavigationProvider(
projectId,
timelineId,
).notifier,
)
.showTimeline(); .showTimeline();
}, },
child: _TimelineEditor(session: session, projectId: projectId), child: _TimelineEditor(session: session, projectId: projectId),
), ),
),
),
],
),
); );
} }
} }
@@ -241,8 +279,8 @@ class _TimelineTabsBarState extends ConsumerState<_TimelineTabsBar> {
Future<void> _createTimeline() async { Future<void> _createTimeline() async {
if (_operationsBusy) return; if (_operationsBusy) return;
if (widget.timelines.length >= Projects.maxTimelineCount) { if (widget.timelines.length >= Projects.maxTimelineCount) {
ScaffoldMessenger.maybeOf(context)?.showSnackBar( ErrorNotificationHost.maybeOf(context)?.show(
SnackBar( ErrorNotification(
content: Text( content: Text(
context.l10n.timelineLimitReached(Projects.maxTimelineCount), context.l10n.timelineLimitReached(Projects.maxTimelineCount),
), ),
@@ -494,60 +532,13 @@ class _TimelineEditor extends StatefulWidget {
class _TimelineEditorState extends State<_TimelineEditor> { class _TimelineEditorState extends State<_TimelineEditor> {
EditorTimelineSession get session => widget.session; EditorTimelineSession get session => widget.session;
String get projectId => widget.projectId; String get projectId => widget.projectId;
late RuntimeTimelineThumbnails _thumbnails; RuntimeTimelineThumbnails get _thumbnails => session.thumbnails;
late RuntimeTimelineWaveforms _waveforms; RuntimeTimelineWaveforms get _waveforms => session.waveforms;
@override @override
void initState() { Widget build(BuildContext context) => ListenableSelector(
super.initState();
_createMediaCaches();
}
@override
void didUpdateWidget(covariant _TimelineEditor oldWidget) {
super.didUpdateWidget(oldWidget);
if (!identical(oldWidget.session, widget.session)) {
_thumbnails.dispose();
_waveforms.dispose();
_createMediaCaches();
}
}
void _createMediaCaches() {
_thumbnails = RuntimeTimelineThumbnails(
resolveTrackSelection: (ref) => session.mediaBinding(ref)?.videoSelection,
resolveMedia: (ref) {
final binding = session.mediaBinding(ref);
if (session.unavailableAssets.containsKey(binding?.media.id)) {
return null;
}
return binding?.videoTrackIndex == null ? null : binding!.media;
},
);
_waveforms = RuntimeTimelineWaveforms(
resolveTrackSelection: (ref) => session.mediaBinding(ref)?.audioSelection,
resolveGain: session.waveformGain,
gainChanges: session.audioGainPreview,
resolveMedia: (ref) {
final binding = session.mediaBinding(ref);
if (session.unavailableAssets.containsKey(binding?.media.id)) {
return null;
}
return binding?.audioTrackIndex == null ? null : binding!.media;
},
);
}
@override
void dispose() {
_thumbnails.dispose();
_waveforms.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: session, listenable: session,
select: () => session.activeSequenceId,
builder: (context, _) => _build(context), builder: (context, _) => _build(context),
); );
@@ -662,8 +653,8 @@ class _TimelineEditorState extends State<_TimelineEditor> {
try { try {
edit(); edit();
} on CommandRejected catch (error) { } on CommandRejected catch (error) {
ScaffoldMessenger.maybeOf(context)?.showSnackBar( ErrorNotificationHost.maybeOf(context)?.show(
SnackBar( ErrorNotification(
content: Text( content: Text(
error.code == 'staleVersion' error.code == 'staleVersion'
? context.l10n.captionChanged ? context.l10n.captionChanged
@@ -706,18 +697,29 @@ class _TimelineEditorState extends State<_TimelineEditor> {
); );
} }
final controller = session.view(sequenceId); final controller = session.view(sequenceId);
final captionCues = _selectedCaptionCues(controller);
final canSplitCaption = _canSplitCaption(controller, captionCues);
return WorkspacePanel( return WorkspacePanel(
headerHeight: 32, headerHeight: 32,
headerPadding: EdgeInsets.zero, headerPadding: EdgeInsets.zero,
controls: ListenableBuilder( controls: ListenableSelector(
listenable: Listenable.merge([ listenable: Listenable.merge([
controller.contentChanges, controller.contentChanges,
controller.playheadChanges, controller.playheadChanges,
session, session,
]), ]),
builder: (context, _) => SizedBox( select: () => (
controller.canUndo,
controller.canRedo,
controller.canCutSelection,
controller.canDeleteSelection,
controller.commandRejection,
_canSplitCaption(controller, _selectedCaptionCues(controller)),
_selectedCaptionCues(controller).singleOrNull,
controller.version.kernelVersion,
),
builder: (context, _) {
final captionCues = _selectedCaptionCues(controller);
final canSplitCaption = _canSplitCaption(controller, captionCues);
return SizedBox(
key: const Key('timeline-toolbar'), key: const Key('timeline-toolbar'),
height: 32, height: 32,
child: Padding( child: Padding(
@@ -783,7 +785,9 @@ class _TimelineEditorState extends State<_TimelineEditor> {
semanticLabel: context.l10n.trimRight, semanticLabel: context.l10n.trimRight,
), ),
_toolbarButton( _toolbarButton(
key: const ValueKey('timeline-delete-selection'), key: const ValueKey(
'timeline-delete-selection',
),
tooltip: context.l10n.deleteSelectedClips, tooltip: context.l10n.deleteSelectedClips,
onPressed: () { onPressed: () {
if (!controller.canDeleteSelection) return; if (!controller.canDeleteSelection) return;
@@ -806,7 +810,8 @@ class _TimelineEditorState extends State<_TimelineEditor> {
), ),
), ),
), ),
), );
},
), ),
child: ListenableBuilder( child: ListenableBuilder(
listenable: controller.contentChanges, listenable: controller.contentChanges,
@@ -860,9 +865,10 @@ class _TimelineEditorState extends State<_TimelineEditor> {
session.detachAudio(sequenceId, detachTarget); session.detachAudio(sequenceId, detachTarget);
} }
} catch (error) { } catch (error) {
ScaffoldMessenger.of(context).showSnackBar( ErrorNotificationHost.of(context).show(
SnackBar( ErrorNotification(
content: Text(context.l10n.errorMessage(error)), content: Text(context.l10n.errorMessage(error)),
details: error.toString(),
), ),
); );
} }
@@ -1,3 +1,5 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'dart:math' as math; import 'dart:math' as math;
import 'package:cutdex_sdk/editor.dart'; import 'package:cutdex_sdk/editor.dart';
@@ -315,9 +317,12 @@ class _ClipSpeedEditorState extends State<_ClipSpeedEditor> {
void _showError(Object error) { void _showError(Object error) {
if (!mounted) return; if (!mounted) return;
ScaffoldMessenger.of( ErrorNotificationHost.of(context).show(
context, ErrorNotification(
).showSnackBar(SnackBar(content: Text(context.l10n.errorMessage(error)))); content: Text(context.l10n.errorMessage(error)),
details: error.toString(),
),
);
} }
void _clearDrag() { void _clearDrag() {
+7 -2
View File
@@ -1,6 +1,7 @@
import 'dart:async'; import 'dart:async';
import '../diagnostics/app_diagnostics.dart'; import '../diagnostics/app_diagnostics.dart';
import 'app_update_configuration.dart';
import 'package:deskup/deskup.dart'; import 'package:deskup/deskup.dart';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
@@ -26,7 +27,11 @@ AppUpdateBridge appUpdateBridge(Ref ref) {
// Application adapter: Riverpod ownership and the macOS workspace quit gate. // Application adapter: Riverpod ownership and the macOS workspace quit gate.
class AppUpdateBridge { class AppUpdateBridge {
AppUpdateBridge([MethodChannel channel = appUpdatesChannel]) AppUpdateBridge([MethodChannel channel = appUpdatesChannel])
: _updater = Deskup(channel: channel); : _updater = Deskup(
channel: channel,
windows: windowsUpdateConfiguration(),
macos: macosUpdateConfiguration(),
);
final Deskup _updater; final Deskup _updater;
Stream<UpdateStatus> get events => _updater.events; Stream<UpdateStatus> get events => _updater.events;
@@ -65,7 +70,7 @@ class AppUpdateBridge {
Future<void> check() => _updater.check(); Future<void> check() => _updater.check();
Future<void> download() => _updater.download(); Future<void> download() => _updater.download();
Future<void> validateInstall() => _updater.validateInstall(); Future<void> validateInstall() => _updater.validateInstall();
Future<void> install() => _updater.install(); Future<void> install() => _updater.install(silent: true, restart: true);
Future<void> setAutomaticChecks(bool enabled) => Future<void> setAutomaticChecks(bool enabled) =>
_updater.setAutomaticChecks(enabled); _updater.setAutomaticChecks(enabled);
@@ -0,0 +1,48 @@
import 'package:deskup/deskup.dart';
import 'package:flutter/services.dart';
// Values are compiled from Dart defines; process environment does not redirect production.
MacOSUpdateConfiguration macosUpdateConfiguration() =>
const MacOSUpdateConfiguration(
allowLocalHttp:
appFlavor == 'development' &&
bool.fromEnvironment('CUTDEX_UPDATE_TEST_HTTP'),
);
WindowsUpdateConfiguration? windowsUpdateConfiguration({
String? flavor,
String developmentUrl = const String.fromEnvironment(
'CUTDEX_WINDOWS_UPDATE_URL',
),
String developmentSource = const String.fromEnvironment(
'CUTDEX_WINDOWS_UPDATE_SOURCE',
defaultValue: 'gitea',
),
bool allowLocalHttp = const bool.fromEnvironment('CUTDEX_UPDATE_TEST_HTTP'),
}) {
final development = (flavor ?? appFlavor) == 'development';
if (development && developmentUrl.isEmpty) return null;
final WindowsUpdateSource source;
if (!development) {
source = GiteaUpdateSource(
repositoryUrl: Uri.parse('https://git.orangraph.com/lingjhf/cutdex'),
);
} else if (developmentSource == 'gitea') {
source = GiteaUpdateSource(
repositoryUrl: Uri.parse(developmentUrl),
allowLocalHttp: allowLocalHttp,
);
} else if (developmentSource == 'web') {
source = WebUpdateSource(
url: Uri.parse(developmentUrl),
allowLocalHttp: allowLocalHttp,
);
} else {
throw ArgumentError.value(developmentSource, 'developmentSource');
}
return WindowsUpdateConfiguration(
source: source,
expectedPackageId: development ? 'Cutdex.Dev' : 'Cutdex',
preferenceNamespace: 'Cutdex',
);
}
@@ -76,7 +76,7 @@ class _EditorWindowChromeState extends State<EditorWindowChrome> {
constraints.maxWidth - WindowCaptionControls.width, constraints.maxWidth - WindowCaptionControls.width,
0, 0,
WindowCaptionControls.width, WindowCaptionControls.width,
widget.headerHeight, WindowCaptionControls.buttonHeight,
), ),
child: Stack( child: Stack(
fit: StackFit.expand, fit: StackFit.expand,
@@ -86,10 +86,10 @@ class _EditorWindowChromeState extends State<EditorWindowChrome> {
top: 0, top: 0,
right: 0, right: 0,
width: WindowCaptionControls.width, width: WindowCaptionControls.width,
height: widget.headerHeight, height: WindowCaptionControls.buttonHeight,
child: WindowCaptionControls( child: WindowCaptionControls(
session: _session, session: _session,
height: widget.headerHeight, height: WindowCaptionControls.buttonHeight,
), ),
), ),
], ],
@@ -14,6 +14,7 @@ class WindowCaptionControls extends StatelessWidget {
required this.height, required this.height,
}); });
static const buttonWidth = 46.0; static const buttonWidth = 46.0;
static const buttonHeight = 38.0;
static const width = buttonWidth * 3; static const width = buttonWidth * 3;
final WindowChromeSession session; final WindowChromeSession session;
final double height; final double height;
@@ -22,7 +23,7 @@ class WindowCaptionControls extends StatelessWidget {
Widget build(BuildContext context) => ListenableBuilder( Widget build(BuildContext context) => ListenableBuilder(
listenable: session, listenable: session,
builder: (context, _) => Material( builder: (context, _) => Material(
color: Theme.of(context).colorScheme.surface, type: MaterialType.transparency,
child: Row( child: Row(
children: [ children: [
_button( _button(
+4 -1
View File
@@ -885,5 +885,8 @@
"diagnostics": "Diagnose", "diagnostics": "Diagnose",
"exportDiagnostics": "Diagnosepaket exportieren", "exportDiagnostics": "Diagnosepaket exportieren",
"exportDiagnosticsFailed": "Die Diagnose konnte nicht exportiert werden. Bitte erneut versuchen.", "exportDiagnosticsFailed": "Die Diagnose konnte nicht exportiert werden. Bitte erneut versuchen.",
"exportDiagnosticsSucceeded": "Diagnosepaket gespeichert." "exportDiagnosticsSucceeded": "Diagnosepaket gespeichert.",
"navigationChat": "Chat",
"navigationLibrary": "Mediathek",
"agentFullscreen": "Expand Agent"
} }
+4 -1
View File
@@ -1338,5 +1338,8 @@
"diagnostics": "Diagnostics", "diagnostics": "Diagnostics",
"exportDiagnostics": "Export diagnostic package", "exportDiagnostics": "Export diagnostic package",
"exportDiagnosticsFailed": "Could not export diagnostics. Please try again.", "exportDiagnosticsFailed": "Could not export diagnostics. Please try again.",
"exportDiagnosticsSucceeded": "Diagnostic package saved." "exportDiagnosticsSucceeded": "Diagnostic package saved.",
"navigationChat": "Chat",
"navigationLibrary": "Library",
"agentFullscreen": "Expand Agent"
} }
+4 -1
View File
@@ -885,5 +885,8 @@
"diagnostics": "Diagnóstico", "diagnostics": "Diagnóstico",
"exportDiagnostics": "Exportar paquete de diagnóstico", "exportDiagnostics": "Exportar paquete de diagnóstico",
"exportDiagnosticsFailed": "No se pudo exportar el diagnóstico. Inténtalo de nuevo.", "exportDiagnosticsFailed": "No se pudo exportar el diagnóstico. Inténtalo de nuevo.",
"exportDiagnosticsSucceeded": "Paquete de diagnóstico guardado." "exportDiagnosticsSucceeded": "Paquete de diagnóstico guardado.",
"navigationChat": "Chat",
"navigationLibrary": "Biblioteca",
"agentFullscreen": "Expand Agent"
} }
+4 -1
View File
@@ -885,5 +885,8 @@
"diagnostics": "Diagnostic", "diagnostics": "Diagnostic",
"exportDiagnostics": "Exporter le diagnostic", "exportDiagnostics": "Exporter le diagnostic",
"exportDiagnosticsFailed": "Impossible d’exporter le diagnostic. Réessayez.", "exportDiagnosticsFailed": "Impossible d’exporter le diagnostic. Réessayez.",
"exportDiagnosticsSucceeded": "Diagnostic enregistré." "exportDiagnosticsSucceeded": "Diagnostic enregistré.",
"navigationChat": "Discussion",
"navigationLibrary": "Bibliothèque",
"agentFullscreen": "Expand Agent"
} }
+4 -1
View File
@@ -885,5 +885,8 @@
"diagnostics": "Diagnostica", "diagnostics": "Diagnostica",
"exportDiagnostics": "Esporta pacchetto diagnostico", "exportDiagnostics": "Esporta pacchetto diagnostico",
"exportDiagnosticsFailed": "Impossibile esportare la diagnostica. Riprova.", "exportDiagnosticsFailed": "Impossibile esportare la diagnostica. Riprova.",
"exportDiagnosticsSucceeded": "Pacchetto diagnostico salvato." "exportDiagnosticsSucceeded": "Pacchetto diagnostico salvato.",
"navigationChat": "Chat",
"navigationLibrary": "Libreria",
"agentFullscreen": "Expand Agent"
} }
+4 -1
View File
@@ -885,5 +885,8 @@
"diagnostics": "診断", "diagnostics": "診断",
"exportDiagnostics": "診断パッケージをエクスポート", "exportDiagnostics": "診断パッケージをエクスポート",
"exportDiagnosticsFailed": "診断をエクスポートできませんでした。もう一度お試しください。", "exportDiagnosticsFailed": "診断をエクスポートできませんでした。もう一度お試しください。",
"exportDiagnosticsSucceeded": "診断パッケージを保存しました。" "exportDiagnosticsSucceeded": "診断パッケージを保存しました。",
"navigationChat": "チャット",
"navigationLibrary": "ライブラリ",
"agentFullscreen": "Expand Agent"
} }
+4 -1
View File
@@ -885,5 +885,8 @@
"diagnostics": "진단", "diagnostics": "진단",
"exportDiagnostics": "진단 패키지 내보내기", "exportDiagnostics": "진단 패키지 내보내기",
"exportDiagnosticsFailed": "진단을 내보낼 수 없습니다. 다시 시도해 주세요.", "exportDiagnosticsFailed": "진단을 내보낼 수 없습니다. 다시 시도해 주세요.",
"exportDiagnosticsSucceeded": "진단 패키지가 저장되었습니다." "exportDiagnosticsSucceeded": "진단 패키지가 저장되었습니다.",
"navigationChat": "채팅",
"navigationLibrary": "라이브러리",
"agentFullscreen": "Expand Agent"
} }
+18
View File
@@ -4093,6 +4093,24 @@ abstract class AppLocalizations {
/// In en, this message translates to: /// In en, this message translates to:
/// **'Diagnostic package saved.'** /// **'Diagnostic package saved.'**
String get exportDiagnosticsSucceeded; String get exportDiagnosticsSucceeded;
/// No description provided for @navigationChat.
///
/// In en, this message translates to:
/// **'Chat'**
String get navigationChat;
/// No description provided for @navigationLibrary.
///
/// In en, this message translates to:
/// **'Library'**
String get navigationLibrary;
/// No description provided for @agentFullscreen.
///
/// In en, this message translates to:
/// **'Expand Agent'**
String get agentFullscreen;
} }
class _AppLocalizationsDelegate class _AppLocalizationsDelegate
+9
View File
@@ -2229,4 +2229,13 @@ class AppLocalizationsDe extends AppLocalizations {
@override @override
String get exportDiagnosticsSucceeded => 'Diagnosepaket gespeichert.'; String get exportDiagnosticsSucceeded => 'Diagnosepaket gespeichert.';
@override
String get navigationChat => 'Chat';
@override
String get navigationLibrary => 'Mediathek';
@override
String get agentFullscreen => 'Expand Agent';
} }
+9
View File
@@ -2195,4 +2195,13 @@ class AppLocalizationsEn extends AppLocalizations {
@override @override
String get exportDiagnosticsSucceeded => 'Diagnostic package saved.'; String get exportDiagnosticsSucceeded => 'Diagnostic package saved.';
@override
String get navigationChat => 'Chat';
@override
String get navigationLibrary => 'Library';
@override
String get agentFullscreen => 'Expand Agent';
} }
+9
View File
@@ -2229,4 +2229,13 @@ class AppLocalizationsEs extends AppLocalizations {
@override @override
String get exportDiagnosticsSucceeded => 'Paquete de diagnóstico guardado.'; String get exportDiagnosticsSucceeded => 'Paquete de diagnóstico guardado.';
@override
String get navigationChat => 'Chat';
@override
String get navigationLibrary => 'Biblioteca';
@override
String get agentFullscreen => 'Expand Agent';
} }
+9
View File
@@ -2232,4 +2232,13 @@ class AppLocalizationsFr extends AppLocalizations {
@override @override
String get exportDiagnosticsSucceeded => 'Diagnostic enregistré.'; String get exportDiagnosticsSucceeded => 'Diagnostic enregistré.';
@override
String get navigationChat => 'Discussion';
@override
String get navigationLibrary => 'Bibliothèque';
@override
String get agentFullscreen => 'Expand Agent';
} }
+9
View File
@@ -2222,4 +2222,13 @@ class AppLocalizationsIt extends AppLocalizations {
@override @override
String get exportDiagnosticsSucceeded => 'Pacchetto diagnostico salvato.'; String get exportDiagnosticsSucceeded => 'Pacchetto diagnostico salvato.';
@override
String get navigationChat => 'Chat';
@override
String get navigationLibrary => 'Libreria';
@override
String get agentFullscreen => 'Expand Agent';
} }
+9
View File
@@ -2130,4 +2130,13 @@ class AppLocalizationsJa extends AppLocalizations {
@override @override
String get exportDiagnosticsSucceeded => '診断パッケージを保存しました。'; String get exportDiagnosticsSucceeded => '診断パッケージを保存しました。';
@override
String get navigationChat => 'チャット';
@override
String get navigationLibrary => 'ライブラリ';
@override
String get agentFullscreen => 'Expand Agent';
} }
+9
View File
@@ -2130,4 +2130,13 @@ class AppLocalizationsKo extends AppLocalizations {
@override @override
String get exportDiagnosticsSucceeded => '진단 패키지가 저장되었습니다.'; String get exportDiagnosticsSucceeded => '진단 패키지가 저장되었습니다.';
@override
String get navigationChat => '채팅';
@override
String get navigationLibrary => '라이브러리';
@override
String get agentFullscreen => 'Expand Agent';
} }
+9
View File
@@ -2222,4 +2222,13 @@ class AppLocalizationsPt extends AppLocalizations {
@override @override
String get exportDiagnosticsSucceeded => 'Pacote de diagnóstico salvo.'; String get exportDiagnosticsSucceeded => 'Pacote de diagnóstico salvo.';
@override
String get navigationChat => 'Chat';
@override
String get navigationLibrary => 'Biblioteca';
@override
String get agentFullscreen => 'Expand Agent';
} }
+9
View File
@@ -2215,4 +2215,13 @@ class AppLocalizationsRu extends AppLocalizations {
@override @override
String get exportDiagnosticsSucceeded => 'Пакет диагностики сохранён.'; String get exportDiagnosticsSucceeded => 'Пакет диагностики сохранён.';
@override
String get navigationChat => 'Чат';
@override
String get navigationLibrary => 'Библиотека';
@override
String get agentFullscreen => 'Expand Agent';
} }
+27
View File
@@ -2088,6 +2088,15 @@ class AppLocalizationsZh extends AppLocalizations {
@override @override
String get exportDiagnosticsSucceeded => '诊断包已保存。'; String get exportDiagnosticsSucceeded => '诊断包已保存。';
@override
String get navigationChat => '聊天';
@override
String get navigationLibrary => '资源库';
@override
String get agentFullscreen => '全屏 Agent';
} }
/// The translations for Chinese, using the Han script (`zh_Hans`). /// The translations for Chinese, using the Han script (`zh_Hans`).
@@ -4173,6 +4182,15 @@ class AppLocalizationsZhHans extends AppLocalizationsZh {
@override @override
String get exportDiagnosticsSucceeded => '诊断包已保存。'; String get exportDiagnosticsSucceeded => '诊断包已保存。';
@override
String get navigationChat => '聊天';
@override
String get navigationLibrary => '资源库';
@override
String get agentFullscreen => '全屏 Agent';
} }
/// The translations for Chinese, using the Han script (`zh_Hant`). /// The translations for Chinese, using the Han script (`zh_Hant`).
@@ -6258,4 +6276,13 @@ class AppLocalizationsZhHant extends AppLocalizationsZh {
@override @override
String get exportDiagnosticsSucceeded => '診斷套件已儲存。'; String get exportDiagnosticsSucceeded => '診斷套件已儲存。';
@override
String get navigationChat => '聊天';
@override
String get navigationLibrary => '資源庫';
@override
String get agentFullscreen => '全屏 Agent';
} }
+4 -1
View File
@@ -885,5 +885,8 @@
"diagnostics": "Diagnóstico", "diagnostics": "Diagnóstico",
"exportDiagnostics": "Exportar pacote de diagnóstico", "exportDiagnostics": "Exportar pacote de diagnóstico",
"exportDiagnosticsFailed": "Não foi possível exportar o diagnóstico. Tente novamente.", "exportDiagnosticsFailed": "Não foi possível exportar o diagnóstico. Tente novamente.",
"exportDiagnosticsSucceeded": "Pacote de diagnóstico salvo." "exportDiagnosticsSucceeded": "Pacote de diagnóstico salvo.",
"navigationChat": "Chat",
"navigationLibrary": "Biblioteca",
"agentFullscreen": "Expand Agent"
} }
+4 -1
View File
@@ -885,5 +885,8 @@
"diagnostics": "Диагностика", "diagnostics": "Диагностика",
"exportDiagnostics": "Экспортировать пакет диагностики", "exportDiagnostics": "Экспортировать пакет диагностики",
"exportDiagnosticsFailed": "Не удалось экспортировать диагностику. Повторите попытку.", "exportDiagnosticsFailed": "Не удалось экспортировать диагностику. Повторите попытку.",
"exportDiagnosticsSucceeded": "Пакет диагностики сохранён." "exportDiagnosticsSucceeded": "Пакет диагностики сохранён.",
"navigationChat": "Чат",
"navigationLibrary": "Библиотека",
"agentFullscreen": "Expand Agent"
} }
+4 -1
View File
@@ -885,5 +885,8 @@
"diagnostics": "诊断", "diagnostics": "诊断",
"exportDiagnostics": "导出诊断包", "exportDiagnostics": "导出诊断包",
"exportDiagnosticsFailed": "无法导出诊断包,请重试。", "exportDiagnosticsFailed": "无法导出诊断包,请重试。",
"exportDiagnosticsSucceeded": "诊断包已保存。" "exportDiagnosticsSucceeded": "诊断包已保存。",
"navigationChat": "聊天",
"navigationLibrary": "资源库",
"agentFullscreen": "全屏 Agent"
} }
+4 -1
View File
@@ -885,5 +885,8 @@
"diagnostics": "诊断", "diagnostics": "诊断",
"exportDiagnostics": "导出诊断包", "exportDiagnostics": "导出诊断包",
"exportDiagnosticsFailed": "无法导出诊断包,请重试。", "exportDiagnosticsFailed": "无法导出诊断包,请重试。",
"exportDiagnosticsSucceeded": "诊断包已保存。" "exportDiagnosticsSucceeded": "诊断包已保存。",
"navigationChat": "聊天",
"navigationLibrary": "资源库",
"agentFullscreen": "全屏 Agent"
} }
+4 -1
View File
@@ -885,5 +885,8 @@
"diagnostics": "診斷", "diagnostics": "診斷",
"exportDiagnostics": "匯出診斷套件", "exportDiagnostics": "匯出診斷套件",
"exportDiagnosticsFailed": "無法匯出診斷套件,請重試。", "exportDiagnosticsFailed": "無法匯出診斷套件,請重試。",
"exportDiagnosticsSucceeded": "診斷套件已儲存。" "exportDiagnosticsSucceeded": "診斷套件已儲存。",
"navigationChat": "聊天",
"navigationLibrary": "資源庫",
"agentFullscreen": "全屏 Agent"
} }
@@ -1,4 +1,7 @@
abstract final class WorkspaceLayoutMetrics { abstract final class WorkspaceLayoutMetrics {
static const desktopSpacing = 1.0;
static const desktopResizeSlop = 2.0;
static const desktopResizeHitExtent = desktopSpacing + 2 * desktopResizeSlop;
static const dualPaneMinimumWidth = 840.0; static const dualPaneMinimumWidth = 840.0;
static const sidebarDefaultWidth = 260.0; static const sidebarDefaultWidth = 260.0;
@@ -0,0 +1,239 @@
import 'dart:async';
import 'dart:collection';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../errors/app_failure.dart';
import '../../l10n/l10n.dart';
class ErrorNotification {
const ErrorNotification({required this.content, this.details});
final Widget content;
final String? details;
String get copyText {
String textOf(Widget widget) {
if (widget is Text) {
return widget.data ?? widget.textSpan?.toPlainText() ?? '';
}
if (widget is SingleChildScrollView && widget.child != null) {
return textOf(widget.child!);
}
if (widget is SingleChildRenderObjectWidget && widget.child != null) {
return textOf(widget.child!);
}
return '';
}
final message = textOf(content);
return details == null || details!.isEmpty || details == message
? message
: '$message\n\n$details';
}
}
/// One error queue above navigation and dialogs, independent of local scaffolds.
class ErrorNotificationHost extends StatefulWidget {
const ErrorNotificationHost({super.key, required this.child});
final Widget child;
static ErrorNotificationHostState? maybeOf(BuildContext context) =>
context.findAncestorStateOfType<ErrorNotificationHostState>();
static ErrorNotificationHostState of(BuildContext context) =>
maybeOf(context)!;
@override
State<ErrorNotificationHost> createState() => ErrorNotificationHostState();
}
class ErrorNotificationHostState extends State<ErrorNotificationHost> {
late final OverlayEntry _entry = OverlayEntry(builder: _buildContent);
final _pending = Queue<ErrorNotification>();
ErrorNotification? _current;
Timer? _timer;
bool _copied = false;
bool _hovered = false;
void show(ErrorNotification notification) {
if (!mounted) return;
_pending.add(notification);
if (_current == null) _next();
}
void showFailure(AppFailure failure, String message) => show(
ErrorNotification(
content: Text(message),
details: [
'code: ${failure.code.name}',
if (failure.httpStatusCode != null) 'HTTP: ${failure.httpStatusCode}',
if (failure.diagnostic != null) failure.diagnostic!,
].join('\n'),
),
);
void _startTimer() {
_timer?.cancel();
if (_current != null && !_hovered) {
_timer = Timer(const Duration(seconds: 8), dismiss);
}
}
void _next() {
setState(() {
_current = _pending.isEmpty ? null : _pending.removeFirst();
_copied = false;
});
_startTimer();
}
void dismiss() {
_timer?.cancel();
_next();
}
void clear() {
_timer?.cancel();
_pending.clear();
setState(() => _current = null);
}
Future<void> _copy() async {
final current = _current;
if (current == null) return;
try {
await Clipboard.setData(ClipboardData(text: current.copyText));
if (mounted && identical(current, _current)) {
setState(() => _copied = true);
_startTimer();
}
} catch (_) {
// Keep the error visible so the user can retry copying.
_timer?.cancel();
}
}
@override
void dispose() {
_timer?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
_entry.markNeedsBuild();
return Overlay(initialEntries: [_entry]);
}
Widget _buildContent(BuildContext context) => Stack(
fit: StackFit.expand,
children: [
widget.child,
if (_current case final current?)
Positioned(
top: MediaQuery.paddingOf(context).top + 48,
left: 12,
right: 12,
child: Align(
alignment: Alignment.topCenter,
child: MouseRegion(
onEnter: (_) {
_hovered = true;
_timer?.cancel();
},
onExit: (_) {
_hovered = false;
_startTimer();
},
child: Material(
key: const Key('global-error-notification'),
elevation: 8,
color: Theme.of(context).colorScheme.surfaceContainerHigh,
borderRadius: BorderRadius.circular(12),
clipBehavior: Clip.antiAlias,
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 520),
child: Padding(
padding: const EdgeInsets.fromLTRB(12, 8, 4, 8),
child: Semantics(
liveRegion: true,
child: Row(
children: [
Icon(
Icons.error_outline,
color: Theme.of(context).colorScheme.error,
size: 20,
),
const SizedBox(width: 8),
Expanded(
child: ConstrainedBox(
constraints: const BoxConstraints(maxHeight: 180),
child: SingleChildScrollView(
child: current.content,
),
),
),
IconButton(
key: const Key('copy-error-button'),
tooltip: MaterialLocalizations.of(context)
.copyButtonLabel,
onPressed: _copy,
icon: Icon(
_copied ? Icons.check : Icons.copy,
size: 18,
),
),
IconButton(
key: const Key('close-error-button'),
tooltip: MaterialLocalizations.of(context)
.closeButtonTooltip,
onPressed: dismiss,
icon: const Icon(Icons.close, size: 18),
),
],
),
),
),
),
),
),
),
),
],
);
}
/// Publishes a changed structured failure after the current build completes.
class ErrorFailureListener extends StatefulWidget {
const ErrorFailureListener({super.key, required this.message});
final AppFailure? message;
@override
State<ErrorFailureListener> createState() => _ErrorFailureListenerState();
}
class _ErrorFailureListenerState extends State<ErrorFailureListener> {
@override
void initState() {
super.initState();
_schedule();
}
@override
void didUpdateWidget(covariant ErrorFailureListener oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.message != oldWidget.message) _schedule();
}
void _schedule() {
final message = widget.message;
if (message == null) return;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
ErrorNotificationHost.maybeOf(context)
?.showFailure(message, context.l10n.failureMessage(message));
});
}
@override
Widget build(BuildContext context) => const SizedBox.shrink();
}
@@ -0,0 +1,54 @@
import 'package:flutter/widgets.dart';
/// Rebuilds a content region only when its selected presentation data changes.
class ListenableSelector<T> extends StatefulWidget {
const ListenableSelector({
super.key,
required this.listenable,
required this.select,
required this.builder,
});
final Listenable? listenable;
final T Function() select;
final Widget Function(BuildContext context, T value) builder;
@override
State<ListenableSelector<T>> createState() => _ListenableSelectorState<T>();
}
class _ListenableSelectorState<T> extends State<ListenableSelector<T>> {
late T _value;
@override
void initState() {
super.initState();
_value = widget.select();
widget.listenable?.addListener(_changed);
}
@override
void didUpdateWidget(covariant ListenableSelector<T> oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.listenable != widget.listenable) {
oldWidget.listenable?.removeListener(_changed);
widget.listenable?.addListener(_changed);
}
_value = widget.select();
}
void _changed() {
final value = widget.select();
if (value == _value) return;
setState(() => _value = value);
}
@override
Widget build(BuildContext context) => widget.builder(context, _value);
@override
void dispose() {
widget.listenable?.removeListener(_changed);
super.dispose();
}
}
+77
View File
@@ -0,0 +1,77 @@
import 'package:cutdex_ui/theme.dart';
import 'package:flutter/material.dart';
/// Paints the border outside the content clip, keeping both curves concentric.
class WorkspaceCard extends StatefulWidget {
const WorkspaceCard({super.key, required this.child});
static const radius = 12.0;
static const borderWidth = 1.0;
final Widget child;
@override
State<WorkspaceCard> createState() => _WorkspaceCardState();
}
class _WorkspaceCardState extends State<WorkspaceCard> {
late final ValueNotifier<Widget> _content;
late final Widget _frame;
@override
void initState() {
super.initState();
_content = ValueNotifier(widget.child);
_frame = _WorkspaceCardFrame(
child: ValueListenableBuilder<Widget>(
valueListenable: _content,
builder: (context, child, _) => child,
),
);
}
@override
void didUpdateWidget(covariant WorkspaceCard oldWidget) {
super.didUpdateWidget(oldWidget);
_content.value = widget.child;
}
@override
Widget build(BuildContext context) => _frame;
@override
void dispose() {
_content.dispose();
super.dispose();
}
}
/// The frame subscribes only to theme changes; content has its own update slot.
class _WorkspaceCardFrame extends StatelessWidget {
const _WorkspaceCardFrame({required this.child});
final Widget child;
@override
Widget build(BuildContext context) {
final surface = Theme.of(context).colorScheme.surface;
return DecoratedBox(
decoration: BoxDecoration(
color: surface,
borderRadius: BorderRadius.circular(WorkspaceCard.radius),
border: Border.all(
color: AppTheme.sidebarDividerColor(context),
width: WorkspaceCard.borderWidth,
),
),
child: Padding(
padding: const EdgeInsets.all(WorkspaceCard.borderWidth),
child: ClipRRect(
borderRadius: BorderRadius.circular(
WorkspaceCard.radius - WorkspaceCard.borderWidth,
),
clipBehavior: Clip.antiAlias,
child: Material(color: surface, child: child),
),
),
);
}
}
@@ -0,0 +1,101 @@
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
/// Keeps the resize cursor active across the window while a split is dragged.
class WorkspaceResizeHandle extends StatefulWidget {
const WorkspaceResizeHandle({
super.key,
required this.axis,
required this.initialValue,
required this.onResize,
this.direction = 1,
this.onEnd,
});
final Axis axis;
final double initialValue;
final double direction;
final ValueChanged<double> onResize;
final VoidCallback? onEnd;
@override
State<WorkspaceResizeHandle> createState() => _WorkspaceResizeHandleState();
}
class _WorkspaceResizeHandleState extends State<WorkspaceResizeHandle> {
OverlayEntry? _cursorOverlay;
double? _startPosition;
double _startValue = 0;
MouseCursor get _cursor => widget.axis == Axis.horizontal
? SystemMouseCursors.resizeColumn
: SystemMouseCursors.resizeRow;
double _coordinate(Offset position) =>
widget.axis == Axis.horizontal ? position.dx : position.dy;
void _start(DragStartDetails details) {
_startPosition = _coordinate(details.globalPosition);
_startValue = widget.initialValue;
_releaseCursor();
final cursor = _cursor;
_cursorOverlay = OverlayEntry(
builder: (_) => Positioned.fill(
child: MouseRegion(
cursor: cursor,
// Register the cursor while letting pointer hits reach widgets below.
hitTestBehavior: HitTestBehavior.translucent,
child: const SizedBox.expand(),
),
),
);
Overlay.of(context, rootOverlay: true).insert(_cursorOverlay!);
}
void _update(DragUpdateDetails details) {
final start = _startPosition;
if (start == null) return;
widget.onResize(
_startValue +
widget.direction * (_coordinate(details.globalPosition) - start),
);
}
void _releaseCursor() {
_cursorOverlay?.remove();
_cursorOverlay?.dispose();
_cursorOverlay = null;
}
void _finish() {
_startPosition = null;
_releaseCursor();
widget.onEnd?.call();
}
@override
void dispose() {
_releaseCursor();
super.dispose();
}
@override
Widget build(BuildContext context) => MouseRegion(
cursor: _cursor,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
dragStartBehavior: DragStartBehavior.down,
onHorizontalDragStart: widget.axis == Axis.horizontal ? _start : null,
onHorizontalDragUpdate: widget.axis == Axis.horizontal ? _update : null,
onHorizontalDragEnd: widget.axis == Axis.horizontal
? (_) => _finish()
: null,
onVerticalDragStart: widget.axis == Axis.vertical ? _start : null,
onVerticalDragUpdate: widget.axis == Axis.vertical ? _update : null,
onVerticalDragEnd: widget.axis == Axis.vertical ? (_) => _finish() : null,
onHorizontalDragCancel: widget.axis == Axis.horizontal ? _finish : null,
onVerticalDragCancel: widget.axis == Axis.vertical ? _finish : null,
child: const SizedBox.expand(),
),
);
}
+11 -3
View File
@@ -267,7 +267,11 @@ class Projects extends _$Projects {
} }
checkCurrent(); checkCurrent();
if (selectedDocument != null) { if (selectedDocument != null) {
await _prepareTimeline(active.id, selectedDocument); await _prepareTimeline(
active.id,
selectedDocument,
preparePreview: false,
);
} }
checkCurrent(); checkCurrent();
await ref await ref
@@ -653,8 +657,9 @@ class Projects extends _$Projects {
Future<EditorTimelineSession> _prepareTimeline( Future<EditorTimelineSession> _prepareTimeline(
String projectId, String projectId,
TimelineDocument document, TimelineDocument document, {
) async { bool preparePreview = true,
}) async {
final session = await _workspace.openTimelineSession(projectId, document); final session = await _workspace.openTimelineSession(projectId, document);
await TimelineViewStateBinding.prepare( await TimelineViewStateBinding.prepare(
projectId: projectId, projectId: projectId,
@@ -662,6 +667,9 @@ class Projects extends _$Projects {
session: session, session: session,
repository: ref.read(timelineViewSettingsRepositoryProvider), repository: ref.read(timelineViewSettingsRepositoryProvider),
); );
// The preview panel owns asynchronous startup after project publication.
// Cached controllers still bind synchronously when revisiting a project.
if (!preparePreview) return session;
try { try {
await ref.read(previewControllerRegistryProvider).prepare(( await ref.read(previewControllerRegistryProvider).prepare((
projectId, projectId,
+1 -1
View File
@@ -33,7 +33,7 @@ final class ProjectsProvider
Projects create() => Projects(); Projects create() => Projects();
} }
String _$projectsHash() => r'7112bbc5f1f4389d91f20aa9ec2ac5d28136eefe'; String _$projectsHash() => r'89495fb433ac9e5d066f0882599598fb2e0a4e54';
abstract class _$Projects extends $AsyncNotifier<ProjectState> { abstract class _$Projects extends $AsyncNotifier<ProjectState> {
FutureOr<ProjectState> build(); FutureOr<ProjectState> build();
+34
View File
@@ -8,6 +8,9 @@ import 'package:cutdex_sdk/timeline_ui.dart';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
import 'package:uuid/uuid.dart'; import 'package:uuid/uuid.dart';
import '../integrations/runtime/timeline_thumbnails.dart';
import '../integrations/runtime/timeline_waveforms.dart';
/// Flutter presentation resources for an SDK-owned editor session. /// Flutter presentation resources for an SDK-owned editor session.
class EditorTimelineSession extends EditorSession implements Listenable { class EditorTimelineSession extends EditorSession implements Listenable {
EditorTimelineSession({ EditorTimelineSession({
@@ -29,6 +32,35 @@ class EditorTimelineSession extends EditorSession implements Listenable {
_activeSequenceId = _activeSequenceId =
document.defaultSequenceId ?? document.sequences.firstOrNull?.id; document.defaultSequenceId ?? document.sequences.firstOrNull?.id;
} }
RuntimeTimelineThumbnails? _thumbnails;
RuntimeTimelineWaveforms? _waveforms;
/// Media caches live until the cached editor session is closed.
RuntimeTimelineThumbnails get thumbnails =>
_thumbnails ??= RuntimeTimelineThumbnails(
resolveTrackSelection: (ref) => mediaBinding(ref)?.videoSelection,
resolveMedia: (ref) {
final binding = mediaBinding(ref);
if (unavailableAssets.containsKey(binding?.media.id)) {
return null;
}
return binding?.videoTrackIndex == null ? null : binding!.media;
},
);
RuntimeTimelineWaveforms get waveforms =>
_waveforms ??= RuntimeTimelineWaveforms(
resolveTrackSelection: (ref) => mediaBinding(ref)?.audioSelection,
resolveGain: waveformGain,
gainChanges: audioGainPreview,
resolveMedia: (ref) {
final binding = mediaBinding(ref);
if (unavailableAssets.containsKey(binding?.media.id)) {
return null;
}
return binding?.audioTrackIndex == null ? null : binding!.media;
},
);
bool _disposed = false; bool _disposed = false;
AppFailure? get error => saveError == null AppFailure? get error => saveError == null
? null ? null
@@ -315,6 +347,8 @@ class EditorTimelineSession extends EditorSession implements Listenable {
if (_viewLeases > 0) return; if (_viewLeases > 0) return;
_disposed = true; _disposed = true;
super.dispose(); super.dispose();
_thumbnails?.dispose();
_waveforms?.dispose();
audioGainPreview.dispose(); audioGainPreview.dispose();
for (final controller in _views.values) { for (final controller in _views.values) {
controller.dispose(); controller.dispose();
+16 -23
View File
@@ -103,6 +103,17 @@ abstract final class AppTheme {
_ => 'sans-serif', _ => 'sans-serif',
}; };
static List<String> systemFontFamilyFallback(TargetPlatform platform) =>
switch (platform) {
TargetPlatform.windows => const [
'Microsoft YaHei UI',
'Microsoft YaHei',
'Noto Sans CJK SC',
'sans-serif',
],
_ => const ['PingFang SC', 'Noto Sans CJK SC', 'sans-serif'],
};
static Color popoverBackground(BuildContext context) { static Color popoverBackground(BuildContext context) {
final theme = Theme.of(context); final theme = Theme.of(context);
return theme.extension<AppSurfaces>()?.popoverBackground ?? return theme.extension<AppSurfaces>()?.popoverBackground ??
@@ -678,11 +689,7 @@ abstract final class AppTheme {
useMaterial3: true, useMaterial3: true,
colorScheme: colors, colorScheme: colors,
fontFamily: systemFontFamily(defaultTargetPlatform), fontFamily: systemFontFamily(defaultTargetPlatform),
fontFamilyFallback: const [ fontFamilyFallback: systemFontFamilyFallback(defaultTargetPlatform),
'PingFang SC',
'Noto Sans CJK SC',
'sans-serif',
],
textTheme: text, textTheme: text,
primaryTextTheme: text, primaryTextTheme: text,
scaffoldBackgroundColor: palette.background, scaffoldBackgroundColor: palette.background,
@@ -956,21 +963,11 @@ abstract final class AppTheme {
}) => TextStyle( }) => TextStyle(
inherit: false, inherit: false,
fontFamily: systemFontFamily(defaultTargetPlatform), fontFamily: systemFontFamily(defaultTargetPlatform),
fontFamilyFallback: const [ fontFamilyFallback: systemFontFamilyFallback(defaultTargetPlatform),
'PingFang SC',
'Noto Sans CJK SC',
'sans-serif',
],
textBaseline: TextBaseline.alphabetic, textBaseline: TextBaseline.alphabetic,
fontSize: size, fontSize: size,
height: lineHeight / size, height: lineHeight / size,
fontWeight: weight, fontWeight: weight,
fontVariations: [
FontVariation(
'wght',
weight == FontWeight.w400 ? 430 : weight.value.toDouble(),
),
],
letterSpacing: 0, letterSpacing: 0,
color: color ?? palette.foreground, color: color ?? palette.foreground,
); );
@@ -1199,16 +1196,12 @@ abstract final class AppSidebarTypography {
Color? color, Color? color,
}) => TextStyle( }) => TextStyle(
fontFamily: AppTheme.systemFontFamily(Theme.of(context).platform), fontFamily: AppTheme.systemFontFamily(Theme.of(context).platform),
fontFamilyFallback: const ['PingFang SC', 'Noto Sans CJK SC', 'sans-serif'], fontFamilyFallback: AppTheme.systemFontFamilyFallback(
Theme.of(context).platform,
),
fontSize: fontSize, fontSize: fontSize,
height: height, height: height,
fontWeight: weight, fontWeight: weight,
fontVariations: [
FontVariation(
'wght',
weight == FontWeight.w400 ? 430 : weight.value.toDouble(),
),
],
color: color ?? AppSidebarColors.of(context).primary, color: color ?? AppSidebarColors.of(context).primary,
); );
} }
@@ -0,0 +1,49 @@
import 'package:flutter/material.dart';
import '../theme/app_theme.dart';
/// A compact menu trigger with neutral interaction feedback.
class AppToolbarDropdownButton extends StatelessWidget {
const AppToolbarDropdownButton({
super.key,
this.buttonKey,
this.focusNode,
this.onPressed,
this.style,
required this.child,
});
final Key? buttonKey;
final FocusNode? focusNode;
final VoidCallback? onPressed;
final ButtonStyle? style;
final Widget child;
@override
Widget build(BuildContext context) => TextButton(
key: buttonKey,
focusNode: focusNode,
onPressed: onPressed,
style: AppTheme.toolbarButtonStyle(context)
.merge(style)
.copyWith(
backgroundColor: const WidgetStatePropertyAll(Colors.transparent),
overlayColor: WidgetStateProperty.resolveWith((states) {
if (states.contains(WidgetState.disabled)) {
return Colors.transparent;
}
return states.any(
{
WidgetState.hovered,
WidgetState.focused,
WidgetState.pressed,
}.contains,
)
? Theme.of(context).colorScheme.onSurface.withValues(alpha: .05)
: Colors.transparent;
}),
splashFactory: NoSplash.splashFactory,
),
child: child,
);
}
+1
View File
@@ -9,6 +9,7 @@ export 'src/widgets/app_scrub_label.dart';
export 'src/widgets/app_slider.dart'; export 'src/widgets/app_slider.dart';
export 'src/widgets/app_switch.dart'; export 'src/widgets/app_switch.dart';
export 'src/widgets/app_tabs.dart'; export 'src/widgets/app_tabs.dart';
export 'src/widgets/app_toolbar_dropdown_button.dart';
export 'src/widgets/app_text_field.dart'; export 'src/widgets/app_text_field.dart';
export 'src/widgets/compact_panel_tabs.dart'; export 'src/widgets/compact_panel_tabs.dart';
export 'src/widgets/delayed_loading_indicator.dart'; export 'src/widgets/delayed_loading_indicator.dart';
@@ -0,0 +1,59 @@
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
for (final theme in [AppTheme.penLight, AppTheme.penDark]) {
testWidgets('toolbar menu feedback is neutral in ${theme.brightness}', (
tester,
) async {
var presses = 0;
final focus = FocusNode();
addTearDown(focus.dispose);
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Scaffold(
body: AppToolbarDropdownButton(
buttonKey: const Key('trigger'),
focusNode: focus,
onPressed: () => presses++,
style: const ButtonStyle(
overlayColor: WidgetStatePropertyAll(Colors.blue),
),
child: const Text('Projects'),
),
),
),
);
final button = tester.widget<TextButton>(
find.byKey(const Key('trigger')),
);
for (final state in [
WidgetState.hovered,
WidgetState.focused,
WidgetState.pressed,
]) {
expect(
button.style!.backgroundColor!.resolve({state}),
Colors.transparent,
);
expect(
button.style!.overlayColor!.resolve({state}),
theme.colorScheme.onSurface.withValues(alpha: .05),
);
expect(
button.style!.overlayColor!.resolve({state, WidgetState.disabled}),
Colors.transparent,
);
}
await tester.tap(find.byKey(const Key('trigger')));
await tester.pump();
expect(presses, 1);
focus.requestFocus();
await tester.pump();
expect(focus.hasFocus, isTrue);
});
}
}
+6 -5
View File
@@ -302,11 +302,12 @@ packages:
deskup: deskup:
dependency: "direct main" dependency: "direct main"
description: description:
name: deskup path: "."
sha256: "5a7fb021ba3207e5a85d440d378832156896d2eea616838ad21547aa0af68df1" ref: ccbeb02ed1bbf6b4388981a0e641aff7404637bd
url: "https://pub.dev" resolved-ref: ccbeb02ed1bbf6b4388981a0e641aff7404637bd
source: hosted url: "https://github.com/lingjhf/deskup.git"
version: "0.1.0" source: git
version: "0.3.0"
drift: drift:
dependency: "direct main" dependency: "direct main"
description: description:
+6 -3
View File
@@ -2,10 +2,10 @@ name: cutdex
description: "Cutdex video editing application." description: "Cutdex video editing application."
publish_to: none publish_to: none
version: 0.1.0+1 version: 0.1.1+2
environment: environment:
sdk: ^3.13.2 sdk: ^3.13.4
workspace: workspace:
- packages/* - packages/*
@@ -13,7 +13,10 @@ workspace:
dependencies: dependencies:
cutdex_ui: ^0.1.0 cutdex_ui: ^0.1.0
cutdex_native: ^0.1.0 cutdex_native: ^0.1.0
deskup: ^0.1.0 deskup:
git:
url: https://github.com/lingjhf/deskup.git
ref: ccbeb02ed1bbf6b4388981a0e641aff7404637bd
flutter: flutter:
sdk: flutter sdk: flutter
+130 -75
View File
@@ -22,7 +22,6 @@ import 'package:cutdex/integrations/agent/conversation_repository.dart';
import 'package:cutdex/integrations/platform/device_experience.dart'; import 'package:cutdex/integrations/platform/device_experience.dart';
import 'package:cutdex/persistence/app_database.dart'; import 'package:cutdex/persistence/app_database.dart';
import 'package:cutdex/persistence/app_settings_repositories.dart'; import 'package:cutdex/persistence/app_settings_repositories.dart';
import 'package:cutdex/shared/layout/workspace_layout_metrics.dart';
import 'package:cutdex/workspace/media_availability.dart'; import 'package:cutdex/workspace/media_availability.dart';
import 'package:cutdex/workspace/project_state.dart'; import 'package:cutdex/workspace/project_state.dart';
import 'package:cutdex/workspace/projects.dart'; import 'package:cutdex/workspace/projects.dart';
@@ -139,6 +138,48 @@ void main() {
await tester.pumpAndSettle(); await tester.pumpAndSettle();
} }
testWidgets(
'desktop navigation switches sidebar content and retains workspace',
(tester) async {
final mounted = await mount(tester, const Size(1200, 800));
final headerToggle = find.byKey(const Key('project-sidebar-toggle'));
final headerTasks = find.byKey(const ValueKey('background-tasks-button'));
expect(tester.getSize(headerToggle), const Size.square(28));
expect(tester.getSize(headerTasks), const Size.square(28));
expect(
tester.getRect(headerToggle).center.dx,
tester.getRect(find.byKey(const Key('desktop-rail-cut'))).center.dx,
);
expect(
tester.getRect(headerTasks).center.dx -
tester.getRect(headerToggle).center.dx,
32,
);
expect(find.byKey(const Key('desktop-rail-agent')), findsNothing);
expect(find.byKey(const Key('desktop-rail-cut')), findsOneWidget);
final library = find.byKey(const Key('desktop-rail-library'));
final editorElement = tester.element(find.byType(EditorWorkspace));
await tester.tap(library);
await tester.pumpAndSettle();
expect(find.byKey(const Key('desktop-library-workspace')), findsNothing);
expect(find.byType(EditorWorkspace), findsOneWidget);
expect(
tester.element(find.byType(EditorWorkspace, skipOffstage: false)),
same(editorElement),
);
expect(find.byType(MediaPanel), findsOneWidget);
expect(tester.widget<IconButton>(library).isSelected, isTrue);
expect(find.byKey(const Key('project-settings-button')), findsOneWidget);
await tester.tap(find.byKey(const Key('desktop-rail-cut')));
await tester.pumpAndSettle();
expect(find.byKey(const Key('desktop-library-workspace')), findsNothing);
expect(tester.element(find.byType(EditorWorkspace)), same(editorElement));
expect(find.byType(MediaPanel), findsNothing);
expect(tester.takeException(), isNull);
await mounted.close();
},
);
testWidgets('Windows caption space follows real workspace pane changes', ( testWidgets('Windows caption space follows real workspace pane changes', (
tester, tester,
) async { ) async {
@@ -160,14 +201,29 @@ void main() {
messenger.setMockMethodCallHandler(dropChannel, null); messenger.setMockMethodCallHandler(dropChannel, null);
}); });
final mounted = await mount(tester, const Size(1200, 800)); final mounted = await mount(tester, const Size(1200, 800));
final contentRect = tester.getRect(
find.byKey(const Key('desktop-content-container')),
);
expect(
contentRect.top,
tester.getRect(find.byKey(const Key('desktop-window-header'))).bottom,
);
expect(
contentRect.left,
tester.getRect(find.byKey(const Key('desktop-navigation-rail'))).right,
);
expect(contentRect.right, 1199);
expect(contentRect.bottom, 799);
for (final mode in [WorkspaceMode.agent, WorkspaceMode.cut]) { for (final mode in [WorkspaceMode.agent, WorkspaceMode.cut]) {
await setMode(tester, mounted.container, mode); await setMode(tester, mounted.container, mode);
for (final width in [1200.0, 700.0, 400.0, 1200.0]) { for (final width in [1200.0, 700.0, 400.0, 1200.0]) {
tester.view.physicalSize = Size(width, 800); tester.view.physicalSize = Size(width, 800);
await tester.pumpAndSettle(); await tester.pumpAndSettle();
final controlsLeft = tester final captionRect = tester
.getTopLeft(find.byKey(const Key('window-minimize'))) .getRect(find.byKey(const Key('window-minimize')))
.dx; .expandToInclude(
tester.getRect(find.byKey(const Key('window-close'))),
);
for (final key in [ for (final key in [
'editor-media-button', 'editor-media-button',
'editor-properties-button', 'editor-properties-button',
@@ -191,8 +247,8 @@ void main() {
}); });
if (rect.isEmpty) continue; if (rect.isEmpty) continue;
expect( expect(
rect.right, rect.overlaps(captionRect),
lessThanOrEqualTo(controlsLeft + 0.1), isFalse,
reason: '$key at $width in $mode', reason: '$key at $width in $mode',
); );
} }
@@ -285,69 +341,45 @@ void main() {
}, },
); );
testWidgets( testWidgets('desktop resources retain state across navigation switches', (
'desktop tools overlay in limited editor space and restore fixed sidebars', tester,
(tester) async { ) async {
final mounted = await mount(tester, const Size(1200, 800)); final mounted = await mount(tester, const Size(1800, 800));
await setMode(tester, mounted.container, WorkspaceMode.cut); await setMode(tester, mounted.container, WorkspaceMode.cut);
await tester.tap(find.byKey(const Key('editor-media-button'))); expect(find.byKey(const Key('editor-media-button')), findsNothing);
await tester.tap(find.byKey(const Key('editor-properties-button'))); await tester.tap(find.byKey(const Key('desktop-rail-library')));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect( final mediaElement = tester.element(find.byType(MediaPanel));
tester.getSize(find.byType(MediaPanel)).width,
WorkspaceLayoutMetrics.mediaPanelWidth,
);
expect(
tester.getSize(find.byType(EditorPropertiesPanel)).width,
WorkspaceLayoutMetrics.propertiesPanelWidth,
);
expect(find.byKey(const Key('editor-tool-surface')), findsNothing);
await setMode(tester, mounted.container, WorkspaceMode.agent);
expect(find.byKey(const Key('editor-tool-surface')), findsOneWidget);
expect(find.byType(EditorPropertiesPanel), findsOneWidget);
expect(find.byType(PropertiesEditorPage), findsNothing);
expect(find.byType(EditorTimelinePanel), findsOneWidget);
expect(
mounted.container
.read(projectViewSettingsProvider(mounted.projectId))
.requireValue
.propertiesOpen,
isTrue,
);
await tester.tap(find.byKey(const Key('editor-media-button')));
await tester.pumpAndSettle();
expect(find.byType(MediaPanel), findsOneWidget);
expect(find.byType(MediaBrowserDrawer), findsNothing);
expect(find.byType(PropertiesToolPanel), findsNothing);
expect( expect(
tester tester
.widget<IconButton>(find.byKey(const Key('editor-media-button'))) .getRect(find.byKey(const Key('desktop-project-card')))
.isSelected, .contains(tester.getRect(find.byType(MediaPanel)).center),
isTrue, isTrue,
); );
await setMode(tester, mounted.container, WorkspaceMode.cut); final browser = mounted.container.read(
expect(find.byKey(const Key('editor-tool-surface')), findsNothing); mediaBrowserProvider(mounted.projectId),
expect(
tester.getSize(find.byType(MediaPanel)).width,
WorkspaceLayoutMetrics.mediaPanelWidth,
);
expect(
tester.getSize(find.byType(EditorPropertiesPanel)).width,
WorkspaceLayoutMetrics.propertiesPanelWidth,
);
expect(
await mounted.container.read(
editorTimelineProvider(mounted.projectId, 'project').future,
),
same(mounted.session),
); );
browser.filter = MediaFilter.image;
browser.selectedAssetId = 'media';
await tester.tap(find.byKey(const Key('desktop-rail-cut')));
await tester.pumpAndSettle();
expect(find.byType(MediaPanel), findsNothing);
await tester.tap(find.byKey(const Key('desktop-rail-library')));
await tester.pumpAndSettle();
expect(tester.element(find.byType(MediaPanel)), same(mediaElement));
expect(browser.filter, MediaFilter.image);
expect(browser.selectedAssetId, 'media');
expect(find.byKey(const Key('sidebar-tab-resources')), findsNothing);
expect(find.byType(EditorWorkspace), findsOneWidget);
await tester.tap(find.byKey(const Key('desktop-rail-cut')));
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('editor-properties-button')));
await tester.pumpAndSettle();
expect(find.byType(EditorPropertiesPanel), findsOneWidget);
expect(find.byKey(const Key('editor-media-region')), findsNothing);
expect(tester.takeException(), isNull); expect(tester.takeException(), isNull);
await mounted.close(); await mounted.close();
}, });
);
testWidgets( testWidgets(
'phone tools use independent pages without changing desktop preferences', 'phone tools use independent pages without changing desktop preferences',
(tester) async { (tester) async {
@@ -449,7 +481,15 @@ void main() {
experience: experience, experience: experience,
); );
await setMode(tester, mounted.container, WorkspaceMode.cut); await setMode(tester, mounted.container, WorkspaceMode.cut);
await tester.tap(find.byKey(const Key('editor-media-button'))); await tester.tap(
find.byKey(
Key(
experience == DeviceExperience.desktop
? 'desktop-rail-library'
: 'editor-media-button',
),
),
);
await tester.pumpAndSettle(); await tester.pumpAndSettle();
final browser = mounted.container.read( final browser = mounted.container.read(
mediaBrowserProvider(mounted.projectId), mediaBrowserProvider(mounted.projectId),
@@ -463,8 +503,19 @@ void main() {
]) { ]) {
tester.view.physicalSize = size; tester.view.physicalSize = size;
await tester.pumpAndSettle(); await tester.pumpAndSettle();
if (experience == DeviceExperience.desktop) {
if (size.width < 700) {
await tester.tap(find.byKey(const Key('project-sidebar-toggle')));
await tester.pumpAndSettle();
}
await tester.tap(find.byKey(const Key('desktop-rail-library')));
await tester.pumpAndSettle();
}
expect( expect(
find.byKey(Key('${experience.name}-workspace-shell')), find.byKey(
Key('${experience.name}-workspace-shell'),
skipOffstage: false,
),
findsOneWidget, findsOneWidget,
); );
expect( expect(
@@ -506,7 +557,10 @@ void main() {
); );
if (experience == DeviceExperience.desktop) { if (experience == DeviceExperience.desktop) {
expect( expect(
find.byKey(const Key('editor-timeline-resize')), find.byKey(
const Key('editor-timeline-resize'),
skipOffstage: false,
),
findsOneWidget, findsOneWidget,
); );
} }
@@ -517,6 +571,10 @@ void main() {
expect(browser.filter, MediaFilter.image); expect(browser.filter, MediaFilter.image);
expect(browser.selectedAssetId, 'media'); expect(browser.selectedAssetId, 'media');
expect(tester.takeException(), isNull); expect(tester.takeException(), isNull);
if (experience == DeviceExperience.desktop && size.width < 700) {
Scaffold.of(tester.element(find.byType(MediaPanel))).closeDrawer();
await tester.pumpAndSettle();
}
} }
await mounted.close(); await mounted.close();
}, },
@@ -957,14 +1015,17 @@ void main() {
} }
resolver.gate.complete(); resolver.gate.complete();
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(find.byType(SnackBar), findsNothing); expect(find.byKey(const Key('global-error-notification')), findsNothing);
if (target == 'media') { if (target == 'media') {
await tester.tap(find.byKey(const Key('editor-media-button'))); await tester.tap(find.byKey(const Key('editor-media-button')));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
} else { } else {
await setMode(tester, mounted.container, WorkspaceMode.agent); await setMode(tester, mounted.container, WorkspaceMode.agent);
} }
expect(find.byType(SnackBar), findsOneWidget); expect(
find.byKey(const Key('global-error-notification')),
findsOneWidget,
);
expect(find.textContaining('bad.mov:'), findsOneWidget); expect(find.textContaining('bad.mov:'), findsOneWidget);
final feedback = target == 'media' final feedback = target == 'media'
? mounted.container ? mounted.container
@@ -980,8 +1041,7 @@ void main() {
) )
.feedback; .feedback;
expect(feedback.hasPending, isFalse); expect(feedback.hasPending, isFalse);
ScaffoldMessenger.of(tester.element(find.byType(SnackBar))) await tester.tap(find.byKey(const Key('close-error-button')));
.removeCurrentSnackBar();
await tester.pumpAndSettle(); await tester.pumpAndSettle();
await setMode(tester, mounted.container, WorkspaceMode.cut); await setMode(tester, mounted.container, WorkspaceMode.cut);
await setMode(tester, mounted.container, WorkspaceMode.agent); await setMode(tester, mounted.container, WorkspaceMode.agent);
@@ -990,7 +1050,7 @@ void main() {
await tester.tap(find.byKey(const Key('editor-media-button'))); await tester.tap(find.byKey(const Key('editor-media-button')));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
} }
expect(find.byType(SnackBar), findsNothing); expect(find.byKey(const Key('global-error-notification')), findsNothing);
expect(tester.takeException(), isNull); expect(tester.takeException(), isNull);
}); });
} }
@@ -1002,14 +1062,9 @@ void main() {
expect(find.byKey(const Key('desktop-workspace-shell')), findsOneWidget); expect(find.byKey(const Key('desktop-workspace-shell')), findsOneWidget);
expect(find.byKey(const Key('agent-panel-resize')), findsNothing); expect(find.byKey(const Key('agent-panel-resize')), findsNothing);
expect(tester.takeException(), isNull); expect(tester.takeException(), isNull);
tester.view.physicalSize = const Size(240, 800); tester.view.physicalSize = const Size(308, 800);
await tester.pumpAndSettle();
expect(find.byKey(const Key('agent-panel-resize')), findsOneWidget);
await tester.drag(
find.byKey(const Key('agent-panel-resize')),
const Offset(-20, 0),
);
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(find.byKey(const Key('agent-panel-resize')), findsNothing);
expect(tester.takeException(), isNull); expect(tester.takeException(), isNull);
tester.view.physicalSize = const Size(200, 800); tester.view.physicalSize = const Size(200, 800);
await tester.pumpAndSettle(); await tester.pumpAndSettle();
+27 -8
View File
@@ -1,3 +1,6 @@
import 'package:go_router/go_router.dart';
import 'package:cutdex/features/settings/settings_page.dart';
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:cutdex/app/editor_theme.dart'; import 'package:cutdex/app/editor_theme.dart';
import 'dart:io'; import 'dart:io';
@@ -110,14 +113,11 @@ void main() {
Future<void> panel(WidgetTester tester, {String? conversationId}) async { Future<void> panel(WidgetTester tester, {String? conversationId}) async {
await tester.binding.setSurfaceSize(const Size(1000, 760)); await tester.binding.setSurfaceSize(const Size(1000, 760));
addTearDown(() => tester.binding.setSurfaceSize(null)); addTearDown(() => tester.binding.setSurfaceSize(null));
await tester.pumpWidget( final router = GoRouter(
UncontrolledProviderScope( routes: [
container: container, GoRoute(
child: MaterialApp( path: '/',
localizationsDelegates: AppLocalizations.localizationsDelegates, builder: (context, state) => Scaffold(
supportedLocales: AppLocalizations.supportedLocales,
theme: EditorTheme.penDark,
home: Scaffold(
body: SizedBox( body: SizedBox(
width: 360, width: 360,
child: AgentChatPanel( child: AgentChatPanel(
@@ -128,6 +128,25 @@ void main() {
), ),
), ),
), ),
GoRoute(
path: '/settings',
builder: (context, state) => SettingsPage(
initialTab: int.parse(state.uri.queryParameters['tab'] ?? '0'),
),
),
],
);
addTearDown(router.dispose);
await tester.pumpWidget(
UncontrolledProviderScope(
container: container,
child: MaterialApp.router(
routerConfig: router,
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
theme: EditorTheme.penDark,
builder: (context, child) => ErrorNotificationHost(child: child!),
),
), ),
); );
await tester.pumpAndSettle(); await tester.pumpAndSettle();
+30
View File
@@ -0,0 +1,30 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:cutdex/integrations/app_update_configuration.dart';
void main() {
test('production ignores development source overrides', () {
final config = windowsUpdateConfiguration(
flavor: 'production',
developmentUrl: 'http://127.0.0.1:8765',
developmentSource: 'web',
allowLocalHttp: true,
)!;
final map = config.toMap();
expect(
(map['source'] as Map)['url'],
'https://git.orangraph.com/lingjhf/cutdex',
);
expect(map['expectedPackageId'], 'Cutdex');
});
test('development requires opt-in and uses an isolated identity', () {
expect(windowsUpdateConfiguration(flavor: 'development'), isNull);
final map = windowsUpdateConfiguration(
flavor: 'development',
developmentUrl: 'http://127.0.0.1:8765',
developmentSource: 'web',
allowLocalHttp: true,
)!.toMap();
expect(map['expectedPackageId'], 'Cutdex.Dev');
expect((map['source'] as Map)['type'], 'web');
});
}
+3 -2
View File
@@ -126,9 +126,10 @@ void main() {
.closeSource(); .closeSource();
} }
await access.dispose(); await access.dispose();
// UI/provider disposal owns the project; allow its async cleanup to finish. // Provider disposal starts async cleanup without waiting for it. Close the
// workspace explicitly before deleting files, especially on Windows.
await container.read(projectsProvider.notifier).prepareToQuit();
container.dispose(); container.dispose();
await Future<void>.delayed(const Duration(milliseconds: 50));
await root.delete(recursive: true); await root.delete(recursive: true);
messenger.setMockMethodCallHandler(native, null); messenger.setMockMethodCallHandler(native, null);
messenger.setMockMethodCallHandler(events, null); messenger.setMockMethodCallHandler(events, null);
+244
View File
@@ -0,0 +1,244 @@
import 'package:cutdex/app/adaptive/desktop_workspace_controller.dart';
import 'package:cutdex/app/shells/desktop_workspace_shell.dart';
import 'package:cutdex/workspace/workspace_mode.dart';
import 'package:cutdex/features/editor/layouts/expanded_editor_layout.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets(
'properties divider spans the preview card including its header',
(tester) async {
tester.view.physicalSize = const Size(1000, 800);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
var showProperties = true;
late StateSetter update;
await tester.pumpWidget(
MaterialApp(
home: StatefulBuilder(
builder: (context, setState) {
update = setState;
return ExpandedEditorLayout(
preview: const SizedBox.expand(key: Key('test-preview')),
header: const SizedBox(height: 40, key: Key('test-header')),
properties: const SizedBox.expand(),
media: const SizedBox(),
showMedia: false,
showProperties: showProperties,
timelineHeight: 200,
onTimelineHeightChanged: (_) {},
onTimelineHeightChangeEnd: () {},
timeline: const SizedBox(),
);
},
),
),
);
final card = tester.getRect(find.byKey(const Key('editor-preview-card')));
final divider = tester.getRect(
find.byKey(const Key('editor-properties-divider')),
);
final properties = tester.getRect(
find.byKey(const Key('editor-properties-region')),
);
final header = tester.getRect(find.byKey(const Key('test-header')));
expect(divider.top, card.top + 1);
expect(divider.bottom, card.bottom - 1);
expect(properties.top, divider.top);
expect(properties.bottom, divider.bottom);
expect(header.right, divider.left);
expect(properties.left, divider.right);
final preview = tester.element(find.byKey(const Key('test-preview')));
update(() => showProperties = false);
await tester.pump();
expect(find.byKey(const Key('editor-properties-divider')), findsNothing);
expect(
tester.getRect(find.byKey(const Key('test-header'))).right,
card.right - 1,
);
expect(
tester.element(find.byKey(const Key('test-preview'))),
same(preview),
);
expect(tester.takeException(), isNull);
},
);
testWidgets('preview and timeline cards resize through their 1 dp gap', (
tester,
) async {
tester.view.physicalSize = const Size(700, 800);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
double? timelineHeight;
var saves = 0;
await tester.pumpWidget(
MaterialApp(
home: StatefulBuilder(
builder: (context, update) => ExpandedEditorLayout(
preview: const Text('Preview'),
header: const SizedBox(height: 46, child: Text('Preview controls')),
properties: const SizedBox(),
media: const SizedBox(),
showMedia: false,
showProperties: false,
timelineHeight: timelineHeight,
onTimelineHeightChanged: (value) =>
update(() => timelineHeight = value),
onTimelineHeightChangeEnd: () => saves++,
timeline: const Column(
children: [
Text('Toolbar'),
Expanded(child: Text('Timeline')),
],
),
),
),
),
);
Rect card(String name) =>
tester.getRect(find.byKey(Key('editor-$name-card')));
final timelineBefore = card('timeline');
expect(timelineBefore.top - card('preview').bottom, 1);
final resize = find.byKey(const Key('editor-timeline-resize'));
expect(tester.getSize(resize).height, 5);
expect(
find.descendant(
of: find.byKey(const Key('editor-timeline-card')),
matching: find.text('Toolbar'),
),
findsOneWidget,
);
await tester.dragFrom(
tester.getCenter(resize) + const Offset(0, -2),
const Offset(0, -80),
);
await tester.pumpAndSettle();
expect(card('timeline').height, timelineBefore.height + 80);
expect(card('timeline').top - card('preview').bottom, 1);
expect(saves, 1);
await tester.dragFrom(
tester.getCenter(resize) + const Offset(0, 2),
const Offset(0, 20),
);
await tester.pumpAndSettle();
expect(card('timeline').height, timelineBefore.height + 60);
expect(saves, 2);
await tester.dragFrom(
tester.getCenter(resize) + const Offset(0, 3),
const Offset(0, -30),
);
await tester.pumpAndSettle();
expect(card('timeline').height, timelineBefore.height + 60);
expect(saves, 2);
expect(tester.takeException(), isNull);
});
testWidgets(
'desktop cards keep their order and resize through both gutters',
(tester) async {
tester.view.physicalSize = const Size(1600, 900);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
final controller = DesktopWorkspaceController();
addTearDown(controller.dispose);
double sidebarWidth = 260;
var mode = WorkspaceMode.agent;
late StateSetter update;
await tester.pumpWidget(
MaterialApp(
home: StatefulBuilder(
builder: (context, setState) {
update = setState;
return DesktopWorkspaceShell(
mode: mode,
controller: controller,
sidebarCollapsed: false,
sidebarWidth: sidebarWidth,
onSidebarCollapsedChanged: (_) {},
onSidebarWidthChanged: (value) =>
setState(() => sidebarWidth = value),
sidebarBuilder: (_, _) => const Text('Projects'),
agentBuilder: (_, _) => const Text('Agent'),
editor: const Text('Editor'),
scaffoldKey: GlobalKey<ScaffoldState>(),
navigationDrawer: const SizedBox(),
);
},
),
),
);
Rect card(String name) =>
tester.getRect(find.byKey(Key('desktop-$name-card')));
final project = card('project');
final editor = card('editor');
final agent = card('agent');
expect(editor.left - project.right, 1);
expect(agent.left - editor.right, 1);
expect(project.top, editor.top);
expect(editor.bottom, agent.bottom);
final projectResize = find.byKey(const Key('project-sidebar-resize'));
final agentResize = find.byKey(const Key('agent-panel-resize'));
expect(tester.getSize(projectResize).width, 5);
expect(tester.getSize(agentResize).width, 5);
await tester.dragFrom(
tester.getCenter(projectResize) + const Offset(-2, 0),
const Offset(60, 0),
);
await tester.pumpAndSettle();
expect(card('project').width, project.width + 60);
expect(card('agent').width, agent.width);
await tester.dragFrom(
tester.getCenter(agentResize) + const Offset(2, 0),
const Offset(-80, 0),
);
await tester.pumpAndSettle();
expect(card('agent').width, agent.width + 80);
expect(card('project').width, project.width + 60);
expect(card('agent').left - card('editor').right, 1);
await tester.dragFrom(
tester.getCenter(projectResize) + const Offset(2, 0),
const Offset(-20, 0),
);
await tester.pumpAndSettle();
expect(card('project').width, project.width + 40);
await tester.dragFrom(
tester.getCenter(agentResize) + const Offset(-2, 0),
const Offset(20, 0),
);
await tester.pumpAndSettle();
expect(card('agent').width, agent.width + 60);
await tester.dragFrom(
tester.getCenter(projectResize) + const Offset(-3, 0),
const Offset(30, 0),
);
await tester.pumpAndSettle();
expect(card('project').width, project.width + 40);
expect(card('editor').left - card('project').right, 1);
update(() => mode = WorkspaceMode.cut);
await tester.pumpAndSettle();
expect(find.byKey(const Key('desktop-agent-card')), findsOneWidget);
expect(card('editor').left, greaterThan(card('project').right));
expect(card('agent').left, greaterThan(card('editor').right));
final agentElement = tester.element(find.text('Agent'));
await tester.drag(agentResize, const Offset(-2000, 0));
await tester.pumpAndSettle();
expect(find.text('Agent'), findsOneWidget);
expect(tester.element(find.text('Agent')), same(agentElement));
expect(find.text('Editor'), findsOneWidget);
expect(card('editor').width, 480);
expect(agentResize, findsOneWidget);
await tester.drag(agentResize, const Offset(600, 0));
await tester.pumpAndSettle();
expect(find.text('Agent'), findsOneWidget);
expect(find.text('Editor'), findsOneWidget);
expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox());
},
);
}
@@ -1,3 +1,5 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'dart:convert'; import 'dart:convert';
import 'dart:io'; import 'dart:io';
@@ -167,6 +169,7 @@ void main() {
localizationsDelegates: AppLocalizations.localizationsDelegates, localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales, supportedLocales: AppLocalizations.supportedLocales,
theme: EditorTheme.penLight, theme: EditorTheme.penLight,
builder: (context, child) => ErrorNotificationHost(child: child!),
home: Scaffold(body: SizedBox(width: 800, height: 600, child: child)), home: Scaffold(body: SizedBox(width: 800, height: 600, child: child)),
); );
+72
View File
@@ -0,0 +1,72 @@
import 'package:cutdex/app/editor_theme.dart';
import 'package:cutdex/features/editor/editor_panel_defaults.dart';
import 'package:cutdex/features/preview/preview_panel.dart';
import 'package:cutdex/l10n/app_localizations.dart';
import 'package:cutdex_sdk/editor.dart';
import 'package:cutdex_ui/widgets.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('pending preview uses black, zero times and default ratio', (
tester,
) async {
await tester.pumpWidget(
ProviderScope(
child: MaterialApp(
theme: EditorTheme.penLight,
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
locale: const Locale('en'),
home: const Scaffold(
body: EditorPreviewPanel(
projectId: 'pending-project',
timelineId: '',
pending: true,
),
),
),
),
);
expect(find.text('00:00:00:00 / 00:00:00:00'), findsOneWidget);
expect(
tester
.widget<ColoredBox>(find.byKey(const Key('preview-default-frame')))
.color,
Colors.black,
);
final ratio = tester.widget<AppSelect<ProjectCanvas>>(
find.byType(AppSelect<ProjectCanvas>),
);
expect(ratio.value, ProjectCanvas.widescreen);
expect(ratio.onChanged, isNull);
final play = tester.widget<IconButton>(
find.widgetWithIcon(IconButton, Icons.play_arrow),
);
expect(play.onPressed, isNull);
expect(find.byType(CircularProgressIndicator), findsNothing);
expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox());
});
testWidgets('default timeline has empty content and disabled commands', (
tester,
) async {
await tester.pumpWidget(
MaterialApp(
theme: EditorTheme.penLight,
home: const Scaffold(body: EditorTimelineDefaults()),
),
);
expect(find.byKey(const Key('timeline-default-tracks')), findsOneWidget);
expect(find.byKey(const Key('timeline-toolbar')), findsOneWidget);
for (final button in tester.widgetList<IconButton>(
find.byType(IconButton),
)) {
expect(button.onPressed, isNull);
}
expect(find.byType(CircularProgressIndicator), findsNothing);
expect(tester.takeException(), isNull);
});
}
+104
View File
@@ -0,0 +1,104 @@
import 'package:cutdex/errors/app_failure.dart';
import 'package:cutdex/l10n/app_localizations.dart';
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
Future<ErrorNotificationHostState> mount(WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
builder: (context, child) => ErrorNotificationHost(child: child!),
home: const Scaffold(body: Text('Workspace')),
),
);
return tester.state<ErrorNotificationHostState>(
find.byType(ErrorNotificationHost),
);
}
testWidgets('top error copies complete details and closes', (tester) async {
String? copied;
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
(call) async {
if (call.method == 'Clipboard.setData') {
copied = (call.arguments as Map)['text'] as String;
}
return null;
},
);
addTearDown(
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
null,
),
);
final host = await mount(tester);
host.showFailure(
const AppFailure(
AppErrorCode.resourceDownloadHttpFailed,
httpStatusCode: 503,
diagnostic: 'service unavailable',
),
'Download failed',
);
await tester.pump();
final notice = find.byKey(const Key('global-error-notification'));
expect(tester.getRect(notice).top, 48);
expect(find.byType(SnackBar), findsNothing);
await tester.tap(find.byKey(const Key('copy-error-button')));
await tester.pump();
expect(copied, contains('Download failed'));
expect(copied, contains('code: resourceDownloadHttpFailed'));
expect(copied, contains('HTTP: 503'));
expect(copied, contains('service unavailable'));
expect(find.byIcon(Icons.check), findsOneWidget);
await tester.tap(find.byKey(const Key('close-error-button')));
await tester.pump();
expect(notice, findsNothing);
});
testWidgets('errors queue and pause dismissal while hovered', (tester) async {
final host = await mount(tester);
host.show(const ErrorNotification(content: Text('First')));
host.show(const ErrorNotification(content: Text('Second')));
await tester.pump();
expect(find.text('First'), findsOneWidget);
expect(find.text('Second'), findsNothing);
final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
await mouse.addPointer(location: Offset.zero);
await mouse.moveTo(
tester.getCenter(find.byKey(const Key('global-error-notification'))),
);
await tester.pump(const Duration(seconds: 9));
expect(find.text('First'), findsOneWidget);
await mouse.moveTo(const Offset(1, 500));
await tester.pump(const Duration(seconds: 8));
expect(find.text('Second'), findsOneWidget);
await tester.pump(const Duration(seconds: 8));
expect(find.byKey(const Key('global-error-notification')), findsNothing);
await mouse.removePointer();
});
testWidgets('error remains above an open dialog', (tester) async {
final host = await mount(tester);
final context = tester.element(find.text('Workspace'));
showDialog<void>(
context: context,
builder: (_) => const AlertDialog(content: Text('Dialog')),
);
await tester.pumpAndSettle();
host.show(const ErrorNotification(content: Text('Dialog error')));
await tester.pump();
expect(find.text('Dialog'), findsOneWidget);
await tester.tap(find.byKey(const Key('close-error-button')));
await tester.pump();
expect(find.text('Dialog error'), findsNothing);
expect(find.text('Dialog'), findsOneWidget);
});
}
@@ -59,6 +59,8 @@ class _Repository extends ConversationRepository {
_Repository() : super(Directory('/unused')); _Repository() : super(Directory('/unused'));
Completer<List<ConversationMetadata>>? blocked; Completer<List<ConversationMetadata>>? blocked;
final started = Completer<void>(); final started = Completer<void>();
int groupReads = 0;
Completer<List<ConversationMetadata>>? blockedTrash;
bool fail = false; bool fail = false;
bool failDelete = false; bool failDelete = false;
final trashed = <ConversationMetadata>[]; final trashed = <ConversationMetadata>[];
@@ -69,7 +71,8 @@ class _Repository extends ConversationRepository {
String projectId, { String projectId, {
bool trash = false, bool trash = false,
}) async { }) async {
if (trash) return List.of(trashed); if (trash) return blockedTrash?.future ?? Future.value(List.of(trashed));
groupReads++;
if (fail) throw StateError('read failed'); if (fail) throw StateError('read failed');
if (projectId == 'a' && blocked != null) { if (projectId == 'a' && blocked != null) {
if (!started.isCompleted) started.complete(); if (!started.isCompleted) started.complete();
@@ -267,6 +270,29 @@ void main() {
}, },
); );
test(
'project switching keeps groups visible without rereading their listings',
() async {
final initial = container.read(conversationSidebarProvider).requireValue;
final reads = repository.groupReads;
repository.blockedTrash = Completer();
(container.read(projectsProvider.notifier) as _Projects).selectProject(1);
await container.pump();
final switching = container.read(conversationSidebarProvider);
expect(switching.isLoading, isFalse);
expect(switching.requireValue.groups['a'], same(initial.groups['a']));
expect(switching.requireValue.groups['b'], same(initial.groups['b']));
expect(repository.groupReads, reads);
repository.blockedTrash!.complete([]);
await container.pump();
expect(
container.read(conversationSidebarProvider).requireValue.projectId,
'b',
);
expect(repository.groupReads, reads);
},
);
test('reopening a project reloads its saved selection', () async { test('reopening a project reloads its saved selection', () async {
final provider = conversationSelectionProvider('a'); final provider = conversationSelectionProvider('a');
container.listen(provider, (_, _) {}); container.listen(provider, (_, _) {});
+48
View File
@@ -0,0 +1,48 @@
import 'package:cutdex/shared/widgets/listenable_selector.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('selection ignores unrelated events and detaches old sources', (
tester,
) async {
final first = _Source((time: 0, playing: false));
final second = _Source((time: 0, playing: true));
addTearDown(first.dispose);
addTearDown(second.dispose);
var builds = 0;
Widget region(ValueNotifier<({int time, bool playing})> source) =>
Directionality(
textDirection: TextDirection.ltr,
child: ListenableSelector(
listenable: source,
select: () => source.value.playing,
builder: (context, playing) {
builds++;
return Text('$playing');
},
),
);
await tester.pumpWidget(region(first));
final initial = builds;
first.value = (time: 1, playing: false);
await tester.pump();
expect(builds, initial);
first.value = (time: 1, playing: true);
await tester.pump();
expect(builds, initial + 1);
await tester.pumpWidget(region(second));
expect(first.subscribed, isFalse);
expect(second.subscribed, isTrue);
second.value = (time: 2, playing: false);
await tester.pump();
expect(find.text('false'), findsOneWidget);
await tester.pumpWidget(const SizedBox());
expect(second.subscribed, isFalse);
});
}
class _Source extends ValueNotifier<({int time, bool playing})> {
_Source(super.value);
bool get subscribed => hasListeners;
}
+15 -7
View File
@@ -1,3 +1,4 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:cutdex/features/media/media_browser_feedback.dart'; import 'package:cutdex/features/media/media_browser_feedback.dart';
import 'package:cutdex/l10n/app_localizations.dart'; import 'package:cutdex/l10n/app_localizations.dart';
import 'package:cutdex/workspace/external_media_import.dart'; import 'package:cutdex/workspace/external_media_import.dart';
@@ -15,6 +16,7 @@ void main() {
late StateSetter changeVisibility; late StateSetter changeVisibility;
await tester.pumpWidget( await tester.pumpWidget(
MaterialApp( MaterialApp(
builder: (context, child) => ErrorNotificationHost(child: child!),
localizationsDelegates: AppLocalizations.localizationsDelegates, localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales, supportedLocales: AppLocalizations.supportedLocales,
home: Scaffold( home: Scaffold(
@@ -42,26 +44,32 @@ void main() {
feedback.recordFailure(); feedback.recordFailure();
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(feedback.hasPending, isTrue); expect(feedback.hasPending, isTrue);
expect(find.byType(SnackBar), findsNothing); expect(find.byKey(const Key('global-error-notification')), findsNothing);
changeVisibility(() => visible = true); changeVisibility(() => visible = true);
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(feedback.hasPending, isFalse); expect(feedback.hasPending, isFalse);
expect(find.byType(SnackBar), findsOneWidget); expect(
final messenger = ScaffoldMessenger.of( find.byKey(const Key('global-error-notification')),
findsOneWidget,
);
final messenger = ErrorNotificationHost.of(
tester.element(find.text('Browser')), tester.element(find.text('Browser')),
); );
messenger.clearSnackBars(); messenger.clear();
messenger.removeCurrentSnackBar();
await tester.pumpAndSettle(); await tester.pumpAndSettle();
changeVisibility(() => visible = false); changeVisibility(() => visible = false);
await tester.pumpAndSettle(); await tester.pumpAndSettle();
changeVisibility(() => visible = true); changeVisibility(() => visible = true);
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(find.byType(SnackBar), findsNothing); expect(find.byKey(const Key('global-error-notification')), findsNothing);
feedback.recordFailure(); feedback.recordFailure();
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(feedback.hasPending, isFalse); expect(feedback.hasPending, isFalse);
expect(find.byType(SnackBar), findsOneWidget); expect(
find.byKey(const Key('global-error-notification')),
findsOneWidget,
);
}, },
); );
} }
+227 -15
View File
@@ -1,7 +1,8 @@
import 'package:cutdex/features/media/media_browser_toolbar.dart';
import 'package:cutdex/features/media/media_browser_controller.dart';
import 'package:cutdex/app/editor_theme.dart'; import 'package:cutdex/app/editor_theme.dart';
import 'package:cutdex/features/media/media_browser_page.dart'; import 'package:cutdex/features/media/media_browser_page.dart';
import 'package:cutdex/l10n/app_localizations.dart'; import 'package:cutdex/l10n/app_localizations.dart';
import 'package:cutdex_ui/widgets.dart';
import 'dart:async'; import 'dart:async';
import 'dart:ui' as ui; import 'dart:ui' as ui;
@@ -39,6 +40,182 @@ void main() {
null, null,
); );
}); });
testWidgets('project switching retains media surface and controls', (
tester,
) async {
final projects = _Projects();
final container = ProviderContainer(
overrides: [projectsProvider.overrideWith(() => projects)],
);
addTearDown(container.dispose);
await container.read(projectsProvider.future);
await tester.pumpWidget(
UncontrolledProviderScope(
container: container,
child: MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
home: Scaffold(
body: Consumer(
builder: (context, ref, _) {
final id = ref.watch(
projectsProvider.select(
(value) => value.value?.activeProject?.id,
),
);
return MediaPanel(projectId: id);
},
),
),
),
),
);
await tester.pumpAndSettle();
final surface = tester.element(
find.byKey(const Key('media-panel-surface')),
);
final header = tester.element(find.byKey(const Key('media-panel-header')));
final body = tester.element(find.byKey(const Key('media-panel-body')));
final filterRow = tester.widget(find.byKey(const Key('media-filter-row')));
final toolbar = tester.widget<MediaBrowserToolbar>(
find.byType(MediaBrowserToolbar),
);
container.read(mediaBrowserProvider('project')).selectedAssetId =
'selection';
await tester.pump();
expect(
tester.widget<MediaBrowserToolbar>(find.byType(MediaBrowserToolbar)),
same(toolbar),
);
projects.switchProject('second');
await tester.pumpAndSettle();
expect(
tester.element(find.byKey(const Key('media-panel-surface'))),
same(surface),
);
expect(
tester.element(find.byKey(const Key('media-panel-header'))),
same(header),
);
expect(
tester.element(find.byKey(const Key('media-panel-body'))),
same(body),
);
expect(
tester
.widget<MediaBrowserToolbar>(find.byType(MediaBrowserToolbar))
.selectedProjectId,
'second',
);
expect(
tester.widget(find.byKey(const Key('media-filter-row'))),
same(filterRow),
);
await tester.tap(find.byKey(const Key('media-layout-toggle')));
await tester.pump();
expect(container.read(mediaBrowserProvider('second')).grid, isFalse);
expect(container.read(mediaBrowserProvider('project')).grid, isTrue);
expect(tester.takeException(), isNull);
});
for (final locale in const [Locale('zh'), Locale('en'), Locale('de')]) {
testWidgets(
'sidebar toolbar fits widths and scaled text in ${locale.languageCode}',
(tester) async {
var imports = 0;
var toggles = 0;
var projectSelections = 0;
for (final width in [120.0, 180.0, 240.0, 360.0]) {
await tester.pumpWidget(
MaterialApp(
locale: locale,
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
theme: EditorTheme.penLight,
home: Scaffold(
body: MediaQuery(
data: const MediaQueryData(
textScaler: TextScaler.linear(1.5),
),
child: Align(
alignment: Alignment.topLeft,
child: SizedBox(
width: width,
child: MediaBrowserToolbar(
projects: const [
RecentProject(
id: 'first',
name: 'First project with a long name',
path: '/first',
),
RecentProject(
id: 'second',
name: 'Second project',
path: '/second',
),
],
selectedProjectId: 'first',
onProjectSelected: (project) {
expect(project.id, 'second');
projectSelections++;
},
canImport: true,
onImport: () => imports++,
filter: MediaFilter.all,
onFilterChanged: (_) {},
grid: true,
onToggleGrid: () => toggles++,
),
),
),
),
),
),
);
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
if (width == 240) {
expect(find.byKey(const Key('media-header-scroll')), findsNothing);
final projectButton = tester.widget<TextButton>(
find.byKey(const Key('media-project-button')),
);
final ink = Theme.of(
tester.element(find.byKey(const Key('media-project-button'))),
).colorScheme.onSurface;
for (final state in [
WidgetState.hovered,
WidgetState.focused,
WidgetState.pressed,
]) {
expect(
projectButton.style!.backgroundColor!.resolve({state}),
Colors.transparent,
);
expect(
projectButton.style!.overlayColor!.resolve({state}),
ink.withValues(alpha: .05),
);
}
expect(
projectButton.style!.overlayColor!.resolve({
WidgetState.disabled,
WidgetState.hovered,
}),
Colors.transparent,
);
await tester.tap(find.byKey(const Key('media-project-button')));
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('media-project-second')));
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('media-import-button')));
await tester.tap(find.byKey(const Key('media-layout-toggle')));
}
}
expect(imports, 1);
expect(toggles, 1);
expect(projectSelections, 1);
},
);
}
testWidgets( testWidgets(
'list and grid share a context menu targeting the clicked asset', 'list and grid share a context menu targeting the clicked asset',
(tester) async { (tester) async {
@@ -262,7 +439,7 @@ void main() {
expect(find.byKey(const Key('media-import-button')), findsOneWidget); expect(find.byKey(const Key('media-import-button')), findsOneWidget);
expect( expect(
tester.getSize(find.byKey(const Key('media-panel-header'))).height, tester.getSize(find.byKey(const Key('media-panel-header'))).height,
AppControlSize.panelToolbar, AppControlSize.panelToolbar * 2,
); );
expect( expect(
tester.getSize(find.byKey(const Key('media-import-button'))).height, tester.getSize(find.byKey(const Key('media-import-button'))).height,
@@ -282,22 +459,34 @@ void main() {
find.byKey(const Key('media-layout-toggle')), find.byKey(const Key('media-layout-toggle')),
); );
final filter = find.byWidgetPredicate( final filter = find.byWidgetPredicate(
(widget) => widget is AppSelect && widget.label == '素材分类', (widget) => widget is Semantics && widget.properties.label == '素材分类',
); );
final filterButton = tester.getRect( final filterButton = tester.getRect(
find.descendant(of: filter, matching: find.byType(TextButton)), find.descendant(of: filter, matching: find.byType(TextButton)),
); );
expect(importButton.left - header.left, AppSpacing.gap); expect(header.right - importButton.right, AppSidebarMetrics.outerPadding);
expect(importButton.top - header.top, AppSpacing.gap); expect(importButton.top - header.top, AppSpacing.gap);
expect(header.right - layoutButton.right, AppSpacing.gap); expect(layoutButton.top - importButton.top, AppControlSize.panelToolbar);
expect(layoutButton.left - filterButton.right, AppSpacing.tiny); expect(
tester.getRect(find.byKey(const Key('media-project-button'))).top,
importButton.top,
);
expect(header.right - layoutButton.right, AppSidebarMetrics.outerPadding);
expect(
layoutButton.left - filterButton.right,
greaterThanOrEqualTo(AppSpacing.tiny),
);
expect(tester.getSize(filter).height, AppControlSize.headerButton); expect(tester.getSize(filter).height, AppControlSize.headerButton);
final importStyle = tester final importStyle = tester
.widget<TextButton>(find.byKey(const Key('media-import-button'))) .widget<TextButton>(find.byKey(const Key('media-import-button')))
.style! .style!
.textStyle! .textStyle!
.resolve({})!; .resolve({})!;
final filterStyle = tester.widget<AppSelect<Object?>>(filter).textStyle!; final filterStyle = tester
.widget<TextButton>(find.byKey(const Key('media-category-button')))
.style!
.textStyle!
.resolve({})!;
expect(importStyle.fontSize, 13); expect(importStyle.fontSize, 13);
expect(importStyle.height, 18 / 13); expect(importStyle.height, 18 / 13);
expect(filterStyle.fontSize, importStyle.fontSize); expect(filterStyle.fontSize, importStyle.fontSize);
@@ -311,7 +500,8 @@ void main() {
await tester.tap( await tester.tap(
find.descendant( find.descendant(
of: find.byWidgetPredicate( of: find.byWidgetPredicate(
(widget) => widget is AppSelect && widget.label == '素材分类', (widget) =>
widget is Semantics && widget.properties.label == '素材分类',
), ),
matching: find.byType(TextButton), matching: find.byType(TextButton),
), ),
@@ -330,7 +520,8 @@ void main() {
await tester.tap( await tester.tap(
find.descendant( find.descendant(
of: find.byWidgetPredicate( of: find.byWidgetPredicate(
(widget) => widget is AppSelect && widget.label == '素材分类', (widget) =>
widget is Semantics && widget.properties.label == '素材分类',
), ),
matching: find.byType(TextButton), matching: find.byType(TextButton),
), ),
@@ -360,7 +551,7 @@ void main() {
(tester.widget<GridView>(find.byType(GridView)).gridDelegate (tester.widget<GridView>(find.byType(GridView)).gridDelegate
as SliverGridDelegateWithFixedCrossAxisCount) as SliverGridDelegateWithFixedCrossAxisCount)
.crossAxisCount; .crossAxisCount;
expect(columns(), 2); expect(columns(), 3);
expect( expect(
find.ancestor( find.ancestor(
of: find.byType(GridView), of: find.byType(GridView),
@@ -407,15 +598,27 @@ void main() {
await tester.tap(find.byTooltip('宫格布局')); await tester.tap(find.byTooltip('宫格布局'));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
for (final (width, count) in [ for (final (width, count) in [
(180.0, 1), (180.0, 2),
(280.0, 2), (280.0, 3),
(520.0, 3), (240.0, 2),
(560.0, 4), (360.0, 3),
(900.0, 6), (520.0, 5),
(560.0, 5),
(900.0, 8),
]) { ]) {
await tester.binding.setSurfaceSize(Size(width, 600)); await tester.binding.setSurfaceSize(Size(width, 600));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(columns(), count); expect(columns(), count);
final grid = tester.widget<GridView>(find.byType(GridView));
final padding = grid.padding!.resolve(TextDirection.ltr);
final delegate =
grid.gridDelegate as SliverGridDelegateWithFixedCrossAxisCount;
final tileWidth =
(tester.getSize(find.byType(GridView)).width -
padding.horizontal -
delegate.crossAxisSpacing * (count - 1)) /
count;
expect(tileWidth, lessThanOrEqualTo(120));
expect(tester.takeException(), isNull); expect(tester.takeException(), isNull);
} }
expect( expect(
@@ -772,6 +975,15 @@ class _Projects extends Projects {
), ),
); );
void switchProject(String id) {
state = AsyncData(
state.requireValue.copyWith(
activeProject: RecentProject(id: id, name: id, path: '/$id.cutdex'),
assets: const [],
),
);
}
void setBusy(bool busy) { void setBusy(bool busy) {
state = AsyncData(state.requireValue.copyWith(projectBusy: busy)); state = AsyncData(state.requireValue.copyWith(projectBusy: busy));
} }
+72
View File
@@ -349,6 +349,8 @@ void main() {
return pending.future; return pending.future;
}); });
final loadingRect = tester.getRect(toolbar); final loadingRect = tester.getRect(toolbar);
expect(find.byKey(const Key('preview-default-frame')), findsOneWidget);
expect(find.byType(CircularProgressIndicator), findsNothing);
expect(find.text('00:00:00:00 / 00:00:00:00'), findsOneWidget); expect(find.text('00:00:00:00 / 00:00:00:00'), findsOneWidget);
expect(tester.widget<IconButton>(playButton).onPressed, isNull); expect(tester.widget<IconButton>(playButton).onPressed, isNull);
pending.completeError(StateError('unavailable')); pending.completeError(StateError('unavailable'));
@@ -408,6 +410,76 @@ void main() {
}, },
); );
testWidgets('clock and playback update only their own preview regions', (
tester,
) async {
final preview = _Preview();
addTearDown(preview.dispose);
await mount(tester, () async => preview);
await tester.pumpAndSettle();
final canvasBefore = tester.widget<PreviewCanvas>(
find.byType(PreviewCanvas),
);
final toolbarBefore = tester.widget(toolbar);
final playBefore = tester.widget<IconButton>(playButton);
final ratioBefore = tester.widget<AppSelect<ProjectCanvas>>(
find.byType(AppSelect<ProjectCanvas>),
);
final timeFinder = find.descendant(
of: find.byKey(const Key('preview-time')),
matching: find.byType(Text),
);
final timeBefore = tester.widget<Text>(timeFinder);
preview.moveTo(TimelineClock.ticksPerSecond);
await tester.pump();
expect(find.text('00:00:01:00 / 02:00:00:00'), findsOneWidget);
expect(tester.widget(toolbar), same(toolbarBefore));
expect(
tester.widget<PreviewCanvas>(find.byType(PreviewCanvas)),
same(canvasBefore),
);
expect(tester.widget<IconButton>(playButton), same(playBefore));
expect(
tester.widget<AppSelect<ProjectCanvas>>(
find.byType(AppSelect<ProjectCanvas>),
),
same(ratioBefore),
);
expect(tester.widget<Text>(timeFinder), isNot(same(timeBefore)));
final timeAfterSeek = tester.widget<Text>(timeFinder);
await preview.togglePlayback();
await tester.pump();
expect(find.byIcon(Icons.pause), findsOneWidget);
expect(tester.widget(toolbar), same(toolbarBefore));
expect(
tester.widget<PreviewCanvas>(find.byType(PreviewCanvas)),
same(canvasBefore),
);
expect(tester.widget<Text>(timeFinder), same(timeAfterSeek));
expect(
tester.widget<AppSelect<ProjectCanvas>>(
find.byType(AppSelect<ProjectCanvas>),
),
same(ratioBefore),
);
preview.setCanvas(
ProjectCanvasPresets.values.values.firstWhere(
(value) => value != preview.canvas,
),
);
await tester.pump();
expect(tester.widget(toolbar), same(toolbarBefore));
expect(tester.widget<Text>(timeFinder), same(timeAfterSeek));
expect(
tester.widget<PreviewCanvas>(find.byType(PreviewCanvas)),
isNot(same(canvasBefore)),
);
await tester.pumpWidget(const SizedBox());
});
testWidgets('offline media keeps playback available with a local notice', ( testWidgets('offline media keeps playback available with a local notice', (
tester, tester,
) async { ) async {
+5 -4
View File
@@ -1,3 +1,4 @@
import 'package:cutdex/shared/widgets/error_notification_host.dart';
import 'package:cutdex/errors/app_failure.dart'; import 'package:cutdex/errors/app_failure.dart';
import 'package:cutdex/app/editor_theme.dart'; import 'package:cutdex/app/editor_theme.dart';
@@ -523,6 +524,7 @@ void main() {
UncontrolledProviderScope( UncontrolledProviderScope(
container: container, container: container,
child: MaterialApp.router( child: MaterialApp.router(
builder: (context, child) => ErrorNotificationHost(child: child!),
localizationsDelegates: AppLocalizations.localizationsDelegates, localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales, supportedLocales: AppLocalizations.supportedLocales,
locale: const Locale('zh'), locale: const Locale('zh'),
@@ -584,6 +586,7 @@ void main() {
UncontrolledProviderScope( UncontrolledProviderScope(
container: container, container: container,
child: MaterialApp.router( child: MaterialApp.router(
builder: (context, child) => ErrorNotificationHost(child: child!),
localizationsDelegates: AppLocalizations.localizationsDelegates, localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales, supportedLocales: AppLocalizations.supportedLocales,
locale: const Locale('zh'), locale: const Locale('zh'),
@@ -638,6 +641,7 @@ void main() {
UncontrolledProviderScope( UncontrolledProviderScope(
container: container, container: container,
child: MaterialApp.router( child: MaterialApp.router(
builder: (context, child) => ErrorNotificationHost(child: child!),
localizationsDelegates: AppLocalizations.localizationsDelegates, localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales, supportedLocales: AppLocalizations.supportedLocales,
locale: const Locale('zh'), locale: const Locale('zh'),
@@ -652,10 +656,7 @@ void main() {
expect(tester.getTopRight(find.byIcon(Icons.close)).dx, lessThan(1200)); expect(tester.getTopRight(find.byIcon(Icons.close)).dx, lessThan(1200));
await tester.tap(find.byIcon(Icons.close)); await tester.tap(find.byIcon(Icons.close));
await tester.pump(const Duration(milliseconds: 200)); await tester.pump(const Duration(milliseconds: 200));
final opacity = tester.widgetList<AnimatedOpacity>( expect(find.byKey(const Key('global-error-notification')), findsNothing);
find.byType(AnimatedOpacity),
);
expect(opacity.any((widget) => widget.opacity == 0), isTrue);
await tester.pumpWidget(const SizedBox()); await tester.pumpWidget(const SizedBox());
container.dispose(); container.dispose();
}); });
+61
View File
@@ -0,0 +1,61 @@
import 'package:cutdex/features/projects/project_switch_region.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
Widget region(String? pending) => Directionality(
textDirection: TextDirection.ltr,
child: ProjectSwitchRegion(
pendingProjectId: pending,
builder: (context, showDefaults) =>
Text(showDefaults ? 'defaults' : 'content'),
),
);
testWidgets(
'fast completion never displays defaults or waits for the timer',
(tester) async {
await tester.pumpWidget(region('A'));
expect(find.text('content'), findsOneWidget);
expect(
tester.widget<IgnorePointer>(find.byType(IgnorePointer)).ignoring,
isTrue,
);
await tester.pump(const Duration(milliseconds: 100));
await tester.pumpWidget(region(null));
expect(find.text('defaults'), findsNothing);
expect(
tester.widget<IgnorePointer>(find.byType(IgnorePointer)).ignoring,
isFalse,
);
await tester.pump(const Duration(milliseconds: 200));
expect(find.text('defaults'), findsNothing);
},
);
testWidgets(
'slow switches show defaults after 150ms and reset on a new target',
(tester) async {
await tester.pumpWidget(region('A'));
await tester.pump(const Duration(milliseconds: 149));
expect(find.text('defaults'), findsNothing);
await tester.pump(const Duration(milliseconds: 1));
expect(find.text('defaults'), findsOneWidget);
await tester.pumpWidget(region('B'));
expect(find.text('defaults'), findsNothing);
await tester.pump(const Duration(milliseconds: 150));
expect(find.text('defaults'), findsOneWidget);
await tester.pumpWidget(region(null));
expect(find.text('content'), findsOneWidget);
},
);
testWidgets('disposing during a switch cancels the pending timer', (
tester,
) async {
await tester.pumpWidget(region('A'));
await tester.pumpWidget(const SizedBox());
await tester.pump(const Duration(milliseconds: 200));
expect(tester.takeException(), isNull);
});
}
Loaded 100 of 126 files, more files were not shown because too many files have changed in this diff. Show more