24 Commits
177 changed files with 10451 additions and 3257 deletions

No files matched your search

+33
View File
@@ -0,0 +1,33 @@
# Copy to .env.local and uncomment only the overrides needed on this machine.
# Existing process environment variables take precedence.
# Values are literal: no shell commands, interpolation or escape expansion.
# Use quotes for spaces; Windows paths may use / or literal backslashes.
# Windows native source development (requires Rust and FFMPEG_DIR).
# CUTDEX_WINDOWS_PATH=D:/workspace/cutdex_windows
# FFMPEG_DIR=D:/tools/ffmpeg
# Alternatively, use an extracted Windows native package. Choose only one path.
# CUTDEX_WINDOWS_PACKAGE_PATH=D:/packages/cutdex-windows
# macOS / iOS native source development.
# CUTDEX_APPLE_PATH=/Users/your-name/workspace/cutdex_apple
# Android native source development (Gradle composite build).
# CUTDEX_ANDROID_PATH=D:/workspace/cutdex-project/cutdex_android
# Optional processing workers directory.
# CUTDEX_PROCESSING_ROOT=D:/packages/cutdex-processing
# Optional authentication for private native packages.
# Token owner's authentication account (not the workflow trigger user).
# GITEA_ACTOR=your-account
# CUTDEX_GITEA_TOKEN=
# Optional macOS release signing and notarization.
# CUTDEX_CODESIGN_IDENTITY=Developer ID Application: Your Name (TEAMID)
# CUTDEX_NOTARY_PROFILE=your-notary-keychain-profile
# Optional macOS update feed. Set both values together.
# CUTDEX_UPDATE_FEED_URL=https://updates.example.com/cutdex/appcast.xml
# CUTDEX_UPDATE_PUBLIC_KEY=your-update-public-key
+3
View File
@@ -0,0 +1,3 @@
{
"flutter": "3.47.5"
}
+82
View File
@@ -0,0 +1,82 @@
# Gitea Windows and Android builds
The Windows x64 host runner needs the Flutter version pinned in `.fvmrc`, Python, Node, Visual Studio C++,
JDK 21 and Android SDK 36. The native cutdex_windows Release and cutdex_android
Maven packages must be published before building this app. The SDK Git dependency
is pinned to Gitea; the runner account needs SSH access to that private repository.
Set CUTDEX_GITEA_TOKEN in repository Actions Secrets with repository read and
package read access. It authenticates private Gitea native package downloads.
The Android APK includes ARM64 and x86_64, uses the production flavor and currently
uses the project's debug signing configuration. Configure formal signing before
shipping a production signed Android release. The Windows ZIP includes the whole
Flutter Release directory and passes the PE dependency audit. Processing workers
and optional models are separate; these four repositories contain no worker bundle.
CI and local checks share `tool/check.py` suites for analysis, app/package tests
and repository/tool tests. Local tooling loads `.env.local` with the project FVM
SDK; CI uses its version-verified preinstalled SDK and ignores that file. Both
use `tool/build.py` production/release presets for platform compilation.
CI always analyzes and tests the app. Ordinary code PRs also compile both
platforms, but skip Windows packaging, artifact uploads and final assembly.
Documentation-only PRs skip platform compilation as well. PR changes to CI,
tooling, native platform configuration, package dependencies or app update code
run the complete pipeline. `ci_scope.py` compares the PR base and head using Git
history, including deleted files; a failed comparison fails code checks.
Main pushes and manual CI runs always execute the complete pipeline and upload
cutdex-release-packages including SHA256SUMS and a release manifest. They also save
cutdex-release-metadata containing only the manifest, checksums, Windows update
index and audit report. Platform, complete and metadata artifacts retain 30 days. Protect main
with `Gitea CI / Gitea CI passed (pull_request)`. This required check validates
every expected job and permits skipped jobs only when the selected scope
explicitly excludes them; failures, cancellations and unexpected skips fail it.
Windows compilation and packaging are separate jobs. Full-pipeline compilation saves the
unpackaged Release directory as `cutdex-windows-app` for 30 days; packaging
downloads it and runs the existing PE audit and Velopack tools. Rerunning a failed
packaging job reuses this app without recompiling. Assembly and Release jobs
similarly reuse their upstream artifacts. Use the failed-job rerun option: a
whole-workflow rerun executes compilation again. A job always restarts from its
first step. Saving the Windows app adds one artifact transfer between the jobs.
CI artifact uploads attempt at most three times, waiting 5 and 15 seconds between
attempts and replacing incomplete artifacts of the same job-owned name. Release
attachment uploads use the same bounded delays for temporary HTTP/network errors,
and check for already saved filenames before repeating a POST. Permanent errors
fail immediately and final attachment byte verification remains required. If the
Windows app cannot be saved after all attempts, its build job still needs to be
rerun. Draft creation and final publication are not automatically retried.
After main CI succeeds, create v<pubspec version> at that exact commit, or manually
dispatch the Release workflow with the existing tag. Release preparation selects
a successful main ci.yml run for the exact tagged commit and requires unexpired
cutdex-android-build, cutdex-windows-build and cutdex-release-metadata artifacts. It creates a draft bound to both that commit and
that CI run. Release jobs never rebuild the app or reinstall Flutter dependencies.
Android and Windows independently download their platform artifacts from the
selected CI run and immediately upload them to the draft. These jobs run in
parallel. The final job accepts only the compact metadata artifact from that same
CI run. Complete binary archives cannot substitute for platform packages or
metadata. Missing, expired or duplicate required artifacts block preparation
before any draft is created. Platform uploads check attachment presence without
reading back their bytes. Before publication, every attachment is read back once
and verified against trusted SHA256 checksums; the full update package also
matches its index SHA1 and size. Upload and verification batches use at most two
requests per job. Verification reads in 1 MiB chunks. Tag, CI, draft and attachment
ID/name bindings are rechecked before the Release is made public.
A failed upload leaves the draft unpublished with successful uploads retained.
Manual dispatch with the same tag resumes the original CI run, even if another CI
for that commit has since succeeded. Matching attachments are reused; changed or
unrelated attachments block publication rather than being replaced. If the
original platform or metadata artifacts have expired, release preparation fails and requires
operator attention. Published Releases are never overwritten. The built-in
GITEA_TOKEN handles release writes and Actions artifact reads; no separate
release-write PAT is required. Do not commit credentials or keystores.
Full-pipeline CI produces Actions artifacts without creating Releases. If a tag is pushed
before main CI succeeds, release preparation fails without creating a draft; retry
the Release workflow once CI has finished. This design overlaps platform uploads,
not main CI builds with Release uploads. There is no legacy whole-archive
promotion entry point or format fallback.
+144
View File
@@ -0,0 +1,144 @@
# CI build performance
The workflow runs checks first, then Android and Windows compilation concurrently
when compilation is required. Ordinary code PRs stop after compilation and native
SDK validation; they skip artifact transfers, Windows packaging and assembly.
Documentation-only PRs run checks without compiling either platform. Changes to
CI, tooling, native platform configuration, dependencies, `.fvmrc` and app update code
force the full pipeline. Main pushes and manual CI runs always use the full
pipeline, preserving the exact-commit artifacts needed by Release.
Scope selection uses the complete PR base/head history in the quality checkout.
Other checkouts retain their default shallow fetch. Git comparisons include
deleted paths and disable rename detection, so moving a packaging file into docs
cannot hide its deletion. Unknown paths compile both platforms; empty PR diffs
run the full pipeline. Scope selection errors fail CI instead of skipping jobs.
The final required check requires success for selected jobs and `skipped` for
excluded jobs, and always requires successful code checks.
In the full pipeline,
Windows compilation saves `cutdex-windows-app`; an independent Windows job
downloads that app, audits it and creates Velopack packages. Packaging needs
neither Flutter dependencies nor another Windows compilation. The Android job
builds the APK. The final job downloads only platform packages and
validates the complete release manifest, update feed and checksums. The public
artifact remains `cutdex-release-packages`.
Build jobs explicitly use persistent runner-user Pub and Gradle caches, respecting
existing `PUB_CACHE` and `GRADLE_USER_HOME` overrides. Gradle task output caching is
enabled for CI. Do not clear these caches between runs. Each job must have its own
checkout; do not share a Flutter `build/` or `.dart_tool/` directory between jobs.
With an ephemeral runner, these user directories must be persisted separately.
The local `prepare-flutter` action owns cache setup, Flutter version validation,
optional Java configuration and locked dependency resolution for the quality,
Android and Windows compilation jobs. `.fvmrc` is the shared local/CI Flutter
version source; the action verifies the preinstalled runner SDK against it, without
installing FVM or resolving a second SDK. Quality checks also run the Flutter
Python version guard and local launcher regression tests. The guard reads `.fvmrc`
before probing the runner SDK and requires no PowerShell-specific implementation.
Local and CI checks share
`tool/check.py --suite analyze|flutter|tools`, including fatal-info analysis,
app/package tests, repository hygiene and portable tooling regressions. Each suite
remains a separate CI step. `tool/build.py` owns production/release defaults and
Android architectures; SDK selection and environment loading use the shared Dart
launcher through its Python adapter. The runner continues using its verified
preinstalled SDK rather than requiring a project FVM link. Platform builds clear their
local native source path environment overrides and never read `.env.local`.
The separate `prepare-windows-packaging` action owns the user .NET
installation and packaging tool setup, so packaging retries do not resolve
Flutter dependencies. Individual setup steps remain visible within each action.
Workflow-level environment variables contain only shared nonsecret settings.
The SDK token is limited to quality and platform compilation jobs. The fixed
Maven account name is set only on the Android build step, matching the SDK token
owner rather than the user who triggered CI. Assembly needs no SDK credentials;
Release credentials remain confined to the Release workflow's publishing jobs.
Build commands keep Flutter's default Pub preparation after the explicit locked
resolution. Do not use `--no-pub`: Flutter also regenerates release plugin
registrants in that preparation, removing dev-only plugins such as integration_test.
The runner needs at least two execution slots. The local runner configuration at
`D:/workspace/gitea-stack/runner/config.yaml` currently has `capacity: 2`. The host
has 12 logical processors and approximately 16 GB RAM; the Android job retains its
3 GB heap and four-worker limit to leave room for concurrent Windows compilation.
`prepare-package-tools.ps1` installs pinned `pefile` and `vpk` on first use under
the runner user's `%LOCALAPPDATA%/Cutdex/ci-tools/`. Later builds reuse them after
version checks. Python interpreter identity and tool versions isolate the cache,
and a mutex protects installation across concurrent workflows. .NET setup remains
in the Windows packaging job to provide SDK 10 and the runtime required by `vpk`.
The .NET installation uses the runner user's `Cutdex/ci-tools/dotnet` directory
through `DOTNET_INSTALL_DIR` and `DOTNET_ROOT`, so setup needs no administrator
access and later jobs reuse the installed SDK and runtime.
The Windows build verifies that the resolved deskup native SDK matches the pinned
Velopack version before saving the app. Packaging imports no Flutter package
configuration and independently verifies the installed vpk version.
APK and Windows package uploads use `compression-level: 0` to avoid recompressing
already compressed artifacts. The saved Windows app uses compression level 1,
preserves nested and hidden runtime assets, and excludes the same debug files and
optional workers omitted by packaging. The saved app, platform packages, compact
metadata and validated release artifact all retain 30 days.
This host runs both Gitea and the runner. The workflows set
`CUTDEX_GITEA_INTERNAL_URL=http://127.0.0.1:3000` and override `ACTIONS_RESULTS_URL`
on artifact upload/download steps, so those transfers stay on the host instead of
looping through the public FRP tunnel. Release API uploads and byte verification
also use this loopback endpoint; tooling rewrites only the validated public Gitea
origin. The server's public URL remains `https://git.orangraph.com`, and the runner
registration is unchanged. These workflow labels require this shared-host layout;
configure a reachable private endpoint before using runners on other hosts.
Checkout uses the same endpoint through its `github-server-url` input, retaining
the requested commit/tag and disabling persisted credentials. Release requests
retain the public Host header so Gitea response links pass the public-origin checks.
CI artifact ZIP download requests retain the loopback Host instead: Gitea returns
a signed redirect to the raw archive, and its Host must remain local for that
second request to avoid the public tunnel. Release attachment links stay public.
Compare warm CI runs after the first cache fill. Measure checks, Android compile,
Windows compile, packaging and artifact transfer separately. Total duration follows
the slower platform branch, plus checks and final assembly; no fixed speedup is
assumed. Release audits and artifact validation remain mandatory.
## Failure recovery
Use Gitea's failed-job rerun rather than rerunning the entire workflow. A job
reruns from its first step, including downstream dependent jobs. Once the Windows
app artifact has been saved, a Windows packaging failure can be retried without
recompilation. Assembly failures reuse the saved Android and Windows packages;
Release failures reuse the successful main CI. Splitting Windows adds one app
upload/download on successful runs in exchange for this recovery point.
Every CI artifact upload uses the local `upload-artifact` composite, with at most
three action attempts and 5/15-second delays. Attempts replace incomplete
artifacts with the same name; each name belongs to one producing job. Exhausted
retries fail the job. If the first Windows app checkpoint cannot be uploaded,
the build job must still be rerun; it has no saved app to restore.
Release attachment uploads retry temporary network errors, HTTP 408/429 and
500/502/503/504 up to three POST attempts per file, also with 5/15-second delays.
The specific FRP HTML "Not Found" page observed during tunnel reconnection is
also treated as temporary; ordinary Gitea API or HTML 404 responses still fail.
Before retrying a POST, the uploader checks whether Gitea already saved the named
attachment, including after the final response is lost. This avoids duplicate
uploads after a timeout. Authorization, invalid-input and other permanent errors
fail immediately. No draft creation or publication PATCH is automatically retried.
Attachment-list reads have their own bounded retries. Final byte verification
remains mandatory even when an existing filename is reused.
The tag/manual Release workflow reuses a successful main CI for the exact tagged
commit; it performs no Flutter builds, dependency resolution or Windows packaging.
A prepare job binds the draft and both platform upload jobs to one CI run. Android
and Windows independently fetch and upload their existing packages in parallel.
Publication requires the small cutdex-release-metadata artifact; it never
downloads the combined binary artifact. Missing or expired metadata/platform
artifacts fail preparation, with no old-format fallback. Every remote file is read and verified once, immediately
before publication, with two verification workers and 1 MiB chunks. Platform
upload steps check presence without repeating binary readbacks. Each upload
batch also uses at most two workers; while both platform jobs run, Android can
have one upload in flight alongside two Windows uploads.
Retries retain the original CI-run binding. Ordinary CI never creates
drafts. Wait for main CI success before tagging or retry Release after it finishes;
platform Release uploads overlap each other, not the original main builds.
-26
View File
@@ -1,26 +0,0 @@
# Gitea Windows and Android builds
The Windows x64 host runner needs Flutter 3.47.5, Python, Node, Visual Studio C++,
JDK 21 and Android SDK 36. The native cutdex_windows Release and cutdex_android
Maven packages must be published before building this app. The SDK Git dependency
is pinned to Gitea; the runner account needs SSH access to that private repository.
Set CUTDEX_GITEA_TOKEN in repository Actions Secrets with repository read and
package read access. It authenticates private Gitea native package downloads.
The Android APK includes ARM64 and x86_64, uses the production flavor and currently
uses the project's debug signing configuration. Configure formal signing before
shipping a production signed Android release. The Windows ZIP includes the whole
Flutter Release directory and passes the PE dependency audit. Processing workers
and optional models are separate; these four repositories contain no worker bundle.
PR/main CI analyzes and tests the app, builds both platforms, and uploads
cutdex-release-packages including SHA256SUMS and a release manifest. Protect main
with `Gitea CI / Gitea CI passed (pull_request)`.
After main CI succeeds, create v<pubspec version> at that exact commit. The Release
workflow downloads the existing CI artifact, requires both APK and Windows ZIP,
checks their digests, uploads to a draft Release, verifies remote bytes, then
publishes it. It refuses to overwrite a published Release. A manual dispatch with
the existing tag can retry an interrupted draft publication. The built-in GITEA_TOKEN
handles release writes and Actions artifact reads; no separate release-write PAT
is required. Do not commit credentials or keystores.
+28
View File
@@ -0,0 +1,28 @@
name: Prepare Flutter build environment
description: Configure persistent caches, verify Flutter and resolve locked dependencies.
inputs:
configure-java:
description: Configure Flutter to use the runner's JAVA_HOME
default: 'false'
runs:
using: composite
steps:
- name: Configure persistent build caches
shell: pwsh
run: ./tool/gitea/prepare-build-cache.ps1
- name: Verify Flutter version
shell: pwsh
run: python tool/gitea/verify_flutter_version.py
- name: Configure Flutter Java
if: ${{ inputs.configure-java == 'true' }}
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
if (-not $env:JAVA_HOME) { throw 'JAVA_HOME is required for Flutter JDK setup.' }
flutter config --jdk-dir=$env:JAVA_HOME
if ($LASTEXITCODE -ne 0) { throw 'Flutter JDK setup failed.' }
- name: Resolve locked Flutter dependencies
shell: pwsh
run: |
flutter pub get --enforce-lockfile
if ($LASTEXITCODE -ne 0) { throw 'Locked Flutter dependency resolution failed.' }
@@ -0,0 +1,20 @@
name: Prepare Windows packaging environment
description: Reuse the user .NET installation and pinned packaging tools independently of Flutter.
runs:
using: composite
steps:
- name: Configure user .NET installation
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$directory = Join-Path $env:LOCALAPPDATA 'Cutdex/ci-tools/dotnet'
[IO.Directory]::CreateDirectory($directory) | Out-Null
"DOTNET_INSTALL_DIR=$directory" | Out-File -LiteralPath $env:GITHUB_ENV -Encoding utf8 -Append
"DOTNET_ROOT=$directory" | Out-File -LiteralPath $env:GITHUB_ENV -Encoding utf8 -Append
- name: Set up .NET SDK
uses: https://github.com/actions/setup-dotnet@26b0ec14cb23fa6904739307f278c14f94c95bf1
with:
dotnet-version: '10.0.x'
- name: Prepare pinned packaging tools
shell: pwsh
run: ./tool/gitea/prepare-package-tools.ps1
+69
View File
@@ -0,0 +1,69 @@
name: Upload CI artifact with bounded retries
description: Save an artifact with at most three attempts, replacing incomplete uploads of the same name.
inputs:
name:
description: Artifact name, unique to this job in the workflow run
required: true
path:
description: Files and directories to upload
required: true
compression-level:
description: ZIP compression level
default: '0'
retention-days:
description: Artifact retention in days
default: '30'
runs:
using: composite
steps:
- name: Upload artifact (attempt 1 of 3)
id: first
continue-on-error: true
uses: https://github.com/actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
env:
ACTIONS_RESULTS_URL: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
with:
name: ${{ inputs.name }}
path: ${{ inputs.path }}
compression-level: ${{ inputs.compression-level }}
retention-days: ${{ inputs.retention-days }}
if-no-files-found: error
include-hidden-files: true
overwrite: true
- name: Wait before second upload attempt
if: ${{ !cancelled() && steps.first.outcome == 'failure' }}
shell: pwsh
run: Start-Sleep -Seconds 5
- name: Upload artifact (attempt 2 of 3)
id: second
if: ${{ !cancelled() && steps.first.outcome == 'failure' }}
continue-on-error: true
uses: https://github.com/actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
env:
ACTIONS_RESULTS_URL: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
with:
name: ${{ inputs.name }}
path: ${{ inputs.path }}
compression-level: ${{ inputs.compression-level }}
retention-days: ${{ inputs.retention-days }}
if-no-files-found: error
include-hidden-files: true
overwrite: true
- name: Wait before final upload attempt
if: ${{ !cancelled() && steps.first.outcome == 'failure' && steps.second.outcome == 'failure' }}
shell: pwsh
run: Start-Sleep -Seconds 15
- name: Upload artifact (attempt 3 of 3)
id: third
if: ${{ !cancelled() && steps.first.outcome == 'failure' && steps.second.outcome == 'failure' }}
uses: https://github.com/actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
env:
ACTIONS_RESULTS_URL: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
with:
name: ${{ inputs.name }}
path: ${{ inputs.path }}
compression-level: ${{ inputs.compression-level }}
retention-days: ${{ inputs.retention-days }}
if-no-files-found: error
include-hidden-files: true
overwrite: true
+198 -31
View File
@@ -12,66 +12,233 @@ concurrency:
group: app-${{ gitea.ref }} group: app-${{ gitea.ref }}
cancel-in-progress: true cancel-in-progress: true
env: env:
CI: 'true'
PYTHONUTF8: '1' PYTHONUTF8: '1'
CUTDEX_GITEA_INTERNAL_URL: http://127.0.0.1:3000
GIT_CONFIG_COUNT: '2' GIT_CONFIG_COUNT: '2'
GIT_CONFIG_KEY_0: core.autocrlf GIT_CONFIG_KEY_0: core.autocrlf
GIT_CONFIG_VALUE_0: 'false' GIT_CONFIG_VALUE_0: 'false'
GIT_CONFIG_KEY_1: core.eol GIT_CONFIG_KEY_1: core.eol
GIT_CONFIG_VALUE_1: lf GIT_CONFIG_VALUE_1: lf
jobs: jobs:
build: quality:
name: Windows x64 and Android name: Check code and tests
runs-on: cutdex-windows-x64 runs-on: cutdex-windows-x64
outputs:
build-app: ${{ steps.scope.outputs.build-app }}
package-app: ${{ steps.scope.outputs.package-app }}
env: env:
GITEA_ACTOR: lingjhf
CUTDEX_GITEA_TOKEN: ${{ secrets.CUTDEX_GITEA_TOKEN }} CUTDEX_GITEA_TOKEN: ${{ secrets.CUTDEX_GITEA_TOKEN }}
steps: steps:
- uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 - name: Check out source
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with: with:
persist-credentials: false persist-credentials: false
- name: Verify toolchains github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
fetch-depth: 0
- name: Select compilation and packaging scope
id: scope
env:
CI_EVENT_NAME: ${{ gitea.event_name }}
CI_PR_BASE_SHA: ${{ gitea.event.pull_request.base.sha }}
CI_PR_HEAD_SHA: ${{ gitea.event.pull_request.head.sha }}
run: | run: |
$version = flutter --version --machine | ConvertFrom-Json python tool/gitea/ci_scope.py
if ($version.frameworkVersion -ne '3.47.5') { throw 'Flutter 3.47.5 required.' } if ($LASTEXITCODE -ne 0) { throw 'CI scope selection failed.' }
flutter config --jdk-dir=$env:JAVA_HOME - name: Prepare Flutter environment
if ($LASTEXITCODE -ne 0) { throw 'Flutter JDK setup failed.' } uses: ./.gitea/actions/prepare-flutter
- run: flutter pub get --enforce-lockfile with:
- run: dart analyze --fatal-infos configure-java: 'true'
- run: flutter test --reporter expanded test packages/cutdex_ui/test packages/cutdex_native/test - name: Analyze Dart code
- name: Bound Android build memory on the shared runner run: python tool/check.py --suite analyze
- name: Run Flutter tests
run: python tool/check.py --suite flutter
- name: Check repository and tool tests
run: python tool/check.py --suite tools
android:
name: Build Android APK
needs: quality
if: ${{ needs.quality.outputs.build-app == 'true' }}
runs-on: cutdex-windows-x64
env:
CUTDEX_GITEA_TOKEN: ${{ secrets.CUTDEX_GITEA_TOKEN }}
steps:
- name: Check out source
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with:
persist-credentials: false
github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
- name: Prepare Flutter environment
uses: ./.gitea/actions/prepare-flutter
with:
configure-java: 'true'
- name: Configure Gradle memory and build cache
run: | run: |
$file = 'android/gradle.properties' $file = 'android/gradle.properties'
$properties = [IO.File]::ReadAllText($file).Replace('-Xmx8G', '-Xmx3G').Replace('MaxMetaspaceSize=4G', 'MaxMetaspaceSize=768m') $properties = [IO.File]::ReadAllText($file).Replace('-Xmx8G', '-Xmx3G').Replace('MaxMetaspaceSize=4G', 'MaxMetaspaceSize=768m')
[IO.File]::WriteAllText($file, $properties + "`norg.gradle.workers.max=4`n") [IO.File]::WriteAllText($file, $properties + "`norg.gradle.workers.max=4`norg.gradle.caching=true`n")
- run: flutter build apk --release --flavor production --target-platform android-arm64,android-x64 - name: Build production Android APK
- name: Build Windows from the pinned Gitea native release env:
GITEA_ACTOR: lingjhf
run: |
Remove-Item Env:CUTDEX_ANDROID_PATH -ErrorAction SilentlyContinue
python tool/build.py android
if ($LASTEXITCODE -ne 0) { throw 'Android build failed.' }
- name: Upload Android CI artifact
if: ${{ needs.quality.outputs.package-app == 'true' }}
uses: ./.gitea/actions/upload-artifact
with:
name: cutdex-android-build
path: build/app/outputs/flutter-apk/app-production-release.apk
compression-level: 0
retention-days: 30
windows-build:
name: Build Windows x64 app
needs: quality
if: ${{ needs.quality.outputs.build-app == 'true' }}
runs-on: cutdex-windows-x64
env:
CUTDEX_GITEA_TOKEN: ${{ secrets.CUTDEX_GITEA_TOKEN }}
steps:
- name: Check out source
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with:
persist-credentials: false
github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
- name: Prepare Flutter environment
uses: ./.gitea/actions/prepare-flutter
- name: Build production Windows app
run: | run: |
Remove-Item Env:CUTDEX_WINDOWS_PATH, Env:CUTDEX_WINDOWS_PACKAGE_PATH -ErrorAction SilentlyContinue Remove-Item Env:CUTDEX_WINDOWS_PATH, Env:CUTDEX_WINDOWS_PACKAGE_PATH -ErrorAction SilentlyContinue
flutter build windows --release --flavor production python tool/build.py windows
if ($LASTEXITCODE -ne 0) { throw 'Windows build failed.' } if ($LASTEXITCODE -ne 0) { throw 'Windows build failed.' }
- name: Prepare isolated packaging tools - name: Verify native SDK matches pinned packaging tools
run: | run: |
python -m venv .build/package-tools python tool/windows/windows_updates.py verify-sdk
if ($LASTEXITCODE -ne 0) { throw 'Packaging environment setup failed.' } if ($LASTEXITCODE -ne 0) { throw 'Windows native SDK version validation failed.' }
& ./.build/package-tools/Scripts/python.exe -m pip install pefile==2024.8.26 - name: Save Windows app for independent packaging retries
if ($LASTEXITCODE -ne 0) { throw 'Packaging dependency installation failed.' } if: ${{ needs.quality.outputs.package-app == 'true' }}
- name: Package application uses: ./.gitea/actions/upload-artifact
with:
name: cutdex-windows-app
path: |
build/windows/x64/production/runner/Release/
!build/windows/x64/production/runner/Release/**/processing/**
!build/windows/x64/production/runner/Release/**/*.pdb
!build/windows/x64/production/runner/Release/**/*.lib
!build/windows/x64/production/runner/Release/**/*.exp
!build/windows/x64/production/runner/Release/**/dartjni.dll
compression-level: 1
retention-days: 30
windows:
name: Audit and package Windows x64
needs: [quality, windows-build]
if: ${{ needs.quality.outputs.package-app == 'true' }}
runs-on: cutdex-windows-x64
steps:
- name: Check out source
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with:
persist-credentials: false
github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
- name: Download saved Windows app
uses: https://github.com/actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093
env:
ACTIONS_RESULTS_URL: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
with:
name: cutdex-windows-app
path: build/windows/x64/production/runner/Release/
- name: Prepare Windows packaging environment
uses: ./.gitea/actions/prepare-windows-packaging
- name: Audit and package Windows release
run: | run: |
& ./.build/package-tools/Scripts/python.exe tool/gitea/package-app.py & $env:PACKAGE_PYTHON tool/gitea/package-app.py --platform windows --vpk $env:VPK_PATH
- name: Upload Android and Windows packages if ($LASTEXITCODE -ne 0) { throw 'Windows packaging failed.' }
uses: https://github.com/actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 - name: Upload Windows CI artifact
uses: ./.gitea/actions/upload-artifact
with:
name: cutdex-windows-build
path: dist/*
compression-level: 0
retention-days: 30
build:
name: Assemble and validate CI artifacts
needs: [quality, android, windows]
if: ${{ needs.quality.outputs.package-app == 'true' }}
runs-on: cutdex-windows-x64
steps:
- name: Check out source
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with:
persist-credentials: false
github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
- name: Download Android CI artifact
uses: https://github.com/actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093
env:
ACTIONS_RESULTS_URL: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
with:
name: cutdex-android-build
path: build/app/outputs/flutter-apk/
- name: Download Windows CI artifact
uses: https://github.com/actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093
env:
ACTIONS_RESULTS_URL: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
with:
name: cutdex-windows-build
path: .build/windows-packages/
- name: Validate packages and generate metadata
run: |
python tool/gitea/package-app.py --platform assemble --windows-packages .build/windows-packages
if ($LASTEXITCODE -ne 0) { throw 'Application artifact validation failed.' }
- name: Upload combined CI artifact
uses: ./.gitea/actions/upload-artifact
with: with:
name: cutdex-release-packages name: cutdex-release-packages
path: dist/* path: dist/*
if-no-files-found: error compression-level: 0
retention-days: 30
- name: Upload release verification metadata
uses: ./.gitea/actions/upload-artifact
with:
name: cutdex-release-metadata
path: .build/release-metadata/*
compression-level: 0
retention-days: 30 retention-days: 30
checks: checks:
name: Gitea CI passed name: Gitea CI passed
if: always() if: always()
needs: build needs: [quality, android, windows-build, windows, build]
runs-on: cutdex-windows-x64 runs-on: cutdex-windows-x64
steps: steps:
- env: - name: Verify CI result
RESULT: ${{ needs.build.result }} env:
QUALITY_RESULT: ${{ needs.quality.result }}
BUILD_APP: ${{ needs.quality.outputs.build-app }}
PACKAGE_APP: ${{ needs.quality.outputs.package-app }}
# The local runner omits results for jobs excluded by their condition.
# Required jobs still fail below if this becomes 'skipped'.
ANDROID_RESULT: ${{ needs.android.result || 'skipped' }}
WINDOWS_BUILD_RESULT: ${{ needs.windows-build.result || 'skipped' }}
WINDOWS_PACKAGE_RESULT: ${{ needs.windows.result || 'skipped' }}
ASSEMBLY_RESULT: ${{ needs.build.result || 'skipped' }}
run: | run: |
if ($env:RESULT -ne 'success') { throw "App build: $env:RESULT" } if ($env:QUALITY_RESULT -ne 'success') { throw "Code checks: $env:QUALITY_RESULT" }
if ($env:BUILD_APP -notin @('true', 'false') -or $env:PACKAGE_APP -notin @('true', 'false')) {
throw 'Missing or invalid CI scope outputs.'
}
if ($env:PACKAGE_APP -eq 'true' -and $env:BUILD_APP -ne 'true') { throw 'Packaging requires compilation.' }
$compileResult = if ($env:BUILD_APP -eq 'true') { 'success' } else { 'skipped' }
$packageResult = if ($env:PACKAGE_APP -eq 'true') { 'success' } else { 'skipped' }
$jobs = @(
@{ Name = 'Android compilation'; Result = $env:ANDROID_RESULT; Expected = $compileResult },
@{ Name = 'Windows compilation'; Result = $env:WINDOWS_BUILD_RESULT; Expected = $compileResult },
@{ Name = 'Windows packaging'; Result = $env:WINDOWS_PACKAGE_RESULT; Expected = $packageResult },
@{ Name = 'Artifact assembly'; Result = $env:ASSEMBLY_RESULT; Expected = $packageResult }
)
foreach ($job in $jobs) {
if ($job.Result -ne $job.Expected) { throw "$($job.Name): $($job.Result), expected $($job.Expected)." }
}
+110 -10
View File
@@ -13,21 +13,121 @@ permissions:
concurrency: concurrency:
group: cutdex-release group: cutdex-release
cancel-in-progress: false cancel-in-progress: false
defaults:
run:
shell: pwsh
env:
PYTHONUTF8: '1'
CUTDEX_GITEA_INTERNAL_URL: http://127.0.0.1:3000
GIT_CONFIG_COUNT: '2'
GIT_CONFIG_KEY_0: core.autocrlf
GIT_CONFIG_VALUE_0: 'false'
GIT_CONFIG_KEY_1: core.eol
GIT_CONFIG_VALUE_1: lf
RELEASE_TAG: ${{ gitea.event.inputs.tag || gitea.ref_name }}
GITEA_REPOSITORY: ${{ gitea.repository }}
jobs: jobs:
release: prepare:
name: Prepare draft Release
runs-on: cutdex-windows-x64 runs-on: cutdex-windows-x64
outputs:
sha: ${{ steps.draft.outputs.sha }}
release-id: ${{ steps.draft.outputs.release-id }}
ci-run-id: ${{ steps.draft.outputs.ci-run-id }}
artifact-id: ${{ steps.draft.outputs.artifact-id }}
android-artifact-id: ${{ steps.draft.outputs.android-artifact-id }}
windows-artifact-id: ${{ steps.draft.outputs.windows-artifact-id }}
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
steps: steps:
- uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 - name: Check out release tag
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with: with:
ref: ${{ gitea.event.inputs.tag || gitea.ref_name }} ref: ${{ gitea.event.inputs.tag || gitea.ref_name }}
persist-credentials: false persist-credentials: false
- name: Publish validated Android and Windows packages github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
shell: pwsh - name: Select successful CI and prepare draft
env: id: draft
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
GITEA_REPOSITORY: ${{ gitea.repository }}
RELEASE_TAG: ${{ gitea.event.inputs.tag || gitea.ref_name }}
run: | run: |
$env:GITEA_SHA = git rev-parse HEAD $env:GITEA_SHA = git rev-parse HEAD
python tool/gitea/promote-release.py if ($LASTEXITCODE -ne 0) { throw 'Release source resolution failed.' }
if ($LASTEXITCODE -ne 0) { throw 'Release promotion failed.' } python tool/gitea/stage-release.py prepare-ci
if ($LASTEXITCODE -ne 0) { throw 'CI selection or draft preparation failed.' }
android:
name: Upload Android to draft Release
needs: prepare
runs-on: cutdex-windows-x64
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
GITEA_SHA: ${{ needs.prepare.outputs.sha }}
RELEASE_ID: ${{ needs.prepare.outputs.release-id }}
CI_RUN_ID: ${{ needs.prepare.outputs.ci-run-id }}
CI_ARTIFACT_ID: ${{ needs.prepare.outputs.android-artifact-id }}
steps:
- name: Check out release commit
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with:
ref: ${{ needs.prepare.outputs.sha }}
persist-credentials: false
github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
- name: Download Android CI artifact
run: |
python tool/gitea/stage-release.py fetch-android --path .build/android
if ($LASTEXITCODE -ne 0) { throw 'android CI artifact download failed.' }
- name: Upload Android packages to draft
run: |
python tool/gitea/stage-release.py android --path .build/android
if ($LASTEXITCODE -ne 0) { throw 'android draft upload failed.' }
windows:
name: Upload Windows to draft Release
needs: prepare
runs-on: cutdex-windows-x64
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
GITEA_SHA: ${{ needs.prepare.outputs.sha }}
RELEASE_ID: ${{ needs.prepare.outputs.release-id }}
CI_RUN_ID: ${{ needs.prepare.outputs.ci-run-id }}
CI_ARTIFACT_ID: ${{ needs.prepare.outputs.windows-artifact-id }}
steps:
- name: Check out release commit
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with:
ref: ${{ needs.prepare.outputs.sha }}
persist-credentials: false
github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
- name: Download Windows CI artifact
run: |
python tool/gitea/stage-release.py fetch-windows --path .build/windows
if ($LASTEXITCODE -ne 0) { throw 'windows CI artifact download failed.' }
- name: Upload Windows packages to draft
run: |
python tool/gitea/stage-release.py windows --path .build/windows
if ($LASTEXITCODE -ne 0) { throw 'windows draft upload failed.' }
publish:
name: Verify and publish Release
needs: [prepare, android, windows]
runs-on: cutdex-windows-x64
env:
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
GITEA_SHA: ${{ needs.prepare.outputs.sha }}
RELEASE_ID: ${{ needs.prepare.outputs.release-id }}
CI_RUN_ID: ${{ needs.prepare.outputs.ci-run-id }}
CI_ARTIFACT_ID: ${{ needs.prepare.outputs.artifact-id }}
steps:
- name: Check out release commit
uses: https://github.com/actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683
with:
ref: ${{ needs.prepare.outputs.sha }}
persist-credentials: false
github-server-url: ${{ env.CUTDEX_GITEA_INTERNAL_URL }}
- name: Download release verification metadata
run: |
python tool/gitea/stage-release.py fetch-release --path dist
if ($LASTEXITCODE -ne 0) { throw 'CI verification metadata validation failed.' }
- name: Verify attachments and publish Release
run: |
python tool/gitea/stage-release.py publish --path dist
if ($LASTEXITCODE -ne 0) { throw 'Release publication failed.' }
+4
View File
@@ -101,3 +101,7 @@ pubspec_overrides.yaml
*.aab *.aab
.vscode/* .vscode/*
!.vscode/launch.json !.vscode/launch.json
!.vscode/settings.json
# FVM Version Cache
.fvm/
+27 -1
View File
@@ -5,7 +5,33 @@
"name": "Cutdex", "name": "Cutdex",
"request": "launch", "request": "launch",
"type": "dart", "type": "dart",
"program": "lib/main.dart" "program": "lib/main.dart",
"customTool": "${workspaceFolder}/tool/flutter-local.sh",
"windows": {
"customTool": "${workspaceFolder}/tool/flutter-local.bat"
}
},
{
"name": "Cutdex (Profile)",
"request": "launch",
"type": "dart",
"program": "lib/main.dart",
"flutterMode": "profile",
"customTool": "${workspaceFolder}/tool/flutter-local.sh",
"windows": {
"customTool": "${workspaceFolder}/tool/flutter-local.bat"
}
},
{
"name": "Cutdex (Release)",
"request": "launch",
"type": "dart",
"program": "lib/main.dart",
"flutterMode": "release",
"customTool": "${workspaceFolder}/tool/flutter-local.sh",
"windows": {
"customTool": "${workspaceFolder}/tool/flutter-local.bat"
}
} }
] ]
} }
+3
View File
@@ -0,0 +1,3 @@
{
"dart.flutterSdkPath": ".fvm/versions/3.47.5"
}
+4 -1
View File
@@ -26,7 +26,10 @@ plugins {
include(":app") include(":app")
// Native source development is opt-in; default resolution uses Gitea Maven packages. // Native source development is opt-in; default resolution uses Gitea Maven packages.
providers.gradleProperty("cutdex.android.path").orNull?.let { nativePath -> val nativeAndroidPath = providers.gradleProperty("cutdex.android.path")
.orElse(providers.environmentVariable("CUTDEX_ANDROID_PATH"))
.orNull
nativeAndroidPath?.takeIf { it.isNotBlank() }?.let { nativePath ->
includeBuild(nativePath) { includeBuild(nativePath) {
dependencySubstitution { dependencySubstitution {
substitute(module("dev.cutdex:cutdex-android")).using(project(":cutdex-android")) substitute(module("dev.cutdex:cutdex-android")).using(project(":cutdex-android"))
+52 -8
View File
@@ -4,20 +4,55 @@
## 准备环境 ## 准备环境
使用满足 `pubspec.yaml` 约束的 Flutter 与 Dart 工具链,并安装目标平台的开发工具。仓库脚本使用 Python 3.11+。 安装 FVM,在仓库根目录运行 `fvm use`,使用 `.fvmrc` 固定的 Flutter 版本,
并准备目标平台的开发工具。CI 按同一文件校验 SDK。`.fvmrc` 提交到仓库,生成的
`.fvm/` SDK 链接与缓存不提交。仓库脚本使用 Python 3.11+。
应用依赖与版本以 `pubspec.yaml`、`pubspec.lock` 为准,通过 `flutter pub get` 获取。依赖的访问权限、配置和工具链要求按各依赖自身的文档准备;依赖未就绪时无法完成应用构建。 应用依赖与版本以 `pubspec.yaml`、`pubspec.lock` 为准,通过 `fvm dart tool/flutter_local.dart pub get` 获取。依赖的访问权限、配置和工具链要求按各依赖自身的文档准备;依赖未就绪时无法完成应用构建。
本地联调其他包时,可参考 `pubspec_overrides.yaml.example` 创建覆盖配置。覆盖文件只用于本机开发,不提交。 本地联调其他包时,可参考 `pubspec_overrides.yaml.example` 创建覆盖配置。覆盖文件只用于本机开发,不提交。
## 运行应用 ## 运行应用
本地路径与原生包认证统一放在应用根目录的 `.env.local`。复制
[配置示例](../.env.example),按需取消注释并填写本机路径;文件已忽略,不提交、
不作为应用资源打包。没有配置时,SDK 使用固定版本的已发布原生包。
Windows 可用 `CUTDEX_WINDOWS_PATH` 联调本地源码(需要 Rust 和 `FFMPEG_DIR`),
或用 `CUTDEX_WINDOWS_PACKAGE_PATH` 指定已解压的离线包,两者只选其一。
macOS/iOS 可用 `CUTDEX_APPLE_PATH` 指定本地源码。
Android 可用 `CUTDEX_ANDROID_PATH` 指向 `cutdex_android` 工程根目录,Gradle 会用
本地源码替换 Maven 原生依赖;未配置或留空时使用已发布包。
已有 Gradle 属性 `cutdex.android.path` 优先于该环境变量,显式空属性会关闭本地替换。
`CUTDEX_PROCESSING_ROOT` 指定处理 worker 目录;Android 私有 Maven 认证可填写
`GITEA_ACTOR` 和 `CUTDEX_GITEA_TOKEN`。这里的 `GITEA_ACTOR` 是令牌所属的认证
账号,CI 中也按令牌账号设置,与触发工作流的用户无关。
VS Code 的 Debug、Profile、Release 启动项与下述命令共用
`tool/flutter_local.dart` 加载规则。VS Code 的项目 SDK 设置由 `fvm use` 自动同步,
启动入口通过 `.fvm/flutter_sdk` 使用同一项目版本,不通过 `FLUTTER` 环境变量或
全局 PATH 选择 Flutter。
未准备项目 SDK 时先运行 `fvm use`。现有进程环境变量优先于文件,包括显式空值。
文件支持 `KEY=value`、单双引号和注释;值按字面读取,不执行命令,不展开变量或
反斜杠转义。格式错误会在构建前报错,不输出配置值。
Flutter 启动入口、Python 构建/检查入口和 macOS 打包共用同一个 Dart 加载器,
配置注入整个工具流水线的子进程环境,不修改系统环境或 SDK 文件。
检测到 `CI`、`GITEA_ACTIONS` 或 `GITHUB_ACTIONS` 为 true/1/yes 时,不读取本地文件。
现有 CI 继续使用工作流配置与 Secrets。直接执行 `fvm flutter` 不加载此文件。
更换 Windows 原生路径后,若 CMake 仍缓存旧路径,先退出应用并运行 `fvm dart tool/flutter_local.dart clean`。
Flutter 自带的 `--dart-define-from-file` 也支持 `.env` 格式,但生成的是 Dart 编译期
配置,由 `String.fromEnvironment` 读取,不会设置 CMake、Gradle 或 Swift 读取的
进程环境。原生依赖路径与认证使用上述启动入口;应用自身的编译期选项可继续使用
`--dart-define` 或 `--dart-define-from-file`,不要把原生包认证文件作为 Dart define 输入。
在 Cutdex 根目录运行: 在 Cutdex 根目录运行:
```sh ```sh
flutter pub get fvm dart tool/flutter_local.dart pub get
dart run build_runner build fvm dart run build_runner build
flutter run -d macos --flavor development fvm dart tool/flutter_local.dart run -d macos --flavor development
``` ```
Android、macOS、Windows 配置了 development 与 production flavor,默认是 development。按目标平台替换设备参数。iOS 使用 `Runner` scheme。构建或集成测试前,退出占用同一构建目录的应用。 Android、macOS、Windows 配置了 development 与 production flavor,默认是 development。按目标平台替换设备参数。iOS 使用 `Runner` scheme。构建或集成测试前,退出占用同一构建目录的应用。
@@ -25,7 +60,7 @@ Android、macOS、Windows 配置了 development 与 production flavor,默认
Android 支持 ARM64 和 x86_64。按架构拆分 APK 时显式指定目标: Android 支持 ARM64 和 x86_64。按架构拆分 APK 时显式指定目标:
```sh ```sh
flutter build apk --flavor development --split-per-abi --target-platform android-arm64,android-x64 python3 tool/build.py android --flavor development --split-per-abi
``` ```
字幕、翻译和抠像的功能验证需要相应资源。按应用提示准备资源,并使用合成或允许再分发的素材;不要把个人媒体、模型服务凭据或项目文件提交到仓库。 字幕、翻译和抠像的功能验证需要相应资源。按应用提示准备资源,并使用合成或允许再分发的素材;不要把个人媒体、模型服务凭据或项目文件提交到仓库。
@@ -48,9 +83,9 @@ flutter build apk --flavor development --split-per-abi --target-platform android
## 文案与代码生成 ## 文案与代码生成
修改需要生成代码的模型后,在所属包目录运行 `dart run build_runner build`,将生成文件与源码一起提交。 修改需要生成代码的模型后,在所属包目录运行 `fvm dart run build_runner build`,将生成文件与源码一起提交。
修改文案时更新 `lib/l10n/` 中的 ARB,再运行 `flutter gen-l10n`。简体中文同时维护 `app_zh.arb` 和 `app_zh_Hans.arb`;增加界面语言时更新语言选择与 Apple bundle 声明。 修改文案时更新 `lib/l10n/` 中的 ARB,再运行 `fvm dart tool/flutter_local.dart gen-l10n`。简体中文同时维护 `app_zh.arb` 和 `app_zh_Hans.arb`;增加界面语言时更新语言选择与 Apple bundle 声明。
执行 [测试指南](testing.md) 中适用的检查。界面改动还需检查桌面、平板和手机布局,以及明暗主题和不同语言下的表现。 执行 [测试指南](testing.md) 中适用的检查。界面改动还需检查桌面、平板和手机布局,以及明暗主题和不同语言下的表现。
@@ -64,6 +99,15 @@ flutter build apk --flavor development --split-per-abi --target-platform android
构建、打包和更新验证入口见 [仓库工具](../tool/README.md)。完成集成测试后,使用 `lib/main.dart` 重建正式应用,避免分发测试入口。 构建、打包和更新验证入口见 [仓库工具](../tool/README.md)。完成集成测试后,使用 `lib/main.dart` 重建正式应用,避免分发测试入口。
`python3 tool/build.py android|windows|macos` 与 CI 共用 production/release 预设,
额外 Flutter 参数放在 `--` 后。仅构建 macOS 应用时使用此入口;完整 ZIP/DMG
打包、processing 嵌入、签名和公证使用 `build_macos_release.py`。
环境文件合并时进程变量优先,包括空值。原生构建仍遵循所属 SDK 的覆盖规则:
Android Gradle 属性先于环境变量;Windows CMake 已缓存的非空路径先于环境变量,
修改后需 clean;processing 的非空 Dart define 先于进程环境,再使用随包默认路径。
`CUTDEX_GITEA_TOKEN` 用于依赖访问,Release 的 `GITEA_TOKEN` 用于发布和 CI 产物读取。
Android release 当前使用调试签名,正式分发前需配置发布签名;production flavor 本身不提供发布证书。 Android release 当前使用调试签名,正式分发前需配置发布签名;production flavor 本身不提供发布证书。
macOS 默认 ad-hoc 签名。开发证书配置放在 `macos/Runner/Configs/Signing.local.xcconfig`;iOS 真机的 Team 设置放在 `ios/Flutter/Signing.local.xcconfig`。这些文件已忽略,凭据与私钥保留在本地或 CI 私密配置中。 macOS 默认 ad-hoc 签名。开发证书配置放在 `macos/Runner/Configs/Signing.local.xcconfig`;iOS 真机的 Team 设置放在 `ios/Flutter/Signing.local.xcconfig`。这些文件已忽略,凭据与私钥保留在本地或 CI 私密配置中。
+1 -1
View File
@@ -7,7 +7,7 @@
MCP 默认关闭,在设置中启用并获取端口和访问令牌。外部客户端设置 `CUTDEX_MCP_PORT`、`CUTDEX_MCP_TOKEN`,以本仓库为工作目录运行: MCP 默认关闭,在设置中启用并获取端口和访问令牌。外部客户端设置 `CUTDEX_MCP_PORT`、`CUTDEX_MCP_TOKEN`,以本仓库为工作目录运行:
```sh ```sh
dart run tool/mcp_stdio.dart fvm dart run tool/mcp_stdio.dart
``` ```
连接通过本机端口访问正在运行的 Cutdex。工具范围由当前工作区和可用功能决定,参数以客户端发现结果为准。 连接通过本机端口访问正在运行的 Cutdex。工具范围由当前工作区和可用功能决定,参数以客户端发现结果为准。
+8 -6
View File
@@ -13,9 +13,7 @@ python3 tool/check_public_repository.py
该检查覆盖 Git 跟踪及未被忽略的待提交文件,可识别常见凭据格式、误纳入的本地产物和失效的本地文档链接;不代替 Git 历史审计,也不能识别任意自定义密码。 该检查覆盖 Git 跟踪及未被忽略的待提交文件,可识别常见凭据格式、误纳入的本地产物和失效的本地文档链接;不代替 Git 历史审计,也不能识别任意自定义密码。
```sh ```sh
flutter pub get fvm dart tool/flutter_local.dart pub get
dart analyze --fatal-infos
flutter test test packages/cutdex_ui/test packages/cutdex_native/test
# Python 3.11+ # Python 3.11+
python3 tool/check.py python3 tool/check.py
``` ```
@@ -27,15 +25,19 @@ python3 tool/check.py
| [integration_test](../integration_test/README.md) | 对应平台上的真实预览、媒体编辑与处理任务 | | [integration_test](../integration_test/README.md) | 对应平台上的真实预览、媒体编辑与处理任务 |
| [tool](../tool/README.md) | 脚本检查、发布包验证和平台诊断 | | [tool](../tool/README.md) | 脚本检查、发布包验证和平台诊断 |
本地完整检查与 CI 共用相同的套件,可用 `python3 tool/check.py --suite analyze`、
`--suite flutter` 或 `--suite tools` 单独执行或重试。静态分析启用 `--fatal-infos`;
Flutter 套件同时运行应用与内部包测试。所有入口使用项目 SDK 和相同环境加载规则。
App 测试验证宿主行为,底层算法、协议及插件生命周期在所属包测试。普通测试通过不代表真实播放或模型质量已经验证。 App 测试验证宿主行为,底层算法、协议及插件生命周期在所属包测试。普通测试通过不代表真实播放或模型质量已经验证。
## 生成文件 ## 生成文件
```sh ```sh
dart run build_runner build fvm dart run build_runner build
# UI 模型修改后,在 packages/cutdex_ui 中运行相同生成命令 # UI 模型修改后,在 packages/cutdex_ui 中运行相同生成命令
flutter gen-l10n fvm dart tool/flutter_local.dart gen-l10n
flutter test test/generated_code_test.dart test/localization_resources_test.dart fvm dart tool/flutter_local.dart test test/generated_code_test.dart test/localization_resources_test.dart
``` ```
生成文件应与源码一同提交。生成校验会重新生成应用与 UI 包并比较前后内容,同时检查应用生成文件的跟踪状态;不要暂存无关文件来掩盖失败。 生成文件应与源码一同提交。生成校验会重新生成应用与 UI 包并比较前后内容,同时检查应用生成文件的跟踪状态;不要暂存无关文件来掩盖失败。
+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
python tool/build.py windows --flavor development -- `
--dart-define=CUTDEX_WINDOWS_UPDATE_SOURCE=web `
--dart-define=CUTDEX_WINDOWS_UPDATE_URL=http://127.0.0.1:8765 `
--dart-define=CUTDEX_UPDATE_TEST_HTTP=true
```
Gitea 开发仓库使用 `CUTDEX_WINDOWS_UPDATE_SOURCE=gitea` 和仓库 URL。
仅设置进程环境变量不会配置 Dart 更新源。正式版忽略开发 defines。
原生 SDK 离线缓存仍通过 `DESKUP_VELOPACK_ARCHIVE` 环境变量指定。
```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 独立分发策略沿用现有流水线。
+19 -19
View File
@@ -2,7 +2,7 @@
`integration_test/` contains opt-in tests for the real application and native `integration_test/` contains opt-in tests for the real application and native
backends. `test_driver/integration_test.dart` is the host driver used by backends. `test_driver/integration_test.dart` is the host driver used by
`flutter drive` for Profile measurements. Both directories contain test source; `fvm dart tool/flutter_local.dart drive` for Profile measurements. Both directories contain test source;
media, models, reports and credentials are supplied locally and stay outside media, models, reports and credentials are supplied locally and stay outside
version control. Normal release builds use `lib/main.dart`. version control. Normal release builds use `lib/main.dart`.
@@ -13,7 +13,7 @@ window chrome, dynamically configured file destinations, and the macOS fullscree
channel. It requires no media or models and does not simulate Finder/Explorer drops. channel. It requires no media or models and does not simulate Finder/Explorer drops.
```sh ```sh
flutter test integration_test/native_desktop_plugins_test.dart -d macos --flavor development fvm dart tool/flutter_local.dart test integration_test/native_desktop_plugins_test.dart -d macos --flavor development
``` ```
Use `-d windows` on Windows. Rebuild the normal application entry point afterwards. Use `-d windows` on Windows. Rebuild the normal application entry point afterwards.
@@ -29,7 +29,7 @@ directory, and a short speech fixture. A local Dart-define JSON specifies
`CUTDEX_PROCESSING_ROOT` and `CUTDEX_ASR_FIXTURE`: `CUTDEX_PROCESSING_ROOT` and `CUTDEX_ASR_FIXTURE`:
```sh ```sh
flutter test integration_test/processing_e2e_test.dart -d macos --flavor development \ fvm dart tool/flutter_local.dart test integration_test/processing_e2e_test.dart -d macos --flavor development \
--dart-define-from-file=/absolute/path/to/processing-e2e.json --dart-define-from-file=/absolute/path/to/processing-e2e.json
``` ```
@@ -53,7 +53,7 @@ fault-injection checks with real media and native playback, not evidence that th
native backend itself produced these failures. native backend itself produced these failures.
```sh ```sh
flutter drive --profile -d macos --flavor production \ fvm dart tool/flutter_local.dart drive --profile -d macos --flavor production \
--driver=test_driver/integration_test.dart \ --driver=test_driver/integration_test.dart \
--target=integration_test/edit_diagnostics_test.dart \ --target=integration_test/edit_diagnostics_test.dart \
--dart-define=CUTDEX_TEST_SOURCE=/absolute/path/to/generated-720p30.mp4 \ --dart-define=CUTDEX_TEST_SOURCE=/absolute/path/to/generated-720p30.mp4 \
@@ -76,7 +76,7 @@ native diagnostics channel is compiled only in Debug, so its frame statistics
must not be presented as Profile measurements. must not be presented as Profile measurements.
```sh ```sh
CUTDEX_PREVIEW_CADENCE_DIAGNOSTICS=1 flutter drive --debug -d macos --flavor development \ CUTDEX_PREVIEW_CADENCE_DIAGNOSTICS=1 fvm dart tool/flutter_local.dart drive --debug -d macos --flavor development \
--driver=test_driver/integration_test.dart \ --driver=test_driver/integration_test.dart \
--target=integration_test/edit_diagnostics_test.dart \ --target=integration_test/edit_diagnostics_test.dart \
--dart-define=CUTDEX_DIAGNOSTIC_CADENCE=true \ --dart-define=CUTDEX_DIAGNOSTIC_CADENCE=true \
@@ -99,7 +99,7 @@ source clock, source duration and undo. No playback backend is mocked. ISO impor
when the native backend can probe an unprotected video stream. when the native backend can probe an unprotected video stream.
```powershell ```powershell
flutter test integration_test/windows_real_media_test.dart -d windows ` fvm dart tool/flutter_local.dart test integration_test/windows_real_media_test.dart -d windows `
--dart-define=CUTDEX_VALIDATION_SOURCE='D:\validation\media-originals' ` --dart-define=CUTDEX_VALIDATION_SOURCE='D:\validation\media-originals' `
--dart-define=CUTDEX_VALIDATION_ROOT='D:\validation\windows-editing' --dart-define=CUTDEX_VALIDATION_ROOT='D:\validation\windows-editing'
``` ```
@@ -112,10 +112,10 @@ native frames, delivered frames per second and the maximum frame gap. These
measure native preview delivery, not physical monitor refresh or speaker sound. measure native preview delivery, not physical monitor refresh or speaker sound.
`CUTDEX_VALIDATION_SOURCE_ROOTS` accepts semicolon-separated source directories `CUTDEX_VALIDATION_SOURCE_ROOTS` accepts semicolon-separated source directories
when validating multiple collections. For Flutter performance measurements use when validating multiple collections. For Flutter performance measurements use
`flutter drive --profile -d windows --flavor production `fvm dart tool/flutter_local.dart drive --profile -d windows --flavor production
--driver=test_driver/integration_test.dart --driver=test_driver/integration_test.dart
--target=integration_test/windows_real_media_test.dart` with the same Dart --target=integration_test/windows_real_media_test.dart` with the same Dart
defines: `flutter test` forces Debug mode. Playback observations additionally defines: `fvm dart tool/flutter_local.dart test` forces Debug mode. Playback observations additionally
record process/time boundaries and Flutter build/raster timings for correlation record process/time boundaries and Flutter build/raster timings for correlation
with actual Windows audio-session peaks. Native textures can redraw without Dart with actual Windows audio-session peaks. Native textures can redraw without Dart
frames, so the observation uses live frames and a continuous 16 ms viewport frames, so the observation uses live frames and a continuous 16 ms viewport
@@ -162,10 +162,10 @@ not play or export every frame of the original movies.
playhead dragging with any playable video at least five seconds long. It probes the playhead dragging with any playable video at least five seconds long. It probes the
source duration and scales the seek points and drag spans to that duration. Provide source duration and scales the seek points and drag spans to that duration. Provide
`CUTDEX_SEEK_SOURCE` and `CUTDEX_SEEK_REPORT`; run it with the shared `CUTDEX_SEEK_SOURCE` and `CUTDEX_SEEK_REPORT`; run it with the shared
`test_driver/integration_test.dart` entry point using `flutter drive --profile`. `test_driver/integration_test.dart` entry point using `fvm dart tool/flutter_local.dart drive --profile`.
```powershell ```powershell
flutter drive --profile --flavor production -d windows ` fvm dart tool/flutter_local.dart drive --profile --flavor production -d windows `
--driver=test_driver/integration_test.dart ` --driver=test_driver/integration_test.dart `
--target=integration_test/windows_seek_latency_test.dart ` --target=integration_test/windows_seek_latency_test.dart `
--dart-define=CUTDEX_SEEK_SOURCE='D:/validation/media-originals/video.mp4' ` --dart-define=CUTDEX_SEEK_SOURCE='D:/validation/media-originals/video.mp4' `
@@ -187,7 +187,7 @@ an incremental `results.json` report. The source should contain audio-only files
longer than ten seconds, with audible content in the 2–6 second edit interval. longer than ten seconds, with audible content in the 2–6 second edit interval.
```powershell ```powershell
flutter test integration_test/windows_audio_media_test.dart -d windows ` fvm dart tool/flutter_local.dart test integration_test/windows_audio_media_test.dart -d windows `
--dart-define=CUTDEX_VALIDATION_SOURCE=D:/validation/audio-originals ` --dart-define=CUTDEX_VALIDATION_SOURCE=D:/validation/audio-originals `
--dart-define=CUTDEX_VALIDATION_ROOT=D:/validation/audio-results --dart-define=CUTDEX_VALIDATION_ROOT=D:/validation/audio-results
``` ```
@@ -225,19 +225,19 @@ after installing an ABI split, without deleting the app's data. Keep complete
originals on the host. On a POSIX shell: originals on the host. On a POSIX shell:
```sh ```sh
flutter build apk --debug --flavor development fvm dart tool/flutter_local.dart build apk --debug --flavor development
adb -s DEVICE_SERIAL install -r -d build/app/outputs/flutter-apk/app-development-debug.apk adb -s DEVICE_SERIAL install -r -d build/app/outputs/flutter-apk/app-development-debug.apk
adb -s DEVICE_SERIAL shell run-as com.example.cutdex.dev mkdir -p files/real-media files/real-validation adb -s DEVICE_SERIAL shell run-as com.example.cutdex.dev mkdir -p files/real-media files/real-validation
adb -s DEVICE_SERIAL shell -T run-as com.example.cutdex.dev tee files/real-media/source.mp4 \ adb -s DEVICE_SERIAL shell -T run-as com.example.cutdex.dev tee files/real-media/source.mp4 \
< /absolute/path/to/source.mp4 > /dev/null < /absolute/path/to/source.mp4 > /dev/null
flutter test integration_test/android_real_media_test.dart -d DEVICE_SERIAL \ fvm dart tool/flutter_local.dart test integration_test/android_real_media_test.dart -d DEVICE_SERIAL \
--flavor development --no-uninstall \ --flavor development --no-uninstall \
--dart-define=CUTDEX_VALIDATION_SOURCE=/data/user/0/com.example.cutdex.dev/files/real-media \ --dart-define=CUTDEX_VALIDATION_SOURCE=/data/user/0/com.example.cutdex.dev/files/real-media \
--dart-define=CUTDEX_VALIDATION_ROOT=/data/user/0/com.example.cutdex.dev/files/real-validation --dart-define=CUTDEX_VALIDATION_ROOT=/data/user/0/com.example.cutdex.dev/files/real-validation
``` ```
Keep `--no-uninstall`: uninstalling also removes copied fixtures and validation Keep `--no-uninstall`: uninstalling also removes copied fixtures and validation
reports. With `flutter drive`, use `--debug --keep-app-running` to retain them. reports. With `fvm dart tool/flutter_local.dart drive`, use `--debug --keep-app-running` to retain them.
An optional An optional
`CUTDEX_VALIDATION_FILTER` selects filenames containing any comma-separated `CUTDEX_VALIDATION_FILTER` selects filenames containing any comma-separated
substring. `CUTDEX_VALIDATION_SAMPLE_START` selects the edit sample start in substring. `CUTDEX_VALIDATION_SAMPLE_START` selects the edit sample start in
@@ -291,7 +291,7 @@ project. The test uses an in-memory recent-project registry and does not write
to the normal application database. Without the required Dart defines, it skips. to the normal application database. Without the required Dart defines, it skips.
```sh ```sh
flutter test integration_test/downloads_workflow_test.dart -d macos \ fvm dart tool/flutter_local.dart test integration_test/downloads_workflow_test.dart -d macos \
--flavor development \ --flavor development \
--dart-define=CUTDEX_VALIDATION_SOURCE=/absolute/path/to/media \ --dart-define=CUTDEX_VALIDATION_SOURCE=/absolute/path/to/media \
--dart-define=CUTDEX_VALIDATION_ROOT=/absolute/path/to/output --dart-define=CUTDEX_VALIDATION_ROOT=/absolute/path/to/output
@@ -335,7 +335,7 @@ Use an unlocked developer-enabled iPhone and a valid signing team. Select the iO
other platforms. First install the test host using the shared empty-timeline test: other platforms. First install the test host using the shared empty-timeline test:
```sh ```sh
flutter test integration_test/preview_startup_test.dart -d <iphone-udid> \ fvm dart tool/flutter_local.dart test integration_test/preview_startup_test.dart -d <iphone-udid> \
--flavor Runner --no-uninstall \ --flavor Runner --no-uninstall \
--plain-name 'opening a timeline initializes native preview through App providers' --plain-name 'opening a timeline initializes native preview through App providers'
``` ```
@@ -349,7 +349,7 @@ xcrun devicectl device copy to --device <iphone-udid> \
--source /absolute/path/to/source.mp4 \ --source /absolute/path/to/source.mp4 \
--destination Documents/cutdex-validation-source.mp4 \ --destination Documents/cutdex-validation-source.mp4 \
--domain-type appDataContainer --domain-identifier com.example.cutdex --domain-type appDataContainer --domain-identifier com.example.cutdex
flutter test integration_test/ios_device_test.dart -d <iphone-udid> \ fvm dart tool/flutter_local.dart test integration_test/ios_device_test.dart -d <iphone-udid> \
--flavor Runner --no-uninstall --reporter expanded \ --flavor Runner --no-uninstall --reporter expanded \
--dart-define=CUTDEX_TEST_SOURCE_DOCUMENT=cutdex-validation-source.mp4 \ --dart-define=CUTDEX_TEST_SOURCE_DOCUMENT=cutdex-validation-source.mp4 \
--dart-define=CUTDEX_TEST_OUTPUT=ios-keyframes --dart-define=CUTDEX_TEST_OUTPUT=ios-keyframes
@@ -379,7 +379,7 @@ seconds of usable video. Supply a file outside the repository with
`CUTDEX_TEST_SOURCE`; `CUTDEX_TEST_OUTPUT` optionally preserves the export. `CUTDEX_TEST_SOURCE`; `CUTDEX_TEST_OUTPUT` optionally preserves the export.
```sh ```sh
flutter test integration_test/media_timebase_drop_test.dart -d macos \ fvm dart tool/flutter_local.dart test integration_test/media_timebase_drop_test.dart -d macos \
--flavor production \ --flavor production \
--dart-define=CUTDEX_TEST_SOURCE=/absolute/path/to/source.mp4 \ --dart-define=CUTDEX_TEST_SOURCE=/absolute/path/to/source.mp4 \
--dart-define=CUTDEX_TEST_OUTPUT=/absolute/path/to/export.mp4 --dart-define=CUTDEX_TEST_OUTPUT=/absolute/path/to/export.mp4
@@ -396,7 +396,7 @@ streamed import into managed project storage, duplicate selection, byte identity
native probing, thumbnails, playback, seeking and a video/audio export. native probing, thumbnails, playback, seeking and a video/audio export.
```sh ```sh
flutter drive --debug --keep-app-running \ fvm dart tool/flutter_local.dart drive --debug --keep-app-running \
--driver=test_driver/integration_test.dart \ --driver=test_driver/integration_test.dart \
--target=integration_test/android_document_import_test.dart \ --target=integration_test/android_document_import_test.dart \
-d DEVICE_SERIAL --flavor development \ -d DEVICE_SERIAL --flavor development \
@@ -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,
),
),
),
),
),
],
),
),
],
),
);
}
+119 -146
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;
final agentHidden =
resolved.editorHidden &&
widget.mode == WorkspaceMode.cut &&
!widget.controller.agentFullscreen;
final geometry = DesktopWorkspaceGeometry(
sidebarWidth: resolved.sidebarWidth,
agentWidth: agentHidden
? 0
: resolved.editorHidden
? width - navigationSpace - navigationGap
: resolved.agentWidth,
editorHidden: resolved.editorHidden && !agentHidden,
);
final available = width - navigationSpace - navigationGap;
void expandEditor() { void expandEditor() {
final collapseNavigation = width - navigationSpace - 1 < 780; final collapseNavigation =
available < 220 + gap + DesktopWorkspaceGeometry.editorMinimumWidth;
if (collapseNavigation) widget.onSidebarCollapsedChanged(true); if (collapseNavigation) widget.onSidebarCollapsedChanged(true);
widget.controller.setSplit( widget.controller.setAgentFullscreen(false);
width - }
(collapseNavigation ? 0 : navigationSpace) -
DesktopWorkspaceGeometry.editorRestoreWidth - void resizeAgent(double requested) {
1, final maximum =
editorCollapsed: false, 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,
top: 0,
bottom: 0, bottom: 0,
left: geometry.sidebarWidth - 4, child: _gutter(
width: 8, name: 'project-sidebar',
child: MouseRegion( initialWidth: navigationSpace,
cursor: SystemMouseCursors.resizeColumn, onResize: (value) => widget.onSidebarWidthChanged(
child: GestureDetector( value.clamp(
key: const Key('project-sidebar-resize'), WorkspaceLayoutMetrics.sidebarMinimumWidth,
behavior: HitTestBehavior.opaque, DesktopWorkspaceGeometry.sidebarMaximum(
dragStartBehavior: DragStartBehavior.down, width - 2 * gap + 1,
onHorizontalDragStart: (details) { WorkspaceMode.agent,
_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 && if (!agentHidden && !geometry.editorHidden)
width - navigationSpace - 1 >= 220)
Positioned( Positioned(
left: geometry.editorHidden
? navigationSpace +
navigationGap +
(widget.sidebarCollapsed
? 0
: WorkspaceLayoutMetrics.desktopResizeSlop)
: width -
geometry.agentWidth -
gap -
WorkspaceLayoutMetrics.desktopResizeSlop,
top: 0, top: 0,
bottom: 0, bottom: 0,
left: child: _gutter(
navigationSpace + name: 'agent-panel',
geometry.agentWidth - initialWidth: geometry.agentWidth,
(geometry.editorHidden ? 8 : 4), direction: -1,
width: 8, onResize: resizeAgent,
child: MouseRegion(
cursor: SystemMouseCursors.resizeColumn,
child: GestureDetector(
key: const Key('agent-panel-resize'),
behavior: HitTestBehavior.opaque,
dragStartBehavior: DragStartBehavior.down,
onHorizontalDragStart: (details) {
_agentDragStart = details.globalPosition.dx;
_agentDragWidth = geometry.agentWidth;
},
onHorizontalDragUpdate: (details) {
final start = _agentDragStart;
if (start == null) return;
final agentWidth =
(_agentDragWidth + details.globalPosition.dx - start)
.clamp(220.0, width - navigationSpace - 1);
final remaining =
width - navigationSpace - agentWidth - 1;
widget.controller.setSplit(
agentWidth,
editorCollapsed: geometry.editorHidden
? remaining <
DesktopWorkspaceGeometry.editorRestoreWidth
: remaining <=
DesktopWorkspaceGeometry.editorCollapseWidth -
DesktopWorkspaceGeometry
.editorCollapseDragBuffer,
);
},
onHorizontalDragEnd: (_) {
_agentDragStart = null;
if (!_editorCollapsedByAgent &&
_agentWidth != null &&
width -
navigationSpace -
DesktopWorkspaceGeometry.editorCollapseWidth -
1 >=
220) {
widget.controller.setSplit(
_agentWidth!.clamp(
220.0,
width -
navigationSpace -
DesktopWorkspaceGeometry.editorCollapseWidth -
1,
),
editorCollapsed: false,
);
}
},
onHorizontalDragCancel: () => _agentDragStart = null,
child: const SizedBox.expand(),
),
), ),
), ),
], ],
+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(
+179 -165
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,53 +82,170 @@ 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
projectId: widget.projectId, ? const EditorEmptyPanel()
timelineId: widget.timelineId, : EditorPropertiesPanel(
); projectId: widget.projectId,
final media = MediaPanel(projectId: widget.projectId); timelineId: widget.timelineId,
);
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.propertiesPanelWidth + 1
? WorkspaceLayoutMetrics.mediaPanelWidth + 1 : 0);
: 0) +
(_propertiesOpen
? WorkspaceLayoutMetrics.propertiesPanelWidth + 1
: 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;
final header = Material(
color: Theme.of(context).colorScheme.surface,
child: SizedBox(
key: const Key('editor-content-header'),
height: headerHeight,
child: Padding(
padding: desktop
? const EdgeInsets.symmetric(
horizontal: AppSidebarMetrics.outerPadding,
vertical: AppSpacing.gap,
)
: EdgeInsets.zero,
child: WindowHeaderPadding(
child: Row(
children: [
widget.headerLeading,
Expanded(
child: widget.showProjectName
? Row(
children: [
Flexible(
fit: FlexFit.loose,
child: Text(
widget.projectName,
key: const Key('workspace-project-title'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context)
.textTheme
.titleSmall,
),
),
Flexible(
fit: FlexFit.loose,
child: widget.projectLoading
? const SizedBox.shrink()
: _TimelineSaveStatus(
projectId: widget.projectId,
timelineId: widget.timelineId,
),
),
],
)
: const SizedBox.shrink(),
),
if (!desktop)
HeaderControlRegion(
child: SizedBox.square(
dimension: desktop
? AppControlSize.headerButton
: 48,
child: IconButton(
key: const Key('editor-media-button'),
tooltip: context.l10n.materials,
isSelected: mediaOpen,
onPressed: () {
if (desktop) {
if (!dockPanels &&
desktopTool != EditorTool.media &&
_presentation.mediaOpen) {
_presentation.preferDesktopTool(
EditorTool.media,
);
} else {
_presentation.toggleMedia();
}
} else {
_presentation.toggleTool(EditorTool.media);
}
},
icon: const Icon(Icons.perm_media_outlined),
),
),
),
if (!desktop) const SizedBox(width: AppSpacing.tiny),
HeaderControlRegion(
child: SizedBox.square(
dimension: desktop ? AppControlSize.headerButton : 48,
child: IconButton(
key: const Key('editor-properties-button'),
tooltip: propertiesOpen
? context.l10n.collapseProperties
: context.l10n.expandProperties,
isSelected: propertiesOpen,
onPressed: !viewSettings.hasValue
? null
: () {
if (desktop) {
if (dockPanels ||
desktopTool ==
EditorTool.properties ||
!_propertiesOpen) {
_viewController.setPropertiesOpen(
!_propertiesOpen,
);
_saveViewSettings();
}
_presentation.preferDesktopTool(
EditorTool.properties,
);
} else {
_presentation.toggleTool(
EditorTool.properties,
);
}
},
icon: const Icon(
Icons.tune,
size: AppIconSize.header,
),
),
),
),
if (!desktop) const SizedBox(width: AppSpacing.compact),
],
),
),
),
),
);
Widget dockedEditing({required bool showTools}) => Widget dockedEditing({required bool showTools}) =>
ExpandedEditorLayout( ExpandedEditorLayout(
preview: preview, preview: preview,
header: header,
properties: properties, properties: properties,
media: media, media: media,
showMedia: showTools && _presentation.mediaOpen, showMedia: false,
showProperties: showTools && _propertiesOpen, showProperties: showTools && _propertiesOpen,
timelineHeight: _timelineHeight, timelineHeight: _timelineHeight,
onTimelineHeightChanged: (height) { onTimelineHeightChanged: (height) {
@@ -141,121 +261,7 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
children: [ children: [
Column( Column(
children: [ children: [
Material( if (!desktop) header,
color: Theme.of(context).colorScheme.surface,
child: SizedBox(
key: const Key('editor-content-header'),
height: headerHeight,
child: WindowHeaderPadding(
child: Row(
children: [
widget.headerLeading,
Expanded(
child: widget.showProjectName
? Row(
children: [
Flexible(
fit: FlexFit.loose,
child: Text(
widget.projectName,
key: const Key(
'workspace-project-title',
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context)
.textTheme
.titleSmall,
),
),
Flexible(
fit: FlexFit.loose,
child: _TimelineSaveStatus(
projectId: widget.projectId,
timelineId: widget.timelineId,
),
),
],
)
: const SizedBox.shrink(),
),
HeaderControlRegion(
child: SizedBox.square(
dimension: desktop
? AppControlSize.headerButton
: 48,
child: IconButton(
key: const Key('editor-media-button'),
tooltip: context.l10n.materials,
isSelected: mediaOpen,
onPressed: () {
if (desktop) {
if (!dockPanels &&
desktopTool != EditorTool.media &&
_presentation.mediaOpen) {
_presentation.preferDesktopTool(
EditorTool.media,
);
} else {
_presentation.toggleMedia();
}
} else {
_presentation.toggleTool(
EditorTool.media,
);
}
},
icon: const Icon(Icons.perm_media_outlined),
),
),
),
const SizedBox(width: AppSpacing.tiny),
HeaderControlRegion(
child: SizedBox.square(
dimension: desktop
? AppControlSize.headerButton
: 48,
child: IconButton(
key: const Key('editor-properties-button'),
tooltip: propertiesOpen
? context.l10n.collapseProperties
: context.l10n.expandProperties,
isSelected: propertiesOpen,
onPressed: !viewSettings.hasValue
? null
: () {
if (desktop) {
if (dockPanels ||
desktopTool ==
EditorTool.properties ||
!_propertiesOpen) {
_viewController.setPropertiesOpen(
!_propertiesOpen,
);
_saveViewSettings();
}
_presentation.preferDesktopTool(
EditorTool.properties,
);
} else {
_presentation.toggleTool(
EditorTool.properties,
);
}
},
icon: const Icon(
Icons.tune,
size: AppIconSize.header,
),
),
),
),
const SizedBox(width: AppSpacing.compact),
],
),
),
),
),
Expanded( Expanded(
child: dockPanels child: dockPanels
? dockedEditing(showTools: true) ? dockedEditing(showTools: true)
@@ -270,26 +276,33 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
tool: desktop tool: desktop
? desktopTool ? desktopTool
: _presentation.activeTool, : _presentation.activeTool,
media: switch (widget.experience) { media: widget.projectLoading
DeviceExperience.desktop => media, ? media
DeviceExperience.tablet => MediaBrowserDrawer( : switch (widget.experience) {
projectId: widget.projectId, DeviceExperience.desktop => media,
), DeviceExperience.tablet =>
DeviceExperience.phone => MediaBrowserPage( MediaBrowserDrawer(
projectId: widget.projectId, projectId: widget.projectId,
), ),
}, DeviceExperience.phone => MediaBrowserPage(
properties: switch (widget.experience) { projectId: widget.projectId,
DeviceExperience.desktop => properties, ),
DeviceExperience.tablet => PropertiesToolPanel( },
projectId: widget.projectId, properties: widget.projectLoading
timelineId: widget.timelineId, ? properties
), : switch (widget.experience) {
DeviceExperience.phone => PropertiesEditorPage( DeviceExperience.desktop => properties,
projectId: widget.projectId, DeviceExperience.tablet =>
timelineId: widget.timelineId, PropertiesToolPanel(
), projectId: widget.projectId,
}, timelineId: widget.timelineId,
),
DeviceExperience.phone =>
PropertiesEditorPage(
projectId: widget.projectId,
timelineId: widget.timelineId,
),
},
onCloseTool: () { onCloseTool: () {
if (!desktop) { if (!desktop) {
_presentation.closeTool(); _presentation.closeTool();
@@ -304,14 +317,15 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
), ),
], ],
), ),
Positioned( if (!desktop)
key: const Key('editing-top-divider'), Positioned(
top: headerHeight, key: const Key('editing-top-divider'),
left: 0, top: headerHeight,
right: 0, left: 0,
height: 1, right: 0,
child: const Divider(height: 1), height: 1,
), child: const Divider(height: 1),
),
], ],
); );
}, },
@@ -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,
@@ -66,76 +75,72 @@ class _ExpandedEditorLayoutState extends State<ExpandedEditorLayout> {
Column( Column(
children: [ children: [
Expanded( Expanded(
child: Row( child: _card(
crossAxisAlignment: CrossAxisAlignment.stretch, 'preview',
children: [ Row(
if (widget.showMedia) ...[ crossAxisAlignment: CrossAxisAlignment.stretch,
SizedBox( children: [
key: const Key('editor-media-region'), Expanded(
width: mediaWidth, child: Column(
child: widget.media, crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
widget.header,
Expanded(
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (widget.showMedia) ...[
SizedBox(
key: const Key('editor-media-region'),
width: mediaWidth,
child: widget.media,
),
const VerticalDivider(width: 1),
],
Expanded(child: widget.preview),
],
),
),
],
),
), ),
const VerticalDivider(width: 1), if (widget.showProperties) ...[
const VerticalDivider(
key: Key('editor-properties-divider'),
width: 1,
),
SizedBox(
key: const Key('editor-properties-region'),
width: propertiesWidth,
child: widget.properties,
),
],
], ],
Expanded(child: widget.preview), ),
if (widget.showProperties) ...[
const VerticalDivider(width: 1),
SizedBox(
key: const Key('editor-properties-region'),
width: propertiesWidth,
child: widget.properties,
),
],
],
), ),
), ),
const SizedBox(height: 1), const SizedBox(height: gap),
SizedBox(height: timelineHeight, child: widget.timeline), SizedBox(
height: timelineHeight,
child: _card('timeline', widget.timeline),
),
], ],
), ),
Positioned( Positioned(
key: const Key('editor-timeline-divider'), key: const Key('editor-timeline-divider'),
left: 0, left: 0,
right: 0, right: 0,
bottom: timelineHeight - 4, bottom: timelineHeight - WorkspaceLayoutMetrics.desktopResizeSlop,
height: 8, height: WorkspaceLayoutMetrics.desktopResizeHitExtent,
child: MouseRegion( child: WorkspaceResizeHandle(
cursor: SystemMouseCursors.resizeRow, key: const Key('editor-timeline-resize'),
child: GestureDetector( axis: Axis.vertical,
key: const Key('editor-timeline-resize'), initialValue: timelineHeight,
behavior: HitTestBehavior.opaque, direction: -1,
dragStartBehavior: DragStartBehavior.down, onResize: (height) => widget.onTimelineHeightChanged(
onVerticalDragStart: (details) { height.clamp(minimum, maximum).toDouble(),
_timelineDragStartY = details.globalPosition.dy;
_timelineDragStartHeight = timelineHeight;
},
onVerticalDragUpdate: (details) {
final start = _timelineDragStartY;
if (start == null) return;
widget.onTimelineHeightChanged(
(_timelineDragStartHeight +
start -
details.globalPosition.dy)
.clamp(minimum, maximum)
.toDouble(),
);
},
onVerticalDragEnd: (_) {
_timelineDragStartY = null;
widget.onTimelineHeightChangeEnd();
},
onVerticalDragCancel: () {
_timelineDragStartY = null;
widget.onTimelineHeightChangeEnd();
},
child: const Center(
child: SizedBox(
height: 1,
width: double.infinity,
child: Divider(height: 1),
),
),
), ),
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!)));
} }
} }
+44 -25
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( ref.read(projectsProvider).asData?.value.error ??
content: Text( const AppFailure(AppErrorCode.operationFailed);
context.l10n.failureMessage( ErrorNotificationHost.of(context)
ref.read(projectsProvider).asData?.value.error ?? .showFailure(failure, context.l10n.failureMessage(failure));
const AppFailure(AppErrorCode.operationFailed),
),
),
),
);
} }
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,15 +206,22 @@ 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
.ceil(), ? ((width + spacing) /
(maximumCompactMediaGridTileWidth + spacing))
.ceil()
: ((width + spacing) /
(maximumMediaGridTileWidth + spacing))
.ceil(),
); );
final tileWidth = (width - spacing * (columns - 1)) / columns; final tileWidth = (width - spacing * (columns - 1)) / columns;
final textStyle = Theme.of(context).textTheme.bodySmall!; final textStyle = Theme.of(context).textTheme.bodySmall!;
@@ -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,
),
), ),
], ],
), ),
+420 -304
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,199 +171,256 @@ 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(
final activeController = controller; headerHeight: 0,
final showCanvas = showHeaderDivider: false,
state.hasError || child: PreviewFullscreenLayout(
(activeController != null && canvas: ListenableSelector(
(activeController.durationTick > 0 || listenable: controller,
activeController.error != null)); select: () => (
final overlayBuilder = controller?.canvas,
activeController != null && controller?.session,
PreviewFullscreenScope.of(context)?.fullscreen != true && controller?.error,
activeController.session != null && (controller?.durationTick ?? 0) > 0,
activeController.error == null ),
? (Rect rect) => ListenableBuilder( builder: (context, _) {
listenable: activeController.positionChanges, final activeController = controller;
builder: (context, _) => Theme( final defaultCanvas =
data: AppTheme.previewCanvasTheme, pending ||
child: (state.isLoading && !state.hasError && controller == null);
activeController.maskEditingElement != null || final showCanvas =
activeController.obscureEditingElement != null defaultCanvas ||
? MaskInteractionOverlay( state.hasError ||
controller: activeController, (activeController != null &&
canvasRect: rect, (activeController.durationTick > 0 ||
obscure: activeController.obscureEditingElement != null, activeController.error != null));
) final overlayBuilder =
: PreviewInteractionOverlay( activeController != null &&
onError: (_) => ScaffoldMessenger.maybeOf(context) PreviewFullscreenScope.of(context)?.fullscreen != true &&
?.showSnackBar( activeController.session != null &&
SnackBar( activeController.error == null
content: Text( ? (Rect rect) => ListenableBuilder(
context.l10n.canvasTransformFailed, listenable: activeController.positionChanges,
), builder: (context, _) => Theme(
),
),
controller: activeController,
canvasRect: rect,
),
),
)
: null;
return WorkspacePanel(
headerHeight: 0,
showHeaderDivider: false,
child: PreviewFullscreenLayout(
canvas: showCanvas
? Padding(
padding:
PreviewFullscreenScope.of(context)?.fullscreen == true
? EdgeInsets.zero
: AppSpacing.panelSection,
child: PreviewCanvas(
alignment: Alignment.center,
horizontalPadding: 0,
backgroundColor: AppSurfaces.of(context).previewBackground,
overlayBuilder: overlayBuilder,
aspectRatio:
(activeController?.canvas ?? ProjectCanvas.widescreen)
.aspectRatio,
child: Theme(
data: AppTheme.previewCanvasTheme, data: AppTheme.previewCanvasTheme,
child: Builder( child:
builder: (context) => state.when( activeController.maskEditingElement != null ||
loading: () => const DelayedLoadingIndicator( activeController.obscureEditingElement != null
child: Center(child: CircularProgressIndicator()), ? MaskInteractionOverlay(
), controller: activeController,
error: (error, _) => Center( canvasRect: rect,
child: SingleChildScrollView( obscure:
primary: false, activeController.obscureEditingElement !=
child: Column( null,
mainAxisSize: MainAxisSize.min, )
children: [ : PreviewInteractionOverlay(
Text( onError: (error) =>
error is EditorSessionStartupException ErrorNotificationHost.maybeOf(context)?.show(
? context.l10n.editorSessionStartFailed ErrorNotification(
: error is RuntimeException && content: Text(
error.code == 'unsupported' context.l10n.canvasTransformFailed,
? context.l10n.nativePreviewUnsupported ),
: context.l10n.previewStartFailed, details: error.toString(),
textAlign: TextAlign.center, ),
), ),
TextButton( controller: activeController,
onPressed: () { canvasRect: rect,
if (error
is EditorSessionStartupException) {
ref.invalidate(
editorTimelineProvider(
projectId,
timelineId,
),
);
} else {
unawaited(
ref
.read(
previewControllerRegistryProvider,
)
.invalidate((
projectId,
timelineId,
)),
);
ref.invalidate(provider);
}
},
child: Text(context.l10n.retry),
),
],
),
), ),
), ),
data: (preview) { )
if (preview == null) { : null;
return const SizedBox.expand( return showCanvas
key: Key('empty-preview-area'), ? Padding(
); padding:
} PreviewFullscreenScope.of(context)?.fullscreen == true
return Stack( ? EdgeInsets.zero
fit: StackFit.expand, : AppSpacing.panelSection,
children: [ child: PreviewCanvas(
if (preview.session case final session?) alignment: Alignment.center,
RuntimePreview(session: session), horizontalPadding: 0,
ListenableBuilder( backgroundColor: AppSurfaces.of(context)
listenable: preview.positionChanges, .previewBackground,
builder: (context, _) { overlayBuilder: overlayBuilder,
final unavailable = aspectRatio:
preview.unavailableAtPlayhead; (activeController?.canvas ?? ProjectCanvas.widescreen)
if (preview.error != null || .aspectRatio,
unavailable.isEmpty) { child: Theme(
return const SizedBox.shrink(); data: AppTheme.previewCanvasTheme,
} child: Builder(
return IgnorePointer( builder: (context) => defaultCanvas
child: Align( ? const ColoredBox(
alignment: Alignment.bottomCenter, key: Key('preview-default-frame'),
child: Padding( color: Colors.black,
padding: const EdgeInsets.all( )
AppSpacing.medium, : state.when(
), skipLoadingOnReload: true,
child: Text( loading: () => const ColoredBox(
context.l10n.mediaOffline( key: Key('preview-default-frame'),
unavailable.join(', '), color: Colors.black,
), ),
maxLines: 2, error: (error, _) => Center(
overflow: TextOverflow.ellipsis, child: SingleChildScrollView(
primary: false,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
error is EditorSessionStartupException
? context
.l10n
.editorSessionStartFailed
: error is RuntimeException &&
error.code ==
'unsupported'
? context
.l10n
.nativePreviewUnsupported
: context.l10n.previewStartFailed,
textAlign: TextAlign.center, textAlign: TextAlign.center,
), ),
), TextButton(
), onPressed: () {
); if (error
}, is EditorSessionStartupException) {
), ref.invalidate(
if (preview.error != null || editorTimelineProvider(
preview.durationTick == 0) projectId,
ColoredBox( timelineId,
color: AppSurfaces.of(context) ),
.previewBackground, );
child: Center( } else {
child: Padding( unawaited(
padding: const EdgeInsets.all( ref
AppSpacing.medium, .read(
), previewControllerRegistryProvider,
child: Text( )
preview.error == null .invalidate((
? context.l10n.noPreviewContent projectId,
: previewErrorMessage( timelineId,
preview.error!, )),
context.l10n, );
), ref.invalidate(provider);
textAlign: TextAlign.center, }
), },
child: Text(context.l10n.retry),
),
],
), ),
), ),
), ),
], data: (preview) {
); if (preview == null) {
}, return const SizedBox.expand(
key: Key('empty-preview-area'),
);
}
return Stack(
fit: StackFit.expand,
children: [
if (preview.session case final session?)
RuntimePreview(session: session),
ListenableSelector(
listenable: Listenable.merge([
preview,
preview.positionChanges,
]),
select: () => (
preview.error,
preview.unavailableAtPlayhead.join(
', ',
),
),
builder: (context, _) {
final unavailable =
preview.unavailableAtPlayhead;
if (preview.error != null ||
unavailable.isEmpty) {
return const SizedBox.shrink();
}
return IgnorePointer(
child: Align(
alignment:
Alignment.bottomCenter,
child: Padding(
padding: const EdgeInsets.all(
AppSpacing.medium,
),
child: Text(
context.l10n.mediaOffline(
unavailable.join(', '),
),
maxLines: 2,
overflow:
TextOverflow.ellipsis,
textAlign: TextAlign.center,
),
),
),
);
},
),
if (preview.error != null ||
preview.durationTick == 0)
ColoredBox(
color: AppSurfaces.of(context)
.previewBackground,
child: Center(
child: Padding(
padding: const EdgeInsets.all(
AppSpacing.medium,
),
child: Text(
preview.error == null
? context
.l10n
.noPreviewContent
: previewErrorMessage(
preview.error!,
context.l10n,
),
textAlign: TextAlign.center,
),
),
),
),
],
);
},
),
), ),
), ),
), ),
), )
) : const SizedBox.expand(key: Key('empty-preview-area'));
: 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,34 +471,40 @@ class _SourcePreviewPanel extends ConsumerWidget {
.watch(mediaAvailabilityProvider(projectId, asset)) .watch(mediaAvailabilityProvider(projectId, asset))
.asData .asData
?.value; ?.value;
return ListenableBuilder( return CallbackShortcuts(
listenable: source, bindings: {
builder: (context, _) { const SingleActivator(LogicalKeyboardKey.space): source.togglePlayback,
// The availability probe can finish while a newly dropped file is },
// still switching security-scoped leases. Once the runtime has opened child: Focus(
// the source, that live session is stronger evidence than the stale autofocus: true,
// probe result and must not be covered by an unavailable placeholder. child: WorkspacePanel(
final unavailable = title: asset.name,
availability != null && showHeaderDivider: false,
availability != MediaAvailability.available && headerHeight: PreviewFullscreenScope.of(context)?.fullscreen == true
source.session == null && ? 0
source.image == null; : AppControlSize.panelHeader,
return CallbackShortcuts( child: PreviewFullscreenLayout(
bindings: { canvas: ListenableSelector(
const SingleActivator(LogicalKeyboardKey.space): listenable: source,
source.togglePlayback, select: () => (
}, source.session,
child: Focus( source.image,
autofocus: true, source.error,
child: WorkspacePanel( source.busy,
title: asset.name, source.aspectRatio,
showHeaderDivider: false, source.audioOnly,
headerHeight: ),
PreviewFullscreenScope.of(context)?.fullscreen == true builder: (context, _) {
? 0 // The availability probe can finish while a newly dropped file is
: AppControlSize.panelHeader, // still switching security-scoped leases. Once the runtime has opened
child: PreviewFullscreenLayout( // the source, that live session is stronger evidence than the stale
canvas: Padding( // probe result and must not be covered by an unavailable placeholder.
final unavailable =
availability != null &&
availability != MediaAvailability.available &&
source.session == null &&
source.image == null;
return Padding(
padding: padding:
PreviewFullscreenScope.of(context)?.fullscreen == true PreviewFullscreenScope.of(context)?.fullscreen == true
? EdgeInsets.zero ? EdgeInsets.zero
@@ -508,13 +575,13 @@ 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,96 +702,128 @@ class _PreviewToolbar extends StatelessWidget {
child: Row( child: Row(
children: [ children: [
Expanded( Expanded(
child: Text.rich( child: ListenableSelector(
TextSpan( key: const Key('preview-time'),
children: [ listenable: _clock,
TextSpan( select: () => (
text: _time( source?.positionTick ?? preview?.positionTick ?? 0,
source?.positionTick ?? preview?.positionTick ?? 0, source?.durationTick ?? preview?.durationTick ?? 0,
frameDuration, _frameDuration,
),
style: TextStyle(
color: Theme.of(context).colorScheme.onSurface,
),
),
TextSpan(
text:
' / ${_time(source?.durationTick ?? preview?.durationTick ?? 0, frameDuration)}',
style: TextStyle(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
],
), ),
maxLines: 1, builder: (context, _) => Text.rich(
overflow: TextOverflow.ellipsis, TextSpan(
style: Theme.of(context).textTheme.bodySmall?.copyWith( children: [
fontFeatures: [const FontFeature.tabularFigures()], TextSpan(
text: _time(
source?.positionTick ?? preview?.positionTick ?? 0,
_frameDuration,
),
style: TextStyle(
color: Theme.of(context).colorScheme.onSurface,
),
),
TextSpan(
text:
' / ${_time(source?.durationTick ?? preview?.durationTick ?? 0, _frameDuration)}',
style: TextStyle(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
],
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
fontFeatures: [const FontFeature.tabularFigures()],
),
), ),
), ),
), ),
IconButton( ListenableSelector(
tooltip: playing ? context.l10n.pause : context.l10n.play, listenable: source ?? preview,
onPressed: source != null select: () => (
? (source!.canPlay ? source!.togglePlayback : null) source?.playing ?? preview?.playing ?? false,
: preview != null && preview.canPlay source?.canPlay ?? preview?.canPlay ?? false,
? preview.togglePlayback ),
: null, builder: (context, value) {
icon: Icon(playing ? Icons.pause : Icons.play_arrow), final playing = value.$1;
return IconButton(
tooltip: playing ? context.l10n.pause : context.l10n.play,
onPressed: source != null
? (source!.canPlay ? source!.togglePlayback : null)
: preview != null && preview.canPlay
? preview.togglePlayback
: null,
icon: Icon(playing ? Icons.pause : Icons.play_arrow),
);
},
), ),
Expanded( Expanded(
child: Align( child: ListenableSelector(
alignment: Alignment.centerRight, listenable: source ?? preview,
child: Row( select: () => (
mainAxisSize: MainAxisSize.min, preview?.canvas,
children: [ preview?.error,
if (preview != null && preview?.hasUnavailableMedia,
(preview.error != null || preview?.busy,
preview.hasUnavailableMedia)) ...[ preview?.session,
IconButton( source?.session,
tooltip: context.l10n.retryPreview, source?.image,
onPressed: preview.busy ? null : preview.retry, ),
icon: const Icon(Icons.refresh), builder: (context, _) => Align(
), alignment: Alignment.centerRight,
const SizedBox(width: AppSpacing.gap), child: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (preview != null &&
(preview.error != null ||
preview.hasUnavailableMedia)) ...[
IconButton(
tooltip: context.l10n.retryPreview,
onPressed: preview.busy ? null : preview.retry,
icon: const Icon(Icons.refresh),
),
const SizedBox(width: AppSpacing.gap),
],
if (source == null &&
PreviewFullscreenScope.of(context)?.fullscreen !=
true)
Flexible(
child: AppSelect<ProjectCanvas>(
emptyLabel: context.l10n.noMatchingOptions,
label: context.l10n.canvasRatio,
outlined: false,
value: preview?.canvas ?? ProjectCanvas.widescreen,
onChanged: preview?.setCanvas,
options: [
for (final entry
in ProjectCanvasPresets.values.entries)
AppSelectOption(entry.value, entry.key),
],
),
),
if (PreviewFullscreenScope.of(context)
case final fullscreen?)
IconButton(
key: const Key('preview-fullscreen'),
tooltip: fullscreen.fullscreen
? context.l10n.exitPreviewFullscreen
: context.l10n.previewFullscreen,
onPressed:
fullscreen.fullscreen ||
source?.session != null ||
source?.image != null ||
preview?.session != null
? fullscreen.toggle
: null,
icon: Icon(
fullscreen.fullscreen
? Icons.fullscreen_exit
: Icons.fullscreen,
),
),
], ],
if (source == null && ),
PreviewFullscreenScope.of(context)?.fullscreen != true)
Flexible(
child: AppSelect<ProjectCanvas>(
emptyLabel: context.l10n.noMatchingOptions,
label: context.l10n.canvasRatio,
outlined: false,
value: preview?.canvas ?? ProjectCanvas.widescreen,
onChanged: preview?.setCanvas,
options: [
for (final entry
in ProjectCanvasPresets.values.entries)
AppSelectOption(entry.value, entry.key),
],
),
),
if (PreviewFullscreenScope.of(context)
case final fullscreen?)
IconButton(
key: const Key('preview-fullscreen'),
tooltip: fullscreen.fullscreen
? context.l10n.exitPreviewFullscreen
: context.l10n.previewFullscreen,
onPressed:
fullscreen.fullscreen ||
source?.session != null ||
source?.image != null ||
preview?.session != null
? fullscreen.toggle
: null,
icon: Icon(
fullscreen.fullscreen
? Icons.fullscreen_exit
: Icons.fullscreen,
),
),
],
), ),
), ),
), ),
@@ -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,32 +12,44 @@ 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
child: WindowHeaderPadding( ? AppControlSize.panelToolbar
child: Row( : AppControlSize.panelHeader,
children: [ child: Padding(
headerLeading, padding: desktop
if (showProjectName) ? const EdgeInsets.symmetric(
Expanded( horizontal: AppSidebarMetrics.outerPadding,
child: Text( vertical: AppSpacing.gap,
state.activeProject?.name ?? '', )
key: const Key('workspace-project-title'), : EdgeInsets.zero,
maxLines: 1, child: WindowHeaderPadding(
overflow: TextOverflow.ellipsis, child: Row(
style: Theme.of(context).textTheme.titleSmall, children: [
headerLeading,
if (showProjectName)
Expanded(
child: Text(
state.activeProject?.name ?? '',
key: const Key('workspace-project-title'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.titleSmall,
),
), ),
), ],
], ),
), ),
), ),
), ),
@@ -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),
),
),
),
),
),
],
);
}
+400 -276
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,74 +325,84 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
) == ) ==
true; true;
Widget _conversationRow(ConversationMetadata item) { Widget _conversationRow(ConversationMetadata item) => Consumer(
final selected = builder: (context, ref, _) {
widget.state.activeProject?.id == item.projectId && final active = ref.watch(
_selectedConversationId == item.id; projectsProvider.select(
List<Widget> actions(BuildContext context) => [ (value) => value.value?.activeProject?.id == item.projectId,
AppMenuItem( ),
label: context.l10n.rename,
onPressed: () => _renameConversation(item),
),
AppMenuItem(
label: context.l10n.agentMoveToTrash,
onPressed: () => _trashConversation(item),
),
AppMenuItem(
label: context.l10n.agentRelinkProvider,
onPressed: () => _relinkProvider(item),
),
const AppMenuSeparator(),
AppMenuItem(
label: '${context.l10n.agentDeleteForever}…',
destructive: true,
onPressed: () => _deleteForever(item),
),
];
if (_touch) {
return TouchConversationTile(
id: item.id,
title: item.title,
selected: selected,
onSelect: () => _selectConversation(item),
actions: actions,
); );
} final selected =
return Padding( ref.watch(
padding: AppSidebarMetrics.rowPadding, conversationSelectionProvider(item.projectId)
child: AppContextMenu( .select((value) => value.selectedId == item.id),
itemsBuilder: actions, ) &&
child: Material( active;
color: selected List<Widget> actions(BuildContext context) => [
? AppSidebarColors.of(context).hover AppMenuItem(
: Colors.transparent, label: context.l10n.rename,
borderRadius: BorderRadius.circular(AppSidebarMetrics.radius), onPressed: () => _renameConversation(item),
child: InkWell( ),
key: ValueKey('sidebar-conversation-${item.id}'), AppMenuItem(
hoverColor: selected label: context.l10n.agentMoveToTrash,
? Colors.transparent onPressed: () => _trashConversation(item),
: AppSidebarColors.of(context).hover, ),
splashColor: Colors.transparent, AppMenuItem(
highlightColor: Colors.transparent, label: context.l10n.agentRelinkProvider,
onPressed: () => _relinkProvider(item),
),
const AppMenuSeparator(),
AppMenuItem(
label: '${context.l10n.agentDeleteForever}…',
destructive: true,
onPressed: () => _deleteForever(item),
),
];
if (_touch) {
return TouchConversationTile(
id: item.id,
title: item.title,
selected: selected,
onSelect: () => _selectConversation(item),
actions: actions,
);
}
return Padding(
padding: AppSidebarMetrics.rowPadding,
child: AppContextMenu(
itemsBuilder: actions,
child: Material(
color: selected
? AppSidebarColors.of(context).hover
: Colors.transparent,
borderRadius: BorderRadius.circular(AppSidebarMetrics.radius), borderRadius: BorderRadius.circular(AppSidebarMetrics.radius),
onTap: () => _selectConversation(item), child: InkWell(
child: SizedBox( key: ValueKey('sidebar-conversation-${item.id}'),
height: AppSidebarMetrics.rowHeight, hoverColor: selected
child: Align( ? Colors.transparent
alignment: AlignmentDirectional.centerStart, : AppSidebarColors.of(context).hover,
child: Padding( splashColor: Colors.transparent,
padding: const EdgeInsetsDirectional.only( highlightColor: Colors.transparent,
start: AppSidebarMetrics.textInset, borderRadius: BorderRadius.circular(AppSidebarMetrics.radius),
end: AppSidebarMetrics.cellPadding, onTap: () => _selectConversation(item),
), child: SizedBox(
child: Text( height: AppSidebarMetrics.rowHeight,
item.title, child: Align(
maxLines: 1, alignment: AlignmentDirectional.centerStart,
overflow: TextOverflow.ellipsis, child: Padding(
style: AppSidebarTypography.style( padding: const EdgeInsetsDirectional.only(
context, start: AppSidebarMetrics.textInset,
fontSize: AppSidebarMetrics.conversationFontSize, end: AppSidebarMetrics.cellPadding,
height: AppSidebarMetrics.conversationLineHeight, ),
child: Text(
item.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: AppSidebarTypography.style(
context,
fontSize: AppSidebarMetrics.conversationFontSize,
height: AppSidebarMetrics.conversationLineHeight,
),
), ),
), ),
), ),
@@ -368,11 +410,39 @@ 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,65 +462,70 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
setState(() => _hoveredProjectId = null); setState(() => _hoveredProjectId = null);
} }
}, },
child: _touch child: ListenableSelector(
? TouchProjectTile( listenable: _projectSelection,
project: project, select: () => _projectSelection.value == project.id,
selected: widget.selectedProjectId == project.id, builder: (context, selected) => _touch
expanded: !collapsed, ? TouchProjectTile(
availabilityLabel: _availabilityLabel(
context,
project.availability,
),
onSelect: () => _selectProjectFromNavigation(project),
onToggle: () => setState(() {
if (collapsed) {
_collapsedProjects.remove(project.id);
} else {
_collapsedProjects.add(project.id);
}
}),
onNewConversation:
widget.state.projectBusy || !project.availability.canOpen
? null
: () => _newConversationForProject(project),
onRename: project.availability.canOpen
? () => widget.onRenameProject(project)
: null,
onRemove: widget.state.projectBusy
? null
: () => _removeProject(project),
)
: Padding(
padding: AppSidebarMetrics.rowPadding,
child: _ProjectTile(
project: project, project: project,
active: widget.selectedProjectId == project.id, selected: selected,
expanded: !collapsed,
availabilityLabel: _availabilityLabel( availabilityLabel: _availabilityLabel(
context, context,
project.availability, project.availability,
), ),
onSelect: () { onSelect: () => _selectProjectFromNavigation(project),
_cutProjectsMenu.close(); onToggle: () => setState(() {
_selectProjectFromNavigation(project);
},
onRename: () => widget.onRenameProject(project),
onRemove: widget.state.projectBusy
? null
: () => _removeProject(project),
expanded: !collapsed,
onToggleExpanded: () => setState(() {
if (collapsed) { if (collapsed) {
_collapsedProjects.remove(project.id); _collapsedProjects.remove(project.id);
} else { } else {
_collapsedProjects.add(project.id); _collapsedProjects.add(project.id);
} }
}), }),
sidebarStyle: true, onNewConversation:
hovered: _hoveredProjectId == project.id, widget.state.projectBusy ||
onNewConversation: () => !project.availability.canOpen
_newConversationForProject(project), ? null
: () => _newConversationForProject(project),
onRename: project.availability.canOpen
? () => widget.onRenameProject(project)
: null,
onRemove: widget.state.projectBusy
? null
: () => _removeProject(project),
)
: Padding(
padding: AppSidebarMetrics.rowPadding,
child: _ProjectTile(
project: project,
active: selected,
availabilityLabel: _availabilityLabel(
context,
project.availability,
),
onSelect: () {
_cutProjectsMenu.close();
_selectProjectFromNavigation(project);
},
onRename: () => widget.onRenameProject(project),
onRemove: widget.state.projectBusy
? null
: () => _removeProject(project),
expanded: !collapsed,
onToggleExpanded: () => setState(() {
if (collapsed) {
_collapsedProjects.remove(project.id);
} else {
_collapsedProjects.add(project.id);
}
}),
sidebarStyle: true,
hovered: _hoveredProjectId == project.id,
onNewConversation: () =>
_newConversationForProject(project),
),
), ),
), ),
), ),
for (final item in visible) ...[ for (final item in visible) ...[
const SizedBox(height: AppSidebarMetrics.rowGap), const SizedBox(height: AppSidebarMetrics.rowGap),
@@ -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,94 +633,95 @@ class _ProjectSidebarState extends ConsumerState<ProjectSidebar> {
), ),
), ),
), ),
Positioned( if (_touch)
top: modeTop, Positioned(
left: AppSidebarMetrics.outerPadding, top: modeTop,
right: AppSidebarMetrics.outerPadding, left: AppSidebarMetrics.outerPadding,
height: AppSidebarMetrics.modeHeight, right: AppSidebarMetrics.outerPadding,
child: Align( height: AppSidebarMetrics.modeHeight,
alignment: AlignmentDirectional.topStart, child: Align(
child: AppPopover( alignment: AlignmentDirectional.topStart,
width: AppMenuMetrics.modeMenuWidth, child: AppPopover(
child: Column( width: AppMenuMetrics.modeMenuWidth,
mainAxisSize: MainAxisSize.min, child: Column(
children: [
for (final mode in WorkspaceMode.values)
AppMenuItem(
key: ValueKey('sidebar-mode-${mode.name}'),
label: mode == WorkspaceMode.agent
? context.l10n.workspaceAgent
: context.l10n.workspaceCut,
selected: widget.mode == mode,
description: mode == WorkspaceMode.agent
? context.l10n.agentLayoutDescription
: context.l10n.editingLayoutDescription,
onPressed: () {
widget.onModeChanged(mode);
if (widget.navigationOnly) _finishNavigation();
},
),
],
),
builder: (context, toggle) => TextButton(
key: const Key('sidebar-mode-trigger'),
onPressed: toggle,
style: ButtonStyle(
foregroundColor: sidebarActionButtonStyle(context)
.foregroundColor,
padding: const WidgetStatePropertyAll(
EdgeInsets.symmetric(horizontal: 8),
),
minimumSize: const WidgetStatePropertyAll(
Size(0, AppSidebarMetrics.modeHeight),
),
alignment: AlignmentDirectional.centerStart,
backgroundColor: WidgetStateProperty.resolveWith(
(states) =>
states.contains(WidgetState.hovered) ||
states.contains(WidgetState.focused) ||
states.contains(WidgetState.pressed)
? AppSidebarColors.of(context).hover
: Colors.transparent,
),
overlayColor: const WidgetStatePropertyAll(
Colors.transparent,
),
shape: WidgetStatePropertyAll(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
),
),
child: Row(
mainAxisSize: MainAxisSize.min, mainAxisSize: MainAxisSize.min,
children: [ children: [
Flexible( for (final mode in WorkspaceMode.values)
child: Text( AppMenuItem(
widget.mode == WorkspaceMode.agent key: ValueKey('sidebar-mode-${mode.name}'),
label: mode == WorkspaceMode.agent
? context.l10n.workspaceAgent ? context.l10n.workspaceAgent
: context.l10n.workspaceCut, : context.l10n.workspaceCut,
maxLines: 1, selected: widget.mode == mode,
overflow: TextOverflow.ellipsis, description: mode == WorkspaceMode.agent
style: AppSidebarTypography.style( ? context.l10n.agentLayoutDescription
context, : context.l10n.editingLayoutDescription,
fontSize: AppSidebarMetrics.titleFontSize, onPressed: () {
height: AppSidebarMetrics.titleLineHeight, widget.onModeChanged(mode);
weight: FontWeight.w600, if (widget.navigationOnly) _finishNavigation();
), },
),
],
),
builder: (context, toggle) => TextButton(
key: const Key('sidebar-mode-trigger'),
onPressed: toggle,
style: ButtonStyle(
foregroundColor: sidebarActionButtonStyle(context)
.foregroundColor,
padding: const WidgetStatePropertyAll(
EdgeInsets.symmetric(horizontal: 8),
),
minimumSize: const WidgetStatePropertyAll(
Size(0, AppSidebarMetrics.modeHeight),
),
alignment: AlignmentDirectional.centerStart,
backgroundColor: WidgetStateProperty.resolveWith(
(states) =>
states.contains(WidgetState.hovered) ||
states.contains(WidgetState.focused) ||
states.contains(WidgetState.pressed)
? AppSidebarColors.of(context).hover
: Colors.transparent,
),
overlayColor: const WidgetStatePropertyAll(
Colors.transparent,
),
shape: WidgetStatePropertyAll(
RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
), ),
), ),
const SizedBox(width: AppSpacing.small), ),
const Icon( child: Row(
Icons.keyboard_arrow_down, mainAxisSize: MainAxisSize.min,
size: AppSidebarMetrics.iconSize, children: [
), Flexible(
], child: Text(
widget.mode == WorkspaceMode.agent
? context.l10n.workspaceAgent
: context.l10n.workspaceCut,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: AppSidebarTypography.style(
context,
fontSize: AppSidebarMetrics.titleFontSize,
height: AppSidebarMetrics.titleLineHeight,
weight: FontWeight.w600,
),
),
),
const SizedBox(width: AppSpacing.small),
const Icon(
Icons.keyboard_arrow_down,
size: AppSidebarMetrics.iconSize,
),
],
),
), ),
), ),
), ),
), ),
),
], ],
), ),
); );
@@ -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,79 +772,102 @@ 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, _) {
padding: const EdgeInsets.all(AppSpacing.small), ref.watch(
child: Text( conversationSidebarProvider.select(
_conversationError!, (value) => (value.hasError, value.value?.reloadFailed),
style: Theme.of(context).textTheme.bodySmall,
),
),
if (widget.state.activeProject != null &&
(_trashed.isNotEmpty || _showTrash))
ExpansionTile(
title: Text(
context.l10n.agentTrash,
style: AppSidebarTypography.style(
context,
color: AppSidebarColors.of(context).tertiary,
weight: FontWeight.w500,
), ),
), );
initiallyExpanded: _showTrash, return _conversationError == null
onExpansionChanged: (value) => setState(() => _showTrash = value), ? const SizedBox.shrink()
trailing: _trashed.isEmpty : Padding(
? null padding: const EdgeInsets.all(AppSpacing.small),
: TextButton( child: Text(
onPressed: _emptyTrash, _conversationError!,
child: Text(context.l10n.agentEmptyTrash), style: Theme.of(context).textTheme.bodySmall,
),
children: [
ListView.builder(
primary: false,
shrinkWrap: true,
itemCount: _trashed.length,
itemBuilder: (context, index) {
final item = _trashed[index];
return ListTile(
dense: true,
title: Text(
item.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: AppSidebarTypography.style(
context,
fontSize: AppSidebarMetrics.fontSize,
height: AppSidebarMetrics.lineHeight,
color: AppSidebarColors.of(context).secondary,
),
),
trailing: PopupMenuButton<String>(
tooltip: context.l10n.agentConversationActions,
onSelected: (value) {
if (value == 'restore') {
_restoreConversation(item);
}
if (value == 'delete') _deleteForever(item);
},
itemBuilder: (context) => [
PopupMenuItem(
height: AppMenuMetrics.rowHeight,
value: 'restore',
child: Text(context.l10n.agentRestore),
),
PopupMenuItem(
height: AppMenuMetrics.rowHeight,
value: 'delete',
child: Text(context.l10n.agentDeleteForever),
),
],
), ),
); );
}, },
),
Consumer(
builder: (context, ref, _) {
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(
context.l10n.agentTrash,
style: AppSidebarTypography.style(
context,
color: AppSidebarColors.of(context).tertiary,
weight: FontWeight.w500,
),
),
initiallyExpanded: _showTrash,
onExpansionChanged: (value) =>
setState(() => _showTrash = value),
trailing: _trashed.isEmpty
? null
: TextButton(
onPressed: _emptyTrash,
child: Text(context.l10n.agentEmptyTrash),
),
children: [
ListView.builder(
primary: false,
shrinkWrap: true,
itemCount: _trashed.length,
itemBuilder: (context, index) {
final item = _trashed[index];
return ListTile(
dense: true,
title: Text(
item.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: AppSidebarTypography.style(
context,
fontSize: AppSidebarMetrics.fontSize,
height: AppSidebarMetrics.lineHeight,
color: AppSidebarColors.of(context).secondary,
),
),
trailing: PopupMenuButton<String>(
tooltip: context.l10n.agentConversationActions,
onSelected: (value) {
if (value == 'restore') {
_restoreConversation(item);
}
if (value == 'delete') _deleteForever(item);
},
itemBuilder: (context) => [
PopupMenuItem(
height: AppMenuMetrics.rowHeight,
value: 'restore',
child: Text(context.l10n.agentRestore),
),
PopupMenuItem(
height: AppMenuMetrics.rowHeight,
value: 'delete',
child: Text(
context.l10n.agentDeleteForever,
),
),
],
),
);
},
),
],
);
},
),
], ],
), ),
); );
@@ -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();
}
}
+360 -278
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,120 +204,138 @@ 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: Row( child: Padding(
mainAxisSize: MainAxisSize.min, padding: EdgeInsets.only(
spacing: AppSpacing.tiny, left: desktop
children: [ ? (DesktopWindowFrame.railWidth -
if (navigationToggle) AppControlSize.headerButton) /
SizedBox.square( 2
dimension: AppControlSize.headerButton, : 0,
child: IconButton( ),
key: const Key( child: Row(
'project-sidebar-toggle', mainAxisSize: MainAxisSize.min,
), spacing: AppSpacing.tiny,
tooltip: navigationCollapsed children: [
? context.l10n.expandSidebar if (navigationToggle)
: context.l10n.collapseSidebar, controlSlot(
onPressed: () { IconButton(
if (navigationHiddenBySpace) { key: const Key(
_desktopScaffoldKey.currentState 'project-sidebar-toggle',
?.openDrawer(); ),
} else { tooltip: navigationCollapsed
_sidebarCollapsed = ? context.l10n.expandSidebar
!_sidebarCollapsed; : context.l10n.collapseSidebar,
_saveViewState(); onPressed: () {
} if (navigationHiddenBySpace) {
}, _desktopScaffoldKey.currentState
style: sidebarActionButtonStyle( ?.openDrawer();
context, } else {
), _sidebarCollapsed =
icon: const Icon( !_sidebarCollapsed;
Icons.view_sidebar_outlined, _saveViewState();
size: AppIconSize.header, }
), },
), style: sidebarActionButtonStyle(
), context,
if (desktop && ),
navigationCollapsed && icon: const Icon(
navigationToggle) Icons.view_sidebar_outlined,
PopupMenuButton<WorkspaceMode>( size: AppIconSize.header,
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,
),
],
), ),
), ),
), if (!desktop)
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(
tooltip: context.l10n.settings, 'project-settings-button',
onPressed: () => ),
showSettingsDialog(context), tooltip: context.l10n.settings,
style: sidebarActionButtonStyle(context), onPressed: () =>
icon: const Icon( showSettingsPage(context),
Icons.settings_outlined, style: sidebarActionButtonStyle(
size: AppIconSize.header, context,
),
icon: const Icon(
Icons.settings_outlined,
size: AppIconSize.header,
),
),
), ),
), controlSlot(const BackgroundTasksButton()),
), ],
SizedBox.square( ),
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,61 +438,210 @@ 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 )
? EditorWorkspace( .firstOrNull
key: _editorKey, : null;
experience: experience, final projectLoading =
projectId: state.activeProject!.id, pendingProject != null &&
timelineId: state.timeline!.id, pendingProject.id != state.activeProject?.id;
projectName: state.activeProject!.name, final editor = ProjectSwitchRegion(
showProjectName: pendingProjectId: projectLoading
desktop && _mode == WorkspaceMode.cut, ? pendingProject.id
integratedTitlebar: desktop && integrated, : null,
headerLeading: builder: (context, showDefaults) {
desktop && _mode == WorkspaceMode.cut final displayDefaults =
? leading() projectLoading && showDefaults;
: const SizedBox( final visibleProject = displayDefaults
width: AppSpacing.compact, ? pendingProject
), : state.activeProject;
) return visibleProject != null &&
: EmptyEditor( (displayDefaults ||
state: state, state.timeline != null)
showProjectName: ? EditorWorkspace(
desktop && _mode == WorkspaceMode.cut, key: _editorKey,
headerLeading: experience: experience,
desktop && _mode == WorkspaceMode.cut projectId: visibleProject.id,
? leading() timelineId: displayDefaults
: const SizedBox( ? ''
width: AppSpacing.compact, : state.timeline!.id,
), projectName: visibleProject.name,
), projectLoading: displayDefaults,
showProjectName:
desktop &&
_mode == WorkspaceMode.cut,
integratedTitlebar: false,
headerLeading: desktop
? const SizedBox.shrink()
: const SizedBox(
width: AppSpacing.compact,
),
)
: EmptyEditor(
desktop: desktop,
state: state,
showProjectName:
desktop &&
_mode == WorkspaceMode.cut,
headerLeading: desktop
? const SizedBox.shrink()
: const SizedBox(
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(
controller: _desktopSplits, integratedTitlebar: integrated,
scaffoldKey: _desktopScaffoldKey, headerControls: controls(),
navigationDrawer: navigation(drawer: true), librarySelected:
mode: _mode, contentSelection.surface ==
sidebarCollapsed: navigationCollapsed, DesktopContent.library,
sidebarWidth: _sidebarWidthOverride, settingsSelected:
onSidebarCollapsedChanged: (value) { contentSelection.surface ==
_sidebarCollapsed = value; DesktopContent.settings,
_saveViewState(); onModeChanged: (mode) {
selectSidebar(false);
_setMode(mode);
}, },
onSidebarWidthChanged: (value) { onLibraryPressed: () => selectSidebar(true),
_sidebarWidthOverride = value; onSettingsPressed: () =>
_saveViewState(); showSettingsPage(context),
}, child: desktopContents(
sidebarBuilder: (geometry, expand) => DesktopWorkspaceShell(
navigation( controller: _desktopSplits,
geometry: geometry, scaffoldKey: _desktopScaffoldKey,
expandEditor: expand, navigationDrawer: navigation(drawer: true),
mode: _mode,
sidebarCollapsed: navigationCollapsed,
sidebarWidth: _sidebarWidthOverride,
onSidebarCollapsedChanged: (value) {
_sidebarCollapsed = value;
_saveViewState();
},
onSidebarWidthChanged: (value) {
_sidebarWidthOverride = value;
_saveViewState();
},
sidebarBuilder: (geometry, expand) =>
navigation(
geometry: geometry,
expandEditor: expand,
),
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,
@@ -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))}';
}
}
+17 -505
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(
title: context.l10n.settings, data: AppTheme.settingsContentTheme(Theme.of(context)),
closeLabel: context.l10n.closeSettings, child: AppDialog(
width: math.min(1120, math.max(560, viewport.width * .9)), title: context.l10n.settings,
height: math.min(704, math.max(520, viewport.height * .88)), closeLabel: context.l10n.closeSettings,
contentOnly: true, width: math.min(1120, math.max(560, viewport.width * .9)),
scrollContent: false, height: math.min(704, math.max(520, viewport.height * .88)),
child: LayoutBuilder( contentOnly: true,
builder: (context, constraints) => Row( scrollContent: false,
crossAxisAlignment: CrossAxisAlignment.stretch, child: SettingsContent(workspace: workspace, initialTab: initialTab),
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) {
+214 -208
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,86 +31,121 @@ 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)), projectId: projectId,
child: Column( timelineId: timelineId,
crossAxisAlignment: CrossAxisAlignment.stretch, timelines: timelines,
children: [ creating: projectState?.creatingTimeline ?? false,
_TimelineTabsBar( openingTimelineId: projectState?.openingTimelineId,
projectId: projectId, );
timelineId: timelineId, }
timelines: timelines, }
creating: projectState?.creatingTimeline ?? false,
openingTimelineId: projectState?.openingTimelineId, class _TimelineSessionContent extends ConsumerWidget {
), const _TimelineSessionContent({
const Divider(height: 1), required this.projectId,
Expanded( required this.timelineId,
child: timeline.when( });
loading: () => const WorkspacePanel( final String projectId;
key: Key('timeline-pending'), final String timelineId;
child: SizedBox.expand(), @override
), Widget build(BuildContext context, WidgetRef ref) {
error: (_, _) => WorkspacePanel( final provider = editorTimelineProvider(projectId, timelineId);
child: Center( final watched = ref.watch(provider);
child: SingleChildScrollView( final cached = watched.isLoading && !watched.hasError
primary: false, ? ref
child: Column( .read(projectsProvider.notifier)
mainAxisSize: MainAxisSize.min, .cachedTimelineSession(projectId, timelineId)
children: [ : null;
Text( final timeline = cached == null ? watched : AsyncData(cached);
context.l10n.openTimelineFailed, return timeline.when(
textAlign: TextAlign.center, loading: () => const EditorTimelineDefaults(
), key: Key('timeline-pending'),
TextButton( showTabs: false,
onPressed: () => ref.invalidate(provider), ),
child: Text(context.l10n.retry), error: (_, _) => WorkspacePanel(
), child: Center(
], child: SingleChildScrollView(
), primary: false,
), child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
context.l10n.openTimelineFailed,
textAlign: TextAlign.center,
), ),
), TextButton(
data: (session) => Listener( onPressed: () => ref.invalidate(provider),
behavior: HitTestBehavior.translucent, child: Text(context.l10n.retry),
onPointerDown: (_) { ),
if (const bool.fromEnvironment('CUTDEX_PREVIEW_TRACE')) { ],
debugPrint(
'CUTDEX_PREVIEW '
'${DateTime.now().millisecondsSinceEpoch} '
'dart pointer-down',
);
}
ref
.read(
previewNavigationProvider(
projectId,
timelineId,
).notifier,
)
.showTimeline();
},
child: _TimelineEditor(session: session, projectId: projectId),
),
), ),
), ),
], ),
),
data: (session) => Listener(
behavior: HitTestBehavior.translucent,
onPointerDown: (_) {
if (const bool.fromEnvironment('CUTDEX_PREVIEW_TRACE')) {
debugPrint(
'CUTDEX_PREVIEW '
'${DateTime.now().millisecondsSinceEpoch} '
'dart pointer-down',
);
}
ref
.read(previewNavigationProvider(projectId, timelineId).notifier)
.showTimeline();
},
child: _TimelineEditor(session: session, projectId: projectId),
), ),
); );
} }
@@ -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,107 +697,121 @@ 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: () => (
key: const Key('timeline-toolbar'), controller.canUndo,
height: 32, controller.canRedo,
child: Padding( controller.canCutSelection,
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.gap), controller.canDeleteSelection,
child: LayoutBuilder( controller.commandRejection,
builder: (context, constraints) => SingleChildScrollView( _canSplitCaption(controller, _selectedCaptionCues(controller)),
scrollDirection: Axis.horizontal, _selectedCaptionCues(controller).singleOrNull,
child: ConstrainedBox( controller.version.kernelVersion,
constraints: BoxConstraints(minWidth: constraints.maxWidth), ),
child: IntrinsicWidth( builder: (context, _) {
child: Row( final captionCues = _selectedCaptionCues(controller);
children: [ final canSplitCaption = _canSplitCaption(controller, captionCues);
Row( return SizedBox(
mainAxisSize: MainAxisSize.min, key: const Key('timeline-toolbar'),
spacing: AppSpacing.tiny, height: 32,
children: [ child: Padding(
_toolbarButton( padding: const EdgeInsets.symmetric(horizontal: AppSpacing.gap),
tooltip: context.l10n.undo, child: LayoutBuilder(
onPressed: controller.canUndo builder: (context, constraints) => SingleChildScrollView(
? controller.undo scrollDirection: Axis.horizontal,
: null, child: ConstrainedBox(
icon: Icons.undo, constraints: BoxConstraints(minWidth: constraints.maxWidth),
), child: IntrinsicWidth(
_toolbarButton( child: Row(
tooltip: context.l10n.redo, children: [
onPressed: controller.canRedo Row(
? controller.redo mainAxisSize: MainAxisSize.min,
: null, spacing: AppSpacing.tiny,
icon: Icons.redo, children: [
), _toolbarButton(
_toolbarButton( tooltip: context.l10n.undo,
tooltip: context.l10n.splitAtPlayhead, onPressed: controller.canUndo
onPressed: canSplitCaption ? controller.undo
? () => _runCaptionEdit( : null,
context, icon: Icons.undo,
() => _splitCaption( ),
sequenceId, _toolbarButton(
controller, tooltip: context.l10n.redo,
captionCues.single, onPressed: controller.canRedo
), ? controller.redo
) : null,
: controller.canCutSelection icon: Icons.redo,
? controller.cutSelectionAtPlayhead ),
: null, _toolbarButton(
icon: Icons.content_cut, tooltip: context.l10n.splitAtPlayhead,
), onPressed: canSplitCaption
_toolbarButton( ? () => _runCaptionEdit(
key: const ValueKey('timeline-trim-left'), context,
tooltip: context.l10n.trimLeftTooltip, () => _splitCaption(
onPressed: controller.canCutSelection sequenceId,
? controller.trimLeftAtPlayhead controller,
: null, captionCues.single,
icon: Icons.align_horizontal_left, ),
semanticLabel: context.l10n.trimLeft, )
), : controller.canCutSelection
_toolbarButton( ? controller.cutSelectionAtPlayhead
key: const ValueKey('timeline-trim-right'), : null,
tooltip: context.l10n.trimRightTooltip, icon: Icons.content_cut,
onPressed: controller.canCutSelection ),
? controller.trimRightAtPlayhead _toolbarButton(
: null, key: const ValueKey('timeline-trim-left'),
icon: Icons.align_horizontal_right, tooltip: context.l10n.trimLeftTooltip,
semanticLabel: context.l10n.trimRight, onPressed: controller.canCutSelection
), ? controller.trimLeftAtPlayhead
_toolbarButton( : null,
key: const ValueKey('timeline-delete-selection'), icon: Icons.align_horizontal_left,
tooltip: context.l10n.deleteSelectedClips, semanticLabel: context.l10n.trimLeft,
onPressed: () { ),
if (!controller.canDeleteSelection) return; _toolbarButton(
controller.deleteSelection(); key: const ValueKey('timeline-trim-right'),
}, tooltip: context.l10n.trimRightTooltip,
icon: Icons.delete_outline, onPressed: controller.canCutSelection
), ? controller.trimRightAtPlayhead
], : null,
), icon: Icons.align_horizontal_right,
const Spacer(), semanticLabel: context.l10n.trimRight,
if (controller.commandRejection != null) ),
Tooltip( _toolbarButton(
message: controller.commandRejection!, key: const ValueKey(
child: const Icon(Icons.info_outline), 'timeline-delete-selection',
),
tooltip: context.l10n.deleteSelectedClips,
onPressed: () {
if (!controller.canDeleteSelection) return;
controller.deleteSelection();
},
icon: Icons.delete_outline,
),
],
), ),
], const Spacer(),
if (controller.commandRejection != null)
Tooltip(
message: controller.commandRejection!,
child: const Icon(Icons.info_outline),
),
],
),
), ),
), ),
), ),
), ),
), ),
), );
), },
), ),
child: ListenableBuilder( 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();
+3 -3
View File
@@ -39,7 +39,7 @@ macOS 宿主窗口继承 `CutdexNativeWindow`,导入 `cutdex_native` 后按 Fl
`NativeContextMenu.show` 接收 `NativeMenuEntry` 和位置,返回选中的操作编号;应用或 UI 包负责执行操作。`NativeFullscreenSession` 接收退出回调,按顺序处理窗口全屏请求。使用 `dispose(exitFullscreen: true)` 在未被替换时恢复窗口;恢复会等待正在进行的转换完成。预览内容和布局由应用管理。 `NativeContextMenu.show` 接收 `NativeMenuEntry` 和位置,返回选中的操作编号;应用或 UI 包负责执行操作。`NativeFullscreenSession` 接收退出回调,按顺序处理窗口全屏请求。使用 `dispose(exitFullscreen: true)` 在未被替换时恢复窗口;恢复会等待正在进行的转换完成。预览内容和布局由应用管理。
在应用根目录执行 `flutter pub get`;在本包目录执行 `flutter test`。真实窗口与系统拖放还需在对应桌面平台验证。 在应用根目录执行 `fvm dart tool/flutter_local.dart pub get`;在本包目录执行 `python3 ../../tool/project_tools.py flutter test`。真实窗口与系统拖放还需在对应桌面平台验证。
## 原生回归 ## 原生回归
@@ -48,7 +48,7 @@ macOS 宿主窗口继承 `CutdexNativeWindow`,导入 `cutdex_native` 后按 Fl
macOS 标题栏手势使用真实 AppKit 响应链,文件引用策略使用临时文件与目录: macOS 标题栏手势使用真实 AppKit 响应链,文件引用策略使用临时文件与目录:
```sh ```sh
flutter build macos --debug --flavor development python3 tool/build.py macos --mode debug --flavor development
bash packages/cutdex_native/tool/macos/test_header_control_gestures.sh bash packages/cutdex_native/tool/macos/test_header_control_gestures.sh
bash packages/cutdex_native/tool/macos/test_file_drop_policy.sh bash packages/cutdex_native/tool/macos/test_file_drop_policy.sh
``` ```
@@ -56,7 +56,7 @@ bash packages/cutdex_native/tool/macos/test_file_drop_policy.sh
Windows 标题栏回归验证真实 HWND、命中区域、最大化、DPI 与标题栏恢复;先准备 Flutter C++ wrapper: Windows 标题栏回归验证真实 HWND、命中区域、最大化、DPI 与标题栏恢复;先准备 Flutter C++ wrapper:
```sh ```sh
flutter build windows --debug --flavor development python tool/build.py windows --mode debug --flavor development
cmake -S packages/cutdex_native/tool/windows/window_chrome_tests -B build/window_chrome_tests -A x64 cmake -S packages/cutdex_native/tool/windows/window_chrome_tests -B build/window_chrome_tests -A x64
cmake --build build/window_chrome_tests --config Release cmake --build build/window_chrome_tests --config Release
ctest --test-dir build/window_chrome_tests -C Release --output-on-failure ctest --test-dir build/window_chrome_tests -C Release --output-on-failure
+3 -3
View File
@@ -12,11 +12,11 @@ Cutdex workspace 内部 Flutter 包,维护通用组件与基础视觉主题,
原生菜单通过 `cutdex_native` 展示,无法展示时回退到 Flutter 菜单。时间线与编辑器的业务样式由应用维护。 原生菜单通过 `cutdex_native` 展示,无法展示时回退到 Flutter 菜单。时间线与编辑器的业务样式由应用维护。
在应用根目录执行 `flutter pub get`;在本包目录执行: 在应用根目录执行 `fvm dart tool/flutter_local.dart pub get`;在本包目录执行:
```sh ```sh
dart run build_runner build python3 ../../tool/project_tools.py dart run build_runner build
flutter test python3 ../../tool/project_tools.py flutter test
``` ```
生成的 Freezed 文件随源码提交。测试维护在本包 `test/`,应用接线测试保留在应用中。 生成的 Freezed 文件随源码提交。测试维护在本包 `test/`,应用接线测试保留在应用中。
+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
+139 -84
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, expect(
WorkspaceLayoutMetrics.mediaPanelWidth, tester
); .getRect(find.byKey(const Key('desktop-project-card')))
expect( .contains(tester.getRect(find.byType(MediaPanel)).center),
tester.getSize(find.byType(EditorPropertiesPanel)).width, isTrue,
WorkspaceLayoutMetrics.propertiesPanelWidth, );
); final browser = mounted.container.read(
expect(find.byKey(const Key('editor-tool-surface')), findsNothing); mediaBrowserProvider(mounted.projectId),
);
await setMode(tester, mounted.container, WorkspaceMode.agent); browser.filter = MediaFilter.image;
expect(find.byKey(const Key('editor-tool-surface')), findsOneWidget); browser.selectedAssetId = 'media';
expect(find.byType(EditorPropertiesPanel), findsOneWidget); await tester.tap(find.byKey(const Key('desktop-rail-cut')));
expect(find.byType(PropertiesEditorPage), findsNothing); await tester.pumpAndSettle();
expect(find.byType(EditorTimelinePanel), findsOneWidget); expect(find.byType(MediaPanel), findsNothing);
expect( await tester.tap(find.byKey(const Key('desktop-rail-library')));
mounted.container await tester.pumpAndSettle();
.read(projectViewSettingsProvider(mounted.projectId)) expect(tester.element(find.byType(MediaPanel)), same(mediaElement));
.requireValue expect(browser.filter, MediaFilter.image);
.propertiesOpen, expect(browser.selectedAssetId, 'media');
isTrue, expect(find.byKey(const Key('sidebar-tab-resources')), findsNothing);
); expect(find.byType(EditorWorkspace), findsOneWidget);
await tester.tap(find.byKey(const Key('editor-media-button'))); await tester.tap(find.byKey(const Key('desktop-rail-cut')));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(find.byType(MediaPanel), findsOneWidget); await tester.tap(find.byKey(const Key('editor-properties-button')));
await tester.pumpAndSettle();
expect(find.byType(MediaBrowserDrawer), findsNothing); expect(find.byType(EditorPropertiesPanel), findsOneWidget);
expect(find.byType(PropertiesToolPanel), findsNothing); expect(find.byKey(const Key('editor-media-region')), findsNothing);
expect( expect(tester.takeException(), isNull);
tester await mounted.close();
.widget<IconButton>(find.byKey(const Key('editor-media-button'))) });
.isSelected,
isTrue,
);
await setMode(tester, mounted.container, WorkspaceMode.cut);
expect(find.byKey(const Key('editor-tool-surface')), findsNothing);
expect(
tester.getSize(find.byType(MediaPanel)).width,
WorkspaceLayoutMetrics.mediaPanelWidth,
);
expect(
tester.getSize(find.byType(EditorPropertiesPanel)).width,
WorkspaceLayoutMetrics.propertiesPanelWidth,
);
expect(
await mounted.container.read(
editorTimelineProvider(mounted.projectId, 'project').future,
),
same(mounted.session),
);
expect(tester.takeException(), isNull);
await mounted.close();
},
);
testWidgets( 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();
Loaded 100 of 177 files, more files were not shown because too many files have changed in this diff. Show more